1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use std::error::Error as StdError;
use std::fmt::{Display, Formatter};
use std::io;

pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Errors that can occur when encoding or decoding binary NBT.
#[derive(Debug)]
pub struct Error {
    /// Box this to keep the size of `Result<T, Error>` small.
    cause: Box<Cause>,
}

#[derive(Debug)]
enum Cause {
    Io(io::Error),
    Owned(Box<str>),
    Static(&'static str),
}

impl Error {
    #[allow(dead_code)]
    pub(crate) fn new_owned(msg: impl Into<Box<str>>) -> Self {
        Self {
            cause: Box::new(Cause::Owned(msg.into())),
        }
    }

    #[allow(dead_code)]
    pub(crate) fn new_static(msg: &'static str) -> Self {
        Self {
            cause: Box::new(Cause::Static(msg)),
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match &*self.cause {
            Cause::Io(e) => e.fmt(f),
            Cause::Owned(msg) => write!(f, "{msg}"),
            Cause::Static(msg) => write!(f, "{msg}"),
        }
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match &*self.cause {
            Cause::Io(e) => Some(e),
            Cause::Owned(_) => None,
            Cause::Static(_) => None,
        }
    }
}

impl From<io::Error> for Error {
    fn from(e: io::Error) -> Self {
        Self {
            cause: Box::new(Cause::Io(e)),
        }
    }
}