Skip to main content

neco_json/
error.rs

1use alloc::string::String;
2use core::fmt;
3
4/// JSON parse error with position information.
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct ParseError {
7    pub kind: ParseErrorKind,
8    pub position: usize,
9}
10
11/// Kinds of parse errors.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum ParseErrorKind {
14    UnexpectedCharacter(u8),
15    UnexpectedEnd,
16    InvalidNumber,
17    InvalidEscape,
18    InvalidUnicodeEscape,
19    NestingTooDeep,
20    TrailingContent,
21    InvalidUtf8,
22}
23
24/// Accessor error.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum AccessError {
27    NotAnObject,
28    MissingField(String),
29    TypeMismatch {
30        field: String,
31        expected: &'static str,
32    },
33}
34
35/// JSON encoding error.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum EncodeError {
38    NonFiniteNumber,
39}
40
41impl fmt::Display for ParseError {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        write!(
44            f,
45            "JSON parse error at position {}: {}",
46            self.position, self.kind
47        )
48    }
49}
50
51impl fmt::Display for ParseErrorKind {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        match self {
54            Self::UnexpectedCharacter(ch) => write!(f, "unexpected character 0x{ch:02X}"),
55            Self::UnexpectedEnd => f.write_str("unexpected end of input"),
56            Self::InvalidNumber => f.write_str("invalid number"),
57            Self::InvalidEscape => f.write_str("invalid escape sequence"),
58            Self::InvalidUnicodeEscape => f.write_str("invalid unicode escape"),
59            Self::NestingTooDeep => f.write_str("nesting too deep"),
60            Self::TrailingContent => f.write_str("trailing content after JSON value"),
61            Self::InvalidUtf8 => f.write_str("invalid UTF-8"),
62        }
63    }
64}
65
66impl fmt::Display for AccessError {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self {
69            Self::NotAnObject => f.write_str("value is not an object"),
70            Self::MissingField(field) => write!(f, "missing field \"{field}\""),
71            Self::TypeMismatch { field, expected } => {
72                write!(f, "field \"{field}\": expected {expected}")
73            }
74        }
75    }
76}
77
78impl fmt::Display for EncodeError {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        match self {
81            Self::NonFiniteNumber => f.write_str("cannot encode non-finite number"),
82        }
83    }
84}
85
86impl core::error::Error for ParseError {}
87impl core::error::Error for AccessError {}
88impl core::error::Error for EncodeError {}