jsn 0.14.0

A library for querying streaming JSON tokens
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use crate::error::Reason;
use crate::input::Input;
use crate::raw_token::RawToken;
use std::io::Read;

// Identifies valid tokens within JSON input
//
// Does nto attempt to validate correct JSON structure.
#[derive(Debug)]
pub struct Scanner {
    leftover: Option<u8>,
    scratch: Vec<u8>,
}

impl Scanner {
    pub fn new() -> Self {
        Self {
            leftover: None,
            scratch: vec![],
        }
    }

    pub fn reset(&mut self) {
        self.scratch.clear();
    }

    #[inline]
    pub fn read_token(&mut self, input: &mut Input<impl Read>) -> Result<RawToken, Reason> {
        let ch = loop {
            let next = match self.leftover.take() {
                Some(d) => Some(d),
                None => input.next()?,
            };
            match next {
                // Skip whitespace
                Some(b'\t' | b'\n' | b'\r' | b' ') => {
                    continue;
                }
                // Signal end of input
                None => return Ok(RawToken::Eof),
                // A byte to process
                Some(c) => break c,
            };
        };

        match ch {
            b'"' => self.string(input),
            n @ b'0'..=b'9' => self.number(n, input),
            b'-' => self.number(b'-', input),
            b'n' => self.null(input),
            b'f' => self.bool_false(input),
            b't' => self.bool_true(input),
            b'{' => Ok(RawToken::ObjectStart),
            b'}' => Ok(RawToken::ObjectEnd),
            b'[' => Ok(RawToken::ArrayStart),
            b']' => Ok(RawToken::ArrayEnd),
            b',' => Ok(RawToken::Comma),
            b':' => Ok(RawToken::Colon),
            _ => Err(Reason::UnexpectedChar),
        }
    }

    /// Tries to read a null value from the input
    pub fn null(&mut self, input: &mut Input<impl Read>) -> Result<RawToken, Reason> {
        let Some([b'u', b'l', b'l']) = input.read_n::<3>()? else {
            return Err(Reason::ExpectedNull);
        };
        Ok(RawToken::Null)
    }

    /// Tries to read a boolean true value from the input
    pub fn bool_true(&mut self, input: &mut Input<impl Read>) -> Result<RawToken, Reason> {
        let Some([b'r', b'u', b'e']) = input.read_n::<3>()? else {
            return Err(Reason::ExpectedBool);
        };
        Ok(RawToken::Bool(true))
    }

    /// Tries to read a boolean false value from the input
    pub fn bool_false(&mut self, input: &mut Input<impl Read>) -> Result<RawToken, Reason> {
        let Some([b'a', b'l', b's', b'e']) = input.read_n::<4>()? else {
            return Err(Reason::ExpectedBool);
        };
        Ok(RawToken::Bool(false))
    }

    /// Tries to extract a JSON string at the input's current location.
    ///
    /// If this call succeeds, the returned `&str` is valid utf-8, with all JSON escape sequences
    /// decoded.
    pub fn string(&mut self, input: &mut Input<impl Read>) -> Result<RawToken, Reason> {
        self.scratch.clear();

        loop {
            let next = match input.next()? {
                Some(c @ b'"') | Some(c @ b'\\') | Some(c @ 0x00..=0x1f) => c,
                Some(c) => {
                    self.scratch.push(c);
                    continue;
                }
                None => return Err(Reason::UnexpectedEof),
            };

            // After the previous statement, the next item is guaranteed to be something that needs
            // escaping (i.e. a double quote or a backslash) or an escape code
            match next {
                b'"' => {
                    // A bare double quote means we have finished parsing the string; its decoded
                    // contents are in the scratch buffer
                    let Ok(s) = std::str::from_utf8(&self.scratch) else {
                        return Err(Reason::InvalidUtf8);
                    };

                    return Ok(RawToken::String(s));
                }
                b'\\' => match input.next()? {
                    // there are no Rust byte literals for these sequences
                    Some(b'b') => self.scratch.push(0x08),
                    Some(b'f') => self.scratch.push(0x0c),
                    // these have equivalent Rust byte literals
                    Some(b't') => self.scratch.push(b'\t'),
                    Some(b'r') => self.scratch.push(b'\r'),
                    Some(b'n') => self.scratch.push(b'\n'),
                    // These do not need to be escaped in a Rust string
                    Some(byte @ (b'/' | b'"' | b'\\')) => self.scratch.push(byte),
                    // Handle unicode codepoint escapes.
                    Some(b'u') => {
                        self.read_unicode_escape(input)?;
                    }
                    Some(_) => return Err(Reason::InvalidEscapeCode),
                    None => return Err(Reason::UnexpectedEof),
                },
                _ => return Err(Reason::UnexpectedCtrlChar),
            }
        }
    }

