diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..c7e4752 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-3.0-only + +use std::error::Error; +use std::fmt::{Debug, Display, Formatter}; + +#[derive(Debug)] +pub struct ReasonError<'a, E: Error> { + msg: &'a str, + source: E, +} + +impl Display for ReasonError<'_, E> { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(self.msg)?; + f.write_str(": ")?; + Display::fmt(&self.source, f) + } +} + +impl Error for ReasonError<'_, E> {} + +pub fn err_reason(msg: &str, source: E) -> ReasonError { + ReasonError { + msg, + source, + } +} \ No newline at end of file diff --git a/src/info.rs b/src/info.rs index c6e14eb..a3d8c7a 100644 --- a/src/info.rs +++ b/src/info.rs @@ -5,8 +5,10 @@ use std::fs; use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; +use crate::error::err_reason; use crate::pcd::{CardType, Deserialized, Game, Partitioned, PCD, PCD_LENGTH, Raw}; + pub fn info(pcd: PathBuf) -> Result<(), Box> { let pcd: PCD = PCD::try_from(fs::read(pcd)?.as_slice())?; let partitioned: PCD = pcd.into(); @@ -17,8 +19,9 @@ pub fn info(pcd: PathBuf) -> Result<(), Box> { pub fn set(title: Option, card_type: Option, card_id: Option, games: Option>, comment: Option, redistribution: Option, icons: Option>, pgt: Option, received: Option, pcd: Option, output: PathBuf) -> Result<(), Box> { let mut pcd = if let Some(f) = pcd { - let raw: PCD = PCD::try_from(fs::read(f)?.as_slice())?; - let parts: PCD = raw.try_into().unwrap(); + let data = fs::read(f).map_err(|e| err_reason("Unable to read pcd file", e))?; + let raw: PCD = PCD::try_from(data.as_slice())?; + let parts: PCD = PCD::from(raw); parts.deserialize() } else { PCD::::new() @@ -57,15 +60,15 @@ pub fn set(title: Option, card_type: Option, card_id: Option = (&pcd.serialize()).try_into()?; let pcd_data: [u8; PCD_LENGTH] = pcd.into(); let mut f = File::create(output)?; - f.write(&pcd_data).expect("Unable to write pcd file"); + f.write(&pcd_data).map_err(|e| err_reason("Unable to write pcd file", e))?; Ok(()) } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 97de9fe..e2b429c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,6 +19,7 @@ mod beacon; mod decrypt; mod pokestr; mod info; +mod error; pub mod pokestrmap { include!(concat!(env!("OUT_DIR"), "/pokestrmap.rs"));