Skip to main content

serde_json/
de.rs

1//! Deserialize JSON data to a Rust data structure.
2
3use crate::error::{Error, ErrorCode, Result};
4#[cfg(feature = "float_roundtrip")]
5use crate::lexical;
6use crate::number::Number;
7use crate::read::{self, Fused, Reference};
8use alloc::string::String;
9use alloc::vec::Vec;
10#[cfg(feature = "float_roundtrip")]
11use core::iter;
12use core::iter::FusedIterator;
13use core::marker::PhantomData;
14use core::result;
15use core::str::FromStr;
16use serde::de::{self, Expected, Unexpected};
17use serde::forward_to_deserialize_any;
18
19#[cfg(feature = "arbitrary_precision")]
20use crate::number::NumberDeserializer;
21
22pub use crate::read::{Read, SliceRead, StrRead};
23
24#[cfg(feature = "std")]
25#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
26pub use crate::read::IoRead;
27
28//////////////////////////////////////////////////////////////////////////////
29
30/// A structure that deserializes JSON into Rust values.
31pub struct Deserializer<R> {
32    read: R,
33    scratch: Vec<u8>,
34    remaining_depth: u8,
35    #[cfg(feature = "float_roundtrip")]
36    single_precision: bool,
37    #[cfg(feature = "unbounded_depth")]
38    disable_recursion_limit: bool,
39}
40
41impl<'de, R> Deserializer<R>
42where
43    R: read::Read<'de>,
44{
45    /// Create a JSON deserializer from one of the possible serde_json input
46    /// sources.
47    ///
48    /// When reading from a source against which short reads are not efficient, such
49    /// as a [`File`], you will want to apply your own buffering because serde_json
50    /// will not buffer the input. See [`std::io::BufReader`].
51    ///
52    /// Typically it is more convenient to use one of these methods instead:
53    ///
54    ///   - Deserializer::from_str
55    ///   - Deserializer::from_slice
56    ///   - Deserializer::from_reader
57    ///
58    /// [`File`]: std::fs::File
59    pub fn new(read: R) -> Self {
60        Deserializer {
61            read,
62            scratch: Vec::new(),
63            remaining_depth: 128,
64            #[cfg(feature = "float_roundtrip")]
65            single_precision: false,
66            #[cfg(feature = "unbounded_depth")]
67            disable_recursion_limit: false,
68        }
69    }
70}
71
72#[cfg(feature = "std")]
73impl<R> Deserializer<read::IoRead<R>>
74where
75    R: crate::io::Read,
76{
77    /// Creates a JSON deserializer from an `io::Read`.
78    ///
79    /// Reader-based deserializers do not support deserializing borrowed types
80    /// like `&str`, since the `std::io::Read` trait has no non-copying methods
81    /// -- everything it does involves copying bytes out of the data source.
82    pub fn from_reader(reader: R) -> Self {
83        Deserializer::new(read::IoRead::new(reader))
84    }
85}
86
87impl<'a> Deserializer<read::SliceRead<'a>> {
88    /// Creates a JSON deserializer from a `&[u8]`.
89    pub fn from_slice(bytes: &'a [u8]) -> Self {
90        Deserializer::new(read::SliceRead::new(bytes))
91    }
92}
93
94impl<'a> Deserializer<read::StrRead<'a>> {
95    /// Creates a JSON deserializer from a `&str`.
96    pub fn from_str(s: &'a str) -> Self {
97        Deserializer::new(read::StrRead::new(s))
98    }
99}
100
101macro_rules! overflow {
102    ($a:ident * 10 + $b:ident, $c:expr) => {
103        match $c {
104            c => $a >= c / 10 && ($a > c / 10 || $b > c % 10),
105        }
106    };
107}
108
109/// The largest significand for which eight more digits cannot overflow `u64`.
110///
111/// `significand * 100_000_000 + 99_999_999 <= u64::MAX`. Below this bound the
112/// per-digit `overflow!` check provably cannot fire, so consuming eight digits
113/// at once takes exactly the branch the byte-at-a-time loop would have taken --
114/// which is what lets the fast path exist without changing a single result,
115/// including the digit at which a long number switches to the slow float path.
116const SAFE_8_DIGIT_SIGNIFICAND: u64 = (u64::MAX - 99_999_999) / 100_000_000;
117
118pub(crate) enum ParserNumber {
119    F64(f64),
120    U64(u64),
121    I64(i64),
122    #[cfg(feature = "arbitrary_precision")]
123    String(String),
124}
125
126impl ParserNumber {
127    fn visit<'de, V>(self, visitor: V) -> Result<V::Value>
128    where
129        V: de::Visitor<'de>,
130    {
131        match self {
132            ParserNumber::F64(x) => visitor.visit_f64(x),
133            ParserNumber::U64(x) => visitor.visit_u64(x),
134            ParserNumber::I64(x) => visitor.visit_i64(x),
135            #[cfg(feature = "arbitrary_precision")]
136            ParserNumber::String(x) => visitor.visit_map(NumberDeserializer { number: x.into() }),
137        }
138    }
139
140    fn invalid_type(self, exp: &dyn Expected) -> Error {
141        match self {
142            ParserNumber::F64(x) => de::Error::invalid_type(Unexpected::Float(x), exp),
143            ParserNumber::U64(x) => de::Error::invalid_type(Unexpected::Unsigned(x), exp),
144            ParserNumber::I64(x) => de::Error::invalid_type(Unexpected::Signed(x), exp),
145            #[cfg(feature = "arbitrary_precision")]
146            ParserNumber::String(_) => de::Error::invalid_type(Unexpected::Other("number"), exp),
147        }
148    }
149}
150
151impl<'de, R: Read<'de>> Deserializer<R> {
152    /// The `Deserializer::end` method should be called after a value has been fully deserialized.
153    /// This allows the `Deserializer` to validate that the input stream is at the end or that it
154    /// only has trailing whitespace.
155    pub fn end(&mut self) -> Result<()> {
156        match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
157            Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)),
158            None => Ok(()),
159        }
160    }
161
162    /// Turn a JSON deserializer into an iterator over values of type T.
163    pub fn into_iter<T>(self) -> StreamDeserializer<'de, R, T>
164    where
165        T: de::Deserialize<'de>,
166    {
167        // This cannot be an implementation of std::iter::IntoIterator because
168        // we need the caller to choose what T is.
169        let offset = self.read.byte_offset();
170        StreamDeserializer {
171            de: self,
172            offset,
173            failed: false,
174            output: PhantomData,
175            lifetime: PhantomData,
176        }
177    }
178
179    /// Parse arbitrarily deep JSON structures without any consideration for
180    /// overflowing the stack.
181    ///
182    /// You will want to provide some other way to protect against stack
183    /// overflows, such as by wrapping your Deserializer in the dynamically
184    /// growing stack adapter provided by the serde_stacker crate. Additionally
185    /// you will need to be careful around other recursive operations on the
186    /// parsed result which may overflow the stack after deserialization has
187    /// completed, including, but not limited to, Display and Debug and Drop
188    /// impls.
189    ///
190    /// *This method is only available if serde_json is built with the
191    /// `"unbounded_depth"` feature.*
192    ///
193    /// # Examples
194    ///
195    /// ```
196    /// use serde::Deserialize;
197    /// use serde_json::Value;
198    ///
199    /// fn main() {
200    ///     let mut json = String::new();
201    ///     for _ in 0..10000 {
202    ///         json = format!("[{}]", json);
203    ///     }
204    ///
205    ///     let mut deserializer = serde_json::Deserializer::from_str(&json);
206    ///     deserializer.disable_recursion_limit();
207    ///     let deserializer = serde_stacker::Deserializer::new(&mut deserializer);
208    ///     let value = Value::deserialize(deserializer).unwrap();
209    ///
210    ///     carefully_drop_nested_arrays(value);
211    /// }
212    ///
213    /// fn carefully_drop_nested_arrays(value: Value) {
214    ///     let mut stack = vec![value];
215    ///     while let Some(value) = stack.pop() {
216    ///         if let Value::Array(array) = value {
217    ///             stack.extend(array);
218    ///         }
219    ///     }
220    /// }
221    /// ```
222    #[cfg(feature = "unbounded_depth")]
223    #[cfg_attr(docsrs, doc(cfg(feature = "unbounded_depth")))]
224    pub fn disable_recursion_limit(&mut self) {
225        self.disable_recursion_limit = true;
226    }
227
228    pub(crate) fn peek(&mut self) -> Result<Option<u8>> {
229        self.read.peek()
230    }
231
232    fn peek_or_null(&mut self) -> Result<u8> {
233        Ok(match self.peek() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek()).unwrap_or(b'\x00'))
234    }
235
236    fn eat_char(&mut self) {
237        self.read.discard();
238    }
239
240    fn next_char(&mut self) -> Result<Option<u8>> {
241        self.read.next()
242    }
243
244    fn next_char_or_null(&mut self) -> Result<u8> {
245        Ok(match self.next_char() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.next_char()).unwrap_or(b'\x00'))
246    }
247
248    /// Error caused by a byte from next_char().
249    #[cold]
250    fn error(&self, reason: ErrorCode) -> Error {
251        let position = self.read.position();
252        Error::syntax(reason, position.line, position.column)
253    }
254
255    /// Error caused by a byte from peek().
256    #[cold]
257    fn peek_error(&self, reason: ErrorCode) -> Error {
258        let position = self.read.peek_position();
259        Error::syntax(reason, position.line, position.column)
260    }
261
262    /// Returns the first non-whitespace byte without consuming it, or `None` if
263    /// EOF is encountered.
264    fn parse_whitespace(&mut self) -> Result<Option<u8>> {
265        // Delegated so a reader over a contiguous buffer can walk the run in
266        // one pass instead of a peek()/discard() round trip per byte. See
267        // `Read::skip_whitespace`; the default implementation there is exactly
268        // the loop this used to be.
269        self.read.skip_whitespace()
270    }
271
272    #[cold]
273    fn peek_invalid_type(&mut self, exp: &dyn Expected) -> Error {
274        let err = match self.peek_or_null().unwrap_or(b'\x00') {
275            b'n' => {
276                self.eat_char();
277                if let Err(err) = self.parse_ident(b"ull") {
278                    return err;
279                }
280                de::Error::invalid_type(Unexpected::Unit, exp)
281            }
282            b't' => {
283                self.eat_char();
284                if let Err(err) = self.parse_ident(b"rue") {
285                    return err;
286                }
287                de::Error::invalid_type(Unexpected::Bool(true), exp)
288            }
289            b'f' => {
290                self.eat_char();
291                if let Err(err) = self.parse_ident(b"alse") {
292                    return err;
293                }
294                de::Error::invalid_type(Unexpected::Bool(false), exp)
295            }
296            b'-' => {
297                self.eat_char();
298                match self.parse_any_number(false) {
299                    Ok(n) => n.invalid_type(exp),
300                    Err(err) => return err,
301                }
302            }
303            b'0'..=b'9' => match self.parse_any_number(true) {
304                Ok(n) => n.invalid_type(exp),
305                Err(err) => return err,
306            },
307            b'"' => {
308                self.eat_char();
309                self.scratch.clear();
310                match self.read.parse_str(&mut self.scratch) {
311                    Ok(s) => de::Error::invalid_type(Unexpected::Str(&s), exp),
312                    Err(err) => return err,
313                }
314            }
315            b'[' => de::Error::invalid_type(Unexpected::Seq, exp),
316            b'{' => de::Error::invalid_type(Unexpected::Map, exp),
317            _ => self.peek_error(ErrorCode::ExpectedSomeValue),
318        };
319
320        self.fix_position(err)
321    }
322
323    pub(crate) fn deserialize_number<'any, V>(&mut self, visitor: V) -> Result<V::Value>
324    where
325        V: de::Visitor<'any>,
326    {
327        let peek = match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
328            Some(b) => b,
329            None => {
330                return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
331            }
332        };
333
334        let value = match peek {
335            b'-' => {
336                self.eat_char();
337                match self.parse_integer(false) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_integer(false)).visit(visitor)
338            }
339            b'0'..=b'9' => match self.parse_integer(true) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_integer(true)).visit(visitor),
340            _ => Err(self.peek_invalid_type(&visitor)),
341        };
342
343        match value {
344            Ok(value) => Ok(value),
345            Err(err) => Err(self.fix_position(err)),
346        }
347    }
348
349    #[cfg(feature = "float_roundtrip")]
350    pub(crate) fn do_deserialize_f32<'any, V>(&mut self, visitor: V) -> Result<V::Value>
351    where
352        V: de::Visitor<'any>,
353    {
354        self.single_precision = true;
355        let val = self.deserialize_number(visitor);
356        self.single_precision = false;
357        val
358    }
359
360    pub(crate) fn do_deserialize_i128<'any, V>(&mut self, visitor: V) -> Result<V::Value>
361    where
362        V: de::Visitor<'any>,
363    {
364        let mut buf = String::new();
365
366        match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
367            Some(b'-') => {
368                self.eat_char();
369                buf.push('-');
370            }
371            Some(_) => {}
372            None => {
373                return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
374            }
375        }
376
377        match self.scan_integer128(&mut buf) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.scan_integer128(&mut buf));
378
379        let value = match buf.parse() {
380            Ok(int) => visitor.visit_i128(int),
381            Err(_) => {
382                return Err(self.error(ErrorCode::NumberOutOfRange));
383            }
384        };
385
386        match value {
387            Ok(value) => Ok(value),
388            Err(err) => Err(self.fix_position(err)),
389        }
390    }
391
392    pub(crate) fn do_deserialize_u128<'any, V>(&mut self, visitor: V) -> Result<V::Value>
393    where
394        V: de::Visitor<'any>,
395    {
396        match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
397            Some(b'-') => {
398                return Err(self.peek_error(ErrorCode::NumberOutOfRange));
399            }
400            Some(_) => {}
401            None => {
402                return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
403            }
404        }
405
406        let mut buf = String::new();
407        match self.scan_integer128(&mut buf) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.scan_integer128(&mut buf));
408
409        let value = match buf.parse() {
410            Ok(int) => visitor.visit_u128(int),
411            Err(_) => {
412                return Err(self.error(ErrorCode::NumberOutOfRange));
413            }
414        };
415
416        match value {
417            Ok(value) => Ok(value),
418            Err(err) => Err(self.fix_position(err)),
419        }
420    }
421
422    fn scan_integer128(&mut self, buf: &mut String) -> Result<()> {
423        match match self.next_char_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.next_char_or_null()) {
424            b'0' => {
425                buf.push('0');
426                // There can be only one leading '0'.
427                match match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
428                    b'0'..=b'9' => Err(self.peek_error(ErrorCode::InvalidNumber)),
429                    _ => Ok(()),
430                }
431            }
432            c @ b'1'..=b'9' => {
433                buf.push(c as char);
434                while let c @ b'0'..=b'9' = match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
435                    self.eat_char();
436                    buf.push(c as char);
437                }
438                Ok(())
439            }
440            _ => Err(self.error(ErrorCode::InvalidNumber)),
441        }
442    }
443
444    #[cold]
445    fn fix_position(&self, err: Error) -> Error {
446        err.fix_position(move |code| self.error(code))
447    }
448
449    fn parse_ident(&mut self, ident: &[u8]) -> Result<()> {
450        for expected in ident {
451            match match self.next_char() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.next_char()) {
452                None => {
453                    return Err(self.error(ErrorCode::EofWhileParsingValue));
454                }
455                Some(next) => {
456                    if next != *expected {
457                        return Err(self.error(ErrorCode::ExpectedSomeIdent));
458                    }
459                }
460            }
461        }
462
463        Ok(())
464    }
465
466    fn parse_integer(&mut self, positive: bool) -> Result<ParserNumber> {
467        let next = match match self.next_char() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.next_char()) {
468            Some(b) => b,
469            None => {
470                return Err(self.error(ErrorCode::EofWhileParsingValue));
471            }
472        };
473
474        match next {
475            b'0' => {
476                // There can be only one leading '0'.
477                match match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
478                    b'0'..=b'9' => Err(self.peek_error(ErrorCode::InvalidNumber)),
479                    _ => self.parse_number(positive, 0),
480                }
481            }
482            c @ b'1'..=b'9' => {
483                let mut significand = (c - b'0') as u64;
484
485                // Eight digits per step while an overflow is impossible for the
486                // whole chunk (see `SAFE_8_DIGIT_SIGNIFICAND`). A reader that is
487                // not backed by a contiguous buffer declines, and the loop below
488                // does all the work exactly as before.
489                while significand <= SAFE_8_DIGIT_SIGNIFICAND {
490                    match self.read.take_8_digits() {
491                        Some(d8) => significand = significand * 100_000_000 + u64::from(d8),
492                        None => break,
493                    }
494                }
495
496                loop {
497                    match match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
498                        c @ b'0'..=b'9' => {
499                            let digit = (c - b'0') as u64;
500
501                            // We need to be careful with overflow. If we can,
502                            // try to keep the number as a `u64` until we grow
503                            // too large. At that point, switch to parsing the
504                            // value as a `f64`.
505                            if match u64::MAX {
    c => significand >= c / 10 && (significand > c / 10 || digit > c % 10),
}overflow!(significand * 10 + digit, u64::MAX) {
506                                return Ok(ParserNumber::F64(match self.parse_long_integer(positive, significand) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(
507                                    self.parse_long_integer(positive, significand),
508                                )));
509                            }
510
511                            self.eat_char();
512                            significand = significand * 10 + digit;
513                        }
514                        _ => {
515                            return self.parse_number(positive, significand);
516                        }
517                    }
518                }
519            }
520            _ => Err(self.error(ErrorCode::InvalidNumber)),
521        }
522    }
523
524    fn parse_number(&mut self, positive: bool, significand: u64) -> Result<ParserNumber> {
525        Ok(match match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
526            b'.' => ParserNumber::F64(match self.parse_decimal(positive, significand, 0) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_decimal(positive, significand, 0))),
527            b'e' | b'E' => ParserNumber::F64(match self.parse_exponent(positive, significand, 0) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_exponent(positive, significand, 0))),
528            _ => {
529                if positive {
530                    ParserNumber::U64(significand)
531                } else {
532                    let neg = (significand as i64).wrapping_neg();
533
534                    // Convert into a float if we underflow, or on `-0`.
535                    if neg >= 0 {
536                        ParserNumber::F64(-(significand as f64))
537                    } else {
538                        ParserNumber::I64(neg)
539                    }
540                }
541            }
542        })
543    }
544
545    fn parse_decimal(
546        &mut self,
547        positive: bool,
548        mut significand: u64,
549        exponent_before_decimal_point: i32,
550    ) -> Result<f64> {
551        self.eat_char();
552
553        let mut exponent_after_decimal_point = 0;
554
555        // As in `parse_integer`: eight fraction digits per step while an
556        // overflow is impossible for the whole chunk. The "at least one digit
557        // after the decimal point" check below reads
558        // `exponent_after_decimal_point`, which this keeps up to date, so a
559        // number whose fraction is consumed entirely here still validates.
560        while significand <= SAFE_8_DIGIT_SIGNIFICAND {
561            match self.read.take_8_digits() {
562                Some(d8) => {
563                    significand = significand * 100_000_000 + u64::from(d8);
564                    exponent_after_decimal_point -= 8;
565                }
566                None => break,
567            }
568        }
569        // There is deliberately no FOUR-digit step here, and none in
570        // `parse_integer`. Both were built and both were refuted, and the
571        // second refutation is the interesting one: at this call site the
572        // four-digit check HITS 110,984 times out of 111,080 on `canada.json`
573        // -- 99.91% -- and removes 443,936 `peek` calls, a third of the file's
574        // total. It is still 2.5% slower (61 pairs, 51 wins, z = +5.25,
575        // best-of-N agreeing at 0.975x, with two stringify controls flat).
576        //
577        // The reason is that the fold below has a FIXED cost that does not
578        // shrink with width. Four digits of the loop that follows are four
579        // dependent `significand * 10 + digit` steps on bytes already in L1
580        // with a perfectly predicted branch: about sixteen cycles. The
581        // four-digit chunk is a load, a validate and a multiply fold: about the
582        // same. Eight digits are thirty-two cycles of scalar against that same
583        // fixed fold, which is why `take_8_digits` wins 1.083x on this file and
584        // its four-digit sibling gives more than half of that back.
585        //
586        // The law, worth more than the brick: a chunk step pays only when the
587        // scalar work it replaces exceeds the fold's fixed cost. Break-even on
588        // this core is above four digits. Removed work is not saved time.
589        while let c @ b'0'..=b'9' = match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
590            let digit = (c - b'0') as u64;
591
592            if match u64::MAX {
    c => significand >= c / 10 && (significand > c / 10 || digit > c % 10),
}overflow!(significand * 10 + digit, u64::MAX) {
593                let exponent = exponent_before_decimal_point + exponent_after_decimal_point;
594                return self.parse_decimal_overflow(positive, significand, exponent);
595            }
596
597            self.eat_char();
598            significand = significand * 10 + digit;
599            exponent_after_decimal_point -= 1;
600        }
601
602        // Error if there is not at least one digit after the decimal point.
603        if exponent_after_decimal_point == 0 {
604            match match self.peek() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek()) {
605                Some(_) => return Err(self.peek_error(ErrorCode::InvalidNumber)),
606                None => return Err(self.peek_error(ErrorCode::EofWhileParsingValue)),
607            }
608        }
609
610        let exponent = exponent_before_decimal_point + exponent_after_decimal_point;
611        match match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
612            b'e' | b'E' => self.parse_exponent(positive, significand, exponent),
613            _ => self.f64_from_parts(positive, significand, exponent),
614        }
615    }
616
617    fn parse_exponent(
618        &mut self,
619        positive: bool,
620        significand: u64,
621        starting_exp: i32,
622    ) -> Result<f64> {
623        self.eat_char();
624
625        let positive_exp = match match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
626            b'+' => {
627                self.eat_char();
628                true
629            }
630            b'-' => {
631                self.eat_char();
632                false
633            }
634            _ => true,
635        };
636
637        let next = match match self.next_char() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.next_char()) {
638            Some(b) => b,
639            None => {
640                return Err(self.error(ErrorCode::EofWhileParsingValue));
641            }
642        };
643
644        // Make sure a digit follows the exponent place.
645        let mut exp = match next {
646            c @ b'0'..=b'9' => (c - b'0') as i32,
647            _ => {
648                return Err(self.error(ErrorCode::InvalidNumber));
649            }
650        };
651
652        while let c @ b'0'..=b'9' = match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
653            self.eat_char();
654            let digit = (c - b'0') as i32;
655
656            if match i32::MAX { c => exp >= c / 10 && (exp > c / 10 || digit > c % 10), }overflow!(exp * 10 + digit, i32::MAX) {
657                let zero_significand = significand == 0;
658                return self.parse_exponent_overflow(positive, zero_significand, positive_exp);
659            }
660
661            exp = exp * 10 + digit;
662        }
663
664        let final_exp = if positive_exp {
665            starting_exp.saturating_add(exp)
666        } else {
667            starting_exp.saturating_sub(exp)
668        };
669
670        self.f64_from_parts(positive, significand, final_exp)
671    }
672
673    #[cfg(feature = "float_roundtrip")]
674    fn f64_from_parts(&mut self, positive: bool, significand: u64, exponent: i32) -> Result<f64> {
675        let f = if self.single_precision {
676            lexical::parse_concise_float::<f32>(significand, exponent) as f64
677        } else {
678            lexical::parse_concise_float::<f64>(significand, exponent)
679        };
680
681        if f.is_infinite() {
682            Err(self.error(ErrorCode::NumberOutOfRange))
683        } else {
684            Ok(if positive { f } else { -f })
685        }
686    }
687
688    #[cfg(not(feature = "float_roundtrip"))]
689    fn f64_from_parts(
690        &mut self,
691        positive: bool,
692        significand: u64,
693        mut exponent: i32,
694    ) -> Result<f64> {
695        let mut f = significand as f64;
696        loop {
697            match POW10.get(exponent.wrapping_abs() as usize) {
698                Some(&pow) => {
699                    if exponent >= 0 {
700                        f *= pow;
701                        if f.is_infinite() {
702                            return Err(self.error(ErrorCode::NumberOutOfRange));
703                        }
704                    } else {
705                        f /= pow;
706                    }
707                    break;
708                }
709                None => {
710                    if f == 0.0 {
711                        break;
712                    }
713                    if exponent >= 0 {
714                        return Err(self.error(ErrorCode::NumberOutOfRange));
715                    }
716                    f /= 1e308;
717                    exponent += 308;
718                }
719            }
720        }
721        Ok(if positive { f } else { -f })
722    }
723
724    #[cfg(feature = "float_roundtrip")]
725    #[cold]
726    #[inline(never)]
727    fn parse_long_integer(&mut self, positive: bool, partial_significand: u64) -> Result<f64> {
728        // To deserialize floats we'll first push the integer and fraction
729        // parts, both as byte strings, into the scratch buffer and then feed
730        // both slices to lexical's parser. For example if the input is
731        // `12.34e5` we'll push b"1234" into scratch and then pass b"12" and
732        // b"34" to lexical. `integer_end` will be used to track where to split
733        // the scratch buffer.
734        //
735        // Note that lexical expects the integer part to contain *no* leading
736        // zeroes and the fraction part to contain *no* trailing zeroes. The
737        // first requirement is already handled by the integer parsing logic.
738        // The second requirement will be enforced just before passing the
739        // slices to lexical in f64_long_from_parts.
740        self.scratch.clear();
741        self.scratch
742            .extend_from_slice(itoa::Buffer::new().format(partial_significand).as_bytes());
743
744        loop {
745            match tri!(self.peek_or_null()) {
746                c @ b'0'..=b'9' => {
747                    self.scratch.push(c);
748                    self.eat_char();
749                }
750                b'.' => {
751                    self.eat_char();
752                    return self.parse_long_decimal(positive, self.scratch.len());
753                }
754                b'e' | b'E' => {
755                    return self.parse_long_exponent(positive, self.scratch.len());
756                }
757                _ => {
758                    return self.f64_long_from_parts(positive, self.scratch.len(), 0);
759                }
760            }
761        }
762    }
763
764    #[cfg(not(feature = "float_roundtrip"))]
765    #[cold]
766    #[inline(never)]
767    fn parse_long_integer(&mut self, positive: bool, significand: u64) -> Result<f64> {
768        let mut exponent = 0;
769        loop {
770            match match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
771                b'0'..=b'9' => {
772                    self.eat_char();
773                    // This could overflow... if your integer is gigabytes long.
774                    // Ignore that possibility.
775                    exponent += 1;
776                }
777                b'.' => {
778                    return self.parse_decimal(positive, significand, exponent);
779                }
780                b'e' | b'E' => {
781                    return self.parse_exponent(positive, significand, exponent);
782                }
783                _ => {
784                    return self.f64_from_parts(positive, significand, exponent);
785                }
786            }
787        }
788    }
789
790    #[cfg(feature = "float_roundtrip")]
791    #[cold]
792    fn parse_long_decimal(&mut self, positive: bool, integer_end: usize) -> Result<f64> {
793        let mut at_least_one_digit = integer_end < self.scratch.len();
794        while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) {
795            self.scratch.push(c);
796            self.eat_char();
797            at_least_one_digit = true;
798        }
799
800        if !at_least_one_digit {
801            match tri!(self.peek()) {
802                Some(_) => return Err(self.peek_error(ErrorCode::InvalidNumber)),
803                None => return Err(self.peek_error(ErrorCode::EofWhileParsingValue)),
804            }
805        }
806
807        match tri!(self.peek_or_null()) {
808            b'e' | b'E' => self.parse_long_exponent(positive, integer_end),
809            _ => self.f64_long_from_parts(positive, integer_end, 0),
810        }
811    }
812
813    #[cfg(feature = "float_roundtrip")]
814    fn parse_long_exponent(&mut self, positive: bool, integer_end: usize) -> Result<f64> {
815        self.eat_char();
816
817        let positive_exp = match tri!(self.peek_or_null()) {
818            b'+' => {
819                self.eat_char();
820                true
821            }
822            b'-' => {
823                self.eat_char();
824                false
825            }
826            _ => true,
827        };
828
829        let next = match tri!(self.next_char()) {
830            Some(b) => b,
831            None => {
832                return Err(self.error(ErrorCode::EofWhileParsingValue));
833            }
834        };
835
836        // Make sure a digit follows the exponent place.
837        let mut exp = match next {
838            c @ b'0'..=b'9' => (c - b'0') as i32,
839            _ => {
840                return Err(self.error(ErrorCode::InvalidNumber));
841            }
842        };
843
844        while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) {
845            self.eat_char();
846            let digit = (c - b'0') as i32;
847
848            if overflow!(exp * 10 + digit, i32::MAX) {
849                let zero_significand = self.scratch.iter().all(|&digit| digit == b'0');
850                return self.parse_exponent_overflow(positive, zero_significand, positive_exp);
851            }
852
853            exp = exp * 10 + digit;
854        }
855
856        let final_exp = if positive_exp { exp } else { -exp };
857
858        self.f64_long_from_parts(positive, integer_end, final_exp)
859    }
860
861    // This cold code should not be inlined into the middle of the hot
862    // decimal-parsing loop above.
863    #[cfg(feature = "float_roundtrip")]
864    #[cold]
865    #[inline(never)]
866    fn parse_decimal_overflow(
867        &mut self,
868        positive: bool,
869        significand: u64,
870        exponent: i32,
871    ) -> Result<f64> {
872        let mut buffer = itoa::Buffer::new();
873        let significand = buffer.format(significand);
874        let fraction_digits = -exponent as usize;
875        self.scratch.clear();
876        if let Some(zeros) = fraction_digits.checked_sub(significand.len() + 1) {
877            self.scratch.extend(iter::repeat_n(b'0', zeros + 1));
878        }
879        self.scratch.extend_from_slice(significand.as_bytes());
880        let integer_end = self.scratch.len() - fraction_digits;
881        self.parse_long_decimal(positive, integer_end)
882    }
883
884    #[cfg(not(feature = "float_roundtrip"))]
885    #[cold]
886    #[inline(never)]
887    fn parse_decimal_overflow(
888        &mut self,
889        positive: bool,
890        significand: u64,
891        exponent: i32,
892    ) -> Result<f64> {
893        // The next multiply/add would overflow, so just ignore all further
894        // digits.
895        while let b'0'..=b'9' = match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
896            self.eat_char();
897        }
898
899        match match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
900            b'e' | b'E' => self.parse_exponent(positive, significand, exponent),
901            _ => self.f64_from_parts(positive, significand, exponent),
902        }
903    }
904
905    // This cold code should not be inlined into the middle of the hot
906    // exponent-parsing loop above.
907    #[cold]
908    #[inline(never)]
909    fn parse_exponent_overflow(
910        &mut self,
911        positive: bool,
912        zero_significand: bool,
913        positive_exp: bool,
914    ) -> Result<f64> {
915        // Error instead of +/- infinity.
916        if !zero_significand && positive_exp {
917            return Err(self.error(ErrorCode::NumberOutOfRange));
918        }
919
920        while let b'0'..=b'9' = match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
921            self.eat_char();
922        }
923        Ok(if positive { 0.0 } else { -0.0 })
924    }
925
926    #[cfg(feature = "float_roundtrip")]
927    fn f64_long_from_parts(
928        &mut self,
929        positive: bool,
930        integer_end: usize,
931        exponent: i32,
932    ) -> Result<f64> {
933        let integer = &self.scratch[..integer_end];
934        let fraction = &self.scratch[integer_end..];
935
936        let f = if self.single_precision {
937            lexical::parse_truncated_float::<f32>(integer, fraction, exponent) as f64
938        } else {
939            lexical::parse_truncated_float::<f64>(integer, fraction, exponent)
940        };
941
942        if f.is_infinite() {
943            Err(self.error(ErrorCode::NumberOutOfRange))
944        } else {
945            Ok(if positive { f } else { -f })
946        }
947    }
948
949    fn parse_any_signed_number(&mut self) -> Result<ParserNumber> {
950        let peek = match match self.peek() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek()) {
951            Some(b) => b,
952            None => {
953                return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
954            }
955        };
956
957        let value = match peek {
958            b'-' => {
959                self.eat_char();
960                self.parse_any_number(false)
961            }
962            b'0'..=b'9' => self.parse_any_number(true),
963            _ => Err(self.peek_error(ErrorCode::InvalidNumber)),
964        };
965
966        let value = match match self.peek() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek()) {
967            Some(_) => Err(self.peek_error(ErrorCode::InvalidNumber)),
968            None => value,
969        };
970
971        match value {
972            Ok(value) => Ok(value),
973            // The de::Error impl creates errors with unknown line and column.
974            // Fill in the position here by looking at the current index in the
975            // input. There is no way to tell whether this should call `error`
976            // or `peek_error` so pick the one that seems correct more often.
977            // Worst case, the position is off by one character.
978            Err(err) => Err(self.fix_position(err)),
979        }
980    }
981
982    #[cfg(not(feature = "arbitrary_precision"))]
983    fn parse_any_number(&mut self, positive: bool) -> Result<ParserNumber> {
984        self.parse_integer(positive)
985    }
986
987    #[cfg(feature = "arbitrary_precision")]
988    fn parse_any_number(&mut self, positive: bool) -> Result<ParserNumber> {
989        let mut buf = String::with_capacity(16);
990        if !positive {
991            buf.push('-');
992        }
993        tri!(self.scan_integer(&mut buf));
994        if positive {
995            if let Ok(unsigned) = buf.parse() {
996                return Ok(ParserNumber::U64(unsigned));
997            }
998        } else {
999            if let Ok(signed) = buf.parse() {
1000                return Ok(ParserNumber::I64(signed));
1001            }
1002        }
1003        Ok(ParserNumber::String(buf))
1004    }
1005
1006    #[cfg(feature = "arbitrary_precision")]
1007    fn scan_or_eof(&mut self, buf: &mut String) -> Result<u8> {
1008        match tri!(self.next_char()) {
1009            Some(b) => {
1010                buf.push(b as char);
1011                Ok(b)
1012            }
1013            None => Err(self.error(ErrorCode::EofWhileParsingValue)),
1014        }
1015    }
1016
1017    #[cfg(feature = "arbitrary_precision")]
1018    fn scan_integer(&mut self, buf: &mut String) -> Result<()> {
1019        match tri!(self.scan_or_eof(buf)) {
1020            b'0' => {
1021                // There can be only one leading '0'.
1022                match tri!(self.peek_or_null()) {
1023                    b'0'..=b'9' => Err(self.peek_error(ErrorCode::InvalidNumber)),
1024                    _ => self.scan_number(buf),
1025                }
1026            }
1027            b'1'..=b'9' => loop {
1028                match tri!(self.peek_or_null()) {
1029                    c @ b'0'..=b'9' => {
1030                        self.eat_char();
1031                        buf.push(c as char);
1032                    }
1033                    _ => {
1034                        return self.scan_number(buf);
1035                    }
1036                }
1037            },
1038            _ => Err(self.error(ErrorCode::InvalidNumber)),
1039        }
1040    }
1041
1042    #[cfg(feature = "arbitrary_precision")]
1043    fn scan_number(&mut self, buf: &mut String) -> Result<()> {
1044        match tri!(self.peek_or_null()) {
1045            b'.' => self.scan_decimal(buf),
1046            b'e' | b'E' => self.scan_exponent(buf),
1047            _ => Ok(()),
1048        }
1049    }
1050
1051    #[cfg(feature = "arbitrary_precision")]
1052    fn scan_decimal(&mut self, buf: &mut String) -> Result<()> {
1053        self.eat_char();
1054        buf.push('.');
1055
1056        let mut at_least_one_digit = false;
1057        while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) {
1058            self.eat_char();
1059            buf.push(c as char);
1060            at_least_one_digit = true;
1061        }
1062
1063        if !at_least_one_digit {
1064            match tri!(self.peek()) {
1065                Some(_) => return Err(self.peek_error(ErrorCode::InvalidNumber)),
1066                None => return Err(self.peek_error(ErrorCode::EofWhileParsingValue)),
1067            }
1068        }
1069
1070        match tri!(self.peek_or_null()) {
1071            b'e' | b'E' => self.scan_exponent(buf),
1072            _ => Ok(()),
1073        }
1074    }
1075
1076    #[cfg(feature = "arbitrary_precision")]
1077    fn scan_exponent(&mut self, buf: &mut String) -> Result<()> {
1078        self.eat_char();
1079        buf.push('e');
1080
1081        match tri!(self.peek_or_null()) {
1082            b'+' => {
1083                self.eat_char();
1084                buf.push('+');
1085            }
1086            b'-' => {
1087                self.eat_char();
1088                buf.push('-');
1089            }
1090            _ => {
1091                buf.push('+');
1092            }
1093        }
1094
1095        // Make sure a digit follows the exponent place.
1096        match tri!(self.scan_or_eof(buf)) {
1097            b'0'..=b'9' => {}
1098            _ => {
1099                return Err(self.error(ErrorCode::InvalidNumber));
1100            }
1101        }
1102
1103        while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) {
1104            self.eat_char();
1105            buf.push(c as char);
1106        }
1107
1108        Ok(())
1109    }
1110
1111    fn parse_object_colon(&mut self) -> Result<()> {
1112        match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1113            Some(b':') => {
1114                self.eat_char();
1115                Ok(())
1116            }
1117            Some(_) => Err(self.peek_error(ErrorCode::ExpectedColon)),
1118            None => Err(self.peek_error(ErrorCode::EofWhileParsingObject)),
1119        }
1120    }
1121
1122    fn end_seq(&mut self) -> Result<()> {
1123        match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1124            Some(b']') => {
1125                self.eat_char();
1126                Ok(())
1127            }
1128            Some(b',') => {
1129                self.eat_char();
1130                match self.parse_whitespace() {
1131                    Ok(Some(b']')) => Err(self.peek_error(ErrorCode::TrailingComma)),
1132                    _ => Err(self.peek_error(ErrorCode::TrailingCharacters)),
1133                }
1134            }
1135            Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)),
1136            None => Err(self.peek_error(ErrorCode::EofWhileParsingList)),
1137        }
1138    }
1139
1140    fn end_map(&mut self) -> Result<()> {
1141        match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1142            Some(b'}') => {
1143                self.eat_char();
1144                Ok(())
1145            }
1146            Some(b',') => Err(self.peek_error(ErrorCode::TrailingComma)),
1147            Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)),
1148            None => Err(self.peek_error(ErrorCode::EofWhileParsingObject)),
1149        }
1150    }
1151
1152    fn ignore_value(&mut self) -> Result<()> {
1153        self.scratch.clear();
1154        let mut enclosing = None;
1155
1156        loop {
1157            let peek = match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1158                Some(b) => b,
1159                None => {
1160                    return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
1161                }
1162            };
1163
1164            let frame = match peek {
1165                b'n' => {
1166                    self.eat_char();
1167                    match self.parse_ident(b"ull") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.parse_ident(b"ull"));
1168                    None
1169                }
1170                b't' => {
1171                    self.eat_char();
1172                    match self.parse_ident(b"rue") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.parse_ident(b"rue"));
1173                    None
1174                }
1175                b'f' => {
1176                    self.eat_char();
1177                    match self.parse_ident(b"alse") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.parse_ident(b"alse"));
1178                    None
1179                }
1180                b'-' => {
1181                    self.eat_char();
1182                    match self.ignore_integer() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.ignore_integer());
1183                    None
1184                }
1185                b'0'..=b'9' => {
1186                    match self.ignore_integer() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.ignore_integer());
1187                    None
1188                }
1189                b'"' => {
1190                    self.eat_char();
1191                    match self.read.ignore_str() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.read.ignore_str());
1192                    None
1193                }
1194                frame @ (b'[' | b'{') => {
1195                    self.scratch.extend(enclosing.take());
1196                    self.eat_char();
1197                    Some(frame)
1198                }
1199                _ => return Err(self.peek_error(ErrorCode::ExpectedSomeValue)),
1200            };
1201
1202            let (mut accept_comma, mut frame) = match frame {
1203                Some(frame) => (false, frame),
1204                None => match enclosing.take() {
1205                    Some(frame) => (true, frame),
1206                    None => match self.scratch.pop() {
1207                        Some(frame) => (true, frame),
1208                        None => return Ok(()),
1209                    },
1210                },
1211            };
1212
1213            loop {
1214                match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1215                    Some(b',') if accept_comma => {
1216                        self.eat_char();
1217                        break;
1218                    }
1219                    Some(b']') if frame == b'[' => {}
1220                    Some(b'}') if frame == b'{' => {}
1221                    Some(_) => {
1222                        if accept_comma {
1223                            return Err(self.peek_error(match frame {
1224                                b'[' => ErrorCode::ExpectedListCommaOrEnd,
1225                                b'{' => ErrorCode::ExpectedObjectCommaOrEnd,
1226                                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1227                            }));
1228                        } else {
1229                            break;
1230                        }
1231                    }
1232                    None => {
1233                        return Err(self.peek_error(match frame {
1234                            b'[' => ErrorCode::EofWhileParsingList,
1235                            b'{' => ErrorCode::EofWhileParsingObject,
1236                            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1237                        }));
1238                    }
1239                }
1240
1241                self.eat_char();
1242                frame = match self.scratch.pop() {
1243                    Some(frame) => frame,
1244                    None => return Ok(()),
1245                };
1246                accept_comma = true;
1247            }
1248
1249            if frame == b'{' {
1250                match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1251                    Some(b'"') => self.eat_char(),
1252                    Some(_) => return Err(self.peek_error(ErrorCode::KeyMustBeAString)),
1253                    None => return Err(self.peek_error(ErrorCode::EofWhileParsingObject)),
1254                }
1255                match self.read.ignore_str() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.read.ignore_str());
1256                match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1257                    Some(b':') => self.eat_char(),
1258                    Some(_) => return Err(self.peek_error(ErrorCode::ExpectedColon)),
1259                    None => return Err(self.peek_error(ErrorCode::EofWhileParsingObject)),
1260                }
1261            }
1262
1263            enclosing = Some(frame);
1264        }
1265    }
1266
1267    fn ignore_integer(&mut self) -> Result<()> {
1268        match match self.next_char_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.next_char_or_null()) {
1269            b'0' => {
1270                // There can be only one leading '0'.
1271                if let b'0'..=b'9' = match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
1272                    return Err(self.peek_error(ErrorCode::InvalidNumber));
1273                }
1274            }
1275            b'1'..=b'9' => {
1276                while let b'0'..=b'9' = match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
1277                    self.eat_char();
1278                }
1279            }
1280            _ => {
1281                return Err(self.error(ErrorCode::InvalidNumber));
1282            }
1283        }
1284
1285        match match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
1286            b'.' => self.ignore_decimal(),
1287            b'e' | b'E' => self.ignore_exponent(),
1288            _ => Ok(()),
1289        }
1290    }
1291
1292    fn ignore_decimal(&mut self) -> Result<()> {
1293        self.eat_char();
1294
1295        let mut at_least_one_digit = false;
1296        while let b'0'..=b'9' = match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
1297            self.eat_char();
1298            at_least_one_digit = true;
1299        }
1300
1301        if !at_least_one_digit {
1302            return Err(self.peek_error(ErrorCode::InvalidNumber));
1303        }
1304
1305        match match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
1306            b'e' | b'E' => self.ignore_exponent(),
1307            _ => Ok(()),
1308        }
1309    }
1310
1311    fn ignore_exponent(&mut self) -> Result<()> {
1312        self.eat_char();
1313
1314        match match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
1315            b'+' | b'-' => self.eat_char(),
1316            _ => {}
1317        }
1318
1319        // Make sure a digit follows the exponent place.
1320        match match self.next_char_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.next_char_or_null()) {
1321            b'0'..=b'9' => {}
1322            _ => {
1323                return Err(self.error(ErrorCode::InvalidNumber));
1324            }
1325        }
1326
1327        while let b'0'..=b'9' = match self.peek_or_null() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.peek_or_null()) {
1328            self.eat_char();
1329        }
1330
1331        Ok(())
1332    }
1333
1334    #[cfg(feature = "raw_value")]
1335    fn deserialize_raw_value<V>(&mut self, visitor: V) -> Result<V::Value>
1336    where
1337        V: de::Visitor<'de>,
1338    {
1339        match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.parse_whitespace());
1340        self.read.begin_raw_buffering();
1341        match self.ignore_value() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.ignore_value());
1342        self.read.end_raw_buffering(visitor)
1343    }
1344}
1345
1346impl FromStr for Number {
1347    type Err = Error;
1348
1349    fn from_str(s: &str) -> result::Result<Self, Self::Err> {
1350        Deserializer::from_str(s)
1351            .parse_any_signed_number()
1352            .map(Into::into)
1353    }
1354}
1355
1356#[cfg(not(feature = "float_roundtrip"))]
1357static POW10: [f64; 309] = [
1358    1e000, 1e001, 1e002, 1e003, 1e004, 1e005, 1e006, 1e007, 1e008, 1e009, //
1359    1e010, 1e011, 1e012, 1e013, 1e014, 1e015, 1e016, 1e017, 1e018, 1e019, //
1360    1e020, 1e021, 1e022, 1e023, 1e024, 1e025, 1e026, 1e027, 1e028, 1e029, //
1361    1e030, 1e031, 1e032, 1e033, 1e034, 1e035, 1e036, 1e037, 1e038, 1e039, //
1362    1e040, 1e041, 1e042, 1e043, 1e044, 1e045, 1e046, 1e047, 1e048, 1e049, //
1363    1e050, 1e051, 1e052, 1e053, 1e054, 1e055, 1e056, 1e057, 1e058, 1e059, //
1364    1e060, 1e061, 1e062, 1e063, 1e064, 1e065, 1e066, 1e067, 1e068, 1e069, //
1365    1e070, 1e071, 1e072, 1e073, 1e074, 1e075, 1e076, 1e077, 1e078, 1e079, //
1366    1e080, 1e081, 1e082, 1e083, 1e084, 1e085, 1e086, 1e087, 1e088, 1e089, //
1367    1e090, 1e091, 1e092, 1e093, 1e094, 1e095, 1e096, 1e097, 1e098, 1e099, //
1368    1e100, 1e101, 1e102, 1e103, 1e104, 1e105, 1e106, 1e107, 1e108, 1e109, //
1369    1e110, 1e111, 1e112, 1e113, 1e114, 1e115, 1e116, 1e117, 1e118, 1e119, //
1370    1e120, 1e121, 1e122, 1e123, 1e124, 1e125, 1e126, 1e127, 1e128, 1e129, //
1371    1e130, 1e131, 1e132, 1e133, 1e134, 1e135, 1e136, 1e137, 1e138, 1e139, //
1372    1e140, 1e141, 1e142, 1e143, 1e144, 1e145, 1e146, 1e147, 1e148, 1e149, //
1373    1e150, 1e151, 1e152, 1e153, 1e154, 1e155, 1e156, 1e157, 1e158, 1e159, //
1374    1e160, 1e161, 1e162, 1e163, 1e164, 1e165, 1e166, 1e167, 1e168, 1e169, //
1375    1e170, 1e171, 1e172, 1e173, 1e174, 1e175, 1e176, 1e177, 1e178, 1e179, //
1376    1e180, 1e181, 1e182, 1e183, 1e184, 1e185, 1e186, 1e187, 1e188, 1e189, //
1377    1e190, 1e191, 1e192, 1e193, 1e194, 1e195, 1e196, 1e197, 1e198, 1e199, //
1378    1e200, 1e201, 1e202, 1e203, 1e204, 1e205, 1e206, 1e207, 1e208, 1e209, //
1379    1e210, 1e211, 1e212, 1e213, 1e214, 1e215, 1e216, 1e217, 1e218, 1e219, //
1380    1e220, 1e221, 1e222, 1e223, 1e224, 1e225, 1e226, 1e227, 1e228, 1e229, //
1381    1e230, 1e231, 1e232, 1e233, 1e234, 1e235, 1e236, 1e237, 1e238, 1e239, //
1382    1e240, 1e241, 1e242, 1e243, 1e244, 1e245, 1e246, 1e247, 1e248, 1e249, //
1383    1e250, 1e251, 1e252, 1e253, 1e254, 1e255, 1e256, 1e257, 1e258, 1e259, //
1384    1e260, 1e261, 1e262, 1e263, 1e264, 1e265, 1e266, 1e267, 1e268, 1e269, //
1385    1e270, 1e271, 1e272, 1e273, 1e274, 1e275, 1e276, 1e277, 1e278, 1e279, //
1386    1e280, 1e281, 1e282, 1e283, 1e284, 1e285, 1e286, 1e287, 1e288, 1e289, //
1387    1e290, 1e291, 1e292, 1e293, 1e294, 1e295, 1e296, 1e297, 1e298, 1e299, //
1388    1e300, 1e301, 1e302, 1e303, 1e304, 1e305, 1e306, 1e307, 1e308,
1389];
1390
1391macro_rules! deserialize_number {
1392    ($method:ident) => {
1393        deserialize_number!($method, deserialize_number);
1394    };
1395
1396    ($method:ident, $using:ident) => {
1397        fn $method<V>(self, visitor: V) -> Result<V::Value>
1398        where
1399            V: de::Visitor<'de>,
1400        {
1401            self.$using(visitor)
1402        }
1403    };
1404}
1405
1406#[cfg(not(feature = "unbounded_depth"))]
1407macro_rules! if_checking_recursion_limit {
1408    ($($body:tt)*) => {
1409        $($body)*
1410    };
1411}
1412
1413#[cfg(feature = "unbounded_depth")]
1414macro_rules! if_checking_recursion_limit {
1415    ($this:ident $($body:tt)*) => {
1416        if !$this.disable_recursion_limit {
1417            $this $($body)*
1418        }
1419    };
1420}
1421
1422macro_rules! check_recursion {
1423    ($this:ident $($body:tt)*) => {
1424        if_checking_recursion_limit! {
1425            $this.remaining_depth -= 1;
1426            if $this.remaining_depth == 0 {
1427                return Err($this.peek_error(ErrorCode::RecursionLimitExceeded));
1428            }
1429        }
1430
1431        $this $($body)*
1432
1433        if_checking_recursion_limit! {
1434            $this.remaining_depth += 1;
1435        }
1436    };
1437}
1438
1439impl<'de, R: Read<'de>> de::Deserializer<'de> for &mut Deserializer<R> {
1440    type Error = Error;
1441
1442    #[inline]
1443    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
1444    where
1445        V: de::Visitor<'de>,
1446    {
1447        let peek = match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1448            Some(b) => b,
1449            None => {
1450                return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
1451            }
1452        };
1453
1454        let value = match peek {
1455            b'n' => {
1456                self.eat_char();
1457                match self.parse_ident(b"ull") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.parse_ident(b"ull"));
1458                visitor.visit_unit()
1459            }
1460            b't' => {
1461                self.eat_char();
1462                match self.parse_ident(b"rue") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.parse_ident(b"rue"));
1463                visitor.visit_bool(true)
1464            }
1465            b'f' => {
1466                self.eat_char();
1467                match self.parse_ident(b"alse") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.parse_ident(b"alse"));
1468                visitor.visit_bool(false)
1469            }
1470            b'-' => {
1471                self.eat_char();
1472                match self.parse_any_number(false) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_any_number(false)).visit(visitor)
1473            }
1474            b'0'..=b'9' => match self.parse_any_number(true) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_any_number(true)).visit(visitor),
1475            b'"' => {
1476                self.eat_char();
1477                self.scratch.clear();
1478                match match self.read.parse_str(&mut self.scratch) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.read.parse_str(&mut self.scratch)) {
1479                    Reference::Borrowed(s) => visitor.visit_borrowed_str(s),
1480                    Reference::Copied(s) => visitor.visit_str(s),
1481                }
1482            }
1483            b'[' => {
1484                if !self.disable_recursion_limit {
    self.remaining_depth -= 1;
    if self.remaining_depth == 0 {
        return Err(self.peek_error(ErrorCode::RecursionLimitExceeded));
    }
}
self.eat_char();
if !self.disable_recursion_limit { self.remaining_depth += 1; }check_recursion! {
1485                    self.eat_char();
1486                    let ret = visitor.visit_seq(SeqAccess::new(self));
1487                }
1488
1489                match (ret, self.end_seq()) {
1490                    (Ok(ret), Ok(())) => Ok(ret),
1491                    (Err(err), _) | (_, Err(err)) => Err(err),
1492                }
1493            }
1494            b'{' => {
1495                if !self.disable_recursion_limit {
    self.remaining_depth -= 1;
    if self.remaining_depth == 0 {
        return Err(self.peek_error(ErrorCode::RecursionLimitExceeded));
    }
}
self.eat_char();
if !self.disable_recursion_limit { self.remaining_depth += 1; }check_recursion! {
1496                    self.eat_char();
1497                    let ret = visitor.visit_map(MapAccess::new(self));
1498                }
1499
1500                match (ret, self.end_map()) {
1501                    (Ok(ret), Ok(())) => Ok(ret),
1502                    (Err(err), _) | (_, Err(err)) => Err(err),
1503                }
1504            }
1505            _ => Err(self.peek_error(ErrorCode::ExpectedSomeValue)),
1506        };
1507
1508        match value {
1509            Ok(value) => Ok(value),
1510            // The de::Error impl creates errors with unknown line and column.
1511            // Fill in the position here by looking at the current index in the
1512            // input. There is no way to tell whether this should call `error`
1513            // or `peek_error` so pick the one that seems correct more often.
1514            // Worst case, the position is off by one character.
1515            Err(err) => Err(self.fix_position(err)),
1516        }
1517    }
1518
1519    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
1520    where
1521        V: de::Visitor<'de>,
1522    {
1523        let peek = match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1524            Some(b) => b,
1525            None => {
1526                return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
1527            }
1528        };
1529
1530        let value = match peek {
1531            b't' => {
1532                self.eat_char();
1533                match self.parse_ident(b"rue") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.parse_ident(b"rue"));
1534                visitor.visit_bool(true)
1535            }
1536            b'f' => {
1537                self.eat_char();
1538                match self.parse_ident(b"alse") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.parse_ident(b"alse"));
1539                visitor.visit_bool(false)
1540            }
1541            _ => Err(self.peek_invalid_type(&visitor)),
1542        };
1543
1544        match value {
1545            Ok(value) => Ok(value),
1546            Err(err) => Err(self.fix_position(err)),
1547        }
1548    }
1549
1550    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_number!(deserialize_i8);
1551    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_number!(deserialize_i16);
1552    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_number!(deserialize_i32);
1553    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_number!(deserialize_i64);
1554    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_number!(deserialize_u8);
1555    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_number!(deserialize_u16);
1556    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_number!(deserialize_u32);
1557    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_number!(deserialize_u64);
1558    #[cfg(not(feature = "float_roundtrip"))]
1559    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_number!(deserialize_f32);
1560    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_number!(deserialize_f64);
1561
1562    #[cfg(feature = "float_roundtrip")]
1563    deserialize_number!(deserialize_f32, do_deserialize_f32);
1564    fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.do_deserialize_i128(visitor)
}deserialize_number!(deserialize_i128, do_deserialize_i128);
1565    fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.do_deserialize_u128(visitor)
}deserialize_number!(deserialize_u128, do_deserialize_u128);
1566
1567    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
1568    where
1569        V: de::Visitor<'de>,
1570    {
1571        self.deserialize_str(visitor)
1572    }
1573
1574    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
1575    where
1576        V: de::Visitor<'de>,
1577    {
1578        let peek = match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1579            Some(b) => b,
1580            None => {
1581                return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
1582            }
1583        };
1584
1585        let value = match peek {
1586            b'"' => {
1587                self.eat_char();
1588                self.scratch.clear();
1589                match match self.read.parse_str(&mut self.scratch) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.read.parse_str(&mut self.scratch)) {
1590                    Reference::Borrowed(s) => visitor.visit_borrowed_str(s),
1591                    Reference::Copied(s) => visitor.visit_str(s),
1592                }
1593            }
1594            _ => Err(self.peek_invalid_type(&visitor)),
1595        };
1596
1597        match value {
1598            Ok(value) => Ok(value),
1599            Err(err) => Err(self.fix_position(err)),
1600        }
1601    }
1602
1603    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
1604    where
1605        V: de::Visitor<'de>,
1606    {
1607        self.deserialize_str(visitor)
1608    }
1609
1610    /// Parses a JSON string as bytes. Note that this function does not check
1611    /// whether the bytes represent a valid UTF-8 string.
1612    ///
1613    /// The relevant part of the JSON specification is Section 8.2 of [RFC
1614    /// 7159]:
1615    ///
1616    /// > When all the strings represented in a JSON text are composed entirely
1617    /// > of Unicode characters (however escaped), then that JSON text is
1618    /// > interoperable in the sense that all software implementations that
1619    /// > parse it will agree on the contents of names and of string values in
1620    /// > objects and arrays.
1621    /// >
1622    /// > However, the ABNF in this specification allows member names and string
1623    /// > values to contain bit sequences that cannot encode Unicode characters;
1624    /// > for example, "\uDEAD" (a single unpaired UTF-16 surrogate). Instances
1625    /// > of this have been observed, for example, when a library truncates a
1626    /// > UTF-16 string without checking whether the truncation split a
1627    /// > surrogate pair.  The behavior of software that receives JSON texts
1628    /// > containing such values is unpredictable; for example, implementations
1629    /// > might return different values for the length of a string value or even
1630    /// > suffer fatal runtime exceptions.
1631    ///
1632    /// [RFC 7159]: https://tools.ietf.org/html/rfc7159
1633    ///
1634    /// The behavior of serde_json is specified to fail on non-UTF-8 strings
1635    /// when deserializing into Rust UTF-8 string types such as String, and
1636    /// succeed with the bytes representing the [WTF-8] encoding of code points
1637    /// when deserializing using this method.
1638    ///
1639    /// [WTF-8]: https://simonsapin.github.io/wtf-8
1640    ///
1641    /// Escape sequences are processed as usual, and for `\uXXXX` escapes it is
1642    /// still checked if the hex number represents a valid Unicode code point.
1643    ///
1644    /// # Examples
1645    ///
1646    /// You can use this to parse JSON strings containing invalid UTF-8 bytes,
1647    /// or unpaired surrogates.
1648    ///
1649    /// ```
1650    /// use serde_bytes::ByteBuf;
1651    ///
1652    /// fn look_at_bytes() -> Result<(), serde_json::Error> {
1653    ///     let json_data = b"\"some bytes: \xe5\x00\xe5\"";
1654    ///     let bytes: ByteBuf = serde_json::from_slice(json_data)?;
1655    ///
1656    ///     assert_eq!(b'\xe5', bytes[12]);
1657    ///     assert_eq!(b'\0', bytes[13]);
1658    ///     assert_eq!(b'\xe5', bytes[14]);
1659    ///
1660    ///     Ok(())
1661    /// }
1662    /// #
1663    /// # look_at_bytes().unwrap();
1664    /// ```
1665    ///
1666    /// Backslash escape sequences like `\n` are still interpreted and required
1667    /// to be valid. `\u` escape sequences are required to represent a valid
1668    /// Unicode code point or lone surrogate.
1669    ///
1670    /// ```
1671    /// use serde_bytes::ByteBuf;
1672    ///
1673    /// fn look_at_bytes() -> Result<(), serde_json::Error> {
1674    ///     let json_data = b"\"lone surrogate: \\uD801\"";
1675    ///     let bytes: ByteBuf = serde_json::from_slice(json_data)?;
1676    ///     let expected = b"lone surrogate: \xED\xA0\x81";
1677    ///     assert_eq!(expected, bytes.as_slice());
1678    ///     Ok(())
1679    /// }
1680    /// #
1681    /// # look_at_bytes();
1682    /// ```
1683    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
1684    where
1685        V: de::Visitor<'de>,
1686    {
1687        let peek = match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1688            Some(b) => b,
1689            None => {
1690                return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
1691            }
1692        };
1693
1694        let value = match peek {
1695            b'"' => {
1696                self.eat_char();
1697                self.scratch.clear();
1698                match match self.read.parse_str_raw(&mut self.scratch) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.read.parse_str_raw(&mut self.scratch)) {
1699                    Reference::Borrowed(b) => visitor.visit_borrowed_bytes(b),
1700                    Reference::Copied(b) => visitor.visit_bytes(b),
1701                }
1702            }
1703            b'[' => self.deserialize_seq(visitor),
1704            _ => Err(self.peek_invalid_type(&visitor)),
1705        };
1706
1707        match value {
1708            Ok(value) => Ok(value),
1709            Err(err) => Err(self.fix_position(err)),
1710        }
1711    }
1712
1713    #[inline]
1714    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
1715    where
1716        V: de::Visitor<'de>,
1717    {
1718        self.deserialize_bytes(visitor)
1719    }
1720
1721    /// Parses a `null` as a None, and any other values as a `Some(...)`.
1722    #[inline]
1723    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
1724    where
1725        V: de::Visitor<'de>,
1726    {
1727        match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1728            Some(b'n') => {
1729                self.eat_char();
1730                match self.parse_ident(b"ull") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.parse_ident(b"ull"));
1731                visitor.visit_none()
1732            }
1733            _ => visitor.visit_some(self),
1734        }
1735    }
1736
1737    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
1738    where
1739        V: de::Visitor<'de>,
1740    {
1741        let peek = match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1742            Some(b) => b,
1743            None => {
1744                return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
1745            }
1746        };
1747
1748        let value = match peek {
1749            b'n' => {
1750                self.eat_char();
1751                match self.parse_ident(b"ull") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.parse_ident(b"ull"));
1752                visitor.visit_unit()
1753            }
1754            _ => Err(self.peek_invalid_type(&visitor)),
1755        };
1756
1757        match value {
1758            Ok(value) => Ok(value),
1759            Err(err) => Err(self.fix_position(err)),
1760        }
1761    }
1762
1763    fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
1764    where
1765        V: de::Visitor<'de>,
1766    {
1767        self.deserialize_unit(visitor)
1768    }
1769
1770    /// Parses a newtype struct as the underlying value.
1771    #[inline]
1772    fn deserialize_newtype_struct<V>(self, name: &str, visitor: V) -> Result<V::Value>
1773    where
1774        V: de::Visitor<'de>,
1775    {
1776        #[cfg(feature = "raw_value")]
1777        {
1778            if name == crate::raw::TOKEN {
1779                return self.deserialize_raw_value(visitor);
1780            }
1781        }
1782
1783        let _ = name;
1784        visitor.visit_newtype_struct(self)
1785    }
1786
1787    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
1788    where
1789        V: de::Visitor<'de>,
1790    {
1791        let peek = match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1792            Some(b) => b,
1793            None => {
1794                return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
1795            }
1796        };
1797
1798        let value = match peek {
1799            b'[' => {
1800                if !self.disable_recursion_limit {
    self.remaining_depth -= 1;
    if self.remaining_depth == 0 {
        return Err(self.peek_error(ErrorCode::RecursionLimitExceeded));
    }
}
self.eat_char();
if !self.disable_recursion_limit { self.remaining_depth += 1; }check_recursion! {
1801                    self.eat_char();
1802                    let ret = visitor.visit_seq(SeqAccess::new(self));
1803                }
1804
1805                match (ret, self.end_seq()) {
1806                    (Ok(ret), Ok(())) => Ok(ret),
1807                    (Err(err), _) | (_, Err(err)) => Err(err),
1808                }
1809            }
1810            _ => Err(self.peek_invalid_type(&visitor)),
1811        };
1812
1813        match value {
1814            Ok(value) => Ok(value),
1815            Err(err) => Err(self.fix_position(err)),
1816        }
1817    }
1818
1819    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value>
1820    where
1821        V: de::Visitor<'de>,
1822    {
1823        self.deserialize_seq(visitor)
1824    }
1825
1826    fn deserialize_tuple_struct<V>(
1827        self,
1828        _name: &'static str,
1829        _len: usize,
1830        visitor: V,
1831    ) -> Result<V::Value>
1832    where
1833        V: de::Visitor<'de>,
1834    {
1835        self.deserialize_seq(visitor)
1836    }
1837
1838    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
1839    where
1840        V: de::Visitor<'de>,
1841    {
1842        let peek = match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1843            Some(b) => b,
1844            None => {
1845                return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
1846            }
1847        };
1848
1849        let value = match peek {
1850            b'{' => {
1851                if !self.disable_recursion_limit {
    self.remaining_depth -= 1;
    if self.remaining_depth == 0 {
        return Err(self.peek_error(ErrorCode::RecursionLimitExceeded));
    }
}
self.eat_char();
if !self.disable_recursion_limit { self.remaining_depth += 1; }check_recursion! {
1852                    self.eat_char();
1853                    let ret = visitor.visit_map(MapAccess::new(self));
1854                }
1855
1856                match (ret, self.end_map()) {
1857                    (Ok(ret), Ok(())) => Ok(ret),
1858                    (Err(err), _) | (_, Err(err)) => Err(err),
1859                }
1860            }
1861            _ => Err(self.peek_invalid_type(&visitor)),
1862        };
1863
1864        match value {
1865            Ok(value) => Ok(value),
1866            Err(err) => Err(self.fix_position(err)),
1867        }
1868    }
1869
1870    fn deserialize_struct<V>(
1871        self,
1872        _name: &'static str,
1873        _fields: &'static [&'static str],
1874        visitor: V,
1875    ) -> Result<V::Value>
1876    where
1877        V: de::Visitor<'de>,
1878    {
1879        let peek = match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1880            Some(b) => b,
1881            None => {
1882                return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
1883            }
1884        };
1885
1886        let value = match peek {
1887            b'[' => {
1888                if !self.disable_recursion_limit {
    self.remaining_depth -= 1;
    if self.remaining_depth == 0 {
        return Err(self.peek_error(ErrorCode::RecursionLimitExceeded));
    }
}
self.eat_char();
if !self.disable_recursion_limit { self.remaining_depth += 1; }check_recursion! {
1889                    self.eat_char();
1890                    let ret = visitor.visit_seq(SeqAccess::new(self));
1891                }
1892
1893                match (ret, self.end_seq()) {
1894                    (Ok(ret), Ok(())) => Ok(ret),
1895                    (Err(err), _) | (_, Err(err)) => Err(err),
1896                }
1897            }
1898            b'{' => {
1899                if !self.disable_recursion_limit {
    self.remaining_depth -= 1;
    if self.remaining_depth == 0 {
        return Err(self.peek_error(ErrorCode::RecursionLimitExceeded));
    }
}
self.eat_char();
if !self.disable_recursion_limit { self.remaining_depth += 1; }check_recursion! {
1900                    self.eat_char();
1901                    let ret = visitor.visit_map(MapAccess::new(self));
1902                }
1903
1904                match (ret, self.end_map()) {
1905                    (Ok(ret), Ok(())) => Ok(ret),
1906                    (Err(err), _) | (_, Err(err)) => Err(err),
1907                }
1908            }
1909            _ => Err(self.peek_invalid_type(&visitor)),
1910        };
1911
1912        match value {
1913            Ok(value) => Ok(value),
1914            Err(err) => Err(self.fix_position(err)),
1915        }
1916    }
1917
1918    /// Parses an enum as an object like `{"$KEY":$VALUE}`, where $VALUE is either a straight
1919    /// value, a `[..]`, or a `{..}`.
1920    #[inline]
1921    fn deserialize_enum<V>(
1922        self,
1923        _name: &str,
1924        _variants: &'static [&'static str],
1925        visitor: V,
1926    ) -> Result<V::Value>
1927    where
1928        V: de::Visitor<'de>,
1929    {
1930        match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1931            Some(b'{') => {
1932                if !self.disable_recursion_limit {
    self.remaining_depth -= 1;
    if self.remaining_depth == 0 {
        return Err(self.peek_error(ErrorCode::RecursionLimitExceeded));
    }
}
self.eat_char();
if !self.disable_recursion_limit { self.remaining_depth += 1; }check_recursion! {
1933                    self.eat_char();
1934                    let ret = visitor.visit_enum(VariantAccess::new(self));
1935                }
1936                let value = match ret {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(ret);
1937
1938                match match self.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.parse_whitespace()) {
1939                    Some(b'}') => {
1940                        self.eat_char();
1941                        Ok(value)
1942                    }
1943                    Some(_) => Err(self.error(ErrorCode::ExpectedSomeValue)),
1944                    None => Err(self.error(ErrorCode::EofWhileParsingObject)),
1945                }
1946            }
1947            Some(b'"') => visitor.visit_enum(UnitVariantAccess::new(self)),
1948            Some(_) => Err(self.peek_error(ErrorCode::ExpectedSomeValue)),
1949            None => Err(self.peek_error(ErrorCode::EofWhileParsingValue)),
1950        }
1951    }
1952
1953    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>
1954    where
1955        V: de::Visitor<'de>,
1956    {
1957        self.deserialize_str(visitor)
1958    }
1959
1960    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
1961    where
1962        V: de::Visitor<'de>,
1963    {
1964        match self.ignore_value() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.ignore_value());
1965        visitor.visit_unit()
1966    }
1967}
1968
1969struct SeqAccess<'a, R: 'a> {
1970    de: &'a mut Deserializer<R>,
1971    first: bool,
1972}
1973
1974impl<'a, R: 'a> SeqAccess<'a, R> {
1975    fn new(de: &'a mut Deserializer<R>) -> Self {
1976        SeqAccess { de, first: true }
1977    }
1978}
1979
1980impl<'de, 'a, R: Read<'de> + 'a> de::SeqAccess<'de> for SeqAccess<'a, R> {
1981    type Error = Error;
1982
1983    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
1984    where
1985        T: de::DeserializeSeed<'de>,
1986    {
1987        fn has_next_element<'de, 'a, R: Read<'de> + 'a>(
1988            seq: &mut SeqAccess<'a, R>,
1989        ) -> Result<bool> {
1990            let peek = match match seq.de.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(seq.de.parse_whitespace()) {
1991                Some(b) => b,
1992                None => {
1993                    return Err(seq.de.peek_error(ErrorCode::EofWhileParsingList));
1994                }
1995            };
1996
1997            if peek == b']' {
1998                Ok(false)
1999            } else if seq.first {
2000                seq.first = false;
2001                Ok(true)
2002            } else if peek == b',' {
2003                seq.de.eat_char();
2004                match match seq.de.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(seq.de.parse_whitespace()) {
2005                    Some(b']') => Err(seq.de.peek_error(ErrorCode::TrailingComma)),
2006                    Some(_) => Ok(true),
2007                    None => Err(seq.de.peek_error(ErrorCode::EofWhileParsingValue)),
2008                }
2009            } else {
2010                Err(seq.de.peek_error(ErrorCode::ExpectedListCommaOrEnd))
2011            }
2012        }
2013
2014        if match has_next_element(self) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(has_next_element(self)) {
2015            Ok(Some(match seed.deserialize(&mut *self.de) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(seed.deserialize(&mut *self.de))))
2016        } else {
2017            Ok(None)
2018        }
2019    }
2020}
2021
2022struct MapAccess<'a, R: 'a> {
2023    de: &'a mut Deserializer<R>,
2024    first: bool,
2025}
2026
2027impl<'a, R: 'a> MapAccess<'a, R> {
2028    fn new(de: &'a mut Deserializer<R>) -> Self {
2029        MapAccess { de, first: true }
2030    }
2031}
2032
2033impl<'de, 'a, R: Read<'de> + 'a> de::MapAccess<'de> for MapAccess<'a, R> {
2034    type Error = Error;
2035
2036    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
2037    where
2038        K: de::DeserializeSeed<'de>,
2039    {
2040        fn has_next_key<'de, 'a, R: Read<'de> + 'a>(map: &mut MapAccess<'a, R>) -> Result<bool> {
2041            let peek = match match map.de.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(map.de.parse_whitespace()) {
2042                Some(b) => b,
2043                None => {
2044                    return Err(map.de.peek_error(ErrorCode::EofWhileParsingObject));
2045                }
2046            };
2047
2048            if peek == b'}' {
2049                Ok(false)
2050            } else if map.first {
2051                map.first = false;
2052                if peek == b'"' {
2053                    Ok(true)
2054                } else {
2055                    Err(map.de.peek_error(ErrorCode::KeyMustBeAString))
2056                }
2057            } else if peek == b',' {
2058                map.de.eat_char();
2059                match match map.de.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(map.de.parse_whitespace()) {
2060                    Some(b'"') => Ok(true),
2061                    Some(b'}') => Err(map.de.peek_error(ErrorCode::TrailingComma)),
2062                    Some(_) => Err(map.de.peek_error(ErrorCode::KeyMustBeAString)),
2063                    None => Err(map.de.peek_error(ErrorCode::EofWhileParsingValue)),
2064                }
2065            } else {
2066                Err(map.de.peek_error(ErrorCode::ExpectedObjectCommaOrEnd))
2067            }
2068        }
2069
2070        if match has_next_key(self) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(has_next_key(self)) {
2071            Ok(Some(match seed.deserialize(MapKey { de: &mut *self.de }) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(seed.deserialize(MapKey { de: &mut *self.de }))))
2072        } else {
2073            Ok(None)
2074        }
2075    }
2076
2077    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
2078    where
2079        V: de::DeserializeSeed<'de>,
2080    {
2081        match self.de.parse_object_colon() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.de.parse_object_colon());
2082
2083        seed.deserialize(&mut *self.de)
2084    }
2085}
2086
2087struct VariantAccess<'a, R: 'a> {
2088    de: &'a mut Deserializer<R>,
2089}
2090
2091impl<'a, R: 'a> VariantAccess<'a, R> {
2092    fn new(de: &'a mut Deserializer<R>) -> Self {
2093        VariantAccess { de }
2094    }
2095}
2096
2097impl<'de, 'a, R: Read<'de> + 'a> de::EnumAccess<'de> for VariantAccess<'a, R> {
2098    type Error = Error;
2099    type Variant = Self;
2100
2101    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)>
2102    where
2103        V: de::DeserializeSeed<'de>,
2104    {
2105        match match self.de.parse_whitespace() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.de.parse_whitespace()) {
2106            Some(b'"') => {}
2107            Some(b'}') => return Err(self.de.peek_error(ErrorCode::ExpectedSomeValue)),
2108            Some(_) => return Err(self.de.peek_error(ErrorCode::KeyMustBeAString)),
2109            None => return Err(self.de.peek_error(ErrorCode::EofWhileParsingObject)),
2110        }
2111
2112        let val = match seed.deserialize(MapKey { de: &mut *self.de }) {
2113            Ok(value) => value,
2114            Err(err) => return Err(self.de.fix_position(err)),
2115        };
2116        match self.de.parse_object_colon() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.de.parse_object_colon());
2117        Ok((val, self))
2118    }
2119}
2120
2121impl<'de, 'a, R: Read<'de> + 'a> de::VariantAccess<'de> for VariantAccess<'a, R> {
2122    type Error = Error;
2123
2124    fn unit_variant(self) -> Result<()> {
2125        de::Deserialize::deserialize(self.de)
2126    }
2127
2128    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
2129    where
2130        T: de::DeserializeSeed<'de>,
2131    {
2132        seed.deserialize(self.de)
2133    }
2134
2135    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
2136    where
2137        V: de::Visitor<'de>,
2138    {
2139        de::Deserializer::deserialize_seq(self.de, visitor)
2140    }
2141
2142    fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value>
2143    where
2144        V: de::Visitor<'de>,
2145    {
2146        de::Deserializer::deserialize_struct(self.de, "", fields, visitor)
2147    }
2148}
2149
2150struct UnitVariantAccess<'a, R: 'a> {
2151    de: &'a mut Deserializer<R>,
2152}
2153
2154impl<'a, R: 'a> UnitVariantAccess<'a, R> {
2155    fn new(de: &'a mut Deserializer<R>) -> Self {
2156        UnitVariantAccess { de }
2157    }
2158}
2159
2160impl<'de, 'a, R: Read<'de> + 'a> de::EnumAccess<'de> for UnitVariantAccess<'a, R> {
2161    type Error = Error;
2162    type Variant = Self;
2163
2164    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)>
2165    where
2166        V: de::DeserializeSeed<'de>,
2167    {
2168        let variant = match seed.deserialize(&mut *self.de) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(seed.deserialize(&mut *self.de));
2169        Ok((variant, self))
2170    }
2171}
2172
2173impl<'de, 'a, R: Read<'de> + 'a> de::VariantAccess<'de> for UnitVariantAccess<'a, R> {
2174    type Error = Error;
2175
2176    fn unit_variant(self) -> Result<()> {
2177        Ok(())
2178    }
2179
2180    fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value>
2181    where
2182        T: de::DeserializeSeed<'de>,
2183    {
2184        Err(de::Error::invalid_type(
2185            Unexpected::UnitVariant,
2186            &"newtype variant",
2187        ))
2188    }
2189
2190    fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value>
2191    where
2192        V: de::Visitor<'de>,
2193    {
2194        Err(de::Error::invalid_type(
2195            Unexpected::UnitVariant,
2196            &"tuple variant",
2197        ))
2198    }
2199
2200    fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value>
2201    where
2202        V: de::Visitor<'de>,
2203    {
2204        Err(de::Error::invalid_type(
2205            Unexpected::UnitVariant,
2206            &"struct variant",
2207        ))
2208    }
2209}
2210
2211/// Only deserialize from this after peeking a '"' byte! Otherwise it may
2212/// deserialize invalid JSON successfully.
2213struct MapKey<'a, R: 'a> {
2214    de: &'a mut Deserializer<R>,
2215}
2216
2217macro_rules! deserialize_numeric_key {
2218    ($method:ident) => {
2219        fn $method<V>(self, visitor: V) -> Result<V::Value>
2220        where
2221            V: de::Visitor<'de>,
2222        {
2223            self.deserialize_number(visitor)
2224        }
2225    };
2226
2227    ($method:ident, $delegate:ident) => {
2228        fn $method<V>(self, visitor: V) -> Result<V::Value>
2229        where
2230            V: de::Visitor<'de>,
2231        {
2232            self.de.eat_char();
2233
2234            match tri!(self.de.peek()) {
2235                Some(b'0'..=b'9' | b'-') => {}
2236                _ => return Err(self.de.error(ErrorCode::ExpectedNumericKey)),
2237            }
2238
2239            let value = tri!(self.de.$delegate(visitor));
2240
2241            match tri!(self.de.peek()) {
2242                Some(b'"') => self.de.eat_char(),
2243                _ => return Err(self.de.peek_error(ErrorCode::ExpectedDoubleQuote)),
2244            }
2245
2246            Ok(value)
2247        }
2248    };
2249}
2250
2251impl<'de, 'a, R> MapKey<'a, R>
2252where
2253    R: Read<'de>,
2254{
2255    fn deserialize_number<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.de.eat_char();
    match match self.de.peek() {
            core::result::Result::Ok(val) => val,
            core::result::Result::Err(err) =>
                return core::result::Result::Err(err),
        } {
        Some(b'0'..=b'9' | b'-') => {}
        _ => return Err(self.de.error(ErrorCode::ExpectedNumericKey)),
    }
    let value =
        match self.de.deserialize_number(visitor) {
            core::result::Result::Ok(val) => val,
            core::result::Result::Err(err) =>
                return core::result::Result::Err(err),
        };
    match match self.de.peek() {
            core::result::Result::Ok(val) => val,
            core::result::Result::Err(err) =>
                return core::result::Result::Err(err),
        } {
        Some(b'"') => self.de.eat_char(),
        _ => return Err(self.de.peek_error(ErrorCode::ExpectedDoubleQuote)),
    }
    Ok(value)
}deserialize_numeric_key!(deserialize_number, deserialize_number);
2256}
2257
2258impl<'de, 'a, R> de::Deserializer<'de> for MapKey<'a, R>
2259where
2260    R: Read<'de>,
2261{
2262    type Error = Error;
2263
2264    #[inline]
2265    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
2266    where
2267        V: de::Visitor<'de>,
2268    {
2269        // PROBE (brick B6): one per object key the JSON side hands over,
2270        // whatever the visitor does with it.
2271        crate::counters::add(&crate::counters::KEYS, 1);
2272        self.de.eat_char();
2273        self.de.scratch.clear();
2274        match match self.de.read.parse_str(&mut self.de.scratch) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.de.read.parse_str(&mut self.de.scratch)) {
2275            Reference::Borrowed(s) => visitor.visit_borrowed_str(s),
2276            Reference::Copied(s) => visitor.visit_str(s),
2277        }
2278    }
2279
2280    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_numeric_key!(deserialize_i8);
2281    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_numeric_key!(deserialize_i16);
2282    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_numeric_key!(deserialize_i32);
2283    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_numeric_key!(deserialize_i64);
2284    fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.de.eat_char();
    match match self.de.peek() {
            core::result::Result::Ok(val) => val,
            core::result::Result::Err(err) =>
                return core::result::Result::Err(err),
        } {
        Some(b'0'..=b'9' | b'-') => {}
        _ => return Err(self.de.error(ErrorCode::ExpectedNumericKey)),
    }
    let value =
        match self.de.deserialize_i128(visitor) {
            core::result::Result::Ok(val) => val,
            core::result::Result::Err(err) =>
                return core::result::Result::Err(err),
        };
    match match self.de.peek() {
            core::result::Result::Ok(val) => val,
            core::result::Result::Err(err) =>
                return core::result::Result::Err(err),
        } {
        Some(b'"') => self.de.eat_char(),
        _ => return Err(self.de.peek_error(ErrorCode::ExpectedDoubleQuote)),
    }
    Ok(value)
}deserialize_numeric_key!(deserialize_i128, deserialize_i128);
2285    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_numeric_key!(deserialize_u8);
2286    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_numeric_key!(deserialize_u16);
2287    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_numeric_key!(deserialize_u32);
2288    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_numeric_key!(deserialize_u64);
2289    fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.de.eat_char();
    match match self.de.peek() {
            core::result::Result::Ok(val) => val,
            core::result::Result::Err(err) =>
                return core::result::Result::Err(err),
        } {
        Some(b'0'..=b'9' | b'-') => {}
        _ => return Err(self.de.error(ErrorCode::ExpectedNumericKey)),
    }
    let value =
        match self.de.deserialize_u128(visitor) {
            core::result::Result::Ok(val) => val,
            core::result::Result::Err(err) =>
                return core::result::Result::Err(err),
        };
    match match self.de.peek() {
            core::result::Result::Ok(val) => val,
            core::result::Result::Err(err) =>
                return core::result::Result::Err(err),
        } {
        Some(b'"') => self.de.eat_char(),
        _ => return Err(self.de.peek_error(ErrorCode::ExpectedDoubleQuote)),
    }
    Ok(value)
}deserialize_numeric_key!(deserialize_u128, deserialize_u128);
2290    #[cfg(not(feature = "float_roundtrip"))]
2291    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_numeric_key!(deserialize_f32);
2292    #[cfg(feature = "float_roundtrip")]
2293    deserialize_numeric_key!(deserialize_f32, deserialize_f32);
2294    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value> where
    V: de::Visitor<'de> {
    self.deserialize_number(visitor)
}deserialize_numeric_key!(deserialize_f64);
2295
2296    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
2297    where
2298        V: de::Visitor<'de>,
2299    {
2300        self.de.eat_char();
2301
2302        let peek = match match self.de.next_char() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.de.next_char()) {
2303            Some(b) => b,
2304            None => {
2305                return Err(self.de.peek_error(ErrorCode::EofWhileParsingValue));
2306            }
2307        };
2308
2309        let value = match peek {
2310            b't' => {
2311                match self.de.parse_ident(b"rue\"") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.de.parse_ident(b"rue\""));
2312                visitor.visit_bool(true)
2313            }
2314            b'f' => {
2315                match self.de.parse_ident(b"alse\"") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.de.parse_ident(b"alse\""));
2316                visitor.visit_bool(false)
2317            }
2318            _ => {
2319                self.de.scratch.clear();
2320                let s = match self.de.read.parse_str(&mut self.de.scratch) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.de.read.parse_str(&mut self.de.scratch));
2321                Err(de::Error::invalid_type(Unexpected::Str(&s), &visitor))
2322            }
2323        };
2324
2325        match value {
2326            Ok(value) => Ok(value),
2327            Err(err) => Err(self.de.fix_position(err)),
2328        }
2329    }
2330
2331    #[inline]
2332    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
2333    where
2334        V: de::Visitor<'de>,
2335    {
2336        // Map keys cannot be null.
2337        visitor.visit_some(self)
2338    }
2339
2340    #[inline]
2341    fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value>
2342    where
2343        V: de::Visitor<'de>,
2344    {
2345        #[cfg(feature = "raw_value")]
2346        {
2347            if name == crate::raw::TOKEN {
2348                return self.de.deserialize_raw_value(visitor);
2349            }
2350        }
2351
2352        let _ = name;
2353        visitor.visit_newtype_struct(self)
2354    }
2355
2356    #[inline]
2357    fn deserialize_enum<V>(
2358        self,
2359        name: &'static str,
2360        variants: &'static [&'static str],
2361        visitor: V,
2362    ) -> Result<V::Value>
2363    where
2364        V: de::Visitor<'de>,
2365    {
2366        self.de.deserialize_enum(name, variants, visitor)
2367    }
2368
2369    #[inline]
2370    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
2371    where
2372        V: de::Visitor<'de>,
2373    {
2374        self.de.deserialize_bytes(visitor)
2375    }
2376
2377    #[inline]
2378    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
2379    where
2380        V: de::Visitor<'de>,
2381    {
2382        self.de.deserialize_bytes(visitor)
2383    }
2384
2385    #[inline]
fn deserialize_ignored_any<V>(self, visitor: V)
    ->
        ::serde_core::__private::Result<V::Value,
        <Self as ::serde_core::de::Deserializer<'de>>::Error> where
    V: ::serde_core::de::Visitor<'de> {
    self.deserialize_any(visitor)
}forward_to_deserialize_any! {
2386        char str string unit unit_struct seq tuple tuple_struct map struct
2387        identifier ignored_any
2388    }
2389}
2390
2391//////////////////////////////////////////////////////////////////////////////
2392
2393/// Iterator that deserializes a stream into multiple JSON values.
2394///
2395/// A stream deserializer can be created from any JSON deserializer using the
2396/// `Deserializer::into_iter` method.
2397///
2398/// The data can consist of any JSON value. Values need to be a self-delineating value e.g.
2399/// arrays, objects, or strings, or be followed by whitespace or a self-delineating value.
2400///
2401/// ```
2402/// use serde_json::{Deserializer, Value};
2403///
2404/// fn main() {
2405///     let data = "{\"k\": 3}1\"cool\"\"stuff\" 3{}  [0, 1, 2]";
2406///
2407///     let stream = Deserializer::from_str(data).into_iter::<Value>();
2408///
2409///     for value in stream {
2410///         println!("{}", value.unwrap());
2411///     }
2412/// }
2413/// ```
2414pub struct StreamDeserializer<'de, R, T> {
2415    de: Deserializer<R>,
2416    offset: usize,
2417    failed: bool,
2418    output: PhantomData<T>,
2419    lifetime: PhantomData<&'de ()>,
2420}
2421
2422impl<'de, R, T> StreamDeserializer<'de, R, T>
2423where
2424    R: read::Read<'de>,
2425    T: de::Deserialize<'de>,
2426{
2427    /// Create a JSON stream deserializer from one of the possible serde_json
2428    /// input sources.
2429    ///
2430    /// Typically it is more convenient to use one of these methods instead:
2431    ///
2432    ///   - Deserializer::from_str(...).into_iter()
2433    ///   - Deserializer::from_slice(...).into_iter()
2434    ///   - Deserializer::from_reader(...).into_iter()
2435    pub fn new(read: R) -> Self {
2436        let offset = read.byte_offset();
2437        StreamDeserializer {
2438            de: Deserializer::new(read),
2439            offset,
2440            failed: false,
2441            output: PhantomData,
2442            lifetime: PhantomData,
2443        }
2444    }
2445
2446    /// Returns the number of bytes so far deserialized into a successful `T`.
2447    ///
2448    /// If a stream deserializer returns an EOF error, new data can be joined to
2449    /// `old_data[stream.byte_offset()..]` to try again.
2450    ///
2451    /// ```
2452    /// let data = b"[0] [1] [";
2453    ///
2454    /// let de = serde_json::Deserializer::from_slice(data);
2455    /// let mut stream = de.into_iter::<Vec<i32>>();
2456    /// assert_eq!(0, stream.byte_offset());
2457    ///
2458    /// println!("{:?}", stream.next()); // [0]
2459    /// assert_eq!(3, stream.byte_offset());
2460    ///
2461    /// println!("{:?}", stream.next()); // [1]
2462    /// assert_eq!(7, stream.byte_offset());
2463    ///
2464    /// println!("{:?}", stream.next()); // error
2465    /// assert_eq!(8, stream.byte_offset());
2466    ///
2467    /// // If err.is_eof(), can join the remaining data to new data and continue.
2468    /// let remaining = &data[stream.byte_offset()..];
2469    /// ```
2470    ///
2471    /// *Note:* In the future this method may be changed to return the number of
2472    /// bytes so far deserialized into a successful T *or* syntactically valid
2473    /// JSON skipped over due to a type error. See [serde-rs/json#70] for an
2474    /// example illustrating this.
2475    ///
2476    /// [serde-rs/json#70]: https://github.com/serde-rs/json/issues/70
2477    pub fn byte_offset(&self) -> usize {
2478        self.offset
2479    }
2480
2481    fn peek_end_of_value(&mut self) -> Result<()> {
2482        match match self.de.peek() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(self.de.peek()) {
2483            Some(b' ' | b'\n' | b'\t' | b'\r' | b'"' | b'[' | b']' | b'{' | b'}' | b',' | b':')
2484            | None => Ok(()),
2485            Some(_) => {
2486                let position = self.de.read.peek_position();
2487                Err(Error::syntax(
2488                    ErrorCode::TrailingCharacters,
2489                    position.line,
2490                    position.column,
2491                ))
2492            }
2493        }
2494    }
2495}
2496
2497impl<'de, R, T> Iterator for StreamDeserializer<'de, R, T>
2498where
2499    R: Read<'de>,
2500    T: de::Deserialize<'de>,
2501{
2502    type Item = Result<T>;
2503
2504    fn next(&mut self) -> Option<Result<T>> {
2505        if R::should_early_return_if_failed && self.failed {
2506            return None;
2507        }
2508
2509        // skip whitespaces, if any
2510        // this helps with trailing whitespaces, since whitespaces between
2511        // values are handled for us.
2512        match self.de.parse_whitespace() {
2513            Ok(None) => {
2514                self.offset = self.de.read.byte_offset();
2515                None
2516            }
2517            Ok(Some(b)) => {
2518                // If the value does not have a clear way to show the end of the value
2519                // (like numbers, null, true etc.) we have to look for whitespace or
2520                // the beginning of a self-delineated value.
2521                let self_delineated_value = match b {
2522                    b'[' | b'"' | b'{' => true,
2523                    _ => false,
2524                };
2525                self.offset = self.de.read.byte_offset();
2526                let result = de::Deserialize::deserialize(&mut self.de);
2527
2528                Some(match result {
2529                    Ok(value) => {
2530                        self.offset = self.de.read.byte_offset();
2531                        if self_delineated_value {
2532                            Ok(value)
2533                        } else {
2534                            self.peek_end_of_value().map(|()| value)
2535                        }
2536                    }
2537                    Err(e) => {
2538                        self.de.read.set_failed(&mut self.failed);
2539                        Err(e)
2540                    }
2541                })
2542            }
2543            Err(e) => {
2544                self.de.read.set_failed(&mut self.failed);
2545                Some(Err(e))
2546            }
2547        }
2548    }
2549}
2550
2551impl<'de, R, T> FusedIterator for StreamDeserializer<'de, R, T>
2552where
2553    R: Read<'de> + Fused,
2554    T: de::Deserialize<'de>,
2555{
2556}
2557
2558//////////////////////////////////////////////////////////////////////////////
2559
2560fn from_trait<'de, R, T>(read: R) -> Result<T>
2561where
2562    R: Read<'de>,
2563    T: de::Deserialize<'de>,
2564{
2565    let mut de = Deserializer::new(read);
2566    let value = match de::Deserialize::deserialize(&mut de) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
}tri!(de::Deserialize::deserialize(&mut de));
2567
2568    // Make sure the whole stream has been consumed.
2569    match de.end() {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(de.end());
2570    Ok(value)
2571}
2572
2573/// Deserialize an instance of type `T` from an I/O stream of JSON.
2574///
2575/// The content of the I/O stream is deserialized directly from the stream
2576/// without being buffered in memory by serde_json.
2577///
2578/// When reading from a source against which short reads are not efficient, such
2579/// as a [`File`], you will want to apply your own buffering because serde_json
2580/// will not buffer the input. See [`std::io::BufReader`].
2581///
2582/// It is expected that the input stream ends after the deserialized object.
2583/// If the stream does not end, such as in the case of a persistent socket connection,
2584/// this function will not return. It is possible instead to deserialize from a prefix of an input
2585/// stream without looking for EOF by managing your own [`Deserializer`].
2586///
2587/// Note that counter to intuition, this function is usually slower than
2588/// reading a file completely into memory and then applying [`from_str`]
2589/// or [`from_slice`] on it. See [issue #160].
2590///
2591/// [`File`]: std::fs::File
2592/// [issue #160]: https://github.com/serde-rs/json/issues/160
2593///
2594/// # Example
2595///
2596/// Reading the contents of a file.
2597///
2598/// ```
2599/// use serde::Deserialize;
2600///
2601/// use std::error::Error;
2602/// use std::fs::File;
2603/// use std::io::BufReader;
2604/// use std::path::Path;
2605///
2606/// #[derive(Deserialize, Debug)]
2607/// struct User {
2608///     fingerprint: String,
2609///     location: String,
2610/// }
2611///
2612/// fn read_user_from_file<P: AsRef<Path>>(path: P) -> Result<User, Box<dyn Error>> {
2613///     // Open the file in read-only mode with buffer.
2614///     let file = File::open(path)?;
2615///     let reader = BufReader::new(file);
2616///
2617///     // Read the JSON contents of the file as an instance of `User`.
2618///     let u = serde_json::from_reader(reader)?;
2619///
2620///     // Return the `User`.
2621///     Ok(u)
2622/// }
2623///
2624/// fn main() {
2625/// # }
2626/// # fn fake_main() {
2627///     let u = read_user_from_file("test.json").unwrap();
2628///     println!("{:#?}", u);
2629/// }
2630/// ```
2631///
2632/// Reading from a persistent socket connection.
2633///
2634/// ```
2635/// use serde::Deserialize;
2636///
2637/// use std::error::Error;
2638/// use std::io::BufReader;
2639/// use std::net::{TcpListener, TcpStream};
2640///
2641/// #[derive(Deserialize, Debug)]
2642/// struct User {
2643///     fingerprint: String,
2644///     location: String,
2645/// }
2646///
2647/// fn read_user_from_stream(stream: &mut BufReader<TcpStream>) -> Result<User, Box<dyn Error>> {
2648///     let mut de = serde_json::Deserializer::from_reader(stream);
2649///     let u = User::deserialize(&mut de)?;
2650///
2651///     Ok(u)
2652/// }
2653///
2654/// fn main() {
2655/// # }
2656/// # fn fake_main() {
2657///     let listener = TcpListener::bind("127.0.0.1:4000").unwrap();
2658///
2659///     for tcp_stream in listener.incoming() {
2660///         let mut buffered = BufReader::new(tcp_stream.unwrap());
2661///         println!("{:#?}", read_user_from_stream(&mut buffered));
2662///     }
2663/// }
2664/// ```
2665///
2666/// # Errors
2667///
2668/// This conversion can fail if the structure of the input does not match the
2669/// structure expected by `T`, for example if `T` is a struct type but the input
2670/// contains something other than a JSON map. It can also fail if the structure
2671/// is correct but `T`'s implementation of `Deserialize` decides that something
2672/// is wrong with the data, for example required struct fields are missing from
2673/// the JSON map or some number is too big to fit in the expected primitive
2674/// type.
2675#[cfg(feature = "std")]
2676#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2677pub fn from_reader<R, T>(rdr: R) -> Result<T>
2678where
2679    R: crate::io::Read,
2680    T: de::DeserializeOwned,
2681{
2682    from_trait(read::IoRead::new(rdr))
2683}
2684
2685/// Deserialize an instance of type `T` from bytes of JSON text.
2686///
2687/// # Example
2688///
2689/// ```
2690/// use serde::Deserialize;
2691///
2692/// #[derive(Deserialize, Debug)]
2693/// struct User {
2694///     fingerprint: String,
2695///     location: String,
2696/// }
2697///
2698/// fn main() {
2699///     // The type of `j` is `&[u8]`
2700///     let j = b"
2701///         {
2702///             \"fingerprint\": \"0xF9BA143B95FF6D82\",
2703///             \"location\": \"Menlo Park, CA\"
2704///         }";
2705///
2706///     let u: User = serde_json::from_slice(j).unwrap();
2707///     println!("{:#?}", u);
2708/// }
2709/// ```
2710///
2711/// # Errors
2712///
2713/// This conversion can fail if the structure of the input does not match the
2714/// structure expected by `T`, for example if `T` is a struct type but the input
2715/// contains something other than a JSON map. It can also fail if the structure
2716/// is correct but `T`'s implementation of `Deserialize` decides that something
2717/// is wrong with the data, for example required struct fields are missing from
2718/// the JSON map or some number is too big to fit in the expected primitive
2719/// type.
2720pub fn from_slice<'a, T>(v: &'a [u8]) -> Result<T>
2721where
2722    T: de::Deserialize<'a>,
2723{
2724    from_trait(read::SliceRead::new(v))
2725}
2726
2727/// Deserialize an instance of type `T` from a string of JSON text.
2728///
2729/// # Example
2730///
2731/// ```
2732/// use serde::Deserialize;
2733///
2734/// #[derive(Deserialize, Debug)]
2735/// struct User {
2736///     fingerprint: String,
2737///     location: String,
2738/// }
2739///
2740/// fn main() {
2741///     // The type of `j` is `&str`
2742///     let j = "
2743///         {
2744///             \"fingerprint\": \"0xF9BA143B95FF6D82\",
2745///             \"location\": \"Menlo Park, CA\"
2746///         }";
2747///
2748///     let u: User = serde_json::from_str(j).unwrap();
2749///     println!("{:#?}", u);
2750/// }
2751/// ```
2752///
2753/// # Errors
2754///
2755/// This conversion can fail if the structure of the input does not match the
2756/// structure expected by `T`, for example if `T` is a struct type but the input
2757/// contains something other than a JSON map. It can also fail if the structure
2758/// is correct but `T`'s implementation of `Deserialize` decides that something
2759/// is wrong with the data, for example required struct fields are missing from
2760/// the JSON map or some number is too big to fit in the expected primitive
2761/// type.
2762pub fn from_str<'a, T>(s: &'a str) -> Result<T>
2763where
2764    T: de::Deserialize<'a>,
2765{
2766    from_trait(read::StrRead::new(s))
2767}