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;
use std::fmt;
use std::io;

/// All crate errors are wrapped in this custom error type
#[derive(Debug)]
pub struct Error {
    original: Option<Box<dyn error::Error>>,
    msg: String,
}

impl Error {
    pub(crate) fn new<S>(msg: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            original: None,
            msg: msg.into(),
        }
    }

    pub(crate) fn with_source<S, E>(msg: S, source: E) -> Self
    where
        S: Into<String>,
        E: error::Error + 'static,
    {
        Self {
            original: Some(Box::new(source)),
            msg: msg.into(),
        }
    }

    pub(crate) fn bail<T, S>(msg: S) -> Result<T, Self>
    where
        S: Into<String>,
    {
        Err(Error::new(msg))
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.msg)
    }
}

impl From<io::Error> for Error {
    fn from(error: io::Error) -> Self {
        let msg = error.to_string();
        Self {
            original: Some(Box::new(error)),
            msg,
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        self.original.as_ref().map(|o| o.as_ref())
    }
}