    // Writes the result of processing a unicode escape to the scratch buffer
    //
    // Returns None if the
    fn read_unicode_escape(&mut self, input: &mut Input<impl Read>) -> Result<(), Reason> {
        // The decode_utf8() function used later requires an input buffer despite
        // returning a value
        let mut buf = [0; 4];

        let Some([h1, h2, h3, h4]) = input.read_n::<4>()? else {
            return Err(Reason::UnexpectedEof);
        };

        let Some(codepoint) = Self::codepoint_value_from_hex(h1, h2, h3, h4) else {
            return Err(Reason::InvalidEscapeCode);
        };

        if !(0xd800..=0xdfff).contains(&codepoint) {
            // Regular non-surrogate unicode character in the basic multilingual plane
            // See: https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane
            // convert the codepoint to utf-8 bytes
            let c = char::from_u32(codepoint as u32).ok_or(Reason::InvalidUtf8)?;

            self.scratch
                .extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
        } else {
            // We detected a surrogate pair. There should be another escape
            // sequence immediately after...
            let Some([b'\\', b'u', h1, h2, h3, h4]) = input.read_n::<6>()? else {
                return Err(Reason::UnexpectedEof);
            };
            let Some(second_codepoint) = Self::codepoint_value_from_hex(h1, h2, h3, h4) else {
                return Err(Reason::InvalidEscapeCode);
            };

            let decoded = char::decode_utf16([codepoint, second_codepoint])
                .next()
                .expect("an unpaired surrogate or a valid surrogate pair");

            let c = decoded.map_err(|_| Reason::InvalidUtf8)?;

            self.scratch
                .extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
        }

        Ok(())
    }

    // Convert an ascii hexadecimal digit to the number it represents
    fn decode_hex_digit(hex: u8) -> Option<u8> {
        match hex {
            b'A'..=b'F' => Some(hex - b'A' + 10),
            b'a'..=b'f' => Some(hex - b'a' + 10),
            b'0'..=b'9' => Some(hex - b'0'),
            _ => None,
        }
    }

    // Smush 4 hexadecimal digits into a 16-bit code point value
    fn codepoint_value_from_hex(h1: u8, h2: u8, h3: u8, h4: u8) -> Option<u16> {
        Some(
            (Self::decode_hex_digit(h1)? as u16) << 12
                | (Self::decode_hex_digit(h2)? as u16) << 8
                | (Self::decode_hex_digit(h3)? as u16) << 4
                | Self::decode_hex_digit(h4)? as u16,
        )
    }

