valence_nbt/
error.rs

1use std::error::Error as StdError;
2use std::fmt::{Display, Formatter};
3use std::io;
4
5pub type Result<T, E = Error> = std::result::Result<T, E>;
6
7/// Errors that can occur when encoding or decoding binary NBT.
8#[derive(Debug)]
9pub struct Error {
10    /// Box this to keep the size of `Result<T, Error>` small.
11    cause: Box<Cause>,
12}
13
14#[derive(Debug)]
15enum Cause {
16    Io(io::Error),
17    Owned(Box<str>),
18    Static(&'static str),
19}
20
21impl Error {
22    #[allow(dead_code)]
23    pub(crate) fn new_owned(msg: impl Into<Box<str>>) -> Self {
24        Self {
25            cause: Box::new(Cause::Owned(msg.into())),
26        }
27    }
28
29    #[allow(dead_code)]
30    pub(crate) fn new_static(msg: &'static str) -> Self {
31        Self {
32            cause: Box::new(Cause::Static(msg)),
33        }
34    }
35}
36
37impl Display for Error {
38    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
39        match &*self.cause {
40            Cause::Io(e) => e.fmt(f),
41            Cause::Owned(msg) => write!(f, "{msg}"),
42            Cause::Static(msg) => write!(f, "{msg}"),
43        }
44    }
45}
46
47impl StdError for Error {
48    fn source(&self) -> Option<&(dyn StdError + 'static)> {
49        match &*self.cause {
50            Cause::Io(e) => Some(e),
51            Cause::Owned(_) => None,
52            Cause::Static(_) => None,
53        }
54    }
55}
56
57impl From<io::Error> for Error {
58    fn from(e: io::Error) -> Self {
59        Self {
60            cause: Box::new(Cause::Io(e)),
61        }
62    }
63}