Skip to main content

sciforge_parser/json/
error.rs

1#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2pub enum JsonErrorKind {
3    Eof,
4    TrailingCharacters,
5    UnexpectedToken,
6    InvalidLiteral,
7    InvalidNumber,
8    InvalidEscape,
9    InvalidUnicodeEscape,
10    InvalidUnicodeSurrogate,
11    ControlCharacterInString,
12    InvalidUtf8,
13    MaxDepthExceeded,
14    MaxStringLengthExceeded,
15    MaxArrayLengthExceeded,
16    MaxObjectLengthExceeded,
17    MaxNodeCountExceeded,
18    DuplicateObjectKey,
19}
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct JsonErrorPosition {
23    pub line: usize,
24    pub column: usize,
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub struct JsonError {
29    pub kind: JsonErrorKind,
30    pub offset: usize,
31}
32
33impl JsonError {
34    pub(crate) const fn new(kind: JsonErrorKind, offset: usize) -> Self {
35        Self { kind, offset }
36    }
37
38    pub fn line_column(&self, input: &[u8]) -> JsonErrorPosition {
39        let end = core::cmp::min(self.offset, input.len());
40        let mut line = 1usize;
41        let mut col = 1usize;
42        let mut idx = 0usize;
43
44        while idx < end {
45            if input[idx] == b'\n' {
46                line += 1;
47                col = 1;
48            } else {
49                col += 1;
50            }
51            idx += 1;
52        }
53
54        JsonErrorPosition { line, column: col }
55    }
56}