1use {
2 serde::de,
3 std::{
4 fmt,
5 io,
6 str::Utf8Error,
7 },
8};
9
10pub type Result<T> = std::result::Result<T, Error>;
11
12#[derive(Debug, Clone, PartialEq)]
15pub enum ErrorCode {
16 Eof,
17 ExpectedBoolean,
18 ExpectedInteger,
19 ExpectedI8,
20 ExpectedI16,
21 ExpectedI32,
22 ExpectedI64,
23 ExpectedU8,
24 ExpectedU16,
25 ExpectedU32,
26 ExpectedU64,
27 ExpectedF32,
28 ExpectedF64,
29 ExpectedPositiveInteger,
30 ExpectedString,
31 ExpectedNull,
32 ExpectedArray,
33 ExpectedArrayComma,
34 ExpectedArrayEnd,
35 ExpectedMap,
36 ExpectedMapColon,
37 ExpectedMapComma,
38 ExpectedMapEnd,
39 ExpectedEnum,
40 ExpectedSingleChar,
41 InvalidEscapeSequence,
42 TrailingCharacters,
43 UnexpectedChar,
44}
45
46#[derive(Debug)]
47#[non_exhaustive]
48pub enum Error {
49
50 Syntax {
53 line: usize,
54 col: usize, code: ErrorCode,
56 at: String, },
58
59 Serde {
61 line: usize,
62 col: usize, message: String,
64 },
65
66 RawSerde(String),
70
71 Utf8(Utf8Error),
74
75 Io(io::Error),
77}
78
79impl Error {
80 #[must_use]
81 pub fn is_eof(&self) -> bool {
82 matches!(self, Error::Syntax { code: ErrorCode::Eof, .. })
83 }
84}
85
86impl de::Error for Error {
87 fn custom<T: fmt::Display>(msg: T) -> Self {
88 Error::RawSerde(msg.to_string())
89 }
90}
91
92impl From<Utf8Error> for Error {
93 fn from(source: Utf8Error) -> Self {
94 Self::Utf8(source)
95 }
96}
97
98impl From<io::Error> for Error {
99 fn from(source: io::Error) -> Self {
100 Self::Io(source)
101 }
102}
103
104impl fmt::Display for Error {
105 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
106 match self {
107 Self::Syntax { line, col, code, at } => {
108 write!(formatter, "{code:?} at {line}:{col} at {at:?}")
109 }
110 Self::Serde { line, col, message } => {
111 write!(formatter, "{message:?} near {line}:{col}")
112 }
113 Self::RawSerde(msg) => {
114 write!(formatter, "error message: {msg:?}")
115 }
116 Self::Utf8(source) => {
117 source.fmt(formatter)
118 }
119 Self::Io(source) => {
120 source.fmt(formatter)
121 }
122 }
123 }
124}
125
126impl std::error::Error for Error {}