xsd_parser/quick_xml/
error.rs

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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
use std::error::Error as StdError;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::mem::take;
use std::str::Utf8Error;

use quick_xml::events::attributes::AttrError;
use quick_xml::{events::Event, Error as XmlError};
use thiserror::Error;

use crate::misc::RawByteStr;

/// Quick XML Error
#[derive(Debug)]
pub struct Error {
    /// Detailed information about the actual error.
    pub kind: Kind,

    /// Cursor position inside the XML document where the error occurred.
    pub position: Option<u64>,

    /// Path of XML tags where the error occurred.
    pub elements: Option<Vec<String>>,
}

/// Quick XML error kind.
#[derive(Debug, Error)]
pub enum Kind {
    /// Error forwarded from the [`quick_xml`] crate.
    #[error("XML Error: message={0}")]
    XmlError(#[from] XmlError),

    /// Attribute error forwarded from the [`quick_xml`] crate.
    #[error("Attribute Error: message={0}")]
    AttrError(#[from] AttrError),

    /// Invalid UTF-8 string.
    #[error("UTF-8 Error: message={0}")]
    InvalidUtf8(#[from] Utf8Error),

    /// Duplicate attribute.
    ///
    /// The attribute was expected only once.
    #[error("Duplicated attribute: name={0}")]
    DuplicateAttribute(RawByteStr),

    /// Duplicate element.
    ///
    /// The element was expected only once.
    #[error("Duplicated element: name={0}")]
    DuplicateElement(RawByteStr),

    /// Unexpected attribute.
    ///
    /// The attribute was not expected for the current element.
    #[error("Unexpected attribute: name={0}")]
    UnexpectedAttribute(RawByteStr),

    /// Missing attribute.
    ///
    /// The attribute was expected to be present, but it was not.
    #[error("Missing attribute: name={0}")]
    MissingAttribute(RawByteStr),

    /// Missing element.
    ///
    /// The element was expected to be present, but it was not.
    #[error("Missing element: name={0}")]
    MissingElement(RawByteStr),

    /// Invalid data.
    #[error("Invalid data: `{0}`")]
    InvalidData(RawByteStr),

    /// Missing content.
    ///
    /// The element was expected to have some content, but it haven't.
    #[error("Missing content")]
    MissingContent,

    /// Missing name.
    ///
    /// The serializer is not able to set a default name for the specified value.
    #[error("Missing name")]
    MissingName,

    /// Unknown or invalid value.
    #[error("Unknown or invalid value: {0}")]
    UnknownOrInvalidValue(RawByteStr),

    /// Insufficient size.
    ///
    /// The element or attribute contains less items then expected.
    #[error("Insufficient size (min={min}, max={max}, actual={actual})")]
    InsufficientSize {
        /// Smallest expected index.
        min: usize,

        /// Largest expected index.
        max: usize,

        /// Actual index.
        actual: usize,
    },

    /// Invalid union.
    #[error("Invalid union: {0}")]
    InvalidUnion(UnionError),

    /// Custom error.
    ///
    /// Can store any kind of error.
    #[error("Custom Error: message={0}")]
    Custom(Box<dyn StdError + Send + Sync>),

    /// Unexpected [`quick_xml`] event.
    #[error("Unexpected event: {0:#?}!")]
    UnexpectedEvent(Event<'static>),

    /// Unexpected end of file.
    #[error("Unexpected EoF!")]
    UnexpectedEof,
}

impl Error {
    /// Create a new error that uses [`Kind::Custom`] to store the passed `error`.
    pub fn custom<E: StdError + Send + Sync + 'static>(error: E) -> Self {
        Kind::Custom(Box::new(error)).into()
    }

    pub(super) fn new<E>(error: E) -> Self
    where
        Kind: From<E>,
    {
        Self {
            kind: Kind::from(error),
            position: None,
            elements: None,
        }
    }

    pub(super) fn with_pos(mut self, position: u64) -> Self {
        self.position = Some(position);

        self
    }

    pub(super) fn with_error_info(mut self, info: &ErrorInfo) -> Self {
        self.elements = Some(info.elements.clone());

        self
    }
}

impl<E> From<E> for Error
where
    Kind: From<E>,
{
    fn from(error: E) -> Self {
        Self::new(error)
    }
}

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

        if let Some(pos) = &self.position {
            write!(f, "; position={}", pos)?;
        }

        if let Some(elements) = &self.elements {
            let mut first = true;

            for element in elements {
                if take(&mut first) {
                    write!(f, "; element={}", element)?;
                } else {
                    write!(f, ">{}", element)?;
                }
            }
        }

        Ok(())
    }
}

impl StdError for Error {}

/// Contains the different errors that occurred when deserializing a union.
pub struct UnionError(Vec<Box<dyn StdError + Send + Sync + 'static>>);

impl<X> From<X> for UnionError
where
    X: IntoIterator,
    X::Item: StdError + Send + Sync + 'static,
{
    fn from(value: X) -> Self {
        Self(
            value
                .into_iter()
                .map(|err| -> Box<dyn StdError + Send + Sync + 'static> { Box::new(err) })
                .collect(),
        )
    }
}

impl Debug for UnionError {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        for err in &self.0 {
            write!(f, "- {err}")?;
        }

        Ok(())
    }
}

impl Display for UnionError {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        for err in &self.0 {
            write!(f, "- {err}")?;
        }

        Ok(())
    }
}

#[derive(Default, Debug)]
pub(super) struct ErrorInfo {
    elements: Vec<String>,
}

impl ErrorInfo {
    pub(super) fn update(&mut self, event: &Event<'_>) {
        match event {
            Event::Start(x) => {
                self.elements
                    .push(String::from_utf8_lossy(x.name().0).to_string());
            }
            Event::End(_) => {
                self.elements.pop();
            }
            _ => (),
        }
    }
}