    /// Tries to extract a JSON number at the input's current location
    ///
    // Fails if there is no valid JSON number at the current input position
    pub fn number(
        &mut self,
        leading_byte: u8,
        input: &mut Input<impl Read>,
    ) -> Result<RawToken, Reason> {
        self.scratch.clear();

        let first_digit = if leading_byte == b'-' {
            self.scratch.push(b'-');
            input.next()?
        } else {
            Some(leading_byte)
        };

        match first_digit {
            Some(b'0') => {
                // there can be only one leading '0'
                match input.next()? {
                    Some(b'0'..=b'9') => Err(Reason::ExpectedNumber),
                    c => {
                        self.scratch.push(b'0');
                        return self.read_decimal(c, input);
                    }
                }
            }
            Some(c @ b'1'..=b'9') => {
                self.scratch.push(c);

                loop {
                    match input.next()? {
                        Some(c @ b'0'..=b'9') => {
                            self.scratch.push(c);
                        }
                        c => return self.read_decimal(c, input),
                    };
                }
            }
            _ => Err(Reason::ExpectedNumber),
        }
    }

    fn read_decimal(
        &mut self,
        leading_byte: Option<u8>,
        input: &mut Input<impl Read>,
    ) -> Result<RawToken, Reason> {
        match leading_byte {
            // Saw a decimal point
            Some(b'.') => {
                self.scratch.push(b'.');
                // There needs to be at least one digit after the decimal
                match input.next()? {
                    Some(c @ b'0'..=b'9') => {
                        self.scratch.push(c);
                    }
                    _ => return Err(Reason::ExpectedNumber),
                }
                // Loop & store whatever other digits come after the decimal
                loop {
                    match input.next()? {
                        Some(c @ b'0'..=b'9') => self.scratch.push(c),
                        c => return self.read_exponent(c, input),
                    }
                }
            }
            // We didn't see a decimal point. That's fine as it is optional.
            // Perhaps an exponent is present?
            c => return self.read_exponent(c, input),
        }
    }

