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
64
65
66
67
68
69
70
71
72
73
74
use std::{
    convert::From,
    fmt::{Debug, Display, Formatter, self},
};

/// Fallible result values returned by the library.
pub type Result<T> = std::result::Result<T, Error>;

/// Errors returned by the library.
#[derive(Debug)]
pub enum Error {
    /// The client is disconnected.
    Disconnected,

    /// An error represented by an implementation of std::error::Error.
    StdError(Box<dyn std::error::Error + Send + Sync>),

    /// An error represented as a String.
    String(String),

    #[doc(hidden)]
    _NonExhaustive
}

impl Error {
    /// Construct an error instance from an implementation of std::error::Error.
    pub fn from_std_err<T: std::error::Error + Send + Sync + 'static>(e: T) -> Error {
        Error::StdError(Box::new(e))
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> std::result::Result<(), fmt::Error> {
        match self {
            Error::Disconnected => write!(f, "Disconnected"),
            Error::StdError(e) => write!(f, "{}", e),
            Error::String(s) => write!(f, "{}", s),
            Error::_NonExhaustive => panic!("Not reachable"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::StdError(e) => Some(&**e),
            _ => None,
        }
    }
}

impl From<String> for Error {
    fn from(s: String) -> Error {
        Error::String(s)
    }
}

impl From<&str> for Error {
    fn from(s: &str) -> Error {
        Error::String(s.to_owned())
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Error {
        Error::StdError(Box::new(e))
    }
}

impl From<mqttrs::Error> for Error {
    fn from(e: mqttrs::Error) -> Error {
        Error::StdError(Box::new(e))
    }
}