Skip to main content

flexon/serde/
error.rs

1//! serde specific errors.
2
3use core::fmt::{Display, Formatter, Result};
4
5use serde::de;
6
7/// Represents error occurred while parsing.
8#[derive(Debug)]
9pub struct Error(Box<Kind>);
10
11/// Represents the type of error.
12#[derive(Debug, PartialEq)]
13pub enum Kind {
14    /// Serde specific error.
15    Message(Box<str>),
16
17    /// Unexpected EOF while parsing.
18    Eof,
19    /// Expected colon while parsing object.
20    ExpectedColon,
21    /// Unexpected token while parsing.
22    UnexpectedToken,
23    /// String wasn't properly terminated.
24    UnclosedString,
25    /// Found raw control characters inside string while parsing.
26    ControlCharacter,
27    /// Invalid escape sequence in string.
28    InvalidEscapeSequnce,
29    /// Invalid JSON literal.
30    InvalidLiteral,
31    /// Comma after the last value of an array or an object.
32    TrailingComma,
33    /// Number starting with a decimal point.
34    LeadingDecimal,
35    /// Number ending with a decimal point.
36    TrailingDecimal,
37    /// Number starting with zero.
38    LeadingZero,
39    /// Number is bigger than it can represent.
40    NumberOverflow,
41}
42
43impl Error {
44    /// Returns the error kind.
45    pub fn kind(&self) -> &Kind {
46        &self.0
47    }
48}
49
50impl Into<Error> for Kind {
51    #[cold]
52    fn into(self) -> Error {
53        Error(Box::new(self))
54    }
55}
56
57impl Display for Error {
58    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
59        f.write_str(match &*self.0 {
60            Kind::Message(data) => data,
61            Kind::Eof => "eof while parsing",
62            Kind::ExpectedColon => "expected colon",
63            Kind::UnexpectedToken => "unexpected token",
64            Kind::UnclosedString => "unclosed string",
65            Kind::ControlCharacter => "control character inside string",
66            Kind::InvalidEscapeSequnce => "invalid escape sequence",
67            Kind::InvalidLiteral => "invalid literal",
68            Kind::TrailingComma => "trailing comma",
69            Kind::LeadingDecimal => "leading decimal in number",
70            Kind::TrailingDecimal => "trailing decimal in number",
71            Kind::LeadingZero => "leading zero in number",
72            Kind::NumberOverflow => "number too large",
73        })
74    }
75}
76
77impl de::Error for Error {
78    fn custom<T: Display>(msg: T) -> Self {
79        Error(Box::new(Kind::Message(msg.to_string().into_boxed_str())))
80    }
81}
82
83impl core::error::Error for Error {}