nbs/
error.rs

1use std::{
2    error::Error,
3    fmt::{self, Display},
4    io,
5    string::FromUtf8Error,
6};
7
8#[derive(Debug)]
9pub enum NbsError {
10    /// This error occures when the format does not contain the expected data
11    InvalidFormat,
12    /// This error occurs when decoding a string thats not utf-8
13    InvalidString(FromUtf8Error),
14    /// This error occures when an io operation fails
15    IoError(io::Error),
16}
17
18impl From<io::Error> for NbsError {
19    fn from(e: io::Error) -> Self {
20        NbsError::IoError(e)
21    }
22}
23
24impl From<FromUtf8Error> for NbsError {
25    fn from(e: FromUtf8Error) -> Self {
26        NbsError::InvalidString(e)
27    }
28}
29
30impl Display for NbsError {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        match self {
33            NbsError::InvalidFormat => {
34                write!(f, "The target format is not supported by the given data.")
35            }
36            NbsError::InvalidString(e) => write!(f, "Failed to decode string; {}", e),
37            NbsError::IoError(e) => write!(f, "{}", e),
38        }
39    }
40}
41
42impl Error for NbsError {
43    fn source(&self) -> Option<&(dyn Error + 'static)> {
44        match self {
45            NbsError::InvalidFormat => None,
46            NbsError::InvalidString(e) => Some(e),
47            NbsError::IoError(e) => Some(e),
48        }
49    }
50    fn description(&self) -> &str {
51        "description() is deprecated; use Display"
52    }
53    fn cause(&self) -> Option<&dyn Error> {
54        self.source()
55    }
56}