rom_analyzer/
error.rs

1//! Defines custom error types for ROM-Analyzer, providing a centralized way
2//! to handle and propagate errors throughout the application.
3
4use std::error::Error;
5use std::fmt;
6
7use zip::result::ZipError;
8
9#[derive(Debug)]
10pub struct RomAnalyzerError {
11    details: String,
12}
13
14impl RomAnalyzerError {
15    /// Creates a new `RomAnalyzerError` with the given message.
16    ///
17    /// # Arguments
18    ///
19    /// * `msg` - A string slice that describes the error.
20    ///
21    /// # Returns
22    ///
23    /// A new `RomAnalyzerError` instance.
24    pub fn new(msg: &str) -> RomAnalyzerError {
25        RomAnalyzerError {
26            details: msg.to_string(),
27        }
28    }
29}
30
31impl fmt::Display for RomAnalyzerError {
32    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33        write!(f, "{}", self.details)
34    }
35}
36
37impl Error for RomAnalyzerError {
38    fn description(&self) -> &str {
39        &self.details
40    }
41}
42
43/// Converts a `zip::result::ZipError` into a `RomAnalyzerError`.
44impl From<ZipError> for RomAnalyzerError {
45    fn from(err: ZipError) -> RomAnalyzerError {
46        RomAnalyzerError::new(&format!("Zip Error: {}", err))
47    }
48}
49
50/// Converts a `std::io::Error` into a `RomAnalyzerError`.
51impl From<std::io::Error> for RomAnalyzerError {
52    fn from(err: std::io::Error) -> RomAnalyzerError {
53        RomAnalyzerError::new(&format!("IO Error: {}", err))
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60    use std::io::{Error as IoError, ErrorKind};
61
62    #[test]
63    fn test_new_error() {
64        let error_msg = "Test error message";
65        let err = RomAnalyzerError::new(error_msg);
66        assert_eq!(err.details, error_msg);
67    }
68
69    #[test]
70    fn test_display_trait() {
71        let error_msg = "Display test";
72        let err = RomAnalyzerError::new(error_msg);
73        assert_eq!(format!("{}", err), error_msg);
74    }
75
76    #[test]
77    fn test_from_zip_error() {
78        let zip_err = ZipError::FileNotFound;
79        let zip_err_display = format!("{}", zip_err);
80        let err: RomAnalyzerError = zip_err.into();
81        assert_eq!(err.details, format!("Zip Error: {}", zip_err_display));
82    }
83
84    #[test]
85    fn test_from_io_error() {
86        let io_err = IoError::new(ErrorKind::NotFound, "File not found");
87        let err: RomAnalyzerError = io_err.into();
88        assert!(err.details.contains("IO Error"));
89        assert!(err.details.contains("File not found"));
90    }
91}