Skip to main content

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 Error {
75    /// The error's line and column in `input` (the text that was parsed),
76    /// both counted from 1, the column in characters: for a message a person
77    /// reads. A line ends at `\n`, `\r\n`, or `\r`.
78    ///
79    /// # Examples
80    ///
81    /// ```
82    /// let text = "{\n  \"a\": tru\n}";
83    /// let err = jsonx_lib::parse(text).unwrap_err();
84    /// assert_eq!(err.line_col(text), (2, 11));
85    /// ```
86    #[must_use]
87    pub fn line_col(&self, input: impl AsRef<[u8]>) -> (usize, usize) {
88        let at = locate(input.as_ref(), self.offset);
89        (at.line + 1, at.chars + 1)
90    }
91
92    /// The error's position in `input` as the Language Server Protocol
93    /// counts it: line and character from 0, the character in UTF-16 code
94    /// units (a character above U+FFFF counts two). A line ends at `\n`,
95    /// `\r\n`, or `\r`.
96    ///
97    /// # Examples
98    ///
99    /// ```
100    /// let text = "[\"\u{1f600}\", tru]";
101    /// let err = jsonx_lib::parse(text).unwrap_err();
102    /// assert_eq!(err.offset(), 12);
103    /// assert_eq!(err.utf16_position(text), (0, 10)); // the emoji is two units
104    /// ```
105    #[must_use]
106    pub fn utf16_position(&self, input: impl AsRef<[u8]>) -> (usize, usize) {
107        let at = locate(input.as_ref(), self.offset);
108        (at.line, at.utf16)
109    }
110}
111
112/// Where a byte offset falls in a text.
113pub(crate) struct Location {
114    /// The line, from 0.
115    pub(crate) line: usize,
116    /// Characters from the start of the line.
117    pub(crate) chars: usize,
118    /// UTF-16 code units from the start of the line.
119    pub(crate) utf16: usize,
120}
121
122/// Finds byte `offset` (clamped to the input) in `input`. A byte that is
123/// not UTF-8 counts as one character.
124pub(crate) fn locate(input: &[u8], offset: usize) -> Location {
125    let head = input.get(..offset.min(input.len())).unwrap_or(input);
126    let mut line = 0;
127    let mut start = 0;
128    for (i, &b) in head.iter().enumerate() {
129        let ends = match b {
130            b'\n' => true,
131            // `\r\n` is one line end, counted at the `\n`.
132            b'\r' => input.get(i + 1) != Some(&b'\n'),
133            _ => false,
134        };
135        if ends {
136            line += 1;
137            start = i + 1;
138        }
139    }
140    let text = head.get(start..).unwrap_or(&[]);
141    // Every byte but a UTF-8 continuation byte starts a character; a lead
142    // byte of a four-byte sequence starts one that is two UTF-16 units.
143    let chars = text.iter().filter(|&&b| b & 0xC0 != 0x80).count();
144    let wide = text.iter().filter(|&&b| b >= 0xF0).count();
145    Location {
146        line,
147        chars,
148        utf16: chars + wide,
149    }
150}
151
152impl fmt::Display for Error {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        write!(f, "{} at byte {}", self.kind, self.offset)
155    }
156}
157
158impl core::error::Error for Error {}
159
160/// The kinds of [`Error`].
161///
162/// The enum is `#[non_exhaustive]`: later versions may report a case more
163/// precisely with a new variant, so a `match` needs a wildcard arm.
164///
165/// # Examples
166///
167/// ```
168/// use jsonx_lib::{parse, ErrorKind};
169///
170/// match parse("[1, 2").unwrap_err().kind() {
171///     ErrorKind::UnexpectedEnd => { /* the input was cut short: wait for more */ }
172///     _ => { /* the input is malformed */ }
173/// }
174/// ```
175#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
176#[non_exhaustive]
177pub enum ErrorKind {
178    /// The input ended inside a value, or held no value at all. The input is
179    /// a truncated document; with a stream, wait for more bytes.
180    UnexpectedEnd,
181    /// A value was expected and this byte cannot start one (values start with
182    /// `{`, `[`, `"`, `-`, a digit, `t`, `f`, or `n`).
183    ExpectedValue,
184    /// An object key must be followed by `:`.
185    ExpectedColon,
186    /// Inside an array, a value must be followed by `,` or `]`.
187    ExpectedCommaOrBracket,
188    /// Inside an object, a member must be followed by `,` or `}`.
189    ExpectedCommaOrBrace,
190    /// An object key was expected: a member must start with a string.
191    ExpectedKey,
192    /// A `,` came directly before the `]` or `}` closing its array or
193    /// object. JSON does not allow trailing commas.
194    TrailingComma,
195    /// The document's value ended, but non-whitespace input followed it.
196    TrailingCharacters,
197    /// The input started `true`, `false`, or `null` but did not finish it.
198    InvalidLiteral,
199    /// A number broke the RFC 8259 number grammar: a leading zero, a missing
200    /// digit after `-`, `.`, or the exponent marker, and so on.
201    InvalidNumber,
202    /// A backslash in a string was followed by a character that is not one of
203    /// `" \ / b f n r t u`.
204    InvalidEscape,
205    /// A `\u` escape was not followed by four hexadecimal digits.
206    InvalidUnicodeEscape,
207    /// A `\u` escape named half of a UTF-16 surrogate pair without the other
208    /// half. Such a string has no Unicode text to decode to; the offset is the
209    /// backslash of the unpaired escape.
210    LoneSurrogate,
211    /// A string contained an unescaped control character (U+0000 to U+001F).
212    /// Control characters must be written as escapes.
213    ControlCharacter,
214    /// The input was not valid UTF-8 ([`parse_bytes`](crate::parse_bytes)
215    /// only). The offset is the first byte of the invalid sequence.
216    InvalidUtf8,
217    /// An object repeated a key, under [`DuplicateKeys::Error`](crate::DuplicateKeys::Error)
218    /// (the default). The offset is the second occurrence's opening quote.
219    /// Duplicates are found when the object closes, so a syntax error later in
220    /// the same object is reported first.
221    DuplicateKey,
222    /// Containers nested deeper than [`Limits::max_depth`](crate::Limits::max_depth).
223    /// The offset is the `[` or `{` that went one level too deep.
224    DepthLimitExceeded,
225    /// The input is longer than [`Limits::max_input_bytes`](crate::Limits::max_input_bytes).
226    /// The offset is the limit: the first byte past the budget.
227    InputTooLarge,
228    /// A string (or key) is longer than [`Limits::max_string_bytes`](crate::Limits::max_string_bytes),
229    /// counted in source bytes between the quotes. The offset is its opening quote.
230    StringTooLong,
231    /// A number's text is longer than [`Limits::max_number_bytes`](crate::Limits::max_number_bytes).
232    /// The offset is the number's first byte.
233    NumberTooLong,
234    /// The document holds more values than [`Limits::max_elements`](crate::Limits::max_elements).
235    /// The offset is the first byte of the value that went over.
236    TooManyElements,
237    /// Building the document's tree would hold more memory than
238    /// [`Limits::max_memory`](crate::Limits::max_memory). The offset is the
239    /// first byte of the value whose storage went over.
240    MemoryLimitExceeded,
241    /// Bytes were fed to a [`StreamReader`](crate::StreamReader) after
242    /// [`end_input`](crate::StreamReader::end_input) said the input had
243    /// ended. A mistake in the calling code, not in the document; the
244    /// offset is the number of bytes accepted before the end.
245    InputAfterEnd,
246}
247
248impl ErrorKind {
249    /// Whether this error comes from a budget in [`Limits`](crate::Limits)
250    /// rather than from the input being invalid JSON. The same input may parse
251    /// with larger limits.
252    ///
253    /// # Examples
254    ///
255    /// ```
256    /// use jsonx_lib::ErrorKind;
257    ///
258    /// assert!(ErrorKind::DepthLimitExceeded.is_budget());
259    /// assert!(!ErrorKind::TrailingComma.is_budget());
260    /// ```
261    #[must_use]
262    pub const fn is_budget(self) -> bool {
263        matches!(
264            self,
265            Self::DepthLimitExceeded
266                | Self::InputTooLarge
267                | Self::StringTooLong
268                | Self::NumberTooLong
269                | Self::TooManyElements
270                | Self::MemoryLimitExceeded
271        )
272    }
273
274    const fn message(self) -> &'static str {
275        match self {
276            Self::UnexpectedEnd => "unexpected end of input",
277            Self::ExpectedValue => "expected a value",
278            Self::ExpectedColon => "expected `:` after an object key",
279            Self::ExpectedCommaOrBracket => "expected `,` or `]` after an array element",
280            Self::ExpectedCommaOrBrace => "expected `,` or `}` after an object member",
281            Self::ExpectedKey => "expected a string key",
282            Self::TrailingComma => "trailing comma before `}` or `]`",
283            Self::TrailingCharacters => "unexpected input after the document's value",
284            Self::InvalidLiteral => "invalid literal (expected `true`, `false`, or `null`)",
285            Self::InvalidNumber => "invalid number",
286            Self::InvalidEscape => "invalid escape sequence",
287            Self::InvalidUnicodeEscape => "`\\u` must be followed by four hex digits",
288            Self::LoneSurrogate => "unpaired UTF-16 surrogate escape",
289            Self::ControlCharacter => "unescaped control character in a string",
290            Self::InvalidUtf8 => "invalid UTF-8",
291            Self::DuplicateKey => "duplicate object key",
292            Self::DepthLimitExceeded => "nesting depth limit exceeded",
293            Self::InputTooLarge => "input size limit exceeded",
294            Self::StringTooLong => "string length limit exceeded",
295            Self::NumberTooLong => "number length limit exceeded",
296            Self::TooManyElements => "element count limit exceeded",
297            Self::MemoryLimitExceeded => "memory limit exceeded",
298            Self::InputAfterEnd => "input fed after the end of input",
299        }
300    }
301}
302
303impl fmt::Display for ErrorKind {
304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305        f.write_str(self.message())
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use alloc::string::ToString;
312
313    use super::*;
314
315    #[test]
316    fn test_error_display_names_kind_and_offset() {
317        let e = Error::new(ErrorKind::ExpectedColon, 7);
318        assert_eq!(e.to_string(), "expected `:` after an object key at byte 7");
319        assert_eq!(e.kind(), ErrorKind::ExpectedColon);
320        assert_eq!(e.offset(), 7);
321    }
322
323    #[test]
324    fn test_locate_counts_lines_and_columns() {
325        let at = |text: &str, offset| {
326            let l = locate(text.as_bytes(), offset);
327            (l.line, l.chars, l.utf16)
328        };
329        assert_eq!(at("abc", 2), (0, 2, 2));
330        assert_eq!(at("a\nbc", 3), (1, 1, 1));
331        assert_eq!(at("a\r\nbc", 4), (1, 1, 1));
332        assert_eq!(at("a\rbc", 3), (1, 1, 1));
333        assert_eq!(at("a\r\n", 2), (0, 2, 2)); // inside the `\r\n`
334        assert_eq!(at("\u{e9}\u{1f600}x", 6), (0, 2, 3));
335        assert_eq!(at("ab", 99), (0, 2, 2));
336        let e = Error::new(ErrorKind::ExpectedValue, 5);
337        assert_eq!(e.line_col("[\n  ]x"), (2, 4));
338        assert_eq!(e.utf16_position(b"[\n  ]x".as_slice()), (1, 3));
339    }
340
341    #[test]
342    fn test_error_kind_budget_classification_is_exact() {
343        let all = [
344            ErrorKind::UnexpectedEnd,
345            ErrorKind::ExpectedValue,
346            ErrorKind::ExpectedColon,
347            ErrorKind::ExpectedCommaOrBracket,
348            ErrorKind::ExpectedCommaOrBrace,
349            ErrorKind::ExpectedKey,
350            ErrorKind::TrailingComma,
351            ErrorKind::TrailingCharacters,
352            ErrorKind::InvalidLiteral,
353            ErrorKind::InvalidNumber,
354            ErrorKind::InvalidEscape,
355            ErrorKind::InvalidUnicodeEscape,
356            ErrorKind::LoneSurrogate,
357            ErrorKind::ControlCharacter,
358            ErrorKind::InvalidUtf8,
359            ErrorKind::DuplicateKey,
360            ErrorKind::DepthLimitExceeded,
361            ErrorKind::InputTooLarge,
362            ErrorKind::StringTooLong,
363            ErrorKind::NumberTooLong,
364            ErrorKind::TooManyElements,
365            ErrorKind::MemoryLimitExceeded,
366            ErrorKind::InputAfterEnd,
367        ];
368        let budgets = all.iter().filter(|k| k.is_budget()).count();
369        assert_eq!(budgets, 6);
370        for kind in all {
371            assert!(!kind.to_string().is_empty());
372        }
373    }
374}