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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
use core::{fmt, str};
use crate::data::Type;

#[cfg(feature = "alloc")]
use alloc::string::ToString;

/// Decoding error.
#[derive(Debug)]
pub struct Error {
    err: ErrorImpl,
    pos: Option<usize>,
    #[cfg(not(feature = "alloc"))]
    msg: &'static str,
    #[cfg(feature = "alloc")]
    msg: alloc::string::String
}

impl Error {
    /// The end of the input bytes has been reached.
    pub fn end_of_input() -> Self {
        Error {
            err: ErrorImpl::EndOfInput,
            pos: None,
            msg: Default::default()
        }
    }

    /// A type error.
    pub fn type_mismatch(ty: Type) -> Self {
        Error {
            err: ErrorImpl::TypeMismatch(ty),
            pos: None,
            msg: Default::default()
        }
    }

    /// Construct an error with a generic message.
    ///
    /// With feature `"alloc"` any type `T: Display` is accepted which allows
    /// formatted strings. Otherwise only a `&'static str` can be used as a
    /// message.
    #[cfg(not(feature = "alloc"))]
    pub fn message(msg: &'static str) -> Self {
        Error {
            err: ErrorImpl::Message,
            pos: None,
            msg
        }
    }

    /// Construct an error with a generic message.
    ///
    /// With feature `"alloc"` any type `T: Display` is accepted which allows
    /// formatted strings. Otherwise only a `&'static str` can be used as a
    /// message.
    #[cfg(feature = "alloc")]
    pub fn message<T: fmt::Display>(msg: T) -> Self {
        Error {
            err: ErrorImpl::Message,
            pos: None,
            msg: msg.to_string()
        }
    }

    /// A custom error.
    ///
    /// *Requires feature* `"std"`.
    #[cfg(feature = "std")]
    pub fn custom<T: std::error::Error + Send + Sync + 'static>(err: T) -> Self {
        Error {
            err: ErrorImpl::Custom(Box::new(err)),
            pos: None,
            msg: Default::default()
        }
    }

    /// An unknown enum variant (denoted by the given index) was encountered.
    #[doc(hidden)]
    pub fn unknown_variant(idx: u32) -> Self {
        Error {
            err: ErrorImpl::UnknownVariant(idx),
            pos: None,
            msg: Default::default()
        }
    }

    /// A value, expected at the given index, was missing.
    #[doc(hidden)]
    pub fn missing_value(idx: u32) -> Self {
        Error {
            err: ErrorImpl::MissingValue(idx),
            pos: None,
            msg: Default::default()
        }
    }

    pub(crate) fn invalid_char(item: u32) -> Self {
        Error {
            err: ErrorImpl::InvalidChar(item),
            pos: None,
            msg: Default::default()
        }
    }

    pub(crate) fn utf8(err: str::Utf8Error) -> Self {
        Error {
            err: ErrorImpl::Utf8(err),
            pos: None,
            msg: Default::default()
        }
    }

    pub(crate) fn overflow(item: u64) -> Self {
        Error {
            err: ErrorImpl::Overflow(item),
            pos: None,
            msg: Default::default()
        }
    }

    /// Set the decoding position where the error happened.
    pub fn at(mut self, pos: usize) -> Self {
        self.pos = Some(pos);
        self
    }

    /// Add a message to this error value.
    ///
    /// With feature `"alloc"` any type `T: Display` is accepted which allows
    /// formatted strings. Otherwise only a `&'static str` can be used as a
    /// message.
    #[cfg(not(feature = "alloc"))]
    pub fn with_message(mut self, msg: &'static str) -> Self {
        self.msg = msg;
        self
    }

    /// Add a message to this error value.
    ///
    /// With feature `"alloc"` any type `T: Display` is accepted which allows
    /// formatted strings. Otherwise only a `&'static str` can be used as a
    /// message.
    #[cfg(feature = "alloc")]
    pub fn with_message<T: fmt::Display>(mut self, msg: T) -> Self {
        self.msg = msg.to_string();
        self
    }

    pub fn is_end_of_input(&self) -> bool {
        matches!(self.err, ErrorImpl::EndOfInput)
    }

    pub fn is_type_mismatch(&self) -> bool {
        matches!(self.err, ErrorImpl::TypeMismatch(_))
    }

    pub fn is_message(&self) -> bool {
        matches!(self.err, ErrorImpl::Message)
    }

    #[cfg(feature = "std")]
    pub fn is_custom(&self) -> bool {
        matches!(self.err, ErrorImpl::Custom(_))
    }

    #[doc(hidden)]
    pub fn is_unknown_variant(&self) -> bool {
        matches!(self.err, ErrorImpl::UnknownVariant(_))
    }

    #[doc(hidden)]
    pub fn is_missing_value(&self) -> bool {
        matches!(self.err, ErrorImpl::MissingValue(_))
    }
}

