dodo/serializer/
error.rs

1use std::{fmt, io, result};
2use std::error::Error;
3
4/// Serializer error.
5#[derive(Debug)]
6pub struct SerializerError(Box<RawSerializerError>);
7
8#[derive(Debug)]
9struct RawSerializerError {
10    kind: SerializerErrorKind,
11    source: Option<Box<dyn std::error::Error + Send + Sync>>,
12}
13
14impl SerializerError {
15    pub(crate) fn io<E>(error: E) -> Self
16        where E: Into<Box<dyn std::error::Error + Send + Sync>> {
17        Self(Box::new(RawSerializerError {
18            kind: SerializerErrorKind::Io,
19            source: Some(error.into()),
20        }))
21    }
22
23    pub(crate) fn syntax<E>(error: E) -> Self
24        where E: Into<Box<dyn std::error::Error + Send + Sync>> {
25        Self(Box::new(RawSerializerError {
26            kind: SerializerErrorKind::Syntax,
27            source: Some(error.into()),
28        }))
29    }
30
31    #[allow(dead_code)]
32    pub(crate) fn other<E>(error: E) -> Self
33        where E: Into<Box<dyn std::error::Error + Send + Sync>> {
34        Self(Box::new(RawSerializerError {
35            kind: SerializerErrorKind::Other,
36            source: Some(error.into()),
37        }))
38    }
39
40    /// Error kind.
41    pub fn kind(&self) -> SerializerErrorKind {
42        self.0.kind
43    }
44
45    /// Returns true if this error is Io.
46    pub fn is_io(&self) -> bool {
47        SerializerErrorKind::Io == self.0.kind
48    }
49
50    /// Returns true if this error Syntax.
51    pub fn is_syntax(&self) -> bool {
52        SerializerErrorKind::Syntax == self.0.kind
53    }
54
55    /// Returns true if this error is Other.
56    pub fn is_other(&self) -> bool {
57        SerializerErrorKind::Other == self.0.kind
58    }
59}
60
61impl Error for SerializerError {
62    fn source(&self) -> Option<&(dyn Error + 'static)> {
63        match self.0.source {
64            Some(ref source) => Some(&**source),
65            None => None
66        }
67    }
68}
69
70impl fmt::Display for SerializerError {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        self.0.kind.fmt(f)
73    }
74}
75
76impl From<io::Error> for SerializerError {
77    fn from(error: io::Error) -> Self {
78        Self::io(error)
79    }
80}
81
82/// Serializer error kind.
83#[derive(Debug, Copy, Clone, Eq, PartialEq)]
84pub enum SerializerErrorKind {
85    /// Invalid Syntax.
86    Syntax,
87    /// Io error (unexpected EOF, interrupted, ...).
88    Io,
89    /// Other error.
90    Other,
91}
92
93impl fmt::Display for SerializerErrorKind {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        use SerializerErrorKind::*;
96
97        match self {
98            Syntax => write!(f, "invalid syntax"),
99            Io => write!(f, "io error"),
100            Other => write!(f, "other error"),
101        }
102    }
103}
104
105/// Serializer result.
106pub type Result<T> = result::Result<T, SerializerError>;