bmp_protocol/
error.rs

1/// Our error type
2#[derive(Debug)]
3pub enum Error {
4    /// Error during decoding a BMP message
5    DecodeError(String),
6    /// std::io::Error
7    WireError(std::io::Error),
8    // Invalid length read
9    // InvalidMessageLength,
10
11    /// Any boxed error that implement std::error::Error
12    Unknown(Box<dyn std::error::Error + Send + Sync>)
13}
14
15unsafe impl Send for Error {}
16unsafe impl Sync for Error {}
17
18impl Error {
19    /// Helper to create a DecodeError instance
20    pub fn decode(msg: &str) -> Self {
21        Self::DecodeError(msg.into())
22    }
23}
24
25impl std::fmt::Display for Error {
26    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
27        match self {
28            Self::DecodeError(error) => write!(f, "Decoding error: {}", error),
29            Self::WireError(error) => write!(f, "IO error: {}", error),
30            // Self::InvalidMessageLength => write!(f, "Invalid message size: {} bytes", error),
31
32            Self::Unknown(error) => write!(f, "Unknown error: {}", error),
33        }
34    }
35}
36
37impl std::error::Error for Error {
38    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
39        None
40    }
41}
42
43impl From<std::io::Error> for Error {
44    fn from(error: std::io::Error) -> Self {
45        Self::WireError(error)
46    }
47}
48
49impl From<Error> for std::io::Error {
50    fn from(err: Error) -> std::io::Error {
51        match err {
52            Error::WireError(e) => e,
53            Error::DecodeError(e) => Self::new(
54                std::io::ErrorKind::Other,
55                format!("{}", e).as_str()
56            ),
57            Error::Unknown(e) => Self::new(
58                std::io::ErrorKind::Other,
59                format!("{}", e).as_str()
60            ),
61        }
62    }
63}
64
65// impl Into<std::io::Error> for Error {
66//     fn into(self) -> std::io::Error {
67//         match self {
68//             Self::WireError(e) => e,
69//             Self::DecodeError(e) => std::io::Error::new(
70//                 std::io::ErrorKind::Other,
71//                 format!("{}", e).as_str()
72//             ),
73//             Self::Unknown(e) => std::io::Error::new(
74//                 std::io::ErrorKind::Other,
75//                 format!("{}", e).as_str()
76//             ),
77//         }
78//     }
79// }
80
81impl From<Box<dyn std::error::Error + Sync + Send>> for Error {
82    fn from(error: Box<dyn std::error::Error + Sync + Send>) -> Self {
83        Self::Unknown(error)
84    }
85}