/// Internal error representation.
#[derive(Debug)]
enum ErrorImpl {
    /// Decoding has (unexpectedly) reached the end of the input slice.
    EndOfInput,
    /// Data item to decode is not a valid `char`.
    InvalidChar(u32),
    /// Decoding a string failed because it is invalid UTF-8.
    Utf8(str::Utf8Error),
    /// A numeric value exceeds its value range.
    Overflow(u64),
    /// An unexpected type was encountered.
    TypeMismatch(Type),
    /// An unknown enum variant was encountered.
    UnknownVariant(u32),
    /// A value was missing at the specified index.
    MissingValue(u32),
    /// Generic error message.
    Message,
    /// Custom error.
    #[cfg(feature = "std")]
    Custom(Box<dyn std::error::Error + Send + Sync>)
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self.err {
            ErrorImpl::EndOfInput =>
                match (self.msg.as_ref(), self.pos) {
                    ("", None)    => write!(f, "end of input bytes"),
                    ("", Some(p)) => write!(f, "end of input bytes at position {p}"),
                    (m, None)     => write!(f, "end of input bytes: {m}"),
                    (m, Some(p))  => write!(f, "end of input bytes at position {p}: {m}")
                }
            ErrorImpl::InvalidChar(n) =>
                match (self.msg.as_ref(), self.pos) {
                    ("", None)    => write!(f, "invalid char {n:#x?}"),
                    ("", Some(p)) => write!(f, "invalid char {n:#x?} at position {p}"),
                    (m, None)     => write!(f, "invalid char {n:#x?}: {m}"),
                    (m, Some(p))  => write!(f, "invalid char {n:#x?} at position {p}: {m}")
                }
            #[cfg(not(feature = "std"))]
            ErrorImpl::Utf8(e) =>
                match (self.msg.as_ref(), self.pos) {
                    ("", None)    => write!(f, "invalid utf-8: {e}"),
                    ("", Some(p)) => write!(f, "invalid utf-8 at position {p}: {e}"),
                    (m, None)     => write!(f, "invalid utf-8: {e}, {m}"),
                    (m, Some(p))  => write!(f, "invalid utf-8 at position {p}: {e}, {m}")
                }
            #[cfg(feature = "std")]
            ErrorImpl::Utf8(_) =>
                match (self.msg.as_ref(), self.pos) {
                    ("", None)    => write!(f, "invalid utf-8"),
                    ("", Some(p)) => write!(f, "invalid utf-8 at position {p}"),
                    (m, None)     => write!(f, "invalid utf-8: {m}"),
                    (m, Some(p))  => write!(f, "invalid utf-8 at position {p}: {m}")
                }
            ErrorImpl::Overflow(n) =>
                match (self.msg.as_ref(), self.pos) {
                    ("", None)    => write!(f, "{n} overflows target type"),
                    ("", Some(p)) => write!(f, "{n} overflows target type at position {p}"),
                    (m, None)     => write!(f, "{n} overflows target type: {m}"),
                    (m, Some(p))  => write!(f, "{n} overflows target type at position {p}: {m}")
                }
            ErrorImpl::TypeMismatch(t) =>
                match (self.msg.as_ref(), self.pos) {
                    ("", None)    => write!(f, "unexpected type {t}"),
                    ("", Some(p)) => write!(f, "unexpected type {t} at position {p}"),
                    (m, None)     => write!(f, "unexpected type {t}: {m}"),
                    (m, Some(p))  => write!(f, "unexpected type {t} at position {p}: {m}")
                }
            ErrorImpl::UnknownVariant(n) =>
                match (self.msg.as_ref(), self.pos) {
                    ("", None)    => write!(f, "unknown enum variant {n}"),
                    ("", Some(p)) => write!(f, "unknown enum variant {n} at position {p}"),
                    (m, None)     => write!(f, "unknown enum variant {n}: {m}"),
                    (m, Some(p))  => write!(f, "unknown enum variant {n} at position {p}: {m}")
                }
            ErrorImpl::MissingValue(n) =>
                match (self.msg.as_ref(), self.pos) {
                    ("", None)    => write!(f, "missing value at index {n}"),
                    ("", Some(p)) => write!(f, "missing value at index {n} in map or array starting at position {p}"),
                    (m, None)     => write!(f, "missing value at index {n} ({m})"),
                    (m, Some(p))  => write!(f, "missing value at index {n} ({m}) in map or array starting at position {p}")
                }
            ErrorImpl::Message =>
                if let Some(p) = self.pos {
                    write!(f, "decode error at position {p}: {}", self.msg)
                } else {
                    write!(f, "decode error: {}", self.msg)
                }
            #[cfg(feature = "std")]
            ErrorImpl::Custom(_) =>
                match (self.msg.as_ref(), self.pos) {
                    ("", None)    => write!(f, "decode error"),
                    ("", Some(p)) => write!(f, "decode error at position {p}"),
                    (m, None)     => write!(f, "decode error: {m}"),
                    (m, Some(p))  => write!(f, "decode error at position {p}: {m}")
                }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self.err {
            ErrorImpl::EndOfInput
            | ErrorImpl::InvalidChar(_)
            | ErrorImpl::Overflow(_)
            | ErrorImpl::TypeMismatch(_)
            | ErrorImpl::UnknownVariant(_)
            | ErrorImpl::MissingValue(_)
            | ErrorImpl::Message
            => None,
            ErrorImpl::Utf8(e)   => Some(e),
            ErrorImpl::Custom(e) => Some(&**e)
        }
    }
}