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
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
//! Error management module

/// The error type used by this crate.
#[derive(Debug)]
pub enum Error {
    /// IO error
    Io(::std::io::Error),
    /// Utf8 error
    Utf8(::std::str::Utf8Error),
    /// Unexpected End of File
    UnexpectedEof(String),
    /// End event mismatch
    EndEventMismatch {
        /// Expected end event
        expected: String,
        /// Found end event
        found: String,
    },
    /// Unexpected token
    UnexpectedToken(String),
    /// Unexpected <!>
    UnexpectedBang,
    /// Text not found, expected `Event::Text`
    TextNotFound,
    /// `Event::XmlDecl` must start with *version* attribute
    XmlDeclWithoutVersion(Option<String>),
    /// Attribute Name contains quote
    NameWithQuote(usize),
    /// Attribute key not followed by with `=`
    NoEqAfterName(usize),
    /// Attribute value not quoted
    UnquotedValue(usize),
    /// Duplicate attribute
    DuplicatedAttribute(usize, usize),
    /// Escape error
    EscapeError(::escape::EscapeError),
}

impl From<::std::io::Error> for Error {
    /// Creates a new `Error::Io` from the given error
    #[inline]
    fn from(error: ::std::io::Error) -> Error {
        Error::Io(error)
    }
}

impl From<::std::str::Utf8Error> for Error {
    /// Creates a new `Error::Utf8` from the given error
    #[inline]
    fn from(error: ::std::str::Utf8Error) -> Error {
        Error::Utf8(error)
    }
}

/// A specialized `Result` type where the error is hard-wired to [`Error`].
///
/// [`Error`]: enum.Error.html
pub type Result<T> = ::std::result::Result<T, Error>;

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Error::Io(e) => write!(f, "I/O error: {}", e),
            Error::Utf8(e) => write!(f, "UTF8 error: {}", e),
            Error::UnexpectedEof(e) => write!(f, "Unexpected EOF during reading {}.", e),
            Error::EndEventMismatch { expected, found } => {
                write!(f, "Expecting </{}> found </{}>", expected, found)
            }
            Error::UnexpectedToken(e) => write!(f, "Unexpected token '{}'", e),
            Error::UnexpectedBang => write!(
                f,
                "Only Comment, CDATA and DOCTYPE nodes can start with a '!'"
            ),
            Error::TextNotFound => write!(f, "Cannot read text, expecting Event::Text"),
            Error::XmlDeclWithoutVersion(e) => write!(
                f,
                "XmlDecl must start with 'version' attribute, found {:?}",
                e
            ),
            Error::NameWithQuote(e) => write!(
                f,
                "error while parsing attribute at position {}: \
                 Attribute key cannot contain quote.",
                e
            ),
            Error::NoEqAfterName(e) => write!(
                f,
                "error while parsing attribute at position {}: \
                 Attribute key must be directly followed by = or space",
                e
            ),
            Error::UnquotedValue(e) => write!(
                f,
                "error while parsing attribute at position {}: \
                 Attribute value must start with a quote.",
                e
            ),
            Error::DuplicatedAttribute(pos1, pos2) => write!(
                f,
                "error while parsing attribute at position {0}: \
                 Duplicate attribute at position {1} and {0}",
                pos1, pos2
            ),
            Error::EscapeError(e) => write!(f, "{}", e),
        }
    }
}

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

#[cfg(feature = "serialize")]
pub mod serialize {
    //! A module to handle serde (de)serialization errors

    use super::Error;
    use std::fmt;

    /// (De)serialization error
    #[derive(Debug)]
    pub enum DeError {
        /// Serde custom error
        Custom(String),
        /// Cannot parse to integer
        Int(std::num::ParseIntError),
        /// Cannot parse to float
        Float(std::num::ParseFloatError),
        /// Xml parsing error
        Xml(Error),
        /// Unexpected end of attributes
        EndOfAttributes,
        /// Unexpected end of file
        Eof,
        /// Invalid value for a boolean
        InvalidBoolean(String),
        /// Invalid unit value
        InvalidUnit(String),
        /// Invalid event for Enum
        InvalidEnum(crate::events::Event<'static>),
        /// Expecting Text event
        Text,
        /// Expecting Start event
        Start,
        /// Expecting End event
        End,
        /// Unsupported operation
        Unsupported(&'static str),
    }

    impl fmt::Display for DeError {
        fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
            match self {
                DeError::Custom(s) => write!(f, "{}", s),
                DeError::Xml(e) => write!(f, "{}", e),
                DeError::Int(e) => write!(f, "{}", e),
                DeError::Float(e) => write!(f, "{}", e),
                DeError::EndOfAttributes => write!(f, "Unexpected end of attributes"),
                DeError::Eof => write!(f, "Unexpected `Event::Eof`"),
                DeError::InvalidBoolean(v) => write!(f, "Invalid boolean value '{}'", v),
                DeError::InvalidUnit(v) => {
                    write!(f, "Invalid unit value '{}', expected empty string", v)
                }
                DeError::InvalidEnum(e) => write!(
                    f,
                    "Invalid event for Enum, expecting Text or Start, got: {:?}",
                    e
                ),
                DeError::Text => write!(f, "Expecting Text event"),
                DeError::Start => write!(f, "Expecting Start event"),
                DeError::End => write!(f, "Expecting End event"),
                DeError::Unsupported(s) => write!(f, "Unsupported operation {}", s),
            }
        }
    }

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

    impl serde::de::Error for DeError {
        fn custom<T: fmt::Display>(msg: T) -> Self {
            DeError::Custom(msg.to_string())
        }
    }

    impl serde::ser::Error for DeError {
        fn custom<T: fmt::Display>(msg: T) -> Self {
            DeError::Custom(msg.to_string())
        }
    }

    impl From<Error> for DeError {
        fn from(e: Error) -> Self {
            DeError::Xml(e)
        }
    }

    impl From<std::num::ParseIntError> for DeError {
        fn from(e: std::num::ParseIntError) -> Self {
            DeError::Int(e)
        }
    }

    impl From<std::num::ParseFloatError> for DeError {
        fn from(e: std::num::ParseFloatError) -> Self {
            DeError::Float(e)
        }
    }
}