ssb_json_msg_data/json/
de.rs

1use std::slice::SliceIndex;
2use std::{error, fmt};
3
4use base64;
5use encode_unicode::{error::InvalidUtf16Tuple, Utf16Char, Utf8Char};
6use lexical_core;
7use serde::de::{
8    self, Deserialize, DeserializeOwned, DeserializeSeed, Deserializer, EnumAccess,
9    IntoDeserializer, MapAccess, SeqAccess, VariantAccess, Visitor,
10};
11
12use super::super::LegacyF64;
13
14/// Error code and byte offset describing a deserialization failure
15#[derive(PartialEq, Eq, Debug, Clone)]
16pub struct DecodeJsonError {
17    /// Reason decoding failed
18    pub code: ErrorCode,
19
20    /// Byte offset at which the decoding failure occurred
21    pub position: usize,
22}
23
24/// Everything that can go wrong during deserialization.
25#[derive(PartialEq, Eq, Debug, Clone)]
26pub enum ErrorCode {
27    /// Expected more data but the input ended.
28    UnexpectedEndOfInput,
29    /// A generic syntax error. Any valid json would have been ok, but alas...
30    Syntax,
31    /// Expected a comma (`,`) to separate collection elements.
32    Comma,
33    /// Expected a colon (`:`) to separate a key from a value.
34    Colon,
35    /// Expected a decimal digit. Didn't get one. Sad times.
36    Digit,
37    /// Expected hexadecimal digit as part of a unicode escape sequence in a string.
38    HexDigit,
39    /// Expected a unicode escape (because we just parsed a unicode escape of a leading
40    /// surrogate codepoint).
41    UnicodeEscape,
42    /// Could not merge two unicode escapes into a single code point.
43    SurrogatePair(InvalidUtf16Tuple),
44    /// A unicode escape encoded a trailing surrogate codepoint without a preceding
45    /// leading surrogate codepoint.
46    TrailingSurrogate,
47    /// A string contained an unescaped control code point.
48    UnescapedControlCodePoint,
49    /// A string contained a backslash followed by a non-escape character.
50    InvalidEscape,
51    /// A string literal contains a non-utf8 byte sequence.
52    InvalidUtf8String,
53    /// A number is valid json but it evaluates to -0 or an infinity
54    InvalidNumber,
55    /// The input contained valid json followed by at least one non-whitespace byte.
56    TrailingCharacters,
57    /// Attempted to parse a number as an `i8` that was out of bounds.
58    OutOfBoundsI8,
59    /// Attempted to parse a number as an `i16` that was out of bounds.
60    OutOfBoundsI16,
61    /// Attempted to parse a number as an `i32` that was out of bounds.
62    OutOfBoundsI32,
63    /// Attempted to parse a number as an `i64` that was less than -2^53 or greater than 2^53.
64    OutOfBoundsI64,
65    /// Attempted to parse a number as an `u8` that was out of bounds.
66    OutOfBoundsU8,
67    /// Attempted to parse a number as an `u16` that was out of bounds.
68    OutOfBoundsU16,
69    /// Attempted to parse a number as an `u32` that was out of bounds.
70    OutOfBoundsU32,
71    /// Attempted to parse a number as an `u64` that was greater than 2^53.
72    OutOfBoundsU64,
73    /// Chars are represented as strings that contain one unicode scalar value.
74    NotAChar,
75    /// Attempted to read a string as base64-encoded bytes, but the string was not valid base64.
76    Base64(base64::DecodeError),
77    /// Expected a boolean, found something else.
78    ExpectedBool,
79    /// Expected a number, found something else.
80    ExpectedNumber,
81    /// Expected a string, found something else.
82    ExpectedString,
83    /// Expected null, found something else.
84    ExpectedNull,
85    /// Expected an array, found something else.
86    ExpectedArray,
87    /// Expected an object, found something else.
88    ExpectedObject,
89    /// Expected an enum, found something else.
90    ExpectedEnum,
91    /// Custom, stringly-typed error.
92    Message(String),
93}
94
95impl fmt::Display for DecodeJsonError {
96    fn fmt(&self, f: &mut fmt::Formatter) -> std::result::Result<(), fmt::Error> {
97        fmt::Debug::fmt(&self.code, f)
98    }
99}
100
101impl error::Error for DecodeJsonError {}
102
103impl de::Error for DecodeJsonError {
104    fn custom<T: fmt::Display>(msg: T) -> Self {
105        DecodeJsonError {
106            code: ErrorCode::Message(msg.to_string()),
107            position: 0, // TODO
108        }
109    }
110}
111
112/// A structure that deserializes json encoded legacy message values.
113///
114/// https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf
115pub struct JsonDeserializer<'de> {
116    input: &'de [u8],
117    position: usize,
118}
119
120impl<'de> JsonDeserializer<'de> {
121    /// Check whether there are no non-whitespace tokens up until the end of the input.
122    pub fn end(&mut self) -> Result<(), DecodeJsonError> {
123        match self.peek_ws() {
124            Ok(_) => self.fail(ErrorCode::TrailingCharacters),
125            Err(DecodeJsonError {
126                code: ErrorCode::UnexpectedEndOfInput,
127                position: _,
128            }) => Ok(()),
129            Err(e) => Err(e),
130        }
131    }
132
133    fn slice<I: SliceIndex<[u8]>>(&self, i: I) -> &'de I::Output {
134        &self.input[i]
135    }
136
137    /// Reference to portion of buffer yet to be deserialiced
138    pub fn rest(&self) -> &'de [u8] {
139        self.slice(self.position()..)
140    }
141
142    /// Current byte offset of buffer being deserialized
143    pub fn position(&self) -> usize {
144        self.position
145    }
146
147    fn fail<T>(&self, code: ErrorCode) -> Result<T, DecodeJsonError> {
148        Err(DecodeJsonError {
149            code,
150            position: self.position(),
151        })
152    }
153
154    fn fail_at_position<T>(&self, code: ErrorCode, position: usize) -> Result<T, DecodeJsonError> {
155        Err(DecodeJsonError { code, position })
156    }
157}
158
159/// Try to parse data from the input. Validates that there are no trailing non-whitespace bytes.
160pub fn from_slice<'de, T>(input: &'de [u8]) -> Result<T, DecodeJsonError>
161where
162    T: DeserializeOwned,
163{
164    let mut de = JsonDeserializer::from_slice(input);
165    match Deserialize::deserialize(&mut de) {
166        Ok(t) => de.end().map(|_| t),
167        Err(e) => Err(e),
168    }
169}
170
171/// Try to parse data from the input, returning the remaining input when done.
172pub fn from_slice_partial<'de, T>(input: &'de [u8]) -> Result<(T, &'de [u8]), DecodeJsonError>
173where
174    T: DeserializeOwned,
175{
176    let mut de = JsonDeserializer::from_slice(input);
177    match Deserialize::deserialize(&mut de) {
178        Ok(t) => Ok((t, de.rest())),
179        Err(e) => Err(e),
180    }
181}
182
183fn is_ws(byte: u8) -> bool {
184    byte == 0x09 || byte == 0x0A || byte == 0x0D || byte == 0x20
185}
186
187fn is_digit(byte: u8) -> bool {
188    byte.is_ascii_digit()
189}
190
191fn is_hex_digit(byte: u8) -> bool {
192    byte.is_ascii_hexdigit()
193}
194
195impl<'de> JsonDeserializer<'de> {
196    /// Creates a `Deserializer` from a `&[u8]`.
197    pub fn from_slice(input: &'de [u8]) -> Self {
198        JsonDeserializer { input, position: 0 }
199    }
200
201    // Advance the input slice by some number of bytes.
202    fn advance(&mut self, offset: usize) {
203        self.position += offset;
204    }
205
206    // Consumes the next byte and returns it.
207    fn next(&mut self) -> Result<u8, DecodeJsonError> {
208        if let Some(c) = self.input.get(self.position()) {
209            self.advance(1);
210            Ok(*c)
211        } else {
212            self.fail(ErrorCode::UnexpectedEndOfInput)
213        }
214    }
215
216    // Consumes the expected byt, gives the given error if it is something else
217    fn expect(&mut self, expected: u8, err: ErrorCode) -> Result<(), DecodeJsonError> {
218        let pos = self.position();
219        if self.next()? == expected {
220            Ok(())
221        } else {
222            self.fail_at_position(err, pos)
223        }
224    }
225
226    // Same as expect, but using a predicate.
227    fn expect_pred(&mut self, pred: fn(u8) -> bool, err: ErrorCode) -> Result<(), DecodeJsonError> {
228        let pos = self.position();
229        if pred(self.next()?) {
230            Ok(())
231        } else {
232            self.fail_at_position(err, pos)
233        }
234    }
235
236    // Returns the next byte without consuming it.
237    fn peek(&self) -> Result<u8, DecodeJsonError> {
238        if let Some(c) = self.input.get(self.position()) {
239            Ok(*c)
240        } else {
241            self.fail(ErrorCode::UnexpectedEndOfInput)
242        }
243    }
244
245    // Returns the next byte without consuming it, or signals end of input as `None`.
246    fn peek_or_end(&self) -> Option<u8> {
247        self.input.get(self.position()).map(|b| *b)
248    }
249
250    // Skips values while the predicate returns true.
251    fn skip(&mut self, pred: fn(u8) -> bool) -> () {
252        loop {
253            match self.peek_or_end() {
254                None => return,
255                Some(peeked) => {
256                    if pred(peeked) {
257                        self.advance(1);
258                    } else {
259                        return;
260                    }
261                }
262            }
263        }
264    }
265
266    fn skip_ws(&mut self) -> () {
267        self.skip(is_ws)
268    }
269
270    // Consumes as much whitespace as possible, then peeks at the next non-whitespace byte.
271    fn peek_ws(&mut self) -> Result<u8, DecodeJsonError> {
272        self.skip_ws();
273        self.peek()
274    }
275
276    fn expect_ws(&mut self, exp: u8, err: ErrorCode) -> Result<(), DecodeJsonError> {
277        self.skip_ws();
278        self.expect(exp, err)
279    }
280
281    fn expect_bytes(&mut self, exp: &[u8], err: ErrorCode) -> Result<(), DecodeJsonError> {
282        if self.rest().starts_with(exp) {
283            self.advance(exp.len());
284            Ok(())
285        } else {
286            self.fail(err)
287        }
288    }
289
290    // Parses the four characters of a unicode escape sequence and returns the codepoint they
291    // encode. Json only allows escaping codepoints in the BMP, that's why it fits into a `u16`.
292    fn parse_unicode_escape(&mut self) -> Result<u16, DecodeJsonError> {
293        let start = self.position();
294
295        for _ in 0..4 {
296            self.expect_pred(is_hex_digit, ErrorCode::HexDigit)?;
297        }
298
299        u16::from_str_radix(
300            unsafe { std::str::from_utf8_unchecked(&self.slice(start..start + 4)) },
301            16,
302        )
303        .map_err(|_| unreachable!("We already checked for valid input"))
304    }
305
306    fn parse_bool(&mut self) -> Result<bool, DecodeJsonError> {
307        match self.expect_bytes(b"true", ErrorCode::ExpectedBool) {
308            Ok(()) => Ok(true),
309            Err(_) => self
310                .expect_bytes(b"false", ErrorCode::ExpectedBool)
311                .map(|_| false),
312        }
313    }
314
315    fn parse_number_except(
316        &mut self,
317        pred: fn(f64) -> bool,
318        err: ErrorCode,
319    ) -> Result<f64, DecodeJsonError> {
320        let pos = self.position();
321        let f = self.parse_number()?;
322        if pred(f) {
323            Ok(f)
324        } else {
325            self.fail_at_position(err, pos)
326        }
327    }
328
329    fn parse_number(&mut self) -> Result<f64, DecodeJsonError> {
330        let start = self.position();
331
332        // trailing `-`
333        match self.peek() {
334            Ok(0x2D) => self.advance(1),
335            Ok(_) => {}
336            Err(_) => return self.fail(ErrorCode::ExpectedNumber),
337        }
338
339        let next = self.next()?;
340        match next {
341            // first digit `0` must be followed by `.`
342            0x30 => {}
343            // first digit nonzero, may be followed by more digits until the `.`
344            0x31..=0x39 => self.skip(is_digit),
345            _ => return self.fail_at_position(ErrorCode::ExpectedNumber, start),
346        }
347
348        // `.`, followed by many1 digits
349        if let Some(0x2E) = self.peek_or_end() {
350            self.advance(1);
351            self.expect_pred(is_digit, ErrorCode::Digit)?;
352            self.skip(is_digit);
353        }
354
355        // `e` or `E`, followed by an optional sign and many1 digits
356        match self.peek_or_end() {
357            Some(0x45) | Some(0x65) => {
358                self.advance(1);
359
360                // optional `+` or `-`
361                if self.peek()? == 0x2B || self.peek()? == 0x2D {
362                    self.advance(1);
363                }
364
365                // many1 digits
366                self.expect_pred(is_digit, ErrorCode::Digit)?;
367                self.skip(is_digit);
368            }
369            _ => {}
370        }
371
372        // done parsing the number, convert it to a rust value
373        let f: f64 = lexical_core::parse(self.slice(start..self.position())).unwrap(); // We already checked that the input is a valid number
374
375        if LegacyF64::is_valid(f) {
376            Ok(f)
377        } else {
378            self.fail_at_position(ErrorCode::InvalidNumber, start)
379        }
380    }
381
382    // Return a slice beginning and ending with 0x22 (`"`)
383    fn parse_naive_string(&mut self) -> Result<&'de [u8], DecodeJsonError> {
384        self.expect(0x22, ErrorCode::ExpectedString)?;
385        let start = self.position();
386
387        while self.next()? != 0x22 {
388            // noop
389        }
390
391        Ok(self.slice(start..self.position()))
392    }
393
394    fn parse_string(&mut self) -> Result<String, DecodeJsonError> {
395        self.expect(0x22, ErrorCode::ExpectedString).unwrap();
396
397        let mut decoded = String::new();
398
399        loop {
400            match self.peek()? {
401                // terminating `"`, return the decoded string
402                0x22 => {
403                    self.advance(1);
404                    return Ok(decoded);
405                }
406
407                // `\` introduces an escape sequence
408                0x5C => {
409                    let pos = self.position();
410                    self.advance(1);
411
412                    match self.next()? {
413                        // single character escape sequences
414                        0x22 => decoded.push_str("\u{22}"), // `\"`
415                        0x5C => decoded.push_str("\u{5C}"), // `\\`
416                        0x2F => decoded.push_str("\u{2F}"), // `\/`
417                        0x62 => decoded.push_str("\u{08}"), // `\b`
418                        0x66 => decoded.push_str("\u{0C}"), // `\f`
419                        0x6E => decoded.push_str("\u{0A}"), // `\n`
420                        0x72 => decoded.push_str("\u{0D}"), // `\r`
421                        0x74 => decoded.push_str("\u{09}"), // `\t`
422
423                        // unicode escape sequences
424                        0x75 => {
425                            let cp = self.parse_unicode_escape()?;
426
427                            match code_unit_type(cp) {
428                                CodeUnitType::Valid => decoded
429                                    .push(unsafe { std::char::from_u32_unchecked(cp as u32) }),
430
431                                CodeUnitType::LeadingSurrogate => {
432                                    // the unicode escape was for a leading surrogate, which
433                                    // must be followed by another unicode escape which is a
434                                    // trailing surrogate
435                                    self.expect(0x5C, ErrorCode::UnicodeEscape)?;
436                                    self.expect(0x75, ErrorCode::UnicodeEscape)?;
437                                    let cp2 = self.parse_unicode_escape()?;
438
439                                    match Utf16Char::from_tuple((cp, Some(cp2))) {
440                                        Ok(c) => decoded.push(c.into()),
441                                        Err(e) => {
442                                            return self
443                                                .fail_at_position(ErrorCode::SurrogatePair(e), pos)
444                                        }
445                                    }
446                                }
447
448                                CodeUnitType::TrailingSurrogate => {
449                                    return self.fail_at_position(ErrorCode::TrailingSurrogate, pos)
450                                }
451                            }
452                        }
453
454                        // Nothing else may follow an unescaped `\`
455                        _ => return self.fail_at_position(ErrorCode::InvalidEscape, pos),
456                    }
457                }
458
459                // the control code points must be escaped
460                0x00..=0x1F => return self.fail(ErrorCode::UnescapedControlCodePoint),
461
462                // a regular utf8-encoded code point (unless it is malformed)
463                _ => match Utf8Char::from_slice_start(self.rest()) {
464                    Err(_) => return self.fail(ErrorCode::InvalidUtf8String),
465                    Ok((_, len)) => unsafe {
466                        decoded.push_str(std::str::from_utf8_unchecked(&self.rest()[..len]));
467                        self.advance(len);
468                    },
469                },
470            }
471        }
472    }
473
474    fn parse_null(&mut self) -> Result<(), DecodeJsonError> {
475        self.expect_bytes(b"null", ErrorCode::ExpectedNull)
476    }
477}
478
479// Every utf16 code unit (a `u16`) falls into one of these categories.
480enum CodeUnitType {
481    // A valid code point in the BMP: either between 0x0000 and 0xD7FF (inclusive)
482    // or between 0xE000 and 0xFFFF (inclusive)
483    Valid,
484    // Leading surrogate: between 0xD800 and 0xDBFF (inclusive)
485    LeadingSurrogate,
486    // Trailing surrogate: between 0xDC00 and 0xDFFF (inclusive)
487    TrailingSurrogate,
488}
489
490// Maps a `u16` to its `CodeUnitType`.
491fn code_unit_type(c: u16) -> CodeUnitType {
492    match c {
493        0x0000..=0xD7FF | 0xE000..=0xFFFF => CodeUnitType::Valid,
494        0xD800..=0xDBFF => CodeUnitType::LeadingSurrogate,
495        0xDC00..=0xDFFF => CodeUnitType::TrailingSurrogate,
496    }
497}
498
499impl<'a, 'de> Deserializer<'de> for &'a mut JsonDeserializer<'de> {
500    type Error = DecodeJsonError;
501
502    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
503    where
504        V: Visitor<'de>,
505    {
506        match self.peek_ws()? {
507            0x6E => {
508                if self.rest()[1..].starts_with(b"ull") {
509                    self.advance(4);
510                    visitor.visit_unit()
511                } else {
512                    self.fail(ErrorCode::Syntax)
513                }
514            }
515            0x66 => {
516                if self.rest()[1..].starts_with(b"alse") {
517                    self.advance(5);
518                    visitor.visit_bool(false)
519                } else {
520                    self.fail(ErrorCode::Syntax)
521                }
522            }
523            0x74 => {
524                if self.rest()[1..].starts_with(b"rue") {
525                    self.advance(4);
526                    visitor.visit_bool(true)
527                } else {
528                    self.fail(ErrorCode::Syntax)
529                }
530            }
531            0x22 => self.deserialize_str(visitor),
532            0x5B => self.deserialize_seq(visitor),
533            0x7B => self.deserialize_map(visitor),
534            0x2D | 0x30..=0x39 => self.deserialize_f64(visitor),
535            _ => self.fail(ErrorCode::Syntax),
536        }
537    }
538
539    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
540    where
541        V: Visitor<'de>,
542    {
543        visitor.visit_bool(self.parse_bool()?)
544    }
545
546    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
547    where
548        V: Visitor<'de>,
549    {
550        let f = self.parse_number_except(
551            |n| n < std::i8::MIN as f64 || n > std::i8::MAX as f64,
552            ErrorCode::OutOfBoundsI8,
553        )?;
554        visitor.visit_i8(f as i8)
555    }
556
557    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
558    where
559        V: Visitor<'de>,
560    {
561        let f = self.parse_number()?;
562        if f < std::i16::MIN as f64 || f > std::i16::MAX as f64 {
563            self.fail(ErrorCode::OutOfBoundsI16)
564        } else {
565            visitor.visit_i16(f as i16)
566        }
567    }
568
569    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
570    where
571        V: Visitor<'de>,
572    {
573        let f = self.parse_number()?;
574        if f < std::i32::MIN as f64 || f > std::i32::MAX as f64 {
575            self.fail(ErrorCode::OutOfBoundsI32)
576        } else {
577            visitor.visit_i32(f as i32)
578        }
579    }
580
581    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
582    where
583        V: Visitor<'de>,
584    {
585        let f = self.parse_number()?;
586        if f < -9007199254740992.0f64 || f > 9007199254740992.0f64 {
587            self.fail(ErrorCode::OutOfBoundsI64)
588        } else {
589            visitor.visit_i64(f as i64)
590        }
591    }
592
593    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
594    where
595        V: Visitor<'de>,
596    {
597        let f = self.parse_number()?;
598        if f > std::u8::MAX as f64 {
599            self.fail(ErrorCode::OutOfBoundsU8)
600        } else {
601            visitor.visit_u8(f as u8)
602        }
603    }
604
605    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
606    where
607        V: Visitor<'de>,
608    {
609        let f = self.parse_number()?;
610        if f > std::u16::MAX as f64 {
611            self.fail(ErrorCode::OutOfBoundsU16)
612        } else {
613            visitor.visit_u16(f as u16)
614        }
615    }
616
617    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
618    where
619        V: Visitor<'de>,
620    {
621        let f = self.parse_number()?;
622        if f > std::u32::MAX as f64 {
623            self.fail(ErrorCode::OutOfBoundsU32)
624        } else {
625            visitor.visit_u32(f as u32)
626        }
627    }
628
629    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
630    where
631        V: Visitor<'de>,
632    {
633        let f = self.parse_number()?;
634        if f > 9007199254740992.0f64 {
635            self.fail(ErrorCode::OutOfBoundsU64)
636        } else {
637            visitor.visit_u64(f as u64)
638        }
639    }
640
641    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
642    where
643        V: Visitor<'de>,
644    {
645        visitor.visit_f32(self.parse_number()? as f32)
646    }
647
648    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
649    where
650        V: Visitor<'de>,
651    {
652        visitor.visit_f64(self.parse_number()?)
653    }
654
655    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
656    where
657        V: Visitor<'de>,
658    {
659        let pos = self.position();
660        let s = self.parse_string()?;
661        let mut chars = s.chars();
662
663        match chars.next() {
664            None => self.fail_at_position(ErrorCode::NotAChar, pos),
665            Some(c) => match chars.next() {
666                None => visitor.visit_char(c),
667                Some(_) => self.fail_at_position(ErrorCode::NotAChar, pos),
668            },
669        }
670    }
671
672    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
673    where
674        V: Visitor<'de>,
675    {
676        // We can't reference json strings directly since they contain escape sequences.
677        // For the conversion, we need to allocate an owned buffer, so always do owned
678        // deserialization.
679        self.deserialize_string(visitor)
680    }
681
682    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
683    where
684        V: Visitor<'de>,
685    {
686        visitor.visit_string(self.parse_string()?)
687    }
688
689    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
690    where
691        V: Visitor<'de>,
692    {
693        // We can't reference bytes directly since they are stored as base64 strings.
694        // For the conversion, we need to allocate an owned buffer, so always do owned
695        // deserialization.
696        self.deserialize_byte_buf(visitor)
697    }
698
699    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
700    where
701        V: Visitor<'de>,
702    {
703        let pos = self.position();
704        match base64::decode(self.parse_naive_string()?) {
705            Ok(buf) => visitor.visit_byte_buf(buf),
706            Err(e) => self.fail_at_position(ErrorCode::Base64(e), pos),
707        }
708    }
709
710    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
711    where
712        V: Visitor<'de>,
713    {
714        if self.rest().starts_with(b"null") {
715            self.advance(4);
716            visitor.visit_none()
717        } else {
718            visitor.visit_some(self)
719        }
720    }
721
722    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
723    where
724        V: Visitor<'de>,
725    {
726        self.parse_null()?;
727        visitor.visit_unit()
728    }
729
730    fn deserialize_unit_struct<V>(
731        self,
732        _name: &'static str,
733        visitor: V,
734    ) -> Result<V::Value, Self::Error>
735    where
736        V: Visitor<'de>,
737    {
738        self.deserialize_unit(visitor)
739    }
740
741    fn deserialize_newtype_struct<V>(
742        self,
743        _name: &'static str,
744        visitor: V,
745    ) -> Result<V::Value, Self::Error>
746    where
747        V: Visitor<'de>,
748    {
749        visitor.visit_newtype_struct(self)
750    }
751
752    fn deserialize_seq<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
753    where
754        V: Visitor<'de>,
755    {
756        self.expect(0x5B, ErrorCode::ExpectedArray)?;
757        let value = visitor.visit_seq(CollectionAccessor::new(&mut self))?;
758        self.expect_ws(0x5D, ErrorCode::Syntax)?; // Can't fail
759        Ok(value)
760    }
761
762    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
763    where
764        V: Visitor<'de>,
765    {
766        self.deserialize_seq(visitor)
767    }
768
769    fn deserialize_tuple_struct<V>(
770        self,
771        _name: &'static str,
772        _len: usize,
773        visitor: V,
774    ) -> Result<V::Value, Self::Error>
775    where
776        V: Visitor<'de>,
777    {
778        self.deserialize_seq(visitor)
779    }
780
781    fn deserialize_map<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
782    where
783        V: Visitor<'de>,
784    {
785        self.expect(0x7B, ErrorCode::ExpectedObject)?;
786        let value = visitor.visit_map(CollectionAccessor::new(&mut self))?;
787        self.expect_ws(0x7D, ErrorCode::Syntax)?; // Can't fail
788        Ok(value)
789    }
790
791    fn deserialize_struct<V>(
792        self,
793        _name: &'static str,
794        _fields: &'static [&'static str],
795        visitor: V,
796    ) -> Result<V::Value, Self::Error>
797    where
798        V: Visitor<'de>,
799    {
800        self.deserialize_map(visitor)
801    }
802
803    fn deserialize_enum<V>(
804        self,
805        _name: &'static str,
806        _variants: &'static [&'static str],
807        visitor: V,
808    ) -> Result<V::Value, Self::Error>
809    where
810        V: Visitor<'de>,
811    {
812        let pos = self.position();
813        if self.peek()? == 0x22 {
814            // Visit a unit variant.
815            visitor.visit_enum(self.parse_string()?.into_deserializer())
816        } else if self.next()? == 0x7B {
817            // Visit a newtype variant, tuple variant, or struct variant.
818            let value = visitor.visit_enum(Enum::new(self))?;
819            self.expect_ws(0x7D, ErrorCode::Syntax)?; // Can't fail
820            Ok(value)
821        } else {
822            self.fail_at_position(ErrorCode::ExpectedEnum, pos)
823        }
824    }
825
826    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
827    where
828        V: Visitor<'de>,
829    {
830        self.deserialize_str(visitor)
831    }
832
833    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
834    where
835        V: Visitor<'de>,
836    {
837        self.deserialize_any(visitor)
838    }
839}
840
841struct CollectionAccessor<'a, 'de> {
842    des: &'a mut JsonDeserializer<'de>,
843    first: bool,
844}
845
846impl<'a, 'de> CollectionAccessor<'a, 'de> {
847    fn new(des: &'a mut JsonDeserializer<'de>) -> CollectionAccessor<'a, 'de> {
848        CollectionAccessor { des, first: true }
849    }
850}
851
852impl<'a, 'de> SeqAccess<'de> for CollectionAccessor<'a, 'de> {
853    type Error = DecodeJsonError;
854
855    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
856    where
857        T: DeserializeSeed<'de>,
858    {
859        // Array ends at `]`
860        if let 0x5D = self.des.peek_ws()? {
861            return Ok(None);
862        }
863
864        // expect `,` before every item except the first
865        if self.first {
866            self.first = false;
867        } else {
868            self.des.expect_ws(0x2C, ErrorCode::Comma)?;
869        }
870
871        self.des.peek_ws()?;
872
873        seed.deserialize(&mut *self.des).map(Some)
874    }
875}
876
877impl<'a, 'de> MapAccess<'de> for CollectionAccessor<'a, 'de> {
878    type Error = DecodeJsonError;
879
880    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
881    where
882        K: DeserializeSeed<'de>,
883    {
884        // Object ends at `}`
885        if let 0x7D = self.des.peek_ws()? {
886            return Ok(None);
887        }
888
889        // expect `,` before every item except the first
890        if self.first {
891            self.first = false;
892        } else {
893            self.des.expect_ws(0x2C, ErrorCode::Comma)?;
894        }
895
896        self.des.peek_ws()?;
897        seed.deserialize(&mut *self.des).map(Some)
898    }
899
900    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
901    where
902        V: DeserializeSeed<'de>,
903    {
904        self.des.expect_ws(0x3A, ErrorCode::Colon)?; // `:`
905
906        self.des.peek_ws()?;
907        seed.deserialize(&mut *self.des)
908    }
909}
910
911struct Enum<'a, 'de> {
912    des: &'a mut JsonDeserializer<'de>,
913}
914
915impl<'a, 'de> Enum<'a, 'de> {
916    fn new(des: &'a mut JsonDeserializer<'de>) -> Self {
917        Enum { des }
918    }
919}
920
921impl<'a, 'de> EnumAccess<'de> for Enum<'a, 'de> {
922    type Error = DecodeJsonError;
923    type Variant = Self;
924
925    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
926    where
927        V: DeserializeSeed<'de>,
928    {
929        self.des.peek_ws()?;
930        let val = seed.deserialize(&mut *self.des)?;
931        self.des.expect_ws(0x3A, ErrorCode::Colon)?; // `:`
932
933        self.des.peek_ws()?;
934        Ok((val, self))
935    }
936}
937
938impl<'a, 'de> VariantAccess<'de> for Enum<'a, 'de> {
939    type Error = DecodeJsonError;
940
941    fn unit_variant(self) -> Result<(), Self::Error> {
942        eprintln!("wtf is this");
943        self.des.fail(ErrorCode::ExpectedString)
944    }
945
946    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
947    where
948        T: DeserializeSeed<'de>,
949    {
950        seed.deserialize(self.des)
951    }
952
953    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
954    where
955        V: Visitor<'de>,
956    {
957        de::Deserializer::deserialize_seq(self.des, visitor)
958    }
959
960    // Struct variants are represented in JSON as `{ NAME: { K: V, ... } }` so
961    // deserialize the inner map here.
962    fn struct_variant<V>(
963        self,
964        _fields: &'static [&'static str],
965        visitor: V,
966    ) -> Result<V::Value, Self::Error>
967    where
968        V: Visitor<'de>,
969    {
970        de::Deserializer::deserialize_map(self.des, visitor)
971    }
972}