forked from serde-rs/json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
de.rs
2683 lines (2426 loc) · 83.6 KB
/
de.rs
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
//! Deserialize JSON data to a Rust data structure.
use crate::error::{Error, ErrorCode, Result};
#[cfg(feature = "float_roundtrip")]
use crate::lexical;
use crate::number::Number;
use crate::read::{self, Fused, Reference};
use alloc::string::String;
use alloc::vec::Vec;
#[cfg(feature = "float_roundtrip")]
use core::iter;
use core::iter::FusedIterator;
use core::marker::PhantomData;
use core::result;
use core::str::FromStr;
use serde::de::{self, Expected, Unexpected};
use serde::forward_to_deserialize_any;
#[cfg(feature = "arbitrary_precision")]
use crate::number::NumberDeserializer;
pub use crate::read::{Read, SliceRead, StrRead};
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub use crate::read::IoRead;
//////////////////////////////////////////////////////////////////////////////
/// A structure that deserializes JSON into Rust values.
pub struct Deserializer<R> {
read: R,
scratch: Vec<u8>,
remaining_depth: u8,
#[cfg(feature = "float_roundtrip")]
single_precision: bool,
#[cfg(feature = "unbounded_depth")]
disable_recursion_limit: bool,
}
impl<'de, R> Deserializer<R>
where
R: read::Read<'de>,
{
/// Create a JSON deserializer from one of the possible serde_json input
/// sources.
///
/// Typically it is more convenient to use one of these methods instead:
///
/// - Deserializer::from_str
/// - Deserializer::from_slice
/// - Deserializer::from_reader
pub fn new(read: R) -> Self {
Deserializer {
read,
scratch: Vec::new(),
remaining_depth: 128,
#[cfg(feature = "float_roundtrip")]
single_precision: false,
#[cfg(feature = "unbounded_depth")]
disable_recursion_limit: false,
}
}
}
#[cfg(feature = "std")]
impl<R> Deserializer<read::IoRead<R>>
where
R: crate::io::Read,
{
/// Creates a JSON deserializer from an `io::Read`.
///
/// Reader-based deserializers do not support deserializing borrowed types
/// like `&str`, since the `std::io::Read` trait has no non-copying methods
/// -- everything it does involves copying bytes out of the data source.
pub fn from_reader(reader: R) -> Self {
Deserializer::new(read::IoRead::new(reader))
}
}
impl<'a> Deserializer<read::SliceRead<'a>> {
/// Creates a JSON deserializer from a `&[u8]`.
pub fn from_slice(bytes: &'a [u8]) -> Self {
Deserializer::new(read::SliceRead::new(bytes))
}
}
impl<'a> Deserializer<read::StrRead<'a>> {
/// Creates a JSON deserializer from a `&str`.
pub fn from_str(s: &'a str) -> Self {
Deserializer::new(read::StrRead::new(s))
}
}
macro_rules! overflow {
($a:ident * 10 + $b:ident, $c:expr) => {
match $c {
c => $a >= c / 10 && ($a > c / 10 || $b > c % 10),
}
};
}
pub(crate) enum ParserNumber {
F64(f64),
U64(u64),
I64(i64),
#[cfg(feature = "arbitrary_precision")]
String(String),
}
impl ParserNumber {
fn visit<'de, V>(self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
match self {
ParserNumber::F64(x) => visitor.visit_f64(x),
ParserNumber::U64(x) => visitor.visit_u64(x),
ParserNumber::I64(x) => visitor.visit_i64(x),
#[cfg(feature = "arbitrary_precision")]
ParserNumber::String(x) => visitor.visit_map(NumberDeserializer { number: x.into() }),
}
}
fn invalid_type(self, exp: &dyn Expected) -> Error {
match self {
ParserNumber::F64(x) => de::Error::invalid_type(Unexpected::Float(x), exp),
ParserNumber::U64(x) => de::Error::invalid_type(Unexpected::Unsigned(x), exp),
ParserNumber::I64(x) => de::Error::invalid_type(Unexpected::Signed(x), exp),
#[cfg(feature = "arbitrary_precision")]
ParserNumber::String(_) => de::Error::invalid_type(Unexpected::Other("number"), exp),
}
}
}
impl<'de, R: Read<'de>> Deserializer<R> {
/// The `Deserializer::end` method should be called after a value has been fully deserialized.
/// This allows the `Deserializer` to validate that the input stream is at the end or that it
/// only has trailing whitespace.
pub fn end(&mut self) -> Result<()> {
match tri!(self.parse_whitespace()) {
Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)),
None => Ok(()),
}
}
/// Turn a JSON deserializer into an iterator over values of type T.
pub fn into_iter<T>(self) -> StreamDeserializer<'de, R, T>
where
T: de::Deserialize<'de>,
{
// This cannot be an implementation of std::iter::IntoIterator because
// we need the caller to choose what T is.
let offset = self.read.byte_offset();
StreamDeserializer {
de: self,
offset,
failed: false,
output: PhantomData,
lifetime: PhantomData,
}
}
/// Parse arbitrarily deep JSON structures without any consideration for
/// overflowing the stack.
///
/// You will want to provide some other way to protect against stack
/// overflows, such as by wrapping your Deserializer in the dynamically
/// growing stack adapter provided by the serde_stacker crate. Additionally
/// you will need to be careful around other recursive operations on the
/// parsed result which may overflow the stack after deserialization has
/// completed, including, but not limited to, Display and Debug and Drop
/// impls.
///
/// *This method is only available if serde_json is built with the
/// `"unbounded_depth"` feature.*
///
/// # Examples
///
/// ```
/// use serde::Deserialize;
/// use serde_json::Value;
///
/// fn main() {
/// let mut json = String::new();
/// for _ in 0..10000 {
/// json = format!("[{}]", json);
/// }
///
/// let mut deserializer = serde_json::Deserializer::from_str(&json);
/// deserializer.disable_recursion_limit();
/// let deserializer = serde_stacker::Deserializer::new(&mut deserializer);
/// let value = Value::deserialize(deserializer).unwrap();
///
/// carefully_drop_nested_arrays(value);
/// }
///
/// fn carefully_drop_nested_arrays(value: Value) {
/// let mut stack = vec![value];
/// while let Some(value) = stack.pop() {
/// if let Value::Array(array) = value {
/// stack.extend(array);
/// }
/// }
/// }
/// ```
#[cfg(feature = "unbounded_depth")]
#[cfg_attr(docsrs, doc(cfg(feature = "unbounded_depth")))]
pub fn disable_recursion_limit(&mut self) {
self.disable_recursion_limit = true;
}
pub(crate) fn peek(&mut self) -> Result<Option<u8>> {
self.read.peek()
}
fn peek_or_null(&mut self) -> Result<u8> {
Ok(tri!(self.peek()).unwrap_or(b'\x00'))
}
fn eat_char(&mut self) {
self.read.discard();
}
fn next_char(&mut self) -> Result<Option<u8>> {
self.read.next()
}
fn next_char_or_null(&mut self) -> Result<u8> {
Ok(tri!(self.next_char()).unwrap_or(b'\x00'))
}
/// Error caused by a byte from next_char().
#[cold]
fn error(&self, reason: ErrorCode) -> Error {
let position = self.read.position();
Error::syntax(reason, position.line, position.column)
}
/// Error caused by a byte from peek().
#[cold]
fn peek_error(&self, reason: ErrorCode) -> Error {
let position = self.read.peek_position();
Error::syntax(reason, position.line, position.column)
}
/// Returns the first non-whitespace byte without consuming it, or `None` if
/// EOF is encountered.
fn parse_whitespace(&mut self) -> Result<Option<u8>> {
loop {
match tri!(self.peek()) {
Some(b' ' | b'\n' | b'\t' | b'\r') => {
self.eat_char();
}
other => {
return Ok(other);
}
}
}
}
#[cold]
fn peek_invalid_type(&mut self, exp: &dyn Expected) -> Error {
let err = match self.peek_or_null().unwrap_or(b'\x00') {
b'n' => {
self.eat_char();
if let Err(err) = self.parse_ident(b"ull") {
return err;
}
de::Error::invalid_type(Unexpected::Unit, exp)
}
b't' => {
self.eat_char();
if let Err(err) = self.parse_ident(b"rue") {
return err;
}
de::Error::invalid_type(Unexpected::Bool(true), exp)
}
b'f' => {
self.eat_char();
if let Err(err) = self.parse_ident(b"alse") {
return err;
}
de::Error::invalid_type(Unexpected::Bool(false), exp)
}
b'-' => {
self.eat_char();
match self.parse_any_number(false) {
Ok(n) => n.invalid_type(exp),
Err(err) => return err,
}
}
b'0'..=b'9' => match self.parse_any_number(true) {
Ok(n) => n.invalid_type(exp),
Err(err) => return err,
},
b'"' => {
self.eat_char();
self.scratch.clear();
match self.read.parse_str(&mut self.scratch) {
Ok(s) => de::Error::invalid_type(Unexpected::Str(&s), exp),
Err(err) => return err,
}
}
b'[' => de::Error::invalid_type(Unexpected::Seq, exp),
b'{' => de::Error::invalid_type(Unexpected::Map, exp),
_ => self.peek_error(ErrorCode::ExpectedSomeValue),
};
self.fix_position(err)
}
pub(crate) fn deserialize_number<'any, V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'any>,
{
let peek = match tri!(self.parse_whitespace()) {
Some(b) => b,
None => {
return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
}
};
let value = match peek {
b'-' => {
self.eat_char();
tri!(self.parse_integer(false)).visit(visitor)
}
b'0'..=b'9' => tri!(self.parse_integer(true)).visit(visitor),
_ => Err(self.peek_invalid_type(&visitor)),
};
match value {
Ok(value) => Ok(value),
Err(err) => Err(self.fix_position(err)),
}
}
#[cfg(feature = "float_roundtrip")]
pub(crate) fn do_deserialize_f32<'any, V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'any>,
{
self.single_precision = true;
let val = self.deserialize_number(visitor);
self.single_precision = false;
val
}
pub(crate) fn do_deserialize_i128<'any, V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'any>,
{
let mut buf = String::new();
match tri!(self.parse_whitespace()) {
Some(b'-') => {
self.eat_char();
buf.push('-');
}
Some(_) => {}
None => {
return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
}
};
tri!(self.scan_integer128(&mut buf));
let value = match buf.parse() {
Ok(int) => visitor.visit_i128(int),
Err(_) => {
return Err(self.error(ErrorCode::NumberOutOfRange));
}
};
match value {
Ok(value) => Ok(value),
Err(err) => Err(self.fix_position(err)),
}
}
pub(crate) fn do_deserialize_u128<'any, V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'any>,
{
match tri!(self.parse_whitespace()) {
Some(b'-') => {
return Err(self.peek_error(ErrorCode::NumberOutOfRange));
}
Some(_) => {}
None => {
return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
}
}
let mut buf = String::new();
tri!(self.scan_integer128(&mut buf));
let value = match buf.parse() {
Ok(int) => visitor.visit_u128(int),
Err(_) => {
return Err(self.error(ErrorCode::NumberOutOfRange));
}
};
match value {
Ok(value) => Ok(value),
Err(err) => Err(self.fix_position(err)),
}
}
fn scan_integer128(&mut self, buf: &mut String) -> Result<()> {
match tri!(self.next_char_or_null()) {
b'0' => {
buf.push('0');
// There can be only one leading '0'.
match tri!(self.peek_or_null()) {
b'0'..=b'9' => Err(self.peek_error(ErrorCode::InvalidNumber)),
_ => Ok(()),
}
}
c @ b'1'..=b'9' => {
buf.push(c as char);
while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) {
self.eat_char();
buf.push(c as char);
}
Ok(())
}
_ => Err(self.error(ErrorCode::InvalidNumber)),
}
}
#[cold]
fn fix_position(&self, err: Error) -> Error {
err.fix_position(move |code| self.error(code))
}
fn parse_ident(&mut self, ident: &[u8]) -> Result<()> {
for expected in ident {
match tri!(self.next_char()) {
None => {
return Err(self.error(ErrorCode::EofWhileParsingValue));
}
Some(next) => {
if next != *expected {
return Err(self.error(ErrorCode::ExpectedSomeIdent));
}
}
}
}
Ok(())
}
fn parse_integer(&mut self, positive: bool) -> Result<ParserNumber> {
let next = match tri!(self.next_char()) {
Some(b) => b,
None => {
return Err(self.error(ErrorCode::EofWhileParsingValue));
}
};
match next {
b'0' => {
// There can be only one leading '0'.
match tri!(self.peek_or_null()) {
b'0'..=b'9' => Err(self.peek_error(ErrorCode::InvalidNumber)),
_ => self.parse_number(positive, 0),
}
}
c @ b'1'..=b'9' => {
let mut significand = (c - b'0') as u64;
loop {
match tri!(self.peek_or_null()) {
c @ b'0'..=b'9' => {
let digit = (c - b'0') as u64;
// We need to be careful with overflow. If we can,
// try to keep the number as a `u64` until we grow
// too large. At that point, switch to parsing the
// value as a `f64`.
if overflow!(significand * 10 + digit, u64::MAX) {
return Ok(ParserNumber::F64(tri!(
self.parse_long_integer(positive, significand),
)));
}
self.eat_char();
significand = significand * 10 + digit;
}
_ => {
return self.parse_number(positive, significand);
}
}
}
}
_ => Err(self.error(ErrorCode::InvalidNumber)),
}
}
fn parse_number(&mut self, positive: bool, significand: u64) -> Result<ParserNumber> {
Ok(match tri!(self.peek_or_null()) {
b'.' => ParserNumber::F64(tri!(self.parse_decimal(positive, significand, 0))),
b'e' | b'E' => ParserNumber::F64(tri!(self.parse_exponent(positive, significand, 0))),
_ => {
if positive {
ParserNumber::U64(significand)
} else {
let neg = (significand as i64).wrapping_neg();
// Convert into a float if we underflow, or on `-0`.
if neg >= 0 {
ParserNumber::F64(-(significand as f64))
} else {
ParserNumber::I64(neg)
}
}
}
})
}
fn parse_decimal(
&mut self,
positive: bool,
mut significand: u64,
exponent_before_decimal_point: i32,
) -> Result<f64> {
self.eat_char();
let mut exponent_after_decimal_point = 0;
while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) {
let digit = (c - b'0') as u64;
if overflow!(significand * 10 + digit, u64::MAX) {
let exponent = exponent_before_decimal_point + exponent_after_decimal_point;
return self.parse_decimal_overflow(positive, significand, exponent);
}
self.eat_char();
significand = significand * 10 + digit;
exponent_after_decimal_point -= 1;
}
// Error if there is not at least one digit after the decimal point.
if exponent_after_decimal_point == 0 {
match tri!(self.peek()) {
Some(_) => return Err(self.peek_error(ErrorCode::InvalidNumber)),
None => return Err(self.peek_error(ErrorCode::EofWhileParsingValue)),
}
}
let exponent = exponent_before_decimal_point + exponent_after_decimal_point;
match tri!(self.peek_or_null()) {
b'e' | b'E' => self.parse_exponent(positive, significand, exponent),
_ => self.f64_from_parts(positive, significand, exponent),
}
}
fn parse_exponent(
&mut self,
positive: bool,
significand: u64,
starting_exp: i32,
) -> Result<f64> {
self.eat_char();
let positive_exp = match tri!(self.peek_or_null()) {
b'+' => {
self.eat_char();
true
}
b'-' => {
self.eat_char();
false
}
_ => true,
};
let next = match tri!(self.next_char()) {
Some(b) => b,
None => {
return Err(self.error(ErrorCode::EofWhileParsingValue));
}
};
// Make sure a digit follows the exponent place.
let mut exp = match next {
c @ b'0'..=b'9' => (c - b'0') as i32,
_ => {
return Err(self.error(ErrorCode::InvalidNumber));
}
};
while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) {
self.eat_char();
let digit = (c - b'0') as i32;
if overflow!(exp * 10 + digit, i32::MAX) {
let zero_significand = significand == 0;
return self.parse_exponent_overflow(positive, zero_significand, positive_exp);
}
exp = exp * 10 + digit;
}
let final_exp = if positive_exp {
starting_exp.saturating_add(exp)
} else {
starting_exp.saturating_sub(exp)
};
self.f64_from_parts(positive, significand, final_exp)
}
#[cfg(feature = "float_roundtrip")]
fn f64_from_parts(&mut self, positive: bool, significand: u64, exponent: i32) -> Result<f64> {
let f = if self.single_precision {
lexical::parse_concise_float::<f32>(significand, exponent) as f64
} else {
lexical::parse_concise_float::<f64>(significand, exponent)
};
if f.is_infinite() {
Err(self.error(ErrorCode::NumberOutOfRange))
} else {
Ok(if positive { f } else { -f })
}
}
#[cfg(not(feature = "float_roundtrip"))]
fn f64_from_parts(
&mut self,
positive: bool,
significand: u64,
mut exponent: i32,
) -> Result<f64> {
let mut f = significand as f64;
loop {
match POW10.get(exponent.wrapping_abs() as usize) {
Some(&pow) => {
if exponent >= 0 {
f *= pow;
if f.is_infinite() {
return Err(self.error(ErrorCode::NumberOutOfRange));
}
} else {
f /= pow;
}
break;
}
None => {
if f == 0.0 {
break;
}
if exponent >= 0 {
return Err(self.error(ErrorCode::NumberOutOfRange));
}
f /= 1e308;
exponent += 308;
}
}
}
Ok(if positive { f } else { -f })
}
#[cfg(feature = "float_roundtrip")]
#[cold]
#[inline(never)]
fn parse_long_integer(&mut self, positive: bool, partial_significand: u64) -> Result<f64> {
// To deserialize floats we'll first push the integer and fraction
// parts, both as byte strings, into the scratch buffer and then feed
// both slices to lexical's parser. For example if the input is
// `12.34e5` we'll push b"1234" into scratch and then pass b"12" and
// b"34" to lexical. `integer_end` will be used to track where to split
// the scratch buffer.
//
// Note that lexical expects the integer part to contain *no* leading
// zeroes and the fraction part to contain *no* trailing zeroes. The
// first requirement is already handled by the integer parsing logic.
// The second requirement will be enforced just before passing the
// slices to lexical in f64_long_from_parts.
self.scratch.clear();
self.scratch
.extend_from_slice(itoa::Buffer::new().format(partial_significand).as_bytes());
loop {
match tri!(self.peek_or_null()) {
c @ b'0'..=b'9' => {
self.scratch.push(c);
self.eat_char();
}
b'.' => {
self.eat_char();
return self.parse_long_decimal(positive, self.scratch.len());
}
b'e' | b'E' => {
return self.parse_long_exponent(positive, self.scratch.len());
}
_ => {
return self.f64_long_from_parts(positive, self.scratch.len(), 0);
}
}
}
}
#[cfg(not(feature = "float_roundtrip"))]
#[cold]
#[inline(never)]
fn parse_long_integer(&mut self, positive: bool, significand: u64) -> Result<f64> {
let mut exponent = 0;
loop {
match tri!(self.peek_or_null()) {
b'0'..=b'9' => {
self.eat_char();
// This could overflow... if your integer is gigabytes long.
// Ignore that possibility.
exponent += 1;
}
b'.' => {
return self.parse_decimal(positive, significand, exponent);
}
b'e' | b'E' => {
return self.parse_exponent(positive, significand, exponent);
}
_ => {
return self.f64_from_parts(positive, significand, exponent);
}
}
}
}
#[cfg(feature = "float_roundtrip")]
#[cold]
fn parse_long_decimal(&mut self, positive: bool, integer_end: usize) -> Result<f64> {
let mut at_least_one_digit = integer_end < self.scratch.len();
while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) {
self.scratch.push(c);
self.eat_char();
at_least_one_digit = true;
}
if !at_least_one_digit {
match tri!(self.peek()) {
Some(_) => return Err(self.peek_error(ErrorCode::InvalidNumber)),
None => return Err(self.peek_error(ErrorCode::EofWhileParsingValue)),
}
}
match tri!(self.peek_or_null()) {
b'e' | b'E' => self.parse_long_exponent(positive, integer_end),
_ => self.f64_long_from_parts(positive, integer_end, 0),
}
}
#[cfg(feature = "float_roundtrip")]
fn parse_long_exponent(&mut self, positive: bool, integer_end: usize) -> Result<f64> {
self.eat_char();
let positive_exp = match tri!(self.peek_or_null()) {
b'+' => {
self.eat_char();
true
}
b'-' => {
self.eat_char();
false
}
_ => true,
};
let next = match tri!(self.next_char()) {
Some(b) => b,
None => {
return Err(self.error(ErrorCode::EofWhileParsingValue));
}
};
// Make sure a digit follows the exponent place.
let mut exp = match next {
c @ b'0'..=b'9' => (c - b'0') as i32,
_ => {
return Err(self.error(ErrorCode::InvalidNumber));
}
};
while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) {
self.eat_char();
let digit = (c - b'0') as i32;
if overflow!(exp * 10 + digit, i32::MAX) {
let zero_significand = self.scratch.iter().all(|&digit| digit == b'0');
return self.parse_exponent_overflow(positive, zero_significand, positive_exp);
}
exp = exp * 10 + digit;
}
let final_exp = if positive_exp { exp } else { -exp };
self.f64_long_from_parts(positive, integer_end, final_exp)
}
// This cold code should not be inlined into the middle of the hot
// decimal-parsing loop above.
#[cfg(feature = "float_roundtrip")]
#[cold]
#[inline(never)]
fn parse_decimal_overflow(
&mut self,
positive: bool,
significand: u64,
exponent: i32,
) -> Result<f64> {
let mut buffer = itoa::Buffer::new();
let significand = buffer.format(significand);
let fraction_digits = -exponent as usize;
self.scratch.clear();
if let Some(zeros) = fraction_digits.checked_sub(significand.len() + 1) {
self.scratch.extend(iter::repeat(b'0').take(zeros + 1));
}
self.scratch.extend_from_slice(significand.as_bytes());
let integer_end = self.scratch.len() - fraction_digits;
self.parse_long_decimal(positive, integer_end)
}
#[cfg(not(feature = "float_roundtrip"))]
#[cold]
#[inline(never)]
fn parse_decimal_overflow(
&mut self,
positive: bool,
significand: u64,
exponent: i32,
) -> Result<f64> {
// The next multiply/add would overflow, so just ignore all further
// digits.
while let b'0'..=b'9' = tri!(self.peek_or_null()) {
self.eat_char();
}
match tri!(self.peek_or_null()) {
b'e' | b'E' => self.parse_exponent(positive, significand, exponent),
_ => self.f64_from_parts(positive, significand, exponent),
}
}
// This cold code should not be inlined into the middle of the hot
// exponent-parsing loop above.
#[cold]
#[inline(never)]
fn parse_exponent_overflow(
&mut self,
positive: bool,
zero_significand: bool,
positive_exp: bool,
) -> Result<f64> {
// Error instead of +/- infinity.
if !zero_significand && positive_exp {
return Err(self.error(ErrorCode::NumberOutOfRange));
}
while let b'0'..=b'9' = tri!(self.peek_or_null()) {
self.eat_char();
}
Ok(if positive { 0.0 } else { -0.0 })
}
#[cfg(feature = "float_roundtrip")]
fn f64_long_from_parts(
&mut self,
positive: bool,
integer_end: usize,
exponent: i32,
) -> Result<f64> {
let integer = &self.scratch[..integer_end];
let fraction = &self.scratch[integer_end..];
let f = if self.single_precision {
lexical::parse_truncated_float::<f32>(integer, fraction, exponent) as f64
} else {
lexical::parse_truncated_float::<f64>(integer, fraction, exponent)
};
if f.is_infinite() {
Err(self.error(ErrorCode::NumberOutOfRange))
} else {
Ok(if positive { f } else { -f })
}
}
fn parse_any_signed_number(&mut self) -> Result<ParserNumber> {
let peek = match tri!(self.peek()) {
Some(b) => b,
None => {
return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
}
};
let value = match peek {
b'-' => {
self.eat_char();
self.parse_any_number(false)
}
b'0'..=b'9' => self.parse_any_number(true),
_ => Err(self.peek_error(ErrorCode::InvalidNumber)),
};
let value = match tri!(self.peek()) {
Some(_) => Err(self.peek_error(ErrorCode::InvalidNumber)),
None => value,
};
match value {
Ok(value) => Ok(value),
// The de::Error impl creates errors with unknown line and column.
// Fill in the position here by looking at the current index in the
// input. There is no way to tell whether this should call `error`
// or `peek_error` so pick the one that seems correct more often.
// Worst case, the position is off by one character.
Err(err) => Err(self.fix_position(err)),
}
}
#[cfg(not(feature = "arbitrary_precision"))]
fn parse_any_number(&mut self, positive: bool) -> Result<ParserNumber> {
self.parse_integer(positive)
}
#[cfg(feature = "arbitrary_precision")]
fn parse_any_number(&mut self, positive: bool) -> Result<ParserNumber> {
let mut buf = String::with_capacity(16);
if !positive {
buf.push('-');
}
tri!(self.scan_integer(&mut buf));
if positive {
if let Ok(unsigned) = buf.parse() {
return Ok(ParserNumber::U64(unsigned));
}
} else {
if let Ok(signed) = buf.parse() {
return Ok(ParserNumber::I64(signed));
}
}
Ok(ParserNumber::String(buf))
}
#[cfg(feature = "arbitrary_precision")]
fn scan_or_eof(&mut self, buf: &mut String) -> Result<u8> {
match tri!(self.next_char()) {
Some(b) => {
buf.push(b as char);
Ok(b)
}
None => Err(self.error(ErrorCode::EofWhileParsingValue)),
}
}
#[cfg(feature = "arbitrary_precision")]
fn scan_integer(&mut self, buf: &mut String) -> Result<()> {
match tri!(self.scan_or_eof(buf)) {
b'0' => {
// There can be only one leading '0'.
match tri!(self.peek_or_null()) {
b'0'..=b'9' => Err(self.peek_error(ErrorCode::InvalidNumber)),
_ => self.scan_number(buf),
}
}
b'1'..=b'9' => loop {
match tri!(self.peek_or_null()) {
c @ b'0'..=b'9' => {
self.eat_char();
buf.push(c as char);
}
_ => {
return self.scan_number(buf);
}
}
},
_ => Err(self.error(ErrorCode::InvalidNumber)),
}
}
#[cfg(feature = "arbitrary_precision")]
fn scan_number(&mut self, buf: &mut String) -> Result<()> {
match tri!(self.peek_or_null()) {
b'.' => self.scan_decimal(buf),
e @ (b'e' | b'E') => self.scan_exponent(e as char, buf),
_ => Ok(()),
}
}
#[cfg(feature = "arbitrary_precision")]
fn scan_decimal(&mut self, buf: &mut String) -> Result<()> {
self.eat_char();
buf.push('.');
let mut at_least_one_digit = false;