-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
2256 lines (1960 loc) · 69.9 KB
/
lib.rs
File metadata and controls
2256 lines (1960 loc) · 69.9 KB
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::HashMap;
use std::fmt::{Display, Write};
use std::io::{BufReader, Bytes, Read};
use std::iter::Peekable;
use std::num::{NonZero, ParseFloatError, ParseIntError};
use std::str;
pub mod diff;
pub mod error;
pub mod serde;
// Make all kinds usable directly, less boilerplate.
use error::Kind::*;
const STRING_QUOTE: u8 = b'"';
const STRING_ESCAPE_OPEN: u8 = b'\\';
const OBJECT_OPEN: u8 = b'{';
const OBJECT_KV_SEP: u8 = b':';
const OBJECT_ENTRIES_SEP: u8 = b',';
const OBJECT_CLOSE: u8 = b'}';
const ARRAY_OPEN: u8 = b'[';
const ARRAY_SEP: u8 = b',';
const ARRAY_CLOSE: u8 = b']';
/// Maximum permissible depth in parsing values. Documents with values (objects, arrays)
/// nested deeper than this are rejected.
const MAX_DEPTH: usize = 256;
type ParseResult<T> = std::result::Result<T, error::Error>;
/// Parse the provided input into a JSON [`Value`].
///
/// Short-hand for [`Parser::new`] followed by [`Parser::parse`].
pub fn parse(data: &[u8]) -> ParseResult<Value> {
let mut parser = Parser::new(data);
parser.parse()
}
/// A [JSON value](https://datatracker.ietf.org/doc/html/rfc8259#section-3).
#[derive(Debug, PartialEq, Clone)]
pub enum Value {
String(String),
Number(Number),
Object(HashMap<String, Value>),
Array(Vec<Value>),
Bool(bool),
Null,
}
/// Prints the JSON, non-pretty string representation of [`Value`].
impl Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Value::String(s) => {
let mut buf = String::with_capacity(s.len());
for c in s.chars() {
// Handle escapes.
match c {
'"' => buf.push_str(r#"\""#),
'\\' => buf.push_str(r#"\\"#),
// Could legally also fall through to `\uXXXX` below but these
// look nicer for common values.
'\n' => buf.push_str(r#"\n"#),
'\t' => buf.push_str(r#"\t"#),
'\r' => buf.push_str(r#"\r"#),
'\x08' => buf.push_str(r#"\b"#),
'\x0c' => buf.push_str(r#"\f"#),
c if c.is_control() => write!(buf, "\\u{:04x}", c as u32)?,
_ => buf.push(c),
}
}
write!(f, "{}{}{}", STRING_QUOTE as char, buf, STRING_QUOTE as char)
}
Value::Number(num) => {
// Assumption: echoing number back verbatim is OK because it can only be
// constructed from parsing incoming JSON, at which point it is
// validated and rejected if invalid.
//
// This enables lossless round-tripping.
write!(f, "{}", num.0)
}
Value::Object(obj) => {
write!(f, "{}", OBJECT_OPEN as char)?;
let mut first = true;
for (k, v) in obj.iter() {
if !first {
write!(f, "{} ", OBJECT_ENTRIES_SEP as char)?;
}
write!(f, "\"{}\"{} ", k, OBJECT_KV_SEP as char)?;
write!(f, "{}", v)?;
first = false;
}
write!(f, "{}", OBJECT_CLOSE as char)?;
Ok(())
}
Value::Array(values) => {
write!(f, "{}", ARRAY_OPEN as char)?;
let mut first = true;
for v in values.iter() {
if !first {
write!(f, "{} ", ARRAY_SEP as char)?;
}
write!(f, "{}", v)?;
first = false;
}
write!(f, "{}", ARRAY_CLOSE as char)?;
Ok(())
}
Value::Bool(b) => write!(f, "{b}"),
Value::Null => write!(f, "null"),
}
}
}
/// A JSON number.
///
/// In the JSON spec, numbers have infinite precision. While often limited to [`f64`] in
/// real-world implementations, this type helps retain original, unlimited JSON
/// precision.
///
/// **Assumption**: [`Parser::parse`] normalized the contained [`String`] to correspond
/// to JSON rules, such that all valid instances are valid JSON (no other constructor).
///
/// Converting to native numeric types is up to consumers. Some common conversions are
/// provided.
#[derive(Debug, Clone)]
pub struct Number(String);
/// Compare numbers in ascending order of precision, by actual numeric value.
impl PartialEq for Number {
fn eq(&self, other: &Self) -> bool {
let left: Result<u64, _> = self.try_into();
let right: Result<u64, _> = other.try_into();
if let (Ok(l), Ok(r)) = (left, right) {
return l == r;
}
let left: Result<i64, _> = self.try_into();
let right: Result<i64, _> = other.try_into();
if let (Ok(l), Ok(r)) = (left, right) {
return l == r;
}
// Precision loss can occur here.
let left: Result<f64, _> = self.try_into();
let right: Result<f64, _> = other.try_into();
if let (Ok(l), Ok(r)) = (left, right) {
return l == r;
}
// Fallback to direct string comparison.
self.0 == other.0
}
}
impl TryFrom<Number> for u64 {
type Error = ParseIntError;
fn try_from(value: Number) -> Result<Self, Self::Error> {
value.0.parse()
}
}
impl TryFrom<&Number> for u64 {
type Error = ParseIntError;
fn try_from(value: &Number) -> Result<Self, Self::Error> {
value.0.parse()
}
}
impl TryFrom<Number> for i64 {
type Error = ParseIntError;
fn try_from(value: Number) -> Result<Self, Self::Error> {
value.0.parse()
}
}
impl TryFrom<&Number> for i64 {
type Error = ParseIntError;
fn try_from(value: &Number) -> Result<Self, Self::Error> {
value.0.parse()
}
}
impl TryFrom<Number> for f64 {
type Error = ParseFloatError;
fn try_from(value: Number) -> Result<Self, Self::Error> {
value.0.parse()
}
}
impl TryFrom<&Number> for f64 {
type Error = ParseFloatError;
fn try_from(value: &Number) -> Result<Self, Self::Error> {
value.0.parse()
}
}
/// A fully-featured, "streaming" JSON parser.
///
/// Spec: <https://www.json.org/json-en.html>
#[derive(Debug)]
pub struct Parser<R: Read> {
stream: Peekable<Bytes<BufReader<R>>>,
/// Bytes read from stream so far.
stream_pos: usize,
/// When processing UTF16 JSON escapes like `\u1234` in JSON strings, surrogate
/// pairs might be encountered. This slot tracks encountered high surrogates,
/// pending pairing with a subsequent low surrogate (at which point the slot is
/// cleared again).
pending_high_surrogate: Option<NonZero<u16>>,
/// Current stack depth in parsing values (in nested arrays, objects). Prevents
/// stack overflows in the parser (best-effort, as we can't know host stack sizes).
depth: usize,
}
impl<R: Read> Parser<R> {
/// Constructs a new parser over the reader implementation. The parser will be
/// buffered.
pub fn new(reader: R) -> Self {
let stream = BufReader::new(reader).bytes().peekable();
Self {
stream,
stream_pos: 0,
pending_high_surrogate: None,
depth: 0,
}
}
/// Entrypoint into parsing. Will try to parse the input as a [JSON
/// *value*](https://www.json.org/json-en.html).
pub fn parse(&mut self) -> ParseResult<Value> {
let value = self.visit_value()?;
// Multi-value documents are not supported: additional data in the stream is a
// failure.
//
// Note, this technically reads one byte too much from the input, for a nicer
// report ("which byte was actually problematic"); `peek` has the same issue. As
// we return the byte to the caller in the error, this should be OK (caller can
// reconstruct everything).
match self.stream.next() {
Some(Ok(more)) => Err(self.err(InvalidByte {
byte: more,
reason: "excessive data in input after parsing one JSON value".into(),
})),
Some(Err(e)) => Err(self.err(Io(e))),
None => Ok(value),
}
}
/// Get the next byte from the underlying reader. Calling this method signals a
/// *need* for a next byte, thus if none is found (reader finished or errored), it
/// is considered an error.
fn advance(&mut self) -> ParseResult<u8> {
let byte = self
.stream
.next()
.ok_or(self.err(UnexpectedEOF))?
.map_err(|io_err| self.err(Io(io_err)))?;
self.stream_pos += 1;
Ok(byte)
}
/// Construct an error of the provided kind, with information from current parser
/// state.
fn err(&self, kind: error::Kind) -> error::Error {
error::Error {
kind,
pos: self.stream_pos,
}
}
fn visit_value(&mut self) -> ParseResult<Value> {
self.depth += 1;
if self.depth >= MAX_DEPTH {
return Err(self.err(NestingTooDeep(self.depth)));
}
self.skip_whitespace()?;
// Peek ahead, but leave actual token consumption to implementations themselves.
// This keeps it symmetrical. The individual functions are essentially the
// diagrams at <https://www.json.org/json-en.html>, where e.g. `object` is
// responsible for its own `{` and `}` handling.
let val = match self.stream.peek() {
Some(Ok(STRING_QUOTE)) => self.visit_string().map(Value::String)?,
Some(Ok(OBJECT_OPEN)) => self.visit_object().map(Value::Object)?,
Some(Ok(ARRAY_OPEN)) => self.visit_array().map(Value::Array)?,
Some(Ok(b't')) | Some(Ok(b'f')) => self.visit_bool().map(Value::Bool)?,
Some(Ok(b'n')) => self.visit_null().map(|_| Value::Null)?,
Some(Ok(b'-')) | Some(Ok(b'0'..=b'9')) => self.visit_number().map(Value::Number)?,
Some(&Ok(byte /* Copy out */)) => {
return Err(self.err(InvalidByte {
byte,
reason: "invalid byte looking for beginning of value".into(),
}));
}
_ => return Err(self.err(UnexpectedEOF)),
};
self.skip_whitespace()?;
self.depth -= 1;
Ok(val)
}
/// Skips all upcoming whitespace, if present.
fn skip_whitespace(&mut self) -> ParseResult<()> {
// If there's no whitespace, do not consume.
while let Some(Ok(c)) = self.stream.peek() {
if is_json_whitespace(*c) {
// Actually consume it. I don't think this can genuinely error after
// having just successfully peeked, but it'd be a shame to unnecessarily
// panic; so just have this return a Result.
self.advance()?;
} else {
break;
}
}
Ok(())
}
fn visit_object(&mut self) -> ParseResult<HashMap<String, Value>> {
assert_eq!(
self.advance()?,
OBJECT_OPEN,
"should only be reachable from visiting value, where it should be peeked correctly before visiting"
);
self.skip_whitespace()?;
let mut map = HashMap::new();
// Early return for empty object
if let Some(Ok(OBJECT_CLOSE)) = self.stream.peek() {
let _ = self.advance()?;
return Ok(map);
}
loop {
let key = self.visit_string()?;
self.skip_whitespace()?;
match self.advance()? {
OBJECT_KV_SEP => { /* OK */ }
byte => {
break Err(self.err(InvalidByte {
byte,
reason: format!(
"parsing object, expected {} after key",
OBJECT_KV_SEP as char
),
}));
}
}
let value = self.visit_value()?;
map.insert(key, value);
match self.advance()? {
OBJECT_CLOSE => break Ok(map),
OBJECT_ENTRIES_SEP => {
self.skip_whitespace()?;
continue;
}
byte => {
break Err(self.err(InvalidByte {
byte,
reason: format!(
"parsing object, expected {} or {} after parsing a key/value pair",
OBJECT_CLOSE as char, OBJECT_ENTRIES_SEP as char,
),
}));
}
}
}
}
fn visit_string(&mut self) -> ParseResult<String> {
{
let byte = self.advance()?;
if byte != STRING_QUOTE {
return Err(self.err(InvalidByte {
byte,
reason: format!("expected {} for start of string", STRING_QUOTE as char),
}));
};
}
// Initial capacity showed ~10% higher throughput in a local benchmark. It
// avoids reallocs for most strings.
let mut s = String::with_capacity(32);
loop {
if let Some(high_surrogate) = self.pending_high_surrogate {
// A pending high surrogate is invalid without a subsequent low
// surrogate.
let (STRING_ESCAPE_OPEN, b'u') = (self.advance()?, self.advance()?) else {
return Err(self.err(UnicodeError(
error::UnicodeError::UnpairedHighSurrogate(high_surrogate.get()),
)));
};
let low_surrogate_candidate = self.collect_unicode_escape_hex_digits()?;
let mut chars = char::decode_utf16([high_surrogate.get(), low_surrogate_candidate]);
let c = chars
.next()
.expect("should have one (potentially error) element after providing surrogate pair candidate")
.map_err(|e| self.err(UnicodeError(error::UnicodeError::InvalidUTF16(e))))?;
s.push(c);
assert!(
chars.next().is_none(),
"should not yield more than 1 character from 1 surrogate pair"
);
self.pending_high_surrogate = None;
}
match self.advance()? {
STRING_QUOTE => break Ok(s),
STRING_ESCAPE_OPEN => match self.advance()? {
b'"' => s.push('"'),
b'\\' => s.push('\\'),
b'/' => s.push('/'),
b'b' => s.push('\x08'),
b'f' => s.push('\x0C'),
b'n' => s.push('\n'),
b'r' => s.push('\r'),
b't' => s.push('\t'),
b'u' => {
let codepoint = self.collect_unicode_escape_hex_digits()?;
assert!(
self.pending_high_surrogate.is_none(),
"should not reach consecutive (high) surrogates"
);
match codepoint {
// https://www.unicode.org/glossary/#high_surrogate_code_unit
0xD800..=0xDBFF => {
// Register it but do not push out yet. Need a low
// surrogate partner, on next loop iteration.
self.pending_high_surrogate =
Some(NonZero::new(codepoint).expect("should have value > 0 in this branch"));
}
// https://www.unicode.org/glossary/#low_surrogate_code_unit
0xDC00..=0xDFFF => {
return Err(self.err(UnicodeError(error::UnicodeError::UnpairedLowSurrogate(codepoint))))
}
val => s.push(char::from_u32(val as u32).expect("non-surrogate, u16 UTF-16 code point should always be a valid char")),
}
}
b => break Err(self.err(InvalidEscapeSequence(b))),
},
ctrl_byte @ 0x00..=0x1F => {
// Note: DELETE aka 0x7F is included in `u8.is_ascii_control()`, but
// permitted literally in JSON strings, cf.
// https://datatracker.ietf.org/doc/html/rfc8259#section-7.
return Err(self.err(InvalidByte {
byte: ctrl_byte,
reason: "unescaped control character".into(),
}));
}
byte @ 0x20..=0x7F => s.push(byte as char), // ASCII: encoding == codepoint
utf8_byte @ 0x80.. => {
assert!(0b1000_0000 & utf8_byte != 0, "continuation bit is set");
let mut bytes = [0u8; 4];
bytes[0] = utf8_byte;
// Assume UTF8, and consume one code point. For pattern see
// https://en.wikipedia.org/wiki/UTF-8#Description. A bit repetitive
// below, but this way we only touch subsequent bytes if the start
// byte actually looks OK. The `str` will be stack-allocated, which
// is a neat bonus.
let i = if 0b0010_0000u8 & utf8_byte == 0 {
bytes[1] = self.advance()?;
2
} else if 0b0001_0000u8 & utf8_byte == 0 {
bytes[1] = self.advance()?;
bytes[2] = self.advance()?;
3
} else if 0b0000_1000u8 & utf8_byte == 0 {
bytes[1] = self.advance()?;
bytes[2] = self.advance()?;
bytes[3] = self.advance()?;
4
} else {
return Err(self.err(UnicodeError(error::UnicodeError::InvalidUTF8Start(
utf8_byte,
))));
};
s.push_str(
str::from_utf8(bytes.get(..i).expect("should set indices correctly"))
.map_err(|utf8err| self.err(utf8err.into()))?,
);
}
}
}
}
fn visit_array(&mut self) -> ParseResult<Vec<Value>> {
assert_eq!(
self.advance()?,
ARRAY_OPEN,
"should only be reachable from visiting value, where it should be peeked correctly before visiting"
);
self.skip_whitespace()?;
let mut array = Vec::new();
// Early return for empty array
if let Some(Ok(ARRAY_CLOSE)) = self.stream.peek() {
let _ = self.advance()?;
return Ok(array);
}
loop {
array.push(self.visit_value()?);
match self.advance()? {
ARRAY_CLOSE => break Ok(array),
ARRAY_SEP => continue,
byte => {
break Err(self.err(InvalidByte {
byte,
reason: format!(
"parsing array, need {} or {} after parsing an array element",
ARRAY_CLOSE as char, ARRAY_SEP as char,
),
}));
}
}
}
}
fn visit_bool(&mut self) -> ParseResult<bool> {
let (expected_remainder, result) = match self.advance()? {
b't' => (b"rue".as_slice(), true),
b'f' => (b"alse".as_slice(), false),
_ => unreachable!(
"should only be reachable from visiting value, where it should be peeked correctly before visiting"
),
};
for expected in expected_remainder.iter().copied() {
let got = self.advance()?;
if expected != got {
return Err(self.err(InvalidByte {
byte: got,
reason: format!(
"expected {} scanning boolean value, got {}",
expected as char, got as char
),
}));
}
}
Ok(result)
}
fn visit_null(&mut self) -> ParseResult<()> {
for expected in b"null".iter().copied() {
let got = self.advance()?;
if expected != got {
return Err(self.err(InvalidByte {
byte: got,
reason: format!(
"expected {} scanning for null, got {}",
expected as char, got as char
),
}));
}
}
Ok(())
}
fn visit_number(&mut self) -> ParseResult<Number> {
let mut number = Number(String::with_capacity(1));
number = self.visit_number_integral_part(number)?;
number = self.visit_number_fractional_part(number)?;
number = self.visit_number_exponent_part(number)?;
match self.stream.peek() {
// If there's a digit left we might have gotten a leading zero followed by
// more digits, e.g. `01`. Without fractional or exponent parts, our parsing
// just exits after `0`, so check.
Some(&Ok(byte @ b'0'..=b'9')) => Err(self.err(InvalidByte {
byte,
reason: format!(
"unexpected digit remaining after processing number ('{number:?}')"
),
})),
_ => Ok(number),
}
}
/// Parses the integral part ("bit before period") of a potentially fractional
/// number. Parsing stops if no valid tokens can be consumed anymore.
///
/// While objects, strings, arrays have delimiters which allow greedy fetching,
/// numbers do not. We need to be careful not to overfetch, thus work with peeking
/// and more manual advancing. In general, for every `push` into the number, there
/// needs to be an advance of the reader.
fn visit_number_integral_part(&mut self, mut number: Number) -> ParseResult<Number> {
// First token is mandatory, there's no way we can overfetch here: so consume
// right away.
match self.advance()? {
b'-' => {
number.0.push('-');
// Finding a digit is mandatory now: can't negate a non-number.
match self.advance()? {
b'0' => {
number.0.push('0');
// Negative zero: terminal case.
Ok(number)
}
byte @ b'1'..=b'9' => {
number.0.push(byte as char);
loop {
// Further digits are optional, so do not overfetch.
match self.stream.peek() {
Some(Ok(byte @ b'0'..=b'9')) => {
number.0.push(*byte as char);
}
_ => return Ok(number),
}
self.advance()?;
}
}
byte => Err(self.err(InvalidByte {
byte,
reason: "expected digit after - sign scanning number".into(),
})),
}
}
b'0' => {
number.0.push('0');
Ok(number)
}
byte @ b'1'..=b'9' => {
number.0.push(byte as char);
// NB: duplicates logic from above.
loop {
match self.stream.peek() {
Some(Ok(byte @ b'0'..=b'9')) => {
number.0.push(*byte as char);
}
_ => return Ok(number),
}
self.advance()?;
}
}
_ => unreachable!(
"should only be reachable from visiting number, which is only reachable from visiting value, where it should be peeked correctly before visiting"
),
}
}
fn visit_number_fractional_part(&mut self, mut number: Number) -> ParseResult<Number> {
match self.stream.peek() {
Some(Ok(b'.')) => {
number.0.push('.');
self.advance()?;
}
_ => return Ok(number),
}
// At least one digit is mandatory now.
match self.advance()? {
byte @ b'0'..=b'9' => number.0.push(byte as char),
byte => {
return Err(self.err(InvalidByte {
byte,
reason: "expected at least one digit for fractional part".into(),
}));
}
}
// Any further digits are optional.
loop {
match self.stream.peek() {
Some(Ok(byte @ b'0'..=b'9')) => {
number.0.push(*byte as char);
}
_ => return Ok(number),
}
self.advance()?;
}
}
fn visit_number_exponent_part(&mut self, mut number: Number) -> ParseResult<Number> {
match self.stream.peek() {
Some(Ok(b'e' | b'E')) => {
number.0.push('e'); // Case doesn't matter
self.advance()?;
}
_ => return Ok(number),
}
// Next token is mandatory, no peeking necessary.
match self.advance()? {
byte @ (b'+' | b'-') => {
number.0.push(byte as char);
// Also mandatory.
match self.advance()? {
byte @ b'0'..=b'9' => number.0.push(byte as char),
byte => {
return Err(self.err(InvalidByte {
byte,
reason: "expected digit after sign scanning number exponent".into(),
}));
}
}
}
byte @ b'0'..=b'9' => number.0.push(byte as char),
byte => {
return Err(self.err(InvalidByte {
byte,
reason: "expected digit or sign scanning number exponent".into(),
}));
}
}
// Any further digits are optional.
loop {
match self.stream.peek() {
Some(Ok(byte @ b'0'..=b'9')) => {
number.0.push(*byte as char);
}
_ => return Ok(number),
}
self.advance()?;
}
}
/// JSON Unicode hex escapes are **required** to be 4 long.
fn collect_unicode_escape_hex_digits(&mut self) -> ParseResult<u16> {
self.collect_hex::<u16, 4>()
}
/// Collect hex digits.
///
/// `T` is the target type to collect into. `N` is the number of hex chars/digits to
/// collect. Note they're indepedent: few digits can be collected into a large `T`
/// etc.
fn collect_hex<T, const N: usize>(&mut self) -> ParseResult<T>
where
// Generic over u8, u16, ...
T: Default
+ Copy
+ From<u8>
+ std::ops::Shl<usize, Output = T>
+ std::ops::BitOr<Output = T>,
{
let mut val = T::default();
for _ in 0..N {
let c = self.advance()? as char;
let digit = c
.to_digit(16)
.ok_or_else(|| self.err(InvalidHexCharacter(c)))?;
#[allow(
clippy::cast_possible_truncation,
reason = "to_digit(16) guarantees values 0-15, which fit u8"
)]
{
val = (val << 4) | T::from(digit as u8); // works thanks to `From<u8>`
}
}
Ok(val)
}
}
/// Note JSON whitespace differs from Unicode whitespace, it's a narrower definition.
#[inline]
fn is_json_whitespace(c: u8) -> bool {
c == b' ' || c == b'\n' || c == b'\r' || c == b'\t'
}
#[cfg(test)]
mod tests {
use super::*;
/// Helper to run the parser and extract the String variant.
///
/// Panics if the result is not a [`Value::String`] or if parsing fails.
fn parse_string(input: &str) -> String {
let mut parser = Parser::new(input.as_bytes());
let val = parser.parse().expect("Failed to parse");
match val {
Value::String(s) => s,
_ => panic!("Expected Value::String, got {:?}", val),
}
}
/// Helper to expect a specific error type.
fn parse_err(input: &[u8]) -> error::Error {
let mut parser = Parser::new(input);
parser.parse().expect_err("Expected error but got success")
}
// ==========================================
// Basic value tests
// ==========================================
#[test]
fn test_parse_value_with_empty_input() {
let err = parse_err(b"");
match err {
error::Error {
kind: UnexpectedEOF,
..
} => {}
_ => panic!("Wrong error type: {:?}", err),
}
}
// ==========================================
// Basic String Tests
// ==========================================
#[test]
fn test_empty_string() {
assert_eq!(parse_string(r#""""#), "");
}
#[test]
fn test_simple_ascii() {
assert_eq!(parse_string(r#""hello world""#), "hello world");
}
#[test]
fn test_alphanumeric() {
assert_eq!(parse_string(r#""abc123XYZ""#), "abc123XYZ");
}
#[test]
fn test_whitespace_around_string() {
assert_eq!(parse_string(" \"trimmed\""), "trimmed");
assert_eq!(parse_string("\n\t \"trimmed\""), "trimmed");
}
// ==========================================
// Escape Sequence Tests
// ==========================================
#[test]
fn test_quote_escape() {
assert_eq!(parse_string(r#""foo\"bar""#), r#"foo"bar"#);
}
#[test]
fn test_backslash_escape() {
assert_eq!(parse_string(r#""C:\\Path""#), r#"C:\Path"#);
}
#[test]
fn test_forward_slash_escape() {
assert_eq!(parse_string(r#""\/""#), "/");
}
#[test]
fn test_control_char_escapes() {
assert_eq!(parse_string(r#""\b""#), "\x08"); // Backspace
assert_eq!(parse_string(r#""\f""#), "\x0C"); // Form feed
assert_eq!(parse_string(r#""\n""#), "\n"); // Newline
assert_eq!(parse_string(r#""\r""#), "\r"); // Carriage return
assert_eq!(parse_string(r#""\t""#), "\t"); // Tab
}
#[test]
fn test_mixed_escapes() {
assert_eq!(
parse_string(r#""Line1\nLine2\tTabbed""#),
"Line1\nLine2\tTabbed"
);
}
// ==========================================
// Unicode & Hex Tests
// ==========================================
#[test]
fn test_basic_unicode_escape() {
// \u0041 is 'A'
assert_eq!(parse_string(r#""\u0041""#), "A");
// \u00A9 is Copyright symbol
assert_eq!(parse_string(r#""\u00A9""#), "©");
}
#[test]
fn test_raw_utf8_input() {
// 2 code points
assert!("é".len() == 2);
assert_eq!(parse_string(r#""José""#), "José");
// 3 code points
assert!("⌣".len() == 3);
assert_eq!(parse_string(r#""⌣""#), "⌣");
// 4 code points
assert!("🔥".len() == 4);
assert_eq!(parse_string(r#""🔥""#), "🔥");
}
#[test]
fn test_utf8_invalid_start_byte_in_string() {
let input = b"\"\xFF\"";
let err = parse_err(input);
match err {
error::Error {
kind: UnicodeError(error::UnicodeError::InvalidUTF8Start(0xFF)),
..
} => {}
_ => panic!("Wrong error type: {:?}", err),
}
}
#[test]
fn test_utf8_invalid_continuation_byte_in_string() {
// 0xC3 starts a 2-byte sequence (expects 1 continuation), but followed by space.
let input = b"\"\xC3 \"";
let err = parse_err(input);
match err {
error::Error {
kind: UnicodeError(error::UnicodeError::InvalidUTF8(_)),
..
} => {}
_ => panic!("Wrong error type: {:?}", err),
}
}
#[test]
fn test_utf8_invalid_start_byte_inside_string() {
// 0xE2 starts a 3-byte sequence, 0x82 is a valid continuation, but 0xC0 is a
// START byte (for 2-byte seq), not a continuation
let input = b"\"\xE2\x82\xC0 \"";
let err = parse_err(input);
match err {
error::Error {
kind: UnicodeError(error::UnicodeError::InvalidUTF8(_)),
..
} => {}
_ => panic!("Wrong error type: {:?}", err),
}
}
#[test]
fn test_utf8_deny_overlong_encoding() {
// More bytes than necessary should be rejected
let input = b"\"\xC0\xAF \"";
let err = parse_err(input);
match err {
error::Error {
kind: UnicodeError(error::UnicodeError::InvalidUTF8(_)),
..
} => {}
_ => panic!("Wrong error type: {:?}", err),
}
}
#[test]
fn test_utf8_premature_end_in_string() {
// Starts 4-byte sequence but ends right away
let input = b"\"\xF0\"";
let err = parse_err(input);
match err {
error::Error {
kind: UnexpectedEOF,
..
} => {}
_ => panic!("Wrong error type: {:?}", err),