jsonx_lib/error.rs
1//! The one error type: what went wrong, and the byte offset where it did.
2
3use core::fmt;
4
5/// Why a document was rejected, and where.
6///
7/// Every error carries the byte offset of the first byte that made the input
8/// invalid. For a syntax error that is the first byte at which the input stops
9/// being the beginning of any valid JSON text, so the offset points at the
10/// mistake itself, not at the start of the value that contains it. When the
11/// input ends too early the offset is the input's length.
12///
13/// A few errors point at a byte that starts something larger: a lone
14/// surrogate at the backslash of its `\u` escape, a duplicate key at the
15/// opening quote of its second occurrence, and the budget errors at the start
16/// of the value that exceeded the budget. [`ErrorKind`] says which applies.
17///
18/// # Examples
19///
20/// ```
21/// use jsonx_lib::{parse, ErrorKind};
22///
23/// let err = parse(r#"{"a": 1,}"#).unwrap_err();
24/// assert_eq!(err.kind(), ErrorKind::TrailingComma);
25/// assert_eq!(err.offset(), 8);
26/// assert_eq!(err.to_string(), "trailing comma before `}` or `]` at byte 8");
27/// ```
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29#[must_use]
30pub struct Error {
31 kind: ErrorKind,
32 offset: usize,
33}
34
35impl Error {
36 /// Creates an error of `kind` at byte `offset`.
37 #[inline]
38 pub(crate) const fn new(kind: ErrorKind, offset: usize) -> Self {
39 Self { kind, offset }
40 }
41
42 /// What went wrong.
43 ///
44 /// # Examples
45 ///
46 /// ```
47 /// use jsonx_lib::{parse, ErrorKind};
48 ///
49 /// assert_eq!(parse("[1 2]").unwrap_err().kind(), ErrorKind::ExpectedCommaOrBracket);
50 /// ```
51 #[inline]
52 #[must_use]
53 pub const fn kind(&self) -> ErrorKind {
54 self.kind
55 }
56
57 /// The byte offset into the input where the error was found.
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// use jsonx_lib::parse;
63 ///
64 /// // The `x` is the first byte that cannot continue `tru`.
65 /// assert_eq!(parse("[tru x]").unwrap_err().offset(), 4);
66 /// ```
67 #[inline]
68 #[must_use]
69 pub const fn offset(&self) -> usize {
70 self.offset
71 }
72}
73
74impl fmt::Display for Error {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 write!(f, "{} at byte {}", self.kind, self.offset)
77 }
78}
79
80impl core::error::Error for Error {}
81
82/// The kinds of [`Error`].
83///
84/// The enum is `#[non_exhaustive]`: later versions may report a case more
85/// precisely with a new variant, so a `match` needs a wildcard arm.
86///
87/// # Examples
88///
89/// ```
90/// use jsonx_lib::{parse, ErrorKind};
91///
92/// match parse("[1, 2").unwrap_err().kind() {
93/// ErrorKind::UnexpectedEnd => { /* the input was cut short: wait for more */ }
94/// _ => { /* the input is malformed */ }
95/// }
96/// ```
97#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
98#[non_exhaustive]
99pub enum ErrorKind {
100 /// The input ended inside a value, or held no value at all. The input is
101 /// a truncated document; with a stream, wait for more bytes.
102 UnexpectedEnd,
103 /// A value was expected and this byte cannot start one (values start with
104 /// `{`, `[`, `"`, `-`, a digit, `t`, `f`, or `n`).
105 ExpectedValue,
106 /// An object key must be followed by `:`.
107 ExpectedColon,
108 /// Inside an array, a value must be followed by `,` or `]`.
109 ExpectedCommaOrBracket,
110 /// Inside an object, a member must be followed by `,` or `}`.
111 ExpectedCommaOrBrace,
112 /// An object key was expected: a member must start with a string.
113 ExpectedKey,
114 /// A `,` came directly before the `]` or `}` closing its array or
115 /// object. JSON does not allow trailing commas.
116 TrailingComma,
117 /// The document's value ended, but non-whitespace input followed it.
118 TrailingCharacters,
119 /// The input started `true`, `false`, or `null` but did not finish it.
120 InvalidLiteral,
121 /// A number broke the RFC 8259 number grammar: a leading zero, a missing
122 /// digit after `-`, `.`, or the exponent marker, and so on.
123 InvalidNumber,
124 /// A backslash in a string was followed by a character that is not one of
125 /// `" \ / b f n r t u`.
126 InvalidEscape,
127 /// A `\u` escape was not followed by four hexadecimal digits.
128 InvalidUnicodeEscape,
129 /// A `\u` escape named half of a UTF-16 surrogate pair without the other
130 /// half. Such a string has no Unicode text to decode to; the offset is the
131 /// backslash of the unpaired escape.
132 LoneSurrogate,
133 /// A string contained an unescaped control character (U+0000 to U+001F).
134 /// Control characters must be written as escapes.
135 ControlCharacter,
136 /// The input was not valid UTF-8 ([`parse_bytes`](crate::parse_bytes)
137 /// only). The offset is the first byte of the invalid sequence.
138 InvalidUtf8,
139 /// An object repeated a key, under [`DuplicateKeys::Error`](crate::DuplicateKeys::Error)
140 /// (the default). The offset is the second occurrence's opening quote.
141 /// Duplicates are found when the object closes, so a syntax error later in
142 /// the same object is reported first.
143 DuplicateKey,
144 /// Containers nested deeper than [`Limits::max_depth`](crate::Limits::max_depth).
145 /// The offset is the `[` or `{` that went one level too deep.
146 DepthLimitExceeded,
147 /// The input is longer than [`Limits::max_input_bytes`](crate::Limits::max_input_bytes).
148 /// The offset is the limit: the first byte past the budget.
149 InputTooLarge,
150 /// A string (or key) is longer than [`Limits::max_string_bytes`](crate::Limits::max_string_bytes),
151 /// counted in source bytes between the quotes. The offset is its opening quote.
152 StringTooLong,
153 /// A number's text is longer than [`Limits::max_number_bytes`](crate::Limits::max_number_bytes).
154 /// The offset is the number's first byte.
155 NumberTooLong,
156 /// The document holds more values than [`Limits::max_elements`](crate::Limits::max_elements).
157 /// The offset is the first byte of the value that went over.
158 TooManyElements,
159}
160
161impl ErrorKind {
162 /// Whether this error comes from a budget in [`Limits`](crate::Limits)
163 /// rather than from the input being invalid JSON. The same input may parse
164 /// with larger limits.
165 ///
166 /// # Examples
167 ///
168 /// ```
169 /// use jsonx_lib::ErrorKind;
170 ///
171 /// assert!(ErrorKind::DepthLimitExceeded.is_budget());
172 /// assert!(!ErrorKind::TrailingComma.is_budget());
173 /// ```
174 #[must_use]
175 pub const fn is_budget(self) -> bool {
176 matches!(
177 self,
178 Self::DepthLimitExceeded
179 | Self::InputTooLarge
180 | Self::StringTooLong
181 | Self::NumberTooLong
182 | Self::TooManyElements
183 )
184 }
185
186 const fn message(self) -> &'static str {
187 match self {
188 Self::UnexpectedEnd => "unexpected end of input",
189 Self::ExpectedValue => "expected a value",
190 Self::ExpectedColon => "expected `:` after an object key",
191 Self::ExpectedCommaOrBracket => "expected `,` or `]` after an array element",
192 Self::ExpectedCommaOrBrace => "expected `,` or `}` after an object member",
193 Self::ExpectedKey => "expected a string key",
194 Self::TrailingComma => "trailing comma before `}` or `]`",
195 Self::TrailingCharacters => "unexpected input after the document's value",
196 Self::InvalidLiteral => "invalid literal (expected `true`, `false`, or `null`)",
197 Self::InvalidNumber => "invalid number",
198 Self::InvalidEscape => "invalid escape sequence",
199 Self::InvalidUnicodeEscape => "`\\u` must be followed by four hex digits",
200 Self::LoneSurrogate => "unpaired UTF-16 surrogate escape",
201 Self::ControlCharacter => "unescaped control character in a string",
202 Self::InvalidUtf8 => "invalid UTF-8",
203 Self::DuplicateKey => "duplicate object key",
204 Self::DepthLimitExceeded => "nesting depth limit exceeded",
205 Self::InputTooLarge => "input size limit exceeded",
206 Self::StringTooLong => "string length limit exceeded",
207 Self::NumberTooLong => "number length limit exceeded",
208 Self::TooManyElements => "element count limit exceeded",
209 }
210 }
211}
212
213impl fmt::Display for ErrorKind {
214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 f.write_str(self.message())
216 }
217}
218
219#[cfg(test)]
220mod tests {
221 use alloc::string::ToString;
222
223 use super::*;
224
225 #[test]
226 fn test_error_display_names_kind_and_offset() {
227 let e = Error::new(ErrorKind::ExpectedColon, 7);
228 assert_eq!(e.to_string(), "expected `:` after an object key at byte 7");
229 assert_eq!(e.kind(), ErrorKind::ExpectedColon);
230 assert_eq!(e.offset(), 7);
231 }
232
233 #[test]
234 fn test_error_kind_budget_classification_is_exact() {
235 let all = [
236 ErrorKind::UnexpectedEnd,
237 ErrorKind::ExpectedValue,
238 ErrorKind::ExpectedColon,
239 ErrorKind::ExpectedCommaOrBracket,
240 ErrorKind::ExpectedCommaOrBrace,
241 ErrorKind::ExpectedKey,
242 ErrorKind::TrailingComma,
243 ErrorKind::TrailingCharacters,
244 ErrorKind::InvalidLiteral,
245 ErrorKind::InvalidNumber,
246 ErrorKind::InvalidEscape,
247 ErrorKind::InvalidUnicodeEscape,
248 ErrorKind::LoneSurrogate,
249 ErrorKind::ControlCharacter,
250 ErrorKind::InvalidUtf8,
251 ErrorKind::DuplicateKey,
252 ErrorKind::DepthLimitExceeded,
253 ErrorKind::InputTooLarge,
254 ErrorKind::StringTooLong,
255 ErrorKind::NumberTooLong,
256 ErrorKind::TooManyElements,
257 ];
258 let budgets = all.iter().filter(|k| k.is_budget()).count();
259 assert_eq!(budgets, 5);
260 for kind in all {
261 assert!(!kind.to_string().is_empty());
262 }
263 }
264}