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
//! Error type.

mod error_kind;

pub use self::error_kind::ErrorKind;

use alloc::string::{String, ToString};
use core::fmt::Display;

/// Error type.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct Error {
    /// Machine-readable error type.
    kind: ErrorKind,

    /// Human-readable error reason.
    reason: String,
}

impl Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}: {}", self.kind, self.reason)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}

impl Error {
    /// Ref to error kind.
    pub fn kind(&self) -> &ErrorKind {
        &self.kind
    }

    fn new(kind: ErrorKind, reason: &str) -> Self {
        Self {
            kind,
            reason: reason.to_string(),
        }
    }

    #[doc(hidden)]
    pub fn serialization_error(reason: &str) -> Self {
        Self::new(ErrorKind::SerializationError, reason)
    }

    #[doc(hidden)]
    pub fn deserialization_error(reason: &str) -> Self {
        Self::new(ErrorKind::DeserializationError, reason)
    }

    #[doc(hidden)]
    pub fn encryption_error(reason: &str) -> Self {
        Self::new(ErrorKind::EncryptionError, reason)
    }

    #[doc(hidden)]
    pub fn decryption_error(reason: &str) -> Self {
        Self::new(ErrorKind::DecryptionError, reason)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::format;

    #[test]
    fn test_display() {
        let e = Error::serialization_error("x");
        let _s = format!("{}", e);
    }
}