    fn read_exponent(
        &mut self,
        leading_byte: Option<u8>,
        input: &mut Input<impl Read>,
    ) -> Result<RawToken, Reason> {
        match leading_byte {
            Some(b'e' | b'E') => {
                self.scratch.push(b'e');

                let first_digit = match input.next()? {
                    Some(b'+') => input.next()?,
                    Some(b'-') => {
                        self.scratch.push(b'-');
                        input.next()?
                    }
                    Some(d) => Some(d),
                    None => return Err(Reason::ExpectedNumber),
                };

                // there needs to be at least one digit after the exponent
                match first_digit {
                    Some(c @ b'0'..=b'9') => {
                        self.scratch.push(c);
                    }
                    _ => return Err(Reason::ExpectedNumber),
                }

                // loop & store whatever other digits come after the exponent
                loop {
                    match input.next()? {
                        Some(c @ b'0'..=b'9') => {
                            self.scratch.push(c);
                        }
                        l => {
                            self.leftover = l;
                            // No more exponent digits. We are done!
                            return Ok(RawToken::Number(&self.scratch[..]));
                        }
                    }
                }
            }
            // No exponent. That's also fine because it is optional.
            // Whatever we have accumulated so far in the scratch buffer is a json number
            l => {
                self.leftover = l;
                return Ok(RawToken::Number(&self.scratch[..]));
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[track_caller]
    fn pass<I>(json: &str, expected: I)
    where
        I: IntoIterator<Item = RawToken<'static>>,
    {
        let mut input = Input::new(json.as_bytes());
        let mut scanner = Scanner::new();

        for e in expected {
            let actual = scanner.read_token(&mut input);

            assert!(
                matches!(actual, Ok(_)),
                "failed to parse token: {}\n{:?}",
                json,
                actual.unwrap_err()
            );
            assert_eq!(actual.unwrap(), e);
        }
    }

    #[track_caller]
    fn fail(json: &str, expected: Reason) {
        let mut input = Input::new(json.as_bytes());
        let mut scanner = Scanner::new();
        let actual = scanner.read_token(&mut input);

        assert!(
            matches!(actual, Err(_)),
            "unexpectedly succeeded to parse token: {}",
            json
        );

        let actual = actual.unwrap_err();
        assert_eq!(actual, expected);
    }

    #[test]
    fn emits_eof_once_end_is_encountered() {
        let mut input = Input::new("".as_bytes());
        let mut scanner = Scanner::new();

        assert_eq!(Ok(RawToken::Eof), scanner.read_token(&mut input));
        assert_eq!(Ok(RawToken::Eof), scanner.read_token(&mut input));
        assert_eq!(Ok(RawToken::Eof), scanner.read_token(&mut input));
        assert_eq!(Ok(RawToken::Eof), scanner.read_token(&mut input));
        assert_eq!(Ok(RawToken::Eof), scanner.read_token(&mut input));
        assert_eq!(Ok(RawToken::Eof), scanner.read_token(&mut input));
    }

    #[test]
    fn number_integer() {
        fail("-", Reason::ExpectedNumber);
        pass("0", [RawToken::Number(b"0")]);
        pass("1", [RawToken::Number(b"1")]);
        fail("01", Reason::ExpectedNumber);
        pass("419", [RawToken::Number(b"419")]);
        pass("-419", [RawToken::Number(b"-419")]);
        pass("-419", [RawToken::Number(b"-419")]);
        pass("-0]", [RawToken::Number(b"-0")]);
    }

    #[test]
    fn number_decimal() {
        pass("23.32", [RawToken::Number(b"23.32")]);
        pass("-0.1234", [RawToken::Number(b"-0.1234")]);
        pass("-0.1234]", [RawToken::Number(b"-0.1234")]);

        fail("3.", Reason::ExpectedNumber);
        fail("0.", Reason::ExpectedNumber);
    }

    #[test]
    fn number_exponent() {
        pass("123e12", [RawToken::Number(b"123e12")]);
        pass("43.43e-12", [RawToken::Number(b"43.43e-12")]);
        pass("43.43e+12", [RawToken::Number(b"43.43e12")]);
        pass("43.43E+12", [RawToken::Number(b"43.43e12")]);

        fail("3.e", Reason::ExpectedNumber);
        fail("3.e-", Reason::ExpectedNumber);
        fail("3.e+", Reason::ExpectedNumber);
    }

    #[test]
    fn string() {
        pass(r#""hello""#, [RawToken::String("hello")]);
        pass(r#""\uE691""#, [RawToken::String("")]);
        pass(r#""\uD834\uDD1E""#, [RawToken::String("𝄞")]);
        pass(r#"" \n""#, [RawToken::String(" \n")]);
    }

    #[test]
    fn bool() {
        pass("true", [RawToken::Bool(true)]);
        fail("tru", Reason::ExpectedBool);
        fail("truf", Reason::ExpectedBool);

        pass("false", [RawToken::Bool(false)]);
        fail("fals", Reason::ExpectedBool);
        fail("falsh", Reason::ExpectedBool);
    }

    #[test]
    fn null() {
        pass("null", [RawToken::Null]);
        fail("nul", Reason::ExpectedNull);
        fail("nulh", Reason::ExpectedNull);
    }

    #[test]
    fn structural() {
        pass("", [RawToken::Eof]);
        pass("[", [RawToken::ArrayStart]);
        pass("]", [RawToken::ArrayEnd]);
        pass("{", [RawToken::ObjectStart]);
        pass("}", [RawToken::ObjectEnd]);
        pass(",", [RawToken::Comma]);
        pass(":", [RawToken::Colon]);
    }

    #[test]
    fn multiple_tokens() {
        pass(
            r#"{}[],:"hello"nullfalsetrue1"#,
            [
                RawToken::ObjectStart,
                RawToken::ObjectEnd,
                RawToken::ArrayStart,
                RawToken::ArrayEnd,
                RawToken::Comma,
                RawToken::Colon,
                RawToken::String("hello"),
                RawToken::Null,
                RawToken::Bool(false),
                RawToken::Bool(true),
                RawToken::Number(b"1"),
            ],
        )
    }
}