ser_write_json/
de.rs

1//! JSON serde deserializer
2// use std::println;
3#[cfg(feature = "std")]
4use std::{string::String, string::ToString};
5
6#[cfg(all(feature = "alloc",not(feature = "std")))]
7use alloc::{string::String, string::ToString};
8
9use core::cell::Cell;
10use core::ops::Neg;
11use core::num::{ParseIntError, ParseFloatError};
12use core::slice::from_raw_parts_mut;
13use core::str::{Utf8Error, FromStr};
14use core::{fmt, str};
15use serde::forward_to_deserialize_any;
16use serde::de::{self, Visitor, SeqAccess, MapAccess, DeserializeSeed};
17
18/// JSON deserializer with bytes deserialized from JSON strings (with unescaping)
19/// without any additional decoding
20pub type DeserializerNopeByteStr<'de> = Deserializer<'de, StringByteNopeDecoder>;
21/// JSON deserializer with bytes deserialized from HEX-encoded strings
22pub type DeserializerHexByteStr<'de> = Deserializer<'de, StringByteHexDecoder>;
23/// JSON deserializer with bytes deserialized from BASE-64 encoded strings
24pub type DeserializerBase64ByteStr<'de> = Deserializer<'de, StringByteBase64Decoder>;
25
26/// Deserialize an instance of type `T` from a mutable slice of bytes of JSON text.
27///
28/// `P` must implement [`StringByteDecoder`] and determines how strings are converted
29/// to bytes.
30///
31/// The provided slice must be writable so the deserializer can unescape strings 
32/// and parse bytes from arrays or strings in-place.
33///
34/// __NOTE__: Assume the original slice content will be modified!
35///
36/// Any `&str` or `&[u8]` in the returned type will contain references to the provided slice.
37pub fn from_mut_slice_with_decoder<'a, P, T>(v: &'a mut [u8]) -> Result<T>
38    where T: de::Deserialize<'a>,
39          P: StringByteDecoder<'a>
40{
41    let mut de = Deserializer::<P>::from_mut_slice(v);
42    let value = de::Deserialize::deserialize(&mut de)?;
43    de.end()?;
44
45    Ok(value)
46}
47
48/// Deserialize an instance of type `T` from a mutable slice of bytes of JSON text.
49///
50/// Byte arrays deserialized from a string retain the original content after
51/// unescaping all `\` tokens. The content of such a byte array is **not** UTF-8
52/// validated.
53///
54/// The provided slice must be writable so the deserializer can unescape strings 
55/// and parse bytes from arrays or strings in-place.
56///
57/// __NOTE__: Assume the original slice content will be modified!
58///
59/// Any `&str` or `&[u8]` in the returned type will contain references to the provided slice.
60pub fn from_mut_slice<'a, T>(v: &'a mut [u8]) -> Result<T>
61    where T: de::Deserialize<'a>
62{
63    from_mut_slice_with_decoder::<StringByteNopeDecoder, _>(v)
64}
65
66/// Deserialize an instance of type `T` from a mutable slice of bytes of JSON text.
67///
68/// Byte arrays deserialized from a string are decoded expecting two hexadecimal ASCII
69/// characters per byte.
70///
71/// The provided slice must be writable so the deserializer can unescape strings 
72/// and parse bytes from arrays or strings in-place.
73///
74/// __NOTE__: Assume the original slice content will be modified!
75///
76/// Any `&str` or `&[u8]` in the returned type will contain references to the provided slice.
77pub fn from_mut_slice_hex_bytes<'a, T>(v: &'a mut [u8]) -> Result<T>
78    where T: de::Deserialize<'a>
79{
80    from_mut_slice_with_decoder::<StringByteHexDecoder, _>(v)
81}
82
83/// Deserialize an instance of type `T` from a mutable slice of bytes of JSON text.
84///
85/// Byte arrays deserialized from a string are decoded expecting [Base64] standard encoding
86/// with optional padding.
87///
88/// The provided slice must be writable so the deserializer can unescape strings 
89/// and parse bytes from arrays or strings in-place.
90///
91/// __NOTE__: Assume the original slice content will be modified!
92///
93/// Any `&str` or `&[u8]` in the returned type will contain references to the provided slice.
94///
95/// [Base64]: https://datatracker.ietf.org/doc/html/rfc4648#section-4
96pub fn from_mut_slice_base64_bytes<'a, T>(v: &'a mut [u8]) -> Result<T>
97    where T: de::Deserialize<'a>
98{
99    from_mut_slice_with_decoder::<StringByteBase64Decoder, _>(v)
100}
101
102/// Serde JSON deserializer.
103///
104/// `P` must implement [`StringByteDecoder`].
105///
106/// * deserializes data from a mutable slice,
107/// * unescapes strings in-place,
108/// * decodes strings or number arrays into bytes in-place,
109/// * deserializes borrowed references to `&str` and `&[u8]` types,
110/// * deserializes bytes from arrays of numbers,
111/// * deserializes bytes from strings using `P` as a string decoder,
112/// * deserializes structs from JSON objects or arrays.
113pub struct Deserializer<'de, P> {
114    input: &'de mut[u8],
115    index: usize,
116    _parser: core::marker::PhantomData<P>
117}
118
119/// Deserialization result
120pub type Result<T> = core::result::Result<T, Error>;
121
122/// Deserialization error
123#[derive(Debug, PartialEq, Eq, Clone)]
124#[non_exhaustive]
125pub enum Error {
126    /// EOF while parsing
127    UnexpectedEof,
128    /// Invalid JSON string escape sequence
129    InvalidEscapeSequence,
130    /// A control ASCII character detected in a JSON input
131    StringControlChar,
132    /// Expected this character to be a `':'`.
133    ExpectedColon,
134    /// Expected this character to be either a `','` or a `']'`.
135    ExpectedArrayCommaOrEnd,
136    /// Expected a `']'` character
137    ExpectedArrayEnd,
138    /// Array content starts with a leading `','`.
139    LeadingArrayComma,
140    /// Array content ends with a trailing `','`.
141    TrailingArrayComma,
142    /// Expected this character to be either a `','` or a `'}'`.
143    ExpectedObjectCommaOrEnd,
144    /// Expected this character to be `'}'`.
145    ExpectedObjectEnd,
146    /// Object content starts with a leading `,`.
147    LeadingObjectComma,
148    /// Object content ends with a trailing `,`.
149    TrailingObjectComma,
150    /// Expected to parse either `true`, `false`, or `null`.
151    ExpectedToken,
152    /// Expected `null`
153    ExpectedNull,
154    /// Expected a `"` character
155    ExpectedString,
156    /// Expected an array
157    ExpectedArray,
158    /// Expected an object
159    ExpectedObject,
160    /// Expected an object or an array
161    ExpectedStruct,
162    /// Expected this character to start an enum variant.
163    ExpectedEnumValue,
164    /// Expected this character to be `'}'`.
165    ExpectedEnumObjectEnd,
166    /// Invalid number
167    InvalidNumber,
168    /// Invalid type
169    InvalidType,
170    /// Invalid unicode code point
171    InvalidUnicodeCodePoint,
172    /// Object key is not a string
173    KeyMustBeAString,
174    /// JSON has non-whitespace trailing characters after the value
175    TrailingCharacters,
176    /// Unexpected character
177    UnexpectedChar,
178    /// Invalid length
179    InvalidLength,
180    #[cfg(any(feature = "std", feature = "alloc"))]
181    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
182    /// An error passed down from a [`serde::de::Deserialize`] implementation
183    DeserializeError(String),
184    #[cfg(not(any(feature = "std", feature = "alloc")))]
185    DeserializeError
186}
187
188impl serde::de::StdError for Error {}
189
190#[cfg(any(feature = "std", feature = "alloc"))]
191impl de::Error for Error {
192    fn custom<T: fmt::Display>(msg: T) -> Self {
193        Error::DeserializeError(msg.to_string())
194    }
195}
196
197#[cfg(not(any(feature = "std", feature = "alloc")))]
198impl de::Error for Error {
199    fn custom<T: fmt::Display>(_msg: T) -> Self {
200        Error::DeserializeError
201    }
202}
203
204impl fmt::Display for Error {
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        f.write_str(match self {
207            Error::UnexpectedEof => "Unexpected end of JSON input",
208            Error::InvalidEscapeSequence => "Invalid JSON string escape sequence",
209            Error::StringControlChar => "A control ASCII character found in a JSON string",
210            Error::ExpectedArrayCommaOrEnd => "Expected `','` or `']'`",
211            Error::ExpectedArrayEnd => "Expected ']'",
212            Error::LeadingArrayComma => "JSON array content starts with a leading `','`",
213            Error::TrailingArrayComma => "JSON array content ends with a trailing `','`",
214            Error::ExpectedObjectCommaOrEnd => "Expected `','` or `'}'`",
215            Error::ExpectedObjectEnd => "Expected `'}'`",
216            Error::LeadingObjectComma => "JSON object content starts with a leading `','`",
217            Error::TrailingObjectComma => "JSON object content ends with a trailing `','`",
218            Error::ExpectedColon => "Expected `':'`",
219            Error::ExpectedToken => {
220                "Expected either `true`, `false`, or `null`."
221            }
222            Error::ExpectedNull => "Expected `null`",
223            Error::ExpectedString => r#"Expected `'"'`"#,
224            Error::ExpectedArray => "Expeced a JSON array",
225            Error::ExpectedObject => "Expected a JSON object",
226            Error::ExpectedStruct => "Expected a JSON object or an array",
227            Error::ExpectedEnumValue => r#"Expected this character to be `'"'` or `'{'`"#,
228            Error::ExpectedEnumObjectEnd => "Expected this character to be `'}'`",
229            Error::InvalidNumber => "Invalid number",
230            Error::InvalidType => "Invalid type",
231            Error::InvalidUnicodeCodePoint => "Invalid unicode code point",
232            Error::KeyMustBeAString => "Object key is not a string",
233            Error::TrailingCharacters => {
234                "JSON has non-whitespace trailing character after the value"
235            }
236            Error::UnexpectedChar => "Unexpected token while parsing a JSON value",
237            Error::InvalidLength => "Invalid length",
238            #[cfg(any(feature = "std", feature = "alloc"))]
239            Error::DeserializeError(s) => return write!(f, "{} while deserializing JSON", s),
240            #[cfg(not(any(feature = "std", feature = "alloc")))]
241            Error::DeserializeError => "JSON does not match deserializer’s expected format",
242        })
243    }
244}
245
246impl From<Utf8Error> for Error {
247    fn from(_err: Utf8Error) -> Self {
248        Error::InvalidUnicodeCodePoint
249    }
250}
251
252impl From<ParseFloatError> for Error {
253    fn from(_err: ParseFloatError) -> Self {
254        Error::InvalidNumber
255    }
256}
257
258impl From<ParseIntError> for Error {
259    fn from(_err: ParseIntError) -> Self {
260        Error::InvalidNumber
261    }
262}
263
264/// Convert strings to byte arrays by unescaping original JSON strings
265/// without any additional decoding
266pub struct StringByteNopeDecoder;
267/// Convert strings to byte arrays by decoding HEX-encoded strings
268pub struct StringByteHexDecoder;
269/// Convert strings to byte arrays by decoding BASE-64 encoded strings
270pub struct StringByteBase64Decoder;
271
272/// Auxiliary trait for objects implementing string to bytes decoding.
273pub trait StringByteDecoder<'de>: Sized {
274    /// Should decode bytes from the JSON string after the opening `b'"'`
275    /// has been consumed and until the closing `b'"'` is found in the input slice.
276    ///
277    /// A decoded byte slice must fit in place where the encoded string originaly was.
278    fn decode_string_to_bytes(de: &mut Deserializer<'de, Self>) -> Result<&'de[u8]>;
279}
280
281/* special JSON characters */
282const SP: u8 = b' ';
283const QU: u8 = b'"';
284const RS: u8 = b'\\';
285const SO: u8 = b'/';
286/* special JSON string escape characters */
287const B_: u8 = 0x08; const BB: u8 = b'b'; // \b -> \x08
288const T_: u8 = 0x09; const TT: u8 = b't'; // \t -> \x09
289const N_: u8 = 0x0A; // const NN: u8 = b'n'; // \n -> \x0A
290const F_: u8 = 0x0C; // const FF: u8 = b'f'; // \f => \x0C
291const R_: u8 = 0x0D; // const RR: u8 = b'r'; // \r => \x0D
292/* \uUUUU */
293const UU: u8 = b'u';
294const __: u8 = 0;
295/* only selected (un)escape codes are permitted */
296static UNESCAPE: [u8;19] = [
297/* \b,  c,  d,  e, \f,  g,  h,  i,  j,  k,  l,  m, \n,  o,  p,  q, \r,  s, \t */
298    B_, __, __, __, F_, __, __, __, __, __, __, __, N_, __, __, __, R_, __, T_
299];
300
301#[inline(always)]
302fn parse_hex_nib(ch: u8) -> Option<u8> {
303    match ch {
304        n@b'0'..=b'9' => Some(n - b'0'),
305        _ => match ch|0x20 {
306            n@b'a'..=b'f' => Some(n - b'a' + 10),
307            _ => None
308        }
309    }
310}
311
312#[inline(always)]
313fn parse_uuuu([a,b,c,d]: [u8;4]) -> Option<u32> {
314    Some(u16::from_le_bytes([
315        (parse_hex_nib(c)? << 4) + parse_hex_nib(d)?,
316        (parse_hex_nib(a)? << 4) + parse_hex_nib(b)?]).into())
317}
318
319/// Helper trait for parsing integers
320pub trait NumParseTool: Sized + Copy {
321    const ZERO: Self;
322    fn try_from_ascii_decimal(code: u8) -> Option<Self>;
323    fn checked_mul_ten(self) -> Result<Self>;
324    fn checked_add(self, rhs: Self) -> Result<Self>;
325}
326
327/// Helper trait for parsing negative integers
328pub trait CheckedSub: Sized + Copy {
329    fn checked_sub(self, rhs: Self) -> Result<Self>;
330}
331
332macro_rules! impl_parse_tool {
333    ($($ty:ty),*) => {$(
334        impl NumParseTool for $ty {
335            const ZERO: Self = 0;
336            #[inline(always)]
337            fn try_from_ascii_decimal(code: u8) -> Option<Self> {
338                if matches!(code, b'0'..=b'9') {
339                    Some((code - b'0') as Self)
340                }
341                else {
342                    None
343                }
344            }
345            #[inline(always)]
346            fn checked_mul_ten(self) -> Result<Self> {
347                self.checked_mul(10)
348                .ok_or(Error::InvalidNumber)
349            }
350            #[inline(always)]
351            fn checked_add(self, rhs: Self) -> Result<Self> {
352                self.checked_add(rhs)
353                .ok_or(Error::InvalidNumber)
354            }
355        }
356    )*};
357}
358
359macro_rules! impl_checked_sub {
360    ($($ty:ty),*) => {$(
361        impl CheckedSub for $ty {
362            #[inline(always)]
363            fn checked_sub(self, rhs: Self) -> Result<Self> {
364                self.checked_sub(rhs)
365                .ok_or(Error::InvalidNumber)
366            }
367        }
368    )*};
369}
370
371impl_parse_tool!(u8, u16, u32, u64, i8, i16, i32, i64);
372impl_checked_sub!(i8, i16, i32, i64);
373
374#[cfg(feature = "de-any-f32")]
375type AnyFloat = f32;
376#[cfg(not(feature = "de-any-f32"))]
377type AnyFloat = f64;
378
379enum AnyNumber {
380    PosInt(u64),
381    NegInt(i64),
382    Float(AnyFloat),
383}
384
385/// Implementation exposes some helper functions for custom [`StringByteDecoder`] implementations.
386impl<'de, P> Deserializer<'de, P> {
387    /// Create a new decoder instance by providing a mutable slice from which to
388    /// deserialize messages.
389    pub fn from_mut_slice(input: &'de mut[u8]) -> Self {
390        Deserializer { input, index: 0, _parser: core::marker::PhantomData }
391    }
392    /// Consume deserializer and check if trailing characters only consist of whitespace
393    pub fn end(mut self) -> Result<()> {
394        // println!("end: {}", core::str::from_utf8(&self.input[self.index..]).unwrap());
395        self.eat_whitespace().err()
396        .map(|_| ())
397        .ok_or(Error::TrailingCharacters)
398    }
399    /// Return the remaining number of unparsed bytes in the input slice.
400    ///
401    /// Returns 0 when the input cursor points either at the end or beyond
402    /// the end of the input slice.
403    #[inline]
404    pub fn remaining_len(&self) -> usize {
405        self.input.len().saturating_sub(self.index)
406    }
407    /// Peek at the next byte code and return it on success, otherwise return
408    /// `Err(Error::UnexpectedEof)` if there are no more unparsed bytes
409    /// remaining in the input slice.
410    pub fn peek(&self) -> Result<u8> {
411        self.input.get(self.index).copied()
412        .ok_or(Error::UnexpectedEof)
413    }
414    /// Advance the input cursor by `len` characters.
415    ///
416    /// _Note_: this function only increases a cursor without any checks!
417    pub fn eat_some(&mut self, len: usize) {
418        self.index += len;
419    }
420    /// Advance the input cursor while discarding any JSON whitespace characters from
421    /// the input slice and peek at the next non-whitespace character and return that
422    /// character on success. Otherwise return `Err(Error::UnexpectedEof)` if there
423    /// are no more unparsed characters remaining in the input slice.
424    pub fn eat_whitespace(&mut self) -> Result<u8> {
425        let index = self.index;
426        self.input[index..].iter()
427        .position(|&b| !matches!(b, SP|T_|N_|R_))
428        .map(|pos| {
429            self.index = index + pos;
430            self.input[index + pos]
431        })
432        .ok_or(Error::UnexpectedEof)
433    }
434    /// Return a mutable reference to the unparsed portion of the input slice on success.
435    /// Otherwise return `Err(Error::UnexpectedEof)`.
436    pub fn input_mut(&mut self) -> Result<&mut[u8]> {
437        self.input.get_mut(self.index..).ok_or(Error::UnexpectedEof)
438    }
439    /// Split the unparsed portion of the input slice between `0..len` and return it with
440    /// the lifetime of the original slice container.
441    ///
442    /// The returned slice can be passed to `visit_borrowed_*` functions of a [`Visitor`].
443    ///
444    /// Drop already parsed bytes and bytes between `len..len+skip` and the new unparsed
445    /// input slice will begin at `len + skip`.
446    ///
447    /// # Panics
448    /// __Panics__ if `len + skip` overflows or is larger than the size of the unparsed
449    /// input slice.
450    pub fn split_input(&mut self, len: usize, skip: usize) -> &'de mut[u8] {
451        let total_len = self.input.len();
452        let ptr = self.input.as_mut_ptr();
453        let index = self.index;
454        let nstart = index.checked_add(len).unwrap().checked_add(skip).unwrap();
455        let newlen = total_len.checked_sub(nstart).unwrap();
456        self.index = 0;
457        // SAFETY: We just checked that `[index;len]` and `[nstart; newlen]`
458        // are not overlapping, because (index + len + skip) <= (nstart + newlen) == total_len
459        // so returning a reference is fine.
460        unsafe {
461            // we can't use slice::split_at_mut here because that would require to re-borrow
462            // self.input (it is a mutable reference) thus shorting the originaly referenced
463            // lifetime 'de
464            self.input = from_raw_parts_mut(ptr.add(nstart), newlen);
465            from_raw_parts_mut(ptr.add(index), len)
466        }
467    }
468
469    #[inline]
470    fn parse_positive_number<T: NumParseTool>(&mut self, mut number: T) -> Result<T> {
471        let mut pos = 0usize;
472        for ch in self.input_mut()?.iter().copied() {
473            match T::try_from_ascii_decimal(ch) {
474                Some(n) => {
475                    number = number
476                        .checked_mul_ten()?
477                        .checked_add(n)?
478                }
479                _ => break
480            }
481            pos += 1;
482        }
483        self.eat_some(pos);
484        Ok(number)
485    }
486
487    #[inline]
488    fn parse_negative_number<T: NumParseTool + CheckedSub>(&mut self, mut number: T) -> Result<T> {
489        let mut pos = 0usize;
490        for ch in self.input_mut()?.iter().copied() {
491            match T::try_from_ascii_decimal(ch) {
492                Some(n) => {
493                    number = number
494                        .checked_mul_ten()?
495                        .checked_sub(n)?
496                }
497                _ => break
498            }
499            pos += 1;
500        }
501        self.eat_some(pos);
502        Ok(number)
503    }
504
505    /// Consume whitespace and then parse a number as an unsigned integer
506    #[inline]
507    pub fn parse_unsigned<T: NumParseTool>(&mut self) -> Result<T> {
508        let peek = self
509            .eat_whitespace()?;
510
511        match peek {
512            b'-' => Err(Error::InvalidNumber),
513            b'0' => {
514                self.eat_some(1);
515                Ok(T::ZERO)
516            }
517            _ => if let Some(number) = T::try_from_ascii_decimal(peek) {
518                self.eat_some(1);
519                self.parse_positive_number(number)
520            }
521            else {
522                Err(Error::InvalidType)
523            }
524        }
525    }
526
527    /// Consume whitespace and then parse a number as a signed integer
528    #[inline]
529    pub fn parse_signed<T>(&mut self) -> Result<T>
530        where T: NumParseTool + CheckedSub + Neg<Output = T>
531    {
532        let mut peek = self
533            .eat_whitespace()?;
534        let is_neg = if peek == b'-' {
535            self.eat_some(1);
536            peek = self.peek()?;
537            true
538        }
539        else {
540            false
541        };
542
543        match peek {
544            b'0' => {
545                self.eat_some(1);
546                Ok(T::ZERO)
547            }
548            _ => if let Some(number) = T::try_from_ascii_decimal(peek) {
549                self.eat_some(1);
550                if is_neg {
551                    self.parse_negative_number(number.neg())
552                }
553                else {
554                    self.parse_positive_number(number)
555                }
556            }
557            else {
558                Err(Error::InvalidType)
559            }
560        }
561    }
562
563    /// Parse a token and if match is found advance the cursor.
564    ///
565    /// Example tokens: `b"null"`, `b"true"`, `b"false"`.
566    pub fn parse_token_content(&mut self, token: &[u8]) -> Result<()> {
567        let size = token.len();
568        if let Some(slice) = self.input.get(self.index..self.index+size) {
569            if slice == token {
570                self.eat_some(size);
571                Ok(())
572            }
573            else {
574                Err(Error::ExpectedToken)
575            }
576        }
577        else {
578            Err(Error::UnexpectedEof)
579        }
580    }
581
582    /// Simple heuristics to decide float or integer,
583    /// call this method ONLY after ensuring the peek character is '0'..='9'|'-'
584    #[inline]
585    fn parse_float_or_int(&mut self, peek: u8) -> Result<AnyNumber> {
586        let is_negative = peek == b'-';
587        let mut is_float = false;
588        let input = &self.input[self.index..];
589        let input = input.iter()
590        .position(|&b| match b {
591            b'0'..=b'9'|b'+'|b'-' => false,
592            b'.'|b'e'|b'E' => {
593                is_float = true;
594                false
595            }
596            _ => true
597        })
598        .map(|len| &input[..len])
599        .unwrap_or(input);
600        // SAFETY: We already checked that it only contains ASCII. This is only true if the
601        // caller has guaranteed that `pattern` contains only ASCII characters.
602        let s = unsafe { str::from_utf8_unchecked(input) };
603        let num = if is_float {
604            AnyNumber::Float(AnyFloat::from_str(s)?)
605        }
606        else if is_negative {
607            AnyNumber::NegInt(i64::from_str(s)?)
608        }
609        else {
610            AnyNumber::PosInt(u64::from_str(s)?)
611        };
612        self.eat_some(input.len());
613        Ok(num)
614    }
615
616    /// Return a slice containing only number characters: `0..=9` and `+-.eE`
617    #[inline]
618    fn match_float(&self) -> &[u8] {
619        let input = &self.input[self.index..];
620        input.iter()
621        .position(|&b| !matches!(b, b'0'..=b'9'|b'+'|b'-'|b'.'|b'e'|b'E'))
622        .map(|len| &input[..len])
623        .unwrap_or(input)
624    }
625
626    /// Consume whitespace and then parse a number as a float
627    #[inline]
628    fn parse_float<E, F: FromStr<Err=E>>(&mut self) -> Result<Option<F>>
629        where Error: From<E>
630    {
631        if b'n' == self.eat_whitespace()? {
632            self.eat_some(1);
633            self.parse_token_content(b"ull")?;
634            return Ok(None)
635        }
636        let input = self.match_float();
637        // SAFETY: We already checked that it only contains ASCII. This is only true if the
638        // caller has guaranteed that `pattern` contains only ASCII characters.
639        let s = unsafe { str::from_utf8_unchecked(input) };
640        let v = F::from_str(s)?;
641        self.eat_some(input.len());
642        Ok(Some(v))
643    }
644
645    /// Eats whitespace and checks if the next character is a colon
646    fn parse_key_colon(&mut self) -> Result<()> {
647        if b':' == self.eat_whitespace()? {
648            self.eat_some(1);
649            Ok(())
650        } else {
651            Err(Error::ExpectedColon)
652        }
653    }
654
655    /// Consume a content of a string until the closing `'"'`, ignoring all escape codes
656    /// except immediately before any `'"'`.
657    ///
658    /// Call after consuming the initial `'"'`.
659    pub fn eat_str_content(&mut self) -> Result<()> {
660        let mut start = self.index;
661        loop {
662            if let Some(found) = self.input.get(start..).and_then(|slice|
663                slice.iter().position(|&b| b == QU || b <= 0x1F))
664            {
665                let end = start + found;
666                // note: we ignore any invalid \ escape codes, but we check for control chars
667                match self.input[end] {
668                    QU => {
669                        let count = self.input[start..end].iter().rev()
670                            .position(|&b| b != RS)
671                            .unwrap_or_else(|| end - start);
672                        if count % 2 == 0 { /* even number of '\' */
673                            // println!("`{}'", core::str::from_utf8(&self.input[start..end]).unwrap());
674                            self.index = end + 1;
675                            return Ok(())
676                        }
677                        /* odd number of '/', continue */
678                        start = end + 1;
679                    }
680                    _ => {
681                        break Err(Error::StringControlChar)
682                    }
683                }
684            }
685            else {
686                break Err(Error::UnexpectedEof)
687            }
688        }
689    }
690    /// Parse a string until a closing `'"'` is found, return a decoded `str` slice.
691    ///
692    /// Handles escape sequences using in-place copy, call after consuming an opening `'"'`
693    pub fn parse_str_content(&mut self) -> Result<&'de str> {
694        core::str::from_utf8(self.parse_str_bytes_content()?)
695        .map_err(From::from)
696    }
697
698    /// Parse a string until a closing `'"'` is found.
699    /// Return decoded in-place string data on success.
700    ///
701    /// Handles escape sequences using in-place copy, call after consuming an opening `'"'`
702    pub fn parse_str_bytes_content(&mut self) -> Result<&'de[u8]> {
703        let mut index = self.index;
704        let mut dest = index;
705        let mut start = index;
706        loop {
707            // "....{dest}<-{gap}->{index}{start}..{end}..."
708            if let Some(found) = self.input.get(start..).and_then(|slice|
709                // println!("slice: {:?} {}", slice, core::str::from_utf8(&self.input[start..]).unwrap());
710                /* search for either '\', '"' or a control character */
711                slice.iter().position(|&b| matches!(b, RS|QU) || b <= 0x1F))
712            {
713                let end = start + found;
714                let gap = index - dest;
715                if gap != 0 {
716                    self.input.copy_within(index..end, dest);
717                }
718                match self.input[end] {
719                    QU => { /* '"' found */
720                        /* return as str and eat a gap with a closing '"' */
721                        break Ok(self.split_input(end - gap - self.index, gap + 1))
722                    }
723                    RS => { /* '\' found */
724                        dest += end - index;
725                        index = end + 1;
726                        match self.input.get(index).copied() {
727                            Some(QU|RS|SO) => { /* preserve escaped */
728                                start = index + 1;
729                            }
730                            Some(c@(BB..=TT)) => { /* control codes */
731                                let unescaped = UNESCAPE[(c-BB) as usize];
732                                if unescaped == 0 {
733                                    break Err(Error::InvalidEscapeSequence)
734                                }
735                                self.input[dest] = unescaped;
736                                dest += 1;
737                                index += 1;
738                                start = index;
739                            }
740                            Some(UU) => { /* u0000 */
741                                // let s = core::str::from_utf8(&self.input[index+1..index+5])?;
742                                // let code = u32::from_str_radix(s, 16)?;
743                                let code = self.input.get(index+1..index+5).ok_or(Error::UnexpectedEof)?
744                                           .try_into().unwrap();
745                                let code = parse_uuuu(code).ok_or(Error::InvalidEscapeSequence)?;
746                                let ch = char::from_u32(code).ok_or(Error::InvalidUnicodeCodePoint)?;
747                                dest += ch.encode_utf8(&mut self.input[dest..]).len();
748                                index += 5;
749                                start = index;
750                            }
751                            Some(..) => break Err(Error::InvalidEscapeSequence),
752                            None => break Err(Error::UnexpectedEof)
753                        }
754                    }
755                    _ => {
756                        break Err(Error::StringControlChar)
757                    }
758                }
759            }
760            else {
761                break Err(Error::UnexpectedEof)
762            }
763        }
764    }
765
766    /// Parse a string as pairs of hexadecimal nibbles until a closing `'"'` is found.
767    /// Return decoded in-place binary data on success.
768    ///
769    /// Call after consuming an opening `'"'`.
770    pub fn parse_hex_bytes_content(&mut self) -> Result<&'de[u8]> {
771        let input = self.input_mut()?;
772        let cells = Cell::from_mut(input).as_slice_of_cells();
773        let mut src = cells.chunks_exact(2);
774        let mut len = 0;
775        let mut iter = src.by_ref().zip(cells.iter());
776        while let Some(([a, b], t)) = iter.next() {
777            if let Some(n) = parse_hex_nib(a.get()) {
778                if let Some(m) = parse_hex_nib(b.get()) {
779                    t.set((n << 4) + m);
780                }
781                else {
782                    return Err(Error::UnexpectedChar)
783                }
784            }
785            else if a.get() == QU {
786                return Ok(self.split_input(len, len + 1))
787            }
788            else {
789                return Err(Error::UnexpectedChar)
790            }
791            len += 1;
792        }
793        match src.remainder() {
794            [c] if c.get() == QU => {
795                Ok(self.split_input(len, len + 1))
796            }
797            _ => Err(Error::UnexpectedEof)
798        }
799    }
800
801    /// Parse a string as BASE-64 encoded bytes until a closing '"' is found.
802    /// Return decoded in-place binary data on success.
803    ///
804    /// Call after consuming an opening `'"'`.
805    pub fn parse_base64_bytes_content(&mut self) -> Result<&'de[u8]> {
806        let input = self.input_mut()?;
807        let (dlen, mut elen) = crate::base64::decode(input);
808        match input.get(elen) {
809            Some(&QU) => Ok(self.split_input(dlen, elen + 1 - dlen)),
810            Some(&b'=') => { /* eat padding */
811                if let Some(pos) = input.get(elen+1..).and_then(|slice|
812                    slice.iter().position(|&b| b != b'='))
813                {
814                    elen = elen + 1 + pos;
815                    return if input[elen] == QU {
816                        Ok(self.split_input(dlen, elen + 1 - dlen))
817                    }
818                    else {
819                        Err(Error::UnexpectedChar)
820                    }
821                }
822                Err(Error::UnexpectedEof)
823            }
824            Some(..) => Err(Error::UnexpectedChar),
825            None => Err(Error::UnexpectedEof)
826        }
827    }
828
829    fn parse_array_bytes_content(&mut self) -> Result<&'de[u8]> {
830        if b']' == self.eat_whitespace()? {
831            return Ok(self.split_input(0, 1))
832        }
833        /* save index */
834        let start = self.index;
835        let mut index = start;
836        #[allow(unused_variables)]
837        #[allow(clippy::let_unit_value)]
838        let input = {
839            #[cfg(debug_assertions)]
840            #[allow(clippy::unused_unit)]
841            {
842                ()
843            }
844            #[cfg(not(debug_assertions))]
845            {
846                self.input.as_mut_ptr()
847            }
848        };
849        loop {
850            let byte = self.parse_unsigned()?;
851            #[cfg(debug_assertions)]
852            {
853                self.input[index] = byte;
854            }
855            #[cfg(not(debug_assertions))]
856            {
857                // SAFETY: depends on parse_unsigned to validate if there is enough room in input
858                // any number in ASCII is >= byte
859                unsafe { input.add(index).write(byte); }
860            }
861            index += 1;
862            match self.eat_whitespace()? {
863                b',' => self.eat_some(1),
864                b']' => break,
865                _ => return Err(Error::UnexpectedChar)
866            }
867        }
868        let offs = self.index + 1 - index;
869        /* restore index back */
870        self.index = start;
871        Ok(self.split_input(index - start, offs))
872    }
873}
874
875impl<'de> StringByteDecoder<'de> for StringByteNopeDecoder {
876    #[inline(always)]
877    fn decode_string_to_bytes(de: &mut Deserializer<'de, Self>) -> Result<&'de[u8]> {
878        de.parse_str_bytes_content()
879    }
880}
881
882impl<'de> StringByteDecoder<'de> for StringByteHexDecoder {
883    #[inline(always)]
884    fn decode_string_to_bytes(de: &mut Deserializer<'de, Self>) -> Result<&'de[u8]> {
885        de.parse_hex_bytes_content()
886    }
887}
888
889impl<'de> StringByteDecoder<'de> for StringByteBase64Decoder {
890    #[inline(always)]
891    fn decode_string_to_bytes(de: &mut Deserializer<'de, Self>) -> Result<&'de[u8]> {
892        de.parse_base64_bytes_content()
893    }
894}
895
896impl<'de, P> de::Deserializer<'de> for &mut Deserializer<'de, P>
897    where P: StringByteDecoder<'de>
898{
899    type Error = Error;
900
901    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
902        where V: Visitor<'de>
903    {
904        match self.eat_whitespace()? {
905            b'n' => self.deserialize_unit(visitor),
906            b't'|b'f' => self.deserialize_bool(visitor),
907            b'"' => self.deserialize_str(visitor),
908            c@(b'0'..=b'9'|b'-') => match self.parse_float_or_int(c)? {
909                AnyNumber::PosInt(n) => visitor.visit_u64(n),
910                AnyNumber::NegInt(n) => visitor.visit_i64(n),
911                #[cfg(feature = "de-any-f32")]
912                AnyNumber::Float(f) => visitor.visit_f32(f),
913                #[cfg(not(feature = "de-any-f32"))]
914                AnyNumber::Float(f) => visitor.visit_f64(f),
915            }
916            b'[' => self.deserialize_seq(visitor),
917            b'{' => self.deserialize_map(visitor),
918            _ => Err(Error::UnexpectedChar),
919        }
920    }
921
922    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
923        where V: Visitor<'de>
924    {
925        let boolean = match self.eat_whitespace()? {
926            b't' => {
927                self.eat_some(1);
928                self.parse_token_content(b"rue")?;
929                true
930            },
931            b'f' => {
932                self.eat_some(1);
933                self.parse_token_content(b"alse")?;
934                false
935            },
936            _ => return Err(Error::UnexpectedChar)
937        };
938        visitor.visit_bool(boolean)
939    }
940
941    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
942        where V: Visitor<'de>
943    {
944        visitor.visit_i8(self.parse_signed()?)
945    }
946
947    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value>
948        where V: Visitor<'de>
949    {
950        visitor.visit_i16(self.parse_signed()?)
951    }
952
953    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value>
954        where V: Visitor<'de>
955    {
956        visitor.visit_i32(self.parse_signed()?)
957    }
958
959    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value>
960        where V: Visitor<'de>
961    {
962        visitor.visit_i64(self.parse_signed()?)
963    }
964
965    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
966        where V: Visitor<'de>
967    {
968        visitor.visit_u8(self.parse_unsigned()?)
969    }
970
971    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value>
972        where V: Visitor<'de>
973    {
974        visitor.visit_u16(self.parse_unsigned()?)
975    }
976
977    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value>
978        where V: Visitor<'de>
979    {
980        visitor.visit_u32(self.parse_unsigned()?)
981    }
982
983    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value>
984        where V: Visitor<'de>
985    {
986        visitor.visit_u64(self.parse_unsigned()?)
987    }
988
989    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value>
990        where V: Visitor<'de>
991    {
992        visitor.visit_f32(self.parse_float()?.unwrap_or(f32::NAN))
993    }
994
995    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value>
996        where V: Visitor<'de>
997    {
998        visitor.visit_f64(self.parse_float()?.unwrap_or(f64::NAN))
999    }
1000
1001    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
1002        where V: Visitor<'de>
1003    {
1004        if b'"' == self.eat_whitespace()? {
1005            self.eat_some(1);
1006            let s = self.parse_str_content()?;
1007            let ch = char::from_str(s).map_err(|_| Error::InvalidLength)?;
1008            visitor.visit_char(ch)
1009        }
1010        else {
1011            Err(Error::ExpectedString)
1012        }
1013    }
1014
1015    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
1016        where V: Visitor<'de>
1017    {
1018        if b'"' == self.eat_whitespace()? {
1019            self.eat_some(1);
1020            visitor.visit_borrowed_str(self.parse_str_content()?)
1021        }
1022        else {
1023            Err(Error::ExpectedString)
1024        }
1025    }
1026
1027    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
1028        where V: Visitor<'de>
1029    {
1030        self.deserialize_str(visitor)
1031    }
1032
1033    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
1034        where V: Visitor<'de>
1035    {
1036        let bytes = match self.eat_whitespace()? {
1037            b'"' => {
1038                self.eat_some(1);
1039                P::decode_string_to_bytes(&mut *self)?
1040            }
1041            b'[' => {
1042                self.eat_some(1);
1043                self.parse_array_bytes_content()?
1044            }
1045            _ => return Err(Error::UnexpectedChar)
1046        };
1047        visitor.visit_borrowed_bytes(bytes)
1048    }
1049
1050    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
1051        where V: Visitor<'de>
1052    {
1053        self.deserialize_bytes(visitor)
1054    }
1055
1056    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
1057        where V: Visitor<'de>
1058    {
1059        match self.eat_whitespace()? {
1060            b'n' => {
1061                self.eat_some(1);
1062                self.parse_token_content(b"ull")?;
1063                visitor.visit_none()
1064            },
1065            _ => visitor.visit_some(self)
1066        }
1067    }
1068
1069    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
1070        where V: Visitor<'de>
1071    {
1072        match self.eat_whitespace()? {
1073            b'n' => {
1074                self.eat_some(1);
1075                self.parse_token_content(b"ull")?;
1076                visitor.visit_unit()
1077            },
1078            _ => Err(Error::ExpectedNull)
1079        }
1080    }
1081
1082    fn deserialize_unit_struct<V>(
1083        self,
1084        _name: &'static str,
1085        visitor: V,
1086    ) -> Result<V::Value>
1087        where V: Visitor<'de>
1088    {
1089        self.deserialize_unit(visitor)
1090    }
1091
1092    // As is done here, serializers are encouraged to treat newtype structs as
1093    // insignificant wrappers around the data they contain. That means not
1094    // parsing anything other than the contained value.
1095    fn deserialize_newtype_struct<V>(
1096        self,
1097        _name: &'static str,
1098        visitor: V,
1099    ) -> Result<V::Value>
1100        where V: Visitor<'de>
1101    {
1102        visitor.visit_newtype_struct(self)
1103    }
1104
1105    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
1106        where V: Visitor<'de>
1107    {
1108        if b'[' == self.eat_whitespace()? {
1109            self.eat_some(1);
1110            let value = visitor.visit_seq(CommaSeparated::new(self))?;
1111            if b']' == self.eat_whitespace()? {
1112                self.eat_some(1);
1113                Ok(value)
1114            } else {
1115                Err(Error::ExpectedArrayEnd)
1116            }
1117        } else {
1118            Err(Error::ExpectedArray)
1119        }
1120    }
1121
1122    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value>
1123        where V: Visitor<'de>
1124    {
1125        self.deserialize_seq(visitor)
1126    }
1127
1128    fn deserialize_tuple_struct<V>(
1129        self,
1130        _name: &'static str,
1131        _len: usize,
1132        visitor: V,
1133    ) -> Result<V::Value>
1134        where V: Visitor<'de>
1135    {
1136        self.deserialize_seq(visitor)
1137    }
1138
1139    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
1140        where V: Visitor<'de>
1141    {
1142        if b'{' == self.eat_whitespace()? {
1143            self.eat_some(1);
1144            let value = visitor.visit_map(CommaSeparated::new(self))?;
1145            if b'}' == self.eat_whitespace()? {
1146                self.eat_some(1);
1147                Ok(value)
1148            } else {
1149                Err(Error::ExpectedObjectEnd)
1150            }
1151        } else {
1152            Err(Error::ExpectedObject)
1153        }
1154    }
1155
1156    fn deserialize_struct<V>(
1157        self,
1158        _name: &'static str,
1159        _fields: &'static [&'static str],
1160        visitor: V,
1161    ) -> Result<V::Value>
1162        where V: Visitor<'de>
1163    {
1164        match self.eat_whitespace()? {
1165            b'{' => self.deserialize_map(visitor),
1166            b'[' => self.deserialize_seq(visitor),
1167            _ => Err(Error::ExpectedStruct)
1168        }
1169    }
1170
1171    fn deserialize_enum<V>(
1172        self,
1173        _name: &'static str,
1174        _variants: &'static [&'static str],
1175        visitor: V,
1176    ) -> Result<V::Value>
1177        where V: Visitor<'de>
1178    {
1179        match self.eat_whitespace()? {
1180            b'"' => visitor.visit_enum(UnitVariantAccess { de: self }),
1181            b'{' => {
1182                self.eat_some(1);
1183                let value = visitor.visit_enum(VariantAccess { de: self })?;
1184                if b'}' == self.eat_whitespace()? {
1185                    self.eat_some(1);
1186                    Ok(value)
1187                }
1188                else {
1189                    Err(Error::ExpectedEnumObjectEnd)
1190                }
1191            }
1192            _ => Err(Error::ExpectedEnumValue)
1193        }
1194    }
1195
1196    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>
1197        where V: Visitor<'de>
1198    {
1199        self.deserialize_str(visitor)
1200    }
1201
1202    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
1203        where V: Visitor<'de>
1204    {
1205        match self.eat_whitespace()? {
1206            b'n' => self.deserialize_unit(visitor),
1207            b't'|b'f' => self.deserialize_bool(visitor),
1208            b'"' => {
1209                self.eat_some(1);
1210                self.eat_str_content()?;
1211                visitor.visit_unit()
1212            }
1213            b'0'..=b'9'|b'-' => {
1214                let len = self.match_float().len();
1215                self.eat_some(len);
1216                visitor.visit_unit()
1217            }
1218            b'[' => self.deserialize_seq(visitor),
1219            b'{' => self.deserialize_map(visitor),
1220            _ => Err(Error::UnexpectedChar),
1221        }
1222    }
1223}
1224
1225struct CommaSeparated<'a, 'de: 'a, P> {
1226    de: &'a mut Deserializer<'de, P>,
1227    first: bool,
1228}
1229
1230impl<'a, 'de, P> CommaSeparated<'a, 'de, P> {
1231    fn new(de: &'a mut Deserializer<'de, P>) -> Self {
1232        CommaSeparated {
1233            de,
1234            first: true,
1235        }
1236    }
1237}
1238
1239impl<'de, 'a, P> SeqAccess<'de> for CommaSeparated<'a, 'de, P> 
1240    where P: StringByteDecoder<'de>
1241{
1242    type Error = Error;
1243
1244    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
1245        where T: DeserializeSeed<'de>
1246    {
1247        match self.de.eat_whitespace()? {
1248            b']' => return Ok(None),
1249            b',' => if self.first {
1250                return Err(Error::LeadingArrayComma)
1251            }
1252            else {
1253                self.de.eat_some(1);
1254                if b']' == self.de.eat_whitespace()? {
1255                    return Err(Error::TrailingArrayComma);
1256                }
1257            }
1258            _ => if self.first {
1259                self.first = false;
1260            }
1261            else {
1262                return Err(Error::ExpectedArrayCommaOrEnd);
1263            }
1264        }
1265        seed.deserialize(&mut *self.de).map(Some)
1266    }
1267}
1268
1269impl<'a, 'de, P> MapAccess<'de> for CommaSeparated<'a, 'de, P> 
1270    where P: StringByteDecoder<'de>
1271{
1272    type Error = Error;
1273
1274    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
1275        where K: DeserializeSeed<'de>
1276    {
1277        let peek = match self.de.eat_whitespace()? {
1278            b'}' => return Ok(None),
1279            b',' => if self.first {
1280                return Err(Error::LeadingObjectComma)
1281            }
1282            else {
1283                self.de.eat_some(1);
1284                match self.de.eat_whitespace()? {
1285                    b'}' => return Err(Error::TrailingObjectComma),
1286                    ch => ch
1287                }
1288            }
1289            ch => if self.first {
1290                self.first = false;
1291                ch
1292            }
1293            else {
1294                return Err(Error::ExpectedObjectCommaOrEnd);
1295            }
1296        };
1297        if peek == b'"' {
1298            seed.deserialize(MapKey { de: &mut *self.de }).map(Some)
1299        }
1300        else {
1301            Err(Error::KeyMustBeAString)
1302        }
1303    }
1304
1305    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
1306        where V: DeserializeSeed<'de>
1307    {
1308        self.de.parse_key_colon()?;
1309        seed.deserialize(&mut *self.de)
1310    }
1311}
1312
1313struct MapKey<'a, 'de, P> {
1314    de: &'a mut Deserializer<'de, P>
1315}
1316
1317impl<'de, 'a, P> MapKey<'a, 'de, P>  {
1318    #[inline]
1319    fn parse_unsigned_numkey<T: NumParseTool>(self) -> Result<T> {
1320        self.de.eat_some(1); // eat '"', the presence of which is checked in MapAccess
1321        let n = self.de.parse_unsigned()?;
1322        // check if we have a closing '"' immediately following a number
1323        if b'"' == self.de.peek()? {
1324            self.de.eat_some(1);
1325            Ok(n)
1326        }
1327        else {
1328            Err(Error::InvalidNumber)
1329        }
1330    }
1331
1332    #[inline]
1333    fn parse_signed_numkey<T>(self) -> Result<T>
1334        where T: NumParseTool + CheckedSub + Neg<Output = T>
1335    {
1336        self.de.eat_some(1); // eat '"', the presence of which is checked in MapAccess
1337        let n = self.de.parse_signed()?;
1338        // check if we have a closing '"' immediately following a number
1339        if b'"' == self.de.peek()? {
1340            self.de.eat_some(1);
1341            Ok(n)
1342        }
1343        else {
1344            Err(Error::InvalidNumber)
1345        }
1346    }
1347}
1348
1349// attempt to deserialize integers directly from string keys if that's what the type expects
1350impl<'de, 'a, P> de::Deserializer<'de> for MapKey<'a, 'de, P> 
1351    where P: StringByteDecoder<'de>
1352{
1353    type Error = Error;
1354
1355    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
1356        where V: Visitor<'de>
1357    {
1358        self.deserialize_str(visitor)
1359    }
1360
1361    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
1362        where V: Visitor<'de>,
1363    {
1364        self.de.deserialize_str(visitor)
1365    }
1366
1367    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
1368        where V: Visitor<'de>
1369    {
1370        self.de.deserialize_char(visitor)
1371    }
1372
1373    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
1374        where V: Visitor<'de>
1375    {
1376        visitor.visit_i8(self.parse_signed_numkey()?)
1377    }
1378
1379    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value>
1380        where V: Visitor<'de>
1381    {
1382        visitor.visit_i16(self.parse_signed_numkey()?)
1383    }
1384
1385    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value>
1386        where V: Visitor<'de>
1387    {
1388        visitor.visit_i32(self.parse_signed_numkey()?)
1389    }
1390
1391    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value>
1392        where V: Visitor<'de>
1393    {
1394        visitor.visit_i64(self.parse_signed_numkey()?)
1395    }
1396
1397    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
1398        where V: Visitor<'de>
1399    {
1400        visitor.visit_u8(self.parse_unsigned_numkey()?)
1401    }
1402
1403    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value>
1404        where V: Visitor<'de>
1405    {
1406        visitor.visit_u16(self.parse_unsigned_numkey()?)
1407    }
1408
1409    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value>
1410        where V: Visitor<'de>
1411    {
1412        visitor.visit_u32(self.parse_unsigned_numkey()?)
1413    }
1414
1415    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value>
1416        where V: Visitor<'de>
1417    {
1418        visitor.visit_u64(self.parse_unsigned_numkey()?)
1419    }
1420
1421    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
1422        where V: Visitor<'de>
1423    {
1424        self.de.eat_some(1); // eat '"', the presence of which is checked in MapAccess
1425        let b = self.de.deserialize_bool(visitor)?;
1426        if b'"' == self.de.peek()? {
1427            self.de.eat_some(1);
1428            Ok(b)
1429        }
1430        else {
1431            Err(Error::InvalidType)
1432        }
1433    }
1434
1435    fn deserialize_enum<V>(
1436        self,
1437        _name: &'static str,
1438        _variants: &'static [&'static str],
1439        visitor: V,
1440    ) -> Result<V::Value>
1441        where V: Visitor<'de>
1442    {
1443        visitor.visit_enum(UnitVariantAccess { de: self.de })
1444    }
1445
1446    forward_to_deserialize_any! {
1447        i128 u128 f32 f64 string
1448        bytes byte_buf option unit unit_struct newtype_struct seq tuple
1449        tuple_struct map struct identifier ignored_any
1450    }
1451}
1452
1453struct UnitVariantAccess<'a, 'de, P> {
1454    de: &'a mut Deserializer<'de, P>,
1455}
1456
1457impl<'a, 'de, P> de::EnumAccess<'de> for UnitVariantAccess<'a, 'de, P> 
1458    where P: StringByteDecoder<'de>
1459{
1460    type Error = Error;
1461    type Variant = Self;
1462
1463    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)>
1464        where V: de::DeserializeSeed<'de>
1465    {
1466        let variant = seed.deserialize(&mut *self.de)?;
1467        Ok((variant, self))
1468    }
1469}
1470
1471impl<'a, 'de, P> de::VariantAccess<'de> for UnitVariantAccess<'a, 'de, P> 
1472    where P: StringByteDecoder<'de>
1473{
1474    type Error = Error;
1475
1476    fn unit_variant(self) -> Result<()> {
1477        Ok(())
1478    }
1479
1480    fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value>
1481        where T: de::DeserializeSeed<'de>
1482    {
1483        Err(Error::InvalidType)
1484    }
1485
1486    fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value>
1487        where V: de::Visitor<'de>
1488    {
1489        Err(Error::InvalidType)
1490    }
1491
1492    fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value>
1493        where V: de::Visitor<'de>
1494    {
1495        Err(Error::InvalidType)
1496    }
1497}
1498
1499struct VariantAccess<'a, 'de, P> {
1500    de: &'a mut Deserializer<'de, P>,
1501}
1502
1503impl<'a, 'de, P> de::EnumAccess<'de> for VariantAccess<'a, 'de, P> 
1504    where P: StringByteDecoder<'de>
1505{
1506    type Error = Error;
1507    type Variant = Self;
1508
1509    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)>
1510        where V: de::DeserializeSeed<'de>
1511    {
1512        let variant = seed.deserialize(&mut *self.de)?;
1513        self.de.parse_key_colon()?;
1514        Ok((variant, self))
1515    }
1516}
1517
1518impl<'a, 'de, P> de::VariantAccess<'de> for VariantAccess<'a, 'de, P> 
1519    where P: StringByteDecoder<'de>
1520{
1521    type Error = Error;
1522
1523    fn unit_variant(self) -> Result<()> {
1524        Err(Error::InvalidType)
1525    }
1526
1527    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
1528        where T: de::DeserializeSeed<'de>
1529    {
1530        seed.deserialize(self.de)
1531    }
1532
1533    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
1534        where V: de::Visitor<'de>
1535    {
1536        de::Deserializer::deserialize_seq(self.de, visitor)
1537    }
1538
1539    fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value>
1540        where V: de::Visitor<'de>
1541    {
1542        de::Deserializer::deserialize_struct(self.de, "", fields, visitor)
1543    }
1544}
1545
1546#[cfg(test)]
1547mod tests {
1548    #[cfg(feature = "std")]
1549    use std::{format, vec, vec::Vec, collections::BTreeMap};
1550    #[cfg(all(feature = "alloc",not(feature = "std")))]
1551    use alloc::{format, vec, vec::Vec, collections::BTreeMap};
1552    use serde::Deserialize;
1553    use crate::ser_write::{SerWrite, SliceWriter};
1554    use super::*;
1555
1556    #[test]
1557    fn test_parse_str_content() {
1558        let mut test = [0;1];
1559        test.copy_from_slice(br#"""#);
1560        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1561        assert_eq!(deser.remaining_len(), 1);
1562        assert_eq!(deser.parse_str_content().unwrap(), "");
1563        assert_eq!(deser.remaining_len(), 0);
1564
1565        let mut test = [0;13];
1566        test.copy_from_slice(br#"Hello World!""#);
1567        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1568        assert_eq!(deser.remaining_len(), 13);
1569        assert_eq!(deser.parse_str_content().unwrap(), "Hello World!");
1570        assert_eq!(deser.remaining_len(), 0);
1571        assert!(deser.input.is_empty());
1572        assert_eq!(deser.index, 0);
1573
1574        let mut test = [0;46];
1575        test.copy_from_slice(br#"\u0020Hello\r\\ \b\nW\tor\fld\u007Fy\u0306!\"""#);
1576        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1577        assert_eq!(deser.remaining_len(), 46);
1578        assert_eq!(deser.parse_str_content().unwrap(), " Hello\r\\ \x08\nW\tor\x0cld\x7fy̆!\"");
1579        assert_eq!(deser.remaining_len(), 0);
1580        assert!(deser.input.is_empty());
1581        assert_eq!(deser.index, 0);
1582
1583        let mut test = [0;1];
1584        test.copy_from_slice(br#"""#);
1585        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1586        assert_eq!(deser.remaining_len(), 1);
1587        assert_eq!(deser.eat_str_content(), Ok(()));
1588        assert_eq!(deser.remaining_len(), 0);
1589        assert_eq!(deser.index, 1);
1590
1591        let mut test = [0;13];
1592        test.copy_from_slice(br#"Hello World!""#);
1593        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1594        assert_eq!(deser.remaining_len(), 13);
1595        assert_eq!(deser.eat_str_content(), Ok(()));
1596        assert_eq!(deser.remaining_len(), 0);
1597        assert_eq!(deser.index, 13);
1598
1599        let mut test = [0;46];
1600        test.copy_from_slice(br#"\u0020Hello\r\\ \b\nW\tor\fld\u007Fy\u0306!\"""#);
1601        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1602        assert_eq!(deser.remaining_len(), 46);
1603        assert_eq!(deser.eat_str_content(), Ok(()));
1604        assert_eq!(deser.remaining_len(), 0);
1605        assert_eq!(deser.index, 46);
1606
1607        let mut test = [0;0];
1608        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1609        assert_eq!(deser.parse_str_content(), Err(Error::UnexpectedEof));
1610        let mut test = [0;2];
1611        test.copy_from_slice(b"\n\"");
1612        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1613        assert_eq!(deser.parse_str_content(), Err(Error::StringControlChar));
1614        let mut test = [0;1];
1615        test.copy_from_slice(br"\");
1616        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1617        assert_eq!(deser.parse_str_content(), Err(Error::UnexpectedEof));
1618
1619        let mut test = [0;1];
1620        test.copy_from_slice(br#"""#);
1621        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1622        assert_eq!(deser.eat_str_content(), Ok(()));
1623        let mut test = [0;3];
1624        test.copy_from_slice(br#"\\""#);
1625        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1626        assert_eq!(deser.eat_str_content(), Ok(()));
1627        let mut test = [0;0];
1628        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1629        assert_eq!(deser.eat_str_content(), Err(Error::UnexpectedEof));
1630        let mut test = [0;3];
1631        test.copy_from_slice(br#" 1_"#);
1632        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1633        assert_eq!(deser.eat_str_content(), Err(Error::UnexpectedEof));
1634        let mut test = [0;2];
1635        test.copy_from_slice(br#"\""#);
1636        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1637        assert_eq!(deser.eat_str_content(), Err(Error::UnexpectedEof));
1638        let mut test = [0;3];
1639        test.copy_from_slice(b" \t ");
1640        let mut deser = DeserializerNopeByteStr::from_mut_slice(&mut test);
1641        assert_eq!(deser.eat_str_content(), Err(Error::StringControlChar));
1642    }
1643
1644    #[test]
1645    fn test_deserializer() {
1646        let mut test = [0;14];
1647        let s: &str = {
1648            test.copy_from_slice(br#""Hello World!""#);
1649            from_mut_slice(&mut test).unwrap()
1650        };
1651        assert_eq!(s, "Hello World!");
1652        let mut test = [0;21];
1653        let s: &str = {
1654            test.copy_from_slice(br#" "Hello\tWorld!\r\n" "#);
1655            from_mut_slice(&mut test).unwrap()
1656        };
1657        assert_eq!(s, "Hello\tWorld!\r\n");
1658        let mut test = [0;57];
1659        let tup: (i8, u32, i64, f32, f64) = {
1660            test.copy_from_slice(br#" [ 0 , 4294967295, -9223372036854775808 ,3.14 , 1.2e+8 ] "#);
1661            from_mut_slice(&mut test).unwrap()
1662        };
1663        assert_eq!(tup, (0i8,4294967295u32,-9223372036854775808i64,3.14f32,1.2e+8));
1664        let mut test = [0;40];
1665        let ary: [&str;3] = {
1666            test.copy_from_slice(br#" ["one\u0031", "\u0032two", "\u003333"] "#);
1667            from_mut_slice(&mut test).unwrap()
1668        };
1669        assert_eq!(ary, ["one1", "2two", "333"]);
1670    }
1671
1672    #[test]
1673    fn test_de_bytes() {
1674        let mut test = [0;2]; test.copy_from_slice(b"[]");
1675        let bytes: &[u8] = from_mut_slice(&mut test).unwrap();
1676        assert_eq!(bytes, b"");
1677
1678        let mut test = [0;2]; test.copy_from_slice(br#""""#);
1679        let bytes: &[u8] = from_mut_slice(&mut test).unwrap();
1680        assert_eq!(bytes, b"");
1681
1682        let mut test = [0;12]; test.copy_from_slice(br#""Hello!\r\n""#);
1683        let bytes: &[u8] = from_mut_slice(&mut test).unwrap();
1684        assert_eq!(bytes, b"Hello!\r\n");
1685
1686        let mut test = [0;3]; test.copy_from_slice(b"[0]");
1687        let bytes: &[u8] = from_mut_slice(&mut test).unwrap();
1688        assert_eq!(bytes, [0]);
1689
1690        let mut test = [0;10]; test.copy_from_slice(b"[0,1 , 2 ]");
1691        let bytes: &[u8] = from_mut_slice(&mut test).unwrap();
1692        assert_eq!(bytes, [0,1,2]);
1693
1694        let mut test = [0;10]; test.copy_from_slice(br#""Ff00ABab""#);
1695        let bytes: &[u8] = from_mut_slice_hex_bytes(&mut test).unwrap();
1696        assert_eq!(bytes, [0xff,0x00,0xab,0xab]);
1697
1698        let mut test = [0;4]; test.copy_from_slice(br#""ABC"#);
1699        assert_eq!(from_mut_slice_hex_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedEof));
1700        let mut test = [0;4]; test.copy_from_slice(br#""ABx"#);
1701        assert_eq!(from_mut_slice_hex_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedEof));
1702        let mut test = [0;5]; test.copy_from_slice(br#""ABCx"#);
1703        assert_eq!(from_mut_slice_hex_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedChar));
1704        let mut test = [0;5]; test.copy_from_slice(br#""ABxy"#);
1705        assert_eq!(from_mut_slice_hex_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedChar));
1706        let mut test = [0;0];
1707        assert_eq!(from_mut_slice_hex_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedEof));
1708        let mut test = [0;3]; test.copy_from_slice(br#""\""#);
1709        assert_eq!(from_mut_slice_hex_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedChar));
1710
1711        let mut test = [0;13]; test.copy_from_slice(br#""/wCrqw=====""#);
1712        let bytes: &[u8] = from_mut_slice_base64_bytes(&mut test).unwrap();
1713        assert_eq!(bytes, [0xff,0x00,0xab,0xab]);
1714        let mut test = [0;10]; test.copy_from_slice(br#""/wCrqw==""#);
1715        let bytes: &[u8] = from_mut_slice_base64_bytes(&mut test).unwrap();
1716        assert_eq!(bytes, [0xff,0x00,0xab,0xab]);
1717        let mut test = [0;9]; test.copy_from_slice(br#""/wCrqw=""#);
1718        let bytes: &[u8] = from_mut_slice_base64_bytes(&mut test).unwrap();
1719        assert_eq!(bytes, [0xff,0x00,0xab,0xab]);
1720        let mut test = [0;8]; test.copy_from_slice(br#""/wCrqw""#);
1721        let bytes: &[u8] = from_mut_slice_base64_bytes(&mut test).unwrap();
1722        assert_eq!(bytes, [0xff,0x00,0xab,0xab]);
1723
1724        let mut test = [0;2]; test.copy_from_slice(br#""\"#);
1725        assert_eq!(from_mut_slice_base64_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedChar));
1726        let mut test = [0;1]; test.copy_from_slice(br#"""#);
1727        assert_eq!(from_mut_slice_base64_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedEof));
1728        let mut test = [0;2]; test.copy_from_slice(br#""="#);
1729        assert_eq!(from_mut_slice_base64_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedEof));
1730        let mut test = [0;3]; test.copy_from_slice(br#""//"#);
1731        assert_eq!(from_mut_slice_base64_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedEof));
1732        let mut test = [0;5]; test.copy_from_slice(br#""//=="#);
1733        assert_eq!(from_mut_slice_base64_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedEof));
1734        let mut test = [0;5]; test.copy_from_slice(br#""//=x"#);
1735        assert_eq!(from_mut_slice_base64_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedChar));
1736        let mut test = [0;7]; test.copy_from_slice(br#""//===x"#);
1737        assert_eq!(from_mut_slice_base64_bytes::<&[u8]>(&mut test), Err(Error::UnexpectedChar));
1738
1739        let mut test = [0;0]; test.copy_from_slice(b"");
1740        assert!(from_mut_slice_hex_bytes::<&[u8]>(&mut test).is_err());
1741        let mut test = [0;1]; test.copy_from_slice(br#"""#);
1742        assert!(from_mut_slice_hex_bytes::<&[u8]>(&mut test).is_err());
1743        let mut test = [0;3]; test.copy_from_slice(br#""0""#);
1744        assert!(from_mut_slice_hex_bytes::<&[u8]>(&mut test).is_err());
1745        let mut test = [0;5]; test.copy_from_slice(br#""ABC""#);
1746        assert!(from_mut_slice_hex_bytes::<&[u8]>(&mut test).is_err());
1747        let mut test = [0;4]; test.copy_from_slice(br#""Xy""#);
1748        assert!(from_mut_slice_hex_bytes::<&[u8]>(&mut test).is_err());
1749        let mut test = [0;1]; test.copy_from_slice(b"[");
1750        assert!(from_mut_slice::<&[u8]>(&mut test).is_err());
1751        let mut test = [0;4]; test.copy_from_slice(b"[-1]");
1752        assert!(from_mut_slice::<&[u8]>(&mut test).is_err());
1753        let mut test = [0;5]; test.copy_from_slice(b"[256]");
1754        assert!(from_mut_slice::<&[u8]>(&mut test).is_err());
1755        let mut test = [0;3]; test.copy_from_slice(b"[,]");
1756        assert!(from_mut_slice::<&[u8]>(&mut test).is_err());
1757        let mut test = [0;4]; test.copy_from_slice(b"[0,]");
1758        assert!(from_mut_slice::<&[u8]>(&mut test).is_err());
1759        let mut test = [0;1]; test.copy_from_slice(br#"["#);
1760        assert_eq!(from_mut_slice::<&[u8]>(&mut test), Err(Error::UnexpectedEof));
1761        let mut test = [0;2]; test.copy_from_slice(br#"[0"#);
1762        assert_eq!(from_mut_slice::<&[u8]>(&mut test), Err(Error::UnexpectedEof));
1763        let mut test = [0;3]; test.copy_from_slice(br#"[0."#);
1764        assert_eq!(from_mut_slice::<&[u8]>(&mut test), Err(Error::UnexpectedChar));
1765        let mut test = [0;1]; test.copy_from_slice(br#"{"#);
1766        assert_eq!(from_mut_slice::<&[u8]>(&mut test), Err(Error::UnexpectedChar));
1767
1768        use serde::Serialize;
1769
1770        #[derive(Default, Debug, PartialEq, Serialize, Deserialize)]
1771        #[serde(default)]
1772        struct Test<'a> {
1773            #[serde(with = "serde_bytes", skip_serializing_if = "Option::is_none")]
1774            borrowed: Option<&'a[u8]>,
1775            #[serde(skip_serializing_if = "Option::is_none")]
1776            tail: Option<bool>,
1777        }
1778        let mut buf = [0u8;52];
1779        let mut writer = SliceWriter::new(&mut buf);
1780        let mut test = Test { borrowed: Some(&[0,10,11,12,13,14,15,16,17,18,19,255]), ..Test::default() };
1781        let expected = br#"{"borrowed":[0,10,11,12,13,14,15,16,17,18,19,255]}"#;
1782        crate::to_writer(&mut writer, &test).unwrap();
1783        assert_eq!(&writer.as_ref(), expected);
1784        assert_eq!(from_mut_slice::<Test>(writer.split().0).unwrap(), test);
1785
1786        let mut writer = SliceWriter::new(&mut buf);
1787        writer.write(br#" { "borrowed" : [  255, 127, 128, 0  ] } "#).unwrap();
1788        assert_eq!(
1789            from_mut_slice::<Test>(writer.split().0).unwrap(),
1790            Test { borrowed: Some(&[255,127,128,0]), ..Test::default() }
1791        );
1792
1793        let mut writer = SliceWriter::new(&mut buf);
1794        test.tail = Some(false);
1795        let expected = br#"{"borrowed":"000A0B0C0D0E0F10111213FF","tail":false}"#;
1796        crate::to_writer_hex_bytes(&mut writer, &test).unwrap();
1797        assert_eq!(&writer.as_ref(), expected);
1798        assert_eq!(from_mut_slice_hex_bytes::<Test>(writer.split().0).unwrap(), test);
1799
1800        let mut writer = SliceWriter::new(&mut buf);
1801        writer.write(br#" { "tail" :true ,"borrowed": "DEADBACA9970" } "#).unwrap();
1802        assert_eq!(
1803            from_mut_slice_hex_bytes::<Test>(writer.split().0).unwrap(),
1804            Test { tail: Some(true), borrowed: Some(&[0xde,0xad,0xba,0xca,0x99,0x70]), ..Test::default() }
1805        );
1806
1807        let mut writer = SliceWriter::new(&mut buf);
1808        test.tail = Some(false);
1809        let expected = br#"{"borrowed":"AAoLDA0ODxAREhP/","tail":false}"#;
1810        crate::to_writer_base64_bytes(&mut writer, &test).unwrap();
1811        assert_eq!(&writer.as_ref(), expected);
1812        assert_eq!(from_mut_slice_base64_bytes::<Test>(writer.split().0).unwrap(), test);
1813
1814        let mut writer = SliceWriter::new(&mut buf);
1815        writer.write(br#" { "tail" :true ,"borrowed": "ABCDefgh" } "#).unwrap();
1816        assert_eq!(
1817            from_mut_slice_base64_bytes::<Test>(writer.split().0).unwrap(),
1818            Test { tail: Some(true), borrowed: Some(&[0, 16, 131, 121, 248, 33]), ..Test::default() }
1819        );
1820
1821        let mut writer = SliceWriter::new(&mut buf);
1822        writer.write(br#" { "borrowed": [  ] , "tail" :  false}  "#).unwrap();
1823        assert_eq!(
1824            from_mut_slice_hex_bytes::<Test>(writer.split().0).unwrap(),
1825            Test { tail: Some(false), borrowed: Some(b"") }
1826        );
1827
1828        let mut writer = SliceWriter::new(&mut buf);
1829        writer.write(br#"{"tail":null,"owned":[],"borrowed":""}"#).unwrap();
1830        assert_eq!(
1831            from_mut_slice_hex_bytes::<Test>(writer.split().0).unwrap(),
1832            Test { borrowed: Some(b""), tail: None }
1833        );
1834
1835        let mut writer = SliceWriter::new(&mut buf);
1836        writer.write(br#" {   }  "#).unwrap();
1837        assert_eq!(
1838            from_mut_slice_hex_bytes::<Test>(writer.split().0).unwrap(),
1839            Test::default()
1840        );
1841    }
1842
1843    #[cfg(any(feature = "std", feature = "alloc"))]
1844    #[test]
1845    fn test_de_bytes_own() {
1846        use serde::Serialize;
1847
1848        #[derive(Default, Debug, PartialEq, Serialize, Deserialize)]
1849        #[serde(default)]
1850        struct Test<'a> {
1851            #[serde(with = "serde_bytes", skip_serializing_if = "Option::is_none")]
1852            owned: Option<Vec<u8>>,
1853            #[serde(with = "serde_bytes", skip_serializing_if = "Option::is_none")]
1854            borrowed: Option<&'a[u8]>,
1855            #[serde(skip_serializing_if = "Option::is_none")]
1856            tail: Option<bool>,
1857        }
1858
1859        let mut vec = Vec::new();
1860        let mut test = Test { owned: Some(vec![0,10,11,12,13,14,15,16,17,18,19,255]), ..Test::default() };
1861        let expected = br#"{"owned":[0,10,11,12,13,14,15,16,17,18,19,255]}"#;
1862        crate::to_writer(&mut vec, &test).unwrap();
1863        assert_eq!(&vec, expected);
1864        assert_eq!(from_mut_slice::<Test>(&mut vec).unwrap(), test);
1865
1866        vec.clear();
1867        vec.extend_from_slice(br#" { "owned" : [  255, 127, 128, 0  ] } "#);
1868        assert_eq!(
1869            from_mut_slice::<Test>(&mut vec).unwrap(),
1870            Test { owned: Some(vec![255,127,128,0]), ..Test::default() }
1871        );
1872
1873        vec.clear();
1874        test.tail = Some(false);
1875        let expected = br#"{"owned":"000A0B0C0D0E0F10111213FF","tail":false}"#;
1876        crate::to_writer_hex_bytes(&mut vec, &test).unwrap();
1877        assert_eq!(&vec, expected);
1878        assert_eq!(from_mut_slice_hex_bytes::<Test>(&mut vec).unwrap(), test);
1879
1880        vec.clear();
1881        vec.extend_from_slice(br#" { "tail" :true ,"owned": "DEADBACA9970" } "#);
1882        assert_eq!(
1883            from_mut_slice_hex_bytes::<Test>(&mut vec).unwrap(),
1884            Test { tail: Some(true), owned: Some(vec![0xde,0xad,0xba,0xca,0x99,0x70]), ..Test::default() }
1885        );
1886
1887        vec.clear();
1888        test.tail = Some(false);
1889        let expected = br#"{"owned":"AAoLDA0ODxAREhP/","tail":false}"#;
1890        crate::to_writer_base64_bytes(&mut vec, &test).unwrap();
1891        assert_eq!(&vec, expected);
1892        assert_eq!(from_mut_slice_base64_bytes::<Test>(&mut vec).unwrap(), test);
1893
1894        vec.clear();
1895        vec.extend_from_slice(br#" { "tail" :true ,"owned": "ABCDefgh" } "#);
1896        assert_eq!(
1897            from_mut_slice_base64_bytes::<Test>(&mut vec).unwrap(),
1898            Test { tail: Some(true), owned: Some(vec![0, 16, 131, 121, 248, 33]), ..Test::default() }
1899        );
1900
1901        vec.clear();
1902        let mut test = Test { borrowed: Some(&[0,10,11,12,13,14,15,16,17,18,19,255]), ..Test::default() };
1903        let expected = br#"{"borrowed":[0,10,11,12,13,14,15,16,17,18,19,255]}"#;
1904        crate::to_writer(&mut vec, &test).unwrap();
1905        assert_eq!(&vec, expected);
1906        assert_eq!(from_mut_slice_hex_bytes::<Test>(&mut vec).unwrap(), test);
1907
1908        vec.clear();
1909        vec.extend_from_slice(br#" { "borrowed" : [  255, 127, 128, 0  ] ,"tail"  :false}"#);
1910        assert_eq!(
1911            from_mut_slice_hex_bytes::<Test>(&mut vec).unwrap(),
1912            Test { borrowed: Some(&[255,127,128,0]), tail: Some(false), ..Test::default() }
1913        );
1914
1915        vec.clear();
1916        vec.extend_from_slice(br#" { "borrowed" : "DEADBACA9970" ,"tail"  :null, "owned":null } "#);
1917        assert_eq!(
1918            from_mut_slice_hex_bytes::<Test>(&mut vec).unwrap(),
1919            Test { borrowed: Some(&[0xde,0xad,0xba,0xca,0x99,0x70]), ..Test::default() }
1920        );
1921
1922        vec.clear();
1923        test.tail = Some(true);
1924        let expected = br#"{"borrowed":"000A0B0C0D0E0F10111213FF","tail":true}"#;
1925        crate::to_writer_hex_bytes(&mut vec, &test).unwrap();
1926        assert_eq!(&vec, expected);
1927        assert_eq!(from_mut_slice_hex_bytes::<Test>(&mut vec).unwrap(), test);
1928
1929        vec.clear();
1930        let expected = br#"{"borrowed":"AAoLDA0ODxAREhP/","tail":true}"#;
1931        crate::to_writer_base64_bytes(&mut vec, &test).unwrap();
1932        assert_eq!(&vec, expected);
1933        assert_eq!(from_mut_slice_base64_bytes::<Test>(&mut vec).unwrap(), test);
1934
1935        vec.clear();
1936        vec.extend_from_slice(br#" { "borrowed": [  ] , "tail" :  false ,  "owned"   :  "" }  "#);
1937        assert_eq!(
1938            from_mut_slice_hex_bytes::<Test>(&mut vec).unwrap(),
1939            Test { borrowed: Some(&[]), tail: Some(false), owned: Some(vec![]) }
1940        );
1941
1942        vec.clear();
1943        vec.extend_from_slice(br#"{"tail":null,"owned":[],"borrowed":""}"#);
1944        assert_eq!(
1945            from_mut_slice_hex_bytes::<Test>(&mut vec).unwrap(),
1946            Test { borrowed: Some(&[]), tail: None, owned: Some(vec![]) }
1947        );
1948
1949        vec.clear();
1950        vec.extend_from_slice(br#" {   }  "#);
1951        assert_eq!(
1952            from_mut_slice_hex_bytes::<Test>(&mut vec).unwrap(),
1953            Test::default()
1954        );
1955    }
1956
1957    #[derive(Debug, Deserialize, PartialEq)]
1958    enum Type {
1959        #[serde(rename = "boolean")]
1960        Boolean,
1961        #[serde(rename = "number")]
1962        Number,
1963        #[serde(rename = "thing")]
1964        Thing,
1965    }
1966
1967    fn from_str<T>(s: &str) -> Result<(T, usize)>
1968        where for<'a> T: de::Deserialize<'a>
1969    {
1970        let mut buf = [0u8;256];
1971        from_bufstr(&mut buf, s)
1972    }
1973
1974    fn from_bufstr<'a, T>(buf: &'a mut[u8], s: &str) -> Result<(T, usize)>
1975        where T: de::Deserialize<'a>
1976    {
1977        let mut writer = SliceWriter::new(buf);
1978        writer.write(s.as_bytes()).unwrap();
1979        let len = writer.len();
1980        let res: T = from_mut_slice(writer.split().0)?;
1981        Ok((res, len))
1982    }
1983
1984    #[test]
1985    fn test_de_array() {
1986        assert_eq!(from_str::<[i32; 0]>("[]"), Ok(([], 2)));
1987        assert_eq!(from_str("[0, 1, 2]"), Ok(([0, 1, 2], 9)));
1988        // error
1989        assert_eq!(from_str::<[i32; 2]>(""), Err(Error::UnexpectedEof));
1990        assert_eq!(from_str::<[i32; 2]>("{}"), Err(Error::ExpectedArray));
1991        assert_eq!(from_str::<[i32; 2]>("[0, 1,"), Err(Error::ExpectedArrayEnd));
1992        assert_eq!(from_str::<[i32; 3]>("[0, 1,]"), Err(Error::TrailingArrayComma));
1993        assert_eq!(from_str::<[i32; 2]>("[,]"), Err(Error::LeadingArrayComma));
1994        assert_eq!(from_str::<[i32; 2]>("[, 0]"), Err(Error::LeadingArrayComma));
1995        assert_eq!(from_str::<[i32; 2]>("[0}"), Err(Error::ExpectedArrayCommaOrEnd));
1996        assert_eq!(from_str::<[i32; 2]>("["), Err(Error::UnexpectedEof));
1997        assert_eq!(from_str::<[i32; 2]>("[0"), Err(Error::UnexpectedEof));
1998        assert_eq!(from_str::<[i32; 2]>("[0,"), Err(Error::UnexpectedEof));
1999        assert_eq!(from_str::<[i32; 2]>("[0,1"), Err(Error::UnexpectedEof));
2000    }
2001
2002    #[test]
2003    fn test_de_bool() {
2004        assert_eq!(from_str("true"), Ok((true, 4)));
2005        assert_eq!(from_str(" true"), Ok((true, 5)));
2006        assert_eq!(from_str("true "), Ok((true, 5)));
2007
2008        assert_eq!(from_str("false"), Ok((false, 5)));
2009        assert_eq!(from_str(" false"), Ok((false, 6)));
2010        assert_eq!(from_str("false "), Ok((false, 6)));
2011        // error
2012        assert_eq!(from_str::<bool>(""), Err(Error::UnexpectedEof));
2013        assert_eq!(from_str::<bool>("true false"), Err(Error::TrailingCharacters));
2014        assert_eq!(from_str::<bool>("tru"), Err(Error::UnexpectedEof));
2015        assert_eq!(from_str::<bool>("truy"), Err(Error::ExpectedToken));
2016        assert_eq!(from_str::<bool>("fals"), Err(Error::UnexpectedEof));
2017        assert_eq!(from_str::<bool>("falsy"), Err(Error::ExpectedToken));
2018        assert_eq!(from_str::<bool>("n"), Err(Error::UnexpectedChar));
2019    }
2020
2021    #[test]
2022    fn test_de_floating_point() {
2023        assert_eq!(from_str("5.0"), Ok((5.0, 3)));
2024        assert_eq!(from_str("1"), Ok((1.0, 1)));
2025        assert_eq!(from_str("-999.9"), Ok((-999.9, 6)));
2026        assert_eq!(from_str("1e5"), Ok((1e5, 3)));
2027        let (f, len): (f32, _) = from_str("null").unwrap();
2028        assert_eq!(len, 4);
2029        assert!(f.is_nan());
2030        let (f, len): (f64, _) = from_str("null").unwrap();
2031        assert_eq!(len, 4);
2032        assert!(f.is_nan());
2033        assert_eq!(from_str::<f32>(""), Err(Error::UnexpectedEof));
2034        assert_eq!(from_str::<f32>("n"), Err(Error::UnexpectedEof));
2035        assert_eq!(from_str::<f32>(","), Err(Error::InvalidNumber));
2036        assert_eq!(from_str::<f64>(","), Err(Error::InvalidNumber));
2037        assert_eq!(from_str::<f32>("-"), Err(Error::InvalidNumber));
2038        assert_eq!(from_str::<f64>("-"), Err(Error::InvalidNumber));
2039    }
2040
2041    #[test]
2042    fn test_de_integer() {
2043        macro_rules! test_de_signed {
2044            ($($ty:ty),*) => {$(
2045                assert_eq!(from_str::<$ty>("-128"), Ok((-128, 4)));
2046                assert_eq!(from_str::<$ty>("-1"), Ok((-1, 2)));
2047                assert_eq!(from_str::<$ty>("-0"), Ok((0, 2)));
2048                assert_eq!(from_str::<$ty>("-01"), Err(Error::TrailingCharacters));
2049                assert_eq!(from_str::<$ty>("-"), Err(Error::UnexpectedEof));
2050                assert_eq!(from_str::<$ty>("-1234567890123456789012345678901234567890"), Err(Error::InvalidNumber));
2051            )*};
2052        }
2053        macro_rules! test_de_unsigned {
2054            ($($ty:ty),*) => {$(
2055                assert_eq!(from_str::<$ty>("0"), Ok((0, 1)));
2056                assert_eq!(from_str::<$ty>("1"), Ok((1, 1)));
2057                assert_eq!(from_str::<$ty>("-1"), Err(Error::InvalidNumber));
2058                assert_eq!(from_str::<$ty>("-01"), Err(Error::InvalidNumber));
2059            )*};
2060        }
2061        macro_rules! test_de_int {
2062            ($($ty:ty),*) => {$(
2063                assert_eq!(from_str::<$ty>("5"), Ok((5, 1)));
2064                assert_eq!(from_str::<$ty>("127"), Ok((127, 3)));
2065                assert_eq!(from_str::<$ty>(","), Err(Error::InvalidType));
2066                assert_eq!(from_str::<$ty>(""), Err(Error::UnexpectedEof));
2067                assert_eq!(from_str::<$ty>("00"), Err(Error::TrailingCharacters));
2068                assert_eq!(from_str::<$ty>("1e5"), Err(Error::TrailingCharacters));
2069                assert_eq!(from_str::<$ty>("1234567890123456789012345678901234567890"), Err(Error::InvalidNumber));
2070            )*};
2071        }
2072        test_de_signed!(i8,i16,i32,i64);
2073        test_de_unsigned!(u8,u16,u32,u64);
2074        test_de_int!(i8,i16,i32,i64,u8,u16,u32,u64);
2075        assert_eq!(from_str::<u8>("256"), Err(Error::InvalidNumber));
2076        assert_eq!(from_str::<i8>("-129"), Err(Error::InvalidNumber));
2077    }
2078
2079    #[test]
2080    fn test_de_enum_clike() {
2081        assert_eq!(from_str(r#" "boolean" "#), Ok((Type::Boolean, 11)));
2082        assert_eq!(from_str(r#" "number" "#), Ok((Type::Number, 10)));
2083        assert_eq!(from_str(r#" "thing" "#), Ok((Type::Thing, 9)));
2084
2085        #[cfg(any(feature = "std", feature = "alloc"))]
2086        assert_eq!(from_str::<Type>(r#" "" "#), Err(Error::DeserializeError(
2087            r#"unknown variant ``, expected one of `boolean`, `number`, `thing`"#.to_string())));
2088        #[cfg(not(any(feature = "std", feature = "alloc")))]
2089        assert_eq!(from_str::<Type>(r#" "" "#), Err(Error::DeserializeError));
2090
2091        #[cfg(any(feature = "std", feature = "alloc"))]
2092        assert_eq!(from_str::<Type>(r#" "xyz" "#), Err(Error::DeserializeError(
2093            r#"unknown variant `xyz`, expected one of `boolean`, `number`, `thing`"#.to_string())));
2094        #[cfg(not(any(feature = "std", feature = "alloc")))]
2095        assert_eq!(from_str::<Type>(r#" "xyz" "#), Err(Error::DeserializeError));
2096
2097        assert_eq!(from_str::<Type>(r#"{"boolean":null}"#), Err(Error::InvalidType));
2098        assert_eq!(from_str::<Type>(r#" {} "#), Err(Error::ExpectedString));
2099        assert_eq!(from_str::<Type>(r#" [] "#), Err(Error::ExpectedEnumValue));
2100    }
2101
2102    #[cfg(any(feature = "std", feature = "alloc"))]
2103    #[test]
2104    fn test_de_string() {
2105        let buf = &mut [0u8;9];
2106        assert_eq!(from_bufstr::<String>(buf, r#""""#), Ok(("".to_string(), 2)));
2107        assert_eq!(from_bufstr::<String>(buf, r#""hello""#), Ok(("hello".to_string(), 7)));
2108        assert_eq!(from_bufstr::<String>(buf, r#" "" "#), Ok(("".to_string(), 4)));
2109        assert_eq!(from_bufstr::<String>(buf, r#" "hello" "#), Ok(("hello".to_string(), 9)));
2110    }
2111
2112    #[test]
2113    fn test_de_str() {
2114        let buf = &mut [0u8;20];
2115        assert_eq!(from_bufstr(buf, r#" "hello" "#), Ok(("hello", 9)));
2116        assert_eq!(from_bufstr(buf, r#" "" "#), Ok(("", 4)));
2117        assert_eq!(from_bufstr(buf, r#" " " "#), Ok((" ", 5)));
2118        assert_eq!(from_bufstr(buf, r#" "👏" "#), Ok(("👏", 8)));
2119
2120        assert_eq!(from_bufstr(buf, r#" "hel\tlo" "#), Ok(("hel\tlo", 11)));
2121        assert_eq!(from_bufstr(buf, r#" "hello \\" "#), Ok(("hello \\", 12)));
2122
2123        // escaped " in the string content
2124        assert_eq!(from_bufstr(buf, r#" "foo\"bar" "#), Ok((r#"foo"bar"#, 12)));
2125        assert_eq!(
2126            from_bufstr(buf, r#" "foo\\\"bar" "#),
2127            Ok((r#"foo\"bar"#, 14))
2128        );
2129        assert_eq!(
2130            from_bufstr(buf, r#" "foo\"\"bar" "#),
2131            Ok((r#"foo""bar"#, 14))
2132        );
2133        assert_eq!(from_bufstr(buf, r#" "\"bar" "#), Ok((r#""bar"#, 9)));
2134        assert_eq!(from_bufstr(buf, r#" "foo\"" "#), Ok((r#"foo""#, 9)));
2135        assert_eq!(from_bufstr(buf, r#" "\"" "#), Ok((r#"""#, 6)));
2136
2137        // non-excaped " preceded by backslashes
2138        assert_eq!(
2139            from_bufstr(buf, r#" "foo bar\\" "#),
2140            Ok((r#"foo bar\"#, 13))
2141        );
2142        assert_eq!(
2143            from_bufstr(buf, r#" "foo bar\\\\" "#),
2144            Ok((r#"foo bar\\"#, 15))
2145        );
2146        assert_eq!(
2147            from_bufstr(buf, r#" "foo bar\\\\\\" "#),
2148            Ok((r#"foo bar\\\"#, 17))
2149        );
2150        assert_eq!(
2151            from_bufstr(buf, r#" "foo bar\\\\\\\\" "#),
2152            Ok((r#"foo bar\\\\"#, 19))
2153        );
2154        assert_eq!(from_bufstr(buf, r#" "\\" "#), Ok((r#"\"#, 6)));
2155        // error
2156        assert_eq!(from_bufstr::<&str>(buf, ""), Err(Error::UnexpectedEof));
2157        assert_eq!(from_bufstr::<&str>(buf, r#" "\x" "#), Err(Error::InvalidEscapeSequence));
2158        assert_eq!(from_bufstr::<&str>(buf, r#" "\c" "#), Err(Error::InvalidEscapeSequence));
2159        assert_eq!(from_bufstr::<&str>(buf, r#" "\ux000" "#), Err(Error::InvalidEscapeSequence));
2160        assert_eq!(from_bufstr::<&str>(buf, r#" "\u0x00" "#), Err(Error::InvalidEscapeSequence));
2161        assert_eq!(from_bufstr::<&str>(buf, r#" "\u00x0" "#), Err(Error::InvalidEscapeSequence));
2162        assert_eq!(from_bufstr::<&str>(buf, r#" "\u000x" "#), Err(Error::InvalidEscapeSequence));
2163        assert_eq!(from_bufstr::<&str>(buf, r#" "\u000" "#), Err(Error::InvalidEscapeSequence));
2164        assert_eq!(from_bufstr::<&str>(buf, r#" "\uD800" "#), Err(Error::InvalidUnicodeCodePoint));
2165        assert_eq!(from_bufstr::<&str>(buf, r#" "\uDFFF" "#), Err(Error::InvalidUnicodeCodePoint));
2166        buf[0..4].copy_from_slice(b"\"\xff\xfe\"");
2167        assert_eq!(from_mut_slice::<&str>(&mut buf[0..4]), Err(Error::InvalidUnicodeCodePoint));
2168    }
2169
2170    #[test]
2171    fn test_de_char() {
2172        assert_eq!(from_str::<char>(r#""A""#), Ok(('A', 3)));
2173        assert_eq!(from_str::<char>(r#"" ""#), Ok((' ', 3)));
2174        assert_eq!(from_str::<char>(r#""\t""#), Ok(('\t', 4)));
2175        assert_eq!(from_str::<char>(r#""👏""#), Ok(('👏', 6)));
2176        assert_eq!(from_str::<char>(""), Err(Error::UnexpectedEof));
2177        assert_eq!(from_str::<char>("["), Err(Error::ExpectedString));
2178        assert_eq!(from_str::<char>(r#""ab""#), Err(Error::InvalidLength));
2179        assert_eq!(from_str::<char>(r#""\""#), Err(Error::UnexpectedEof));
2180    }
2181
2182    #[test]
2183    fn test_de_struct() {
2184        #[derive(Default, Debug, Deserialize, PartialEq)]
2185        #[serde(default)]
2186        struct Test {
2187            foo: i8,
2188            bar: f64
2189        }
2190        assert_eq!(
2191            from_str("{}"),
2192            Ok((Test { foo: 0, bar: 0.0 }, 2))
2193        );
2194        assert_eq!(
2195            from_str(r#"{ "foo": 0 }"#),
2196            Ok((Test { foo: 0, bar: 0.0 }, 12))
2197        );
2198        assert_eq!(
2199            from_str(r#"{"bar":3.14,"foo":-1}"#),
2200            Ok((Test {bar: 3.14, foo:-1}, 21))
2201        );
2202        assert_eq!(
2203            from_str(r#" {
2204                "bar" : -9.5e-10 ,
2205                "foo" : -128
2206            }"#),
2207            Ok((Test {bar: -9.5e-10, foo:-128}, 80))
2208        );
2209        assert_eq!(
2210            from_str(r#"[]"#),
2211            Ok((Test {bar: 0.0, foo:0}, 2))
2212        );
2213        assert_eq!(
2214            from_str(r#"[5]"#),
2215            Ok((Test {foo:5, bar: 0.0}, 3))
2216        );
2217        assert_eq!(
2218            from_str(r#"[5,999.9]"#),
2219            Ok((Test {foo:5, bar: 999.9}, 9))
2220        );
2221        // error
2222        assert_eq!(from_str::<Test>(""), Err(Error::UnexpectedEof));
2223        assert_eq!(from_str::<Test>(r#""""#), Err(Error::ExpectedStruct));
2224        assert_eq!(from_str::<Test>(r#"{"foo":0]"#), Err(Error::ExpectedObjectCommaOrEnd));
2225        assert_eq!(from_str::<Test>(r#"{"foo":0,}"#), Err(Error::TrailingObjectComma));
2226        assert_eq!(from_str::<Test>(r#"{"foo",0}"#), Err(Error::ExpectedColon));
2227        assert_eq!(from_str::<Test>(r#"{,}"#), Err(Error::LeadingObjectComma));
2228        assert_eq!(from_str::<Test>(r#"{,"foo":0}"#), Err(Error::LeadingObjectComma));
2229    }
2230
2231    #[test]
2232    fn test_de_struct_bool() {
2233        #[derive(Debug, Deserialize, PartialEq)]
2234        struct Led {
2235            led: bool,
2236        }
2237
2238        assert_eq!(
2239            from_str(r#"{ "led": true }"#),
2240            Ok((Led { led: true }, 15))
2241        );
2242        assert_eq!(
2243            from_str(r#"{ "led": false }"#),
2244            Ok((Led { led: false }, 16))
2245        );
2246    }
2247
2248    #[test]
2249    fn test_de_struct_i8() {
2250        #[derive(Debug, Deserialize, PartialEq)]
2251        struct Temperature {
2252            temperature: i8,
2253        }
2254
2255        assert_eq!(
2256            from_str(r#"{ "temperature": -17 }"#),
2257            Ok((Temperature { temperature: -17 }, 22))
2258        );
2259
2260        assert_eq!(
2261            from_str(r#"{ "temperature": -0 }"#),
2262            Ok((Temperature { temperature: -0 }, 21))
2263        );
2264
2265        assert_eq!(
2266            from_str(r#"{ "temperature": 0 }"#),
2267            Ok((Temperature { temperature: 0 }, 20))
2268        );
2269
2270        // out of range
2271        assert!(from_str::<Temperature>(r#"{ "temperature": 128 }"#).is_err());
2272        assert!(from_str::<Temperature>(r#"{ "temperature": -129 }"#).is_err());
2273    }
2274
2275    #[test]
2276    fn test_de_struct_u8() {
2277        #[derive(Debug, Deserialize, PartialEq)]
2278        struct Temperature {
2279            temperature: u8,
2280        }
2281
2282        assert_eq!(
2283            from_str(r#"{ "temperature": 20 }"#),
2284            Ok((Temperature { temperature: 20 }, 21))
2285        );
2286
2287        assert_eq!(
2288            from_str(r#"{ "temperature": 0 }"#),
2289            Ok((Temperature { temperature: 0 }, 20))
2290        );
2291
2292        // out of range
2293        assert!(from_str::<Temperature>(r#"{ "temperature": 256 }"#).is_err());
2294        assert!(from_str::<Temperature>(r#"{ "temperature": -1 }"#).is_err());
2295    }
2296
2297    #[test]
2298    fn test_de_struct_f32() {
2299        #[derive(Debug, Deserialize, PartialEq)]
2300        struct Temperature {
2301            temperature: f32,
2302        }
2303
2304        assert_eq!(
2305            from_str(r#"{ "temperature": -17.2 }"#),
2306            Ok((Temperature { temperature: -17.2 }, 24))
2307        );
2308
2309        assert_eq!(
2310            from_str(r#"{ "temperature": -0.0 }"#),
2311            Ok((Temperature { temperature: -0. }, 23))
2312        );
2313
2314        assert_eq!(
2315            from_str(r#"{ "temperature": -2.1e-3 }"#),
2316            Ok((
2317                Temperature {
2318                    temperature: -2.1e-3
2319                },
2320                26
2321            ))
2322        );
2323
2324        assert_eq!(
2325            from_str(r#"{ "temperature": -3 }"#),
2326            Ok((Temperature { temperature: -3. }, 21))
2327        );
2328
2329        use core::f32;
2330
2331        assert_eq!(
2332            from_str(r#"{ "temperature": -1e500 }"#),
2333            Ok((
2334                Temperature {
2335                    temperature: f32::NEG_INFINITY
2336                },
2337                25
2338            ))
2339        );
2340
2341        // NaNs will always compare unequal.
2342        let (r, n): (Temperature, usize) = from_str(r#"{ "temperature": null }"#).unwrap();
2343        assert!(r.temperature.is_nan());
2344        assert_eq!(n, 23);
2345
2346        assert!(from_str::<Temperature>(r#"{ "temperature": 1e1e1 }"#).is_err());
2347        assert!(from_str::<Temperature>(r#"{ "temperature": -2-2 }"#).is_err());
2348        assert!(from_str::<Temperature>(r#"{ "temperature": 1 1 }"#).is_err());
2349        assert!(from_str::<Temperature>(r#"{ "temperature": 0.0. }"#).is_err());
2350        assert!(from_str::<Temperature>(r#"{ "temperature": ä }"#).is_err());
2351        assert!(from_str::<Temperature>(r#"{ "temperature": None }"#).is_err());
2352        assert!(from_str::<Temperature>(r#"{"temperature":+}"#).is_err());
2353    }
2354
2355    #[test]
2356    fn test_de_struct_option() {
2357        #[derive(Debug, Deserialize, PartialEq)]
2358        struct Property<'a> {
2359            #[serde(borrow)]
2360            description: Option<&'a str>,
2361        }
2362
2363        let buf = &mut [0u8;50];
2364
2365        assert_eq!(
2366            from_bufstr(buf, r#"{ "description": "An ambient temperature sensor" }"#),
2367            Ok((
2368                Property {
2369                    description: Some("An ambient temperature sensor"),
2370                },
2371                50
2372            ))
2373        );
2374
2375        assert_eq!(
2376            from_bufstr(buf, r#"{ "description": null }"#),
2377            Ok((Property { description: None }, 23))
2378        );
2379
2380        assert_eq!(
2381            from_bufstr(buf, r#"{}"#),
2382            Ok((Property { description: None }, 2))
2383        );
2384    }
2385
2386    #[test]
2387    fn test_de_unit() {
2388        assert_eq!(from_str(r#"null"#), Ok(((), 4)));
2389        #[derive(Debug, Deserialize, PartialEq)]
2390        struct Unit;
2391        assert_eq!(from_str(r#"null"#), Ok((Unit, 4)));
2392        assert_eq!(from_str::<()>("x"), Err(Error::ExpectedNull));
2393        assert_eq!(from_str::<Unit>("x"), Err(Error::ExpectedNull));
2394        assert_eq!(from_str::<()>("nil"), Err(Error::UnexpectedEof));
2395        assert_eq!(from_str::<Unit>("nil"), Err(Error::UnexpectedEof));
2396        assert_eq!(from_str::<()>("nill"), Err(Error::ExpectedToken));
2397        assert_eq!(from_str::<Unit>("nill"), Err(Error::ExpectedToken));
2398        assert_eq!(from_str::<()>(""), Err(Error::UnexpectedEof));
2399        assert_eq!(from_str::<Unit>(""), Err(Error::UnexpectedEof));
2400    }
2401
2402    #[test]
2403    fn test_de_option() {
2404        assert_eq!(from_str::<Option<bool>>(r#"null"#), Ok((None, 4)));
2405        assert_eq!(from_str::<Option<bool>>(r#"true"#), Ok((Some(true), 4)));
2406        assert_eq!(from_str::<Option<bool>>(r#"false"#), Ok((Some(false), 5)));
2407        assert_eq!(from_str::<Option<bool>>("x"), Err(Error::UnexpectedChar));
2408        assert_eq!(from_str::<Option<bool>>("nil"), Err(Error::UnexpectedEof));
2409        assert_eq!(from_str::<Option<bool>>("nill"), Err(Error::ExpectedToken));
2410        assert_eq!(from_str::<Option<bool>>(""), Err(Error::UnexpectedEof));
2411    }
2412
2413    #[test]
2414    fn test_de_newtype_variant() {
2415        #[derive(Deserialize, Debug, PartialEq)]
2416        enum A {
2417            A(u32),
2418        }
2419        let a = A::A(54);
2420        let (x, len) = from_str::<A>(r#"{"A":54}"#).unwrap();
2421        assert_eq!(len, 8);
2422        assert_eq!(x, a);
2423        let (y, len) = from_str::<A>(r#" { "A" : 54 } "#).unwrap();
2424        assert_eq!(len, 14);
2425        assert_eq!(x, y);
2426        assert_eq!(from_str::<A>(r#""A""#), Err(Error::InvalidType));
2427        assert_eq!(from_str::<A>(r#"{"A","#), Err(Error::ExpectedColon));
2428        assert_eq!(from_str::<A>(r#"{"A":54,"#), Err(Error::ExpectedEnumObjectEnd));
2429        assert_eq!(from_str::<A>(r#"{"A":54"#), Err(Error::UnexpectedEof));
2430        assert_eq!(from_str::<A>(r#" "#), Err(Error::UnexpectedEof));
2431    }
2432
2433    #[test]
2434    fn test_de_struct_variant() {
2435        #[derive(Deserialize, Debug, PartialEq)]
2436        enum A {
2437            A { x: u32, y: u16 },
2438        }
2439        let a = A::A { x: 54, y: 720 };
2440        let (x, len) = from_str::<A>(r#"{"A":{"x":54,"y":720}}"#).unwrap();
2441        assert_eq!(len, 22);
2442        assert_eq!(x, a);
2443        let (z, len) = from_str::<A>(r#" { "A"  : { "x" : 54 , "y" : 720 } } "#).unwrap();
2444        assert_eq!(len, 37);
2445        assert_eq!(z, x);
2446        let (y, len) = from_str::<A>(r#"{"A":[54,720]}"#).unwrap();
2447        assert_eq!(len, 14);
2448        assert_eq!(y, z);
2449        let (yy, len) = from_str::<A>(r#" { "A" : [ 54 , 720 ] } "#).unwrap();
2450        assert_eq!(len, 24);
2451        assert_eq!(yy, y);
2452        assert_eq!(from_str::<A>(r#""A""#), Err(Error::InvalidType));
2453    }
2454
2455    #[test]
2456    fn test_de_tuple_variant() {
2457        #[derive(Deserialize, Debug, PartialEq)]
2458        enum A {
2459            A(i32,u16),
2460        }
2461        let a = A::A(-981,10000);
2462        let (x, len) = from_str::<A>(r#"{"A":[-981,10000]}"#).unwrap();
2463        assert_eq!(len, 18);
2464        assert_eq!(x, a);
2465        let (y, len) = from_str::<A>(r#" { "A" : [ -981 , 10000 ] } "#).unwrap();
2466        assert_eq!(len, 28);
2467        assert_eq!(y, x);
2468        assert_eq!(from_str::<A>(r#""A""#), Err(Error::InvalidType));
2469    }
2470
2471    #[test]
2472    fn test_de_newtype_struct() {
2473        #[derive(Deserialize, Debug, PartialEq)]
2474        struct A(u32);
2475
2476        assert_eq!(from_str::<A>(r#"54"#), Ok((A(54), 2)));
2477    }
2478
2479    #[test]
2480    fn test_de_struct_tuple() {
2481        #[derive(Debug, Deserialize, PartialEq)]
2482        struct Xy(i8, i8);
2483
2484        assert_eq!(from_str(r#"[10, 20]"#), Ok((Xy(10, 20), 8)));
2485        assert_eq!(from_str(r#"[10, -20]"#), Ok((Xy(10, -20), 9)));
2486
2487        // wrong number of args
2488        #[cfg(any(feature = "std", feature = "alloc"))]
2489        assert_eq!(
2490            from_str::<Xy>(r#"[10]"#),
2491            Err(Error::DeserializeError(
2492                r#"invalid length 1, expected tuple struct Xy with 2 elements"#.to_string()))
2493        );
2494        #[cfg(not(any(feature = "std", feature = "alloc")))]
2495        assert_eq!(
2496            from_str::<Xy>(r#"[10]"#),
2497            Err(Error::DeserializeError)
2498        );
2499        assert_eq!(
2500            from_str::<Xy>(r#"[10, 20, 30]"#),
2501            Err(Error::ExpectedArrayEnd)
2502        );
2503    }
2504
2505    #[test]
2506    fn test_de_struct_with_array_field() {
2507        #[derive(Debug, Deserialize, PartialEq, Clone, Copy)]
2508        struct Test {
2509            status: bool,
2510            point: [u32; 3],
2511        }
2512        let test = Test {
2513            status: true,
2514            point: [1, 2, 3]
2515        };
2516        assert_eq!(
2517            from_str(r#"{ "status": true,
2518                          "point": [1, 2, 3] }"#),
2519            Ok((test, 64))
2520        );
2521
2522        assert_eq!(
2523            from_str(r#"{"status":true,"point":[1,2,3]}"#),
2524            Ok((test, 31))
2525        );
2526    }
2527
2528    #[test]
2529    fn test_de_struct_with_tuple_field() {
2530        #[derive(Debug, Deserialize, PartialEq)]
2531        struct Test {
2532            status: bool,
2533            point: (u32, u32, u32),
2534        }
2535
2536        assert_eq!(
2537            from_str(r#"{ "status": true, "point": [1, 2, 3] }"#),
2538            Ok((
2539                Test {
2540                    status: true,
2541                    point: (1, 2, 3)
2542                },
2543                38
2544            ))
2545        );
2546    }
2547
2548    #[test]
2549    fn test_de_ignoring_extra_fields() {
2550        #[derive(Debug, Deserialize, PartialEq)]
2551        struct Temperature {
2552            temperature: u8,
2553        }
2554
2555        assert_eq!(
2556            from_str(r#"{ "temperature": 20, "high": 80, "low": -10, "updated": true, "unused": null }"#),
2557            Ok((Temperature { temperature: 20 }, 78)));
2558
2559        assert_eq!(
2560            from_str(
2561                r#"{ "temperature": 20, "conditions": "windy", "forecast": "cloudy" }"#
2562            ),
2563            Ok((Temperature { temperature: 20 }, 66)));
2564
2565        assert_eq!(
2566            from_str(r#"{ "temperature": 20, "hourly_conditions": ["windy", "rainy"] }"#),
2567            Ok((Temperature { temperature: 20 }, 62)));
2568
2569        assert_eq!(
2570            from_str(
2571                r#"{ "temperature"  :  20, "source": { "station": "dock", "sensors": ["front", "back"] } }"#
2572            ),
2573            Ok((Temperature { temperature: 20 }, 87)));
2574
2575        assert_eq!(
2576            from_str(
2577                r#"{ "source": { "station": "dock", "sensors": ["\\", "\"", "x\\\"y\\"] }, "temperature":20}"#
2578            ),
2579            Ok((Temperature { temperature: 20 }, 89)));
2580        // error
2581        assert_eq!(
2582            from_str::<Temperature>(r#"{ "temperature": 20, "invalid": this-is-not-ignored }"#),
2583            Err(Error::ExpectedToken));
2584        assert_eq!(
2585            from_str::<Temperature>(r#"{ "temperature": 20, "broken": }"#),
2586            Err(Error::UnexpectedChar));
2587        assert_eq!(
2588            from_str::<Temperature>(r#"{ "temperature": 20, "broken": [ }"#),
2589            Err(Error::UnexpectedChar));
2590        assert_eq!(
2591            from_str::<Temperature>(r#"{ "temperature": 20, "broken": ] }"#),
2592            Err(Error::UnexpectedChar));
2593        assert_eq!(
2594            from_str::<Temperature>(r#"{"temperature":20,"broken":1"#),
2595            Err(Error::UnexpectedEof));
2596        assert_eq!(
2597            from_str::<Temperature>(r#"{"temperature":20,"broken":"#),
2598            Err(Error::UnexpectedEof));
2599        assert_eq!(
2600            from_str::<Temperature>(r#"{"temperature":20,"broken":""#),
2601            Err(Error::UnexpectedEof));
2602        assert_eq!(
2603            from_str::<Temperature>(r#"{"temperature":20,"#),
2604            Err(Error::UnexpectedEof));
2605    }
2606
2607    #[test]
2608    fn test_de_map_err() {
2609        use core::marker::PhantomData;
2610        use serde::de::Deserializer;
2611        #[derive(Debug, PartialEq)]
2612        struct PhonyMap(Option<(i32,i32)>);
2613        struct PhonyMapVisitor(PhantomData<PhonyMap>);
2614        impl<'de> Visitor<'de> for PhonyMapVisitor {
2615            type Value = PhonyMap;
2616            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2617                formatter.write_str("a map")
2618            }
2619            fn visit_map<M: MapAccess<'de>>(self, mut access: M) -> core::result::Result<Self::Value, M::Error> {
2620                if let Some((k, v)) = access.next_entry()? {
2621                    return Ok(PhonyMap(Some((k,v))))
2622                }
2623                Ok(PhonyMap(None))
2624            }
2625        }
2626        impl<'de> Deserialize<'de> for PhonyMap {
2627            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> core::result::Result<Self, D::Error> {
2628                deserializer.deserialize_any(PhonyMapVisitor(PhantomData))
2629            }
2630        }
2631        assert_eq!(
2632            from_str::<PhonyMap>(r#"{}"#),
2633            Ok((PhonyMap(None), 2)));
2634        assert_eq!(
2635            from_str::<PhonyMap>(r#"{"0":1}"#),
2636            Ok((PhonyMap(Some((0,1))), 7)));
2637        assert_eq!(from_str::<PhonyMap>(r#""#), Err(Error::UnexpectedEof));
2638        assert_eq!(from_str::<PhonyMap>(r#"{"#), Err(Error::UnexpectedEof));
2639        assert_eq!(from_str::<PhonyMap>(r#"{"":0}"#), Err(Error::InvalidType));
2640        assert_eq!(from_str::<PhonyMap>(r#"{"0":1"#), Err(Error::UnexpectedEof));
2641        assert_eq!(from_str::<PhonyMap>(r#"{"0":1]"#), Err(Error::ExpectedObjectEnd));
2642        assert_eq!(from_str::<PhonyMap>(r#"{"0":1,"#), Err(Error::ExpectedObjectEnd));
2643        assert!(from_str::<PhonyMap>(r#"[]"#).is_err());
2644    }
2645
2646    #[cfg(any(feature = "std", feature = "alloc"))]
2647    #[test]
2648    fn test_de_map() {
2649        let buf = &mut [0u8;160];
2650        macro_rules! test_de_map_int {
2651            ($($ty:ty),*) => {$(
2652                let mut amap = BTreeMap::<$ty,&str>::new();
2653                amap.insert(<$ty>::MIN, "Minimum");
2654                amap.insert(1, "One");
2655                amap.insert(<$ty>::MAX, "Maximum");
2656                let s = format!(r#" {{ "  {}" : "Minimum" ,
2657                    " {}" : "One", 
2658                    "   {}" : "Maximum"
2659                }} "#,
2660                    <$ty>::MIN, 1, <$ty>::MAX);
2661                assert_eq!(
2662                    from_bufstr(buf, &s),
2663                    Ok((amap.clone(), s.len())));
2664                let s = format!(r#"{{"{}":"Minimum","{}":"One","{}":"Maximum"}}"#,
2665                            <$ty>::MIN, 1, <$ty>::MAX);
2666                assert_eq!(
2667                    from_bufstr(buf, &s),
2668                    Ok((amap, s.len())));
2669                // error
2670                assert_eq!(
2671                    from_bufstr::<BTreeMap::<$ty,&str>>(buf, r#"{"0"#),
2672                    Err(Error::UnexpectedEof));
2673                assert_eq!(
2674                    from_bufstr::<BTreeMap::<$ty,&str>>(buf, r#"{"0""#),
2675                    Err(Error::UnexpectedEof));
2676                assert_eq!(
2677                    from_bufstr::<BTreeMap::<$ty,&str>>(buf, r#"{"0":"#),
2678                    Err(Error::UnexpectedEof));
2679                assert_eq!(
2680                    from_bufstr::<BTreeMap::<$ty,&str>>(buf, r#"{"0":"""#),
2681                    Err(Error::UnexpectedEof));
2682                assert_eq!(
2683                    from_bufstr::<BTreeMap::<$ty,&str>>(buf, r#"{"0":"","#),
2684                    Err(Error::UnexpectedEof));
2685                assert_eq!(
2686                    from_bufstr::<BTreeMap::<$ty,&str>>(buf, r#"{ "  0 " : "" }"#),
2687                    Err(Error::InvalidNumber));
2688                assert_eq!(
2689                    from_bufstr::<BTreeMap::<$ty,&str>>(buf, r#"{ "  0." : "" }"#),
2690                    Err(Error::InvalidNumber));
2691                assert_eq!(
2692                    from_bufstr::<BTreeMap::<$ty,&str>>(buf, r#"{ "" : "" }"#),
2693                    Err(Error::InvalidType));
2694                assert_eq!(
2695                    from_bufstr::<BTreeMap::<$ty,&str>>(buf, r#"{ "foo" : "" }"#),
2696                    Err(Error::InvalidType));
2697            )*};
2698        }
2699        test_de_map_int!(i8, u8, i16, u16, i32, u32, i64, u64);
2700        let mut amap = BTreeMap::<&str,Option<bool>>::new();
2701        amap.insert("", None);
2702        amap.insert("  ", Some(false));
2703        amap.insert("  1", Some(true));
2704        amap.insert("\tfoo\n", Some(true));
2705        assert_eq!(
2706            from_bufstr(buf, r#"{"  ":false,"":null,"  1":true,"\tfoo\n":true}"#),
2707            Ok((amap.clone(), 46)));
2708        assert_eq!(
2709            from_bufstr(buf, r#" {
2710                "  " : false ,
2711                "" : null,
2712                "  1" :  true,
2713                "\tfoo\n"  : true
2714            }"#),
2715            Ok((amap.clone(), 139)));
2716        let mut amap = BTreeMap::<char,i32>::new();
2717        amap.insert(' ', 0);
2718        amap.insert('1', 1);
2719        amap.insert('\t', -9);
2720        amap.insert('_', -1);
2721        amap.insert('ℝ', 999);
2722        assert_eq!(
2723            from_bufstr(buf, r#"{" ":0,"1":1,"\t":-9,"ℝ":999,"_":-1}"#),
2724            Ok((amap.clone(), 38)));
2725        #[derive(Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord)]
2726        enum CKey {
2727            Foo, Bar
2728        }
2729        let mut amap = BTreeMap::<CKey,i8>::new();
2730        amap.insert(CKey::Foo, 0);
2731        amap.insert(CKey::Bar, 1);
2732        assert_eq!(
2733            from_bufstr(buf, r#"{"Foo":0,"Bar":1}"#),
2734            Ok((amap, 17)));
2735        let mut amap = BTreeMap::<bool,i8>::new();
2736        amap.insert(false, 0);
2737        amap.insert(true, 1);
2738        assert_eq!(
2739            from_bufstr(buf, r#"{"true":1,"false":0}"#),
2740            Ok((amap.clone(), 20)));
2741        // error
2742        assert_eq!(
2743            from_bufstr::<BTreeMap::<CKey,i8>>(buf, r#"{"Baz":0}"#),
2744            Err(Error::DeserializeError("unknown variant `Baz`, expected `Foo` or `Bar`".to_string())));
2745        assert_eq!(
2746            from_bufstr::<BTreeMap::<char,i32>>(buf, r#"{"":0}"#),
2747            Err(Error::InvalidLength));
2748        assert_eq!(
2749            from_bufstr::<BTreeMap::<char,i32>>(buf, r#"{"ab":0}"#),
2750            Err(Error::InvalidLength));
2751        assert_eq!(
2752            from_bufstr::<BTreeMap::<bool,i32>>(buf, r#"{"true ":0}"#),
2753            Err(Error::InvalidType));
2754        assert_eq!(
2755            from_bufstr::<BTreeMap::<&str,i8>>(buf, r#"[]"#),
2756            Err(Error::ExpectedObject));
2757        assert_eq!(
2758            from_bufstr::<BTreeMap::<&str,i8>>(buf, r#"{"x":9]"#),
2759            Err(Error::ExpectedObjectCommaOrEnd));
2760        assert_eq!(
2761            from_bufstr::<BTreeMap::<i8,i8>>(buf, r#"{1:1}"#),
2762            Err(Error::KeyMustBeAString));
2763        assert_eq!(
2764            from_bufstr::<BTreeMap::<bool,i8>>(buf, r#"{"null":0}"#),
2765            Err(Error::UnexpectedChar));
2766        assert_eq!(
2767            from_bufstr::<BTreeMap::<bool,i8>>(buf, r#"{"truu":0}"#),
2768            Err(Error::ExpectedToken));
2769        assert_eq!(
2770            from_bufstr::<BTreeMap::<bool,i8>>(buf, r#"{"true"#),
2771            Err(Error::UnexpectedEof));
2772    }
2773
2774    #[test]
2775    fn test_de_wot() {
2776        #[derive(Debug, Deserialize, PartialEq)]
2777        struct Thing<'a> {
2778            #[serde(borrow)]
2779            properties: Properties<'a>,
2780            #[serde(rename = "type")]
2781            ty: Type,
2782        }
2783
2784        #[derive(Debug, Deserialize, PartialEq)]
2785        struct Properties<'a> {
2786            #[serde(borrow)]
2787            temperature: Property<'a>,
2788            #[serde(borrow)]
2789            humidity: Property<'a>,
2790            #[serde(borrow)]
2791            led: Property<'a>,
2792        }
2793
2794        #[derive(Debug, Deserialize, PartialEq)]
2795        struct Property<'a> {
2796            #[serde(rename = "type")]
2797            ty: Type,
2798            unit: Option<&'a str>,
2799            #[serde(borrow)]
2800            description: Option<&'a str>,
2801            href: &'a str,
2802        }
2803
2804        let buf = &mut [0u8;852];
2805
2806        assert_eq!(
2807            from_bufstr::<Thing<'_>>(buf,
2808                r#"
2809                    {
2810                    "type": "thing",
2811                    "properties": {
2812                        "temperature": {
2813                        "type": "number",
2814                        "unit": "celsius",
2815                        "description": "An ambient temperature sensor",
2816                        "href": "/properties/temperature"
2817                        },
2818                        "humidity": {
2819                        "type": "number",
2820                        "unit": "percent",
2821                        "href": "/properties/humidity"
2822                        },
2823                        "led": {
2824                        "type": "boolean",
2825                        "description": "A red LED",
2826                        "href": "/properties/led"
2827                        }
2828                    }
2829                    }
2830                    "#
2831            ),
2832            Ok((
2833                Thing {
2834                    properties: Properties {
2835                        temperature: Property {
2836                            ty: Type::Number,
2837                            unit: Some("celsius"),
2838                            description: Some("An ambient temperature sensor"),
2839                            href: "/properties/temperature",
2840                        },
2841                        humidity: Property {
2842                            ty: Type::Number,
2843                            unit: Some("percent"),
2844                            description: None,
2845                            href: "/properties/humidity",
2846                        },
2847                        led: Property {
2848                            ty: Type::Boolean,
2849                            unit: None,
2850                            description: Some("A red LED"),
2851                            href: "/properties/led",
2852                        },
2853                    },
2854                    ty: Type::Thing,
2855                },
2856                852
2857            ))
2858        )
2859    }
2860
2861    #[test]
2862    fn test_de_any() {
2863        #[derive(Debug, Deserialize, PartialEq)]
2864        #[serde(untagged)]
2865        enum Thing<'a> {
2866            Nope,
2867            Bool(bool),
2868            Str(&'a str),
2869            Uint(u32),
2870            Int(i32),
2871            LongUint(u64),
2872            LongInt(i64),
2873            Float(f64),
2874            Array([&'a str;2]),
2875            Map{ a: u32, b: &'a str},
2876        }
2877        let mut buf = [0u8;22];
2878        let input = "null";
2879        assert_eq!(
2880            from_bufstr(&mut buf, input),
2881            Ok((Thing::Nope, input.len()))
2882        );
2883        let input = "false";
2884        assert_eq!(
2885            from_bufstr(&mut buf, input),
2886            Ok((Thing::Bool(false), input.len()))
2887        );
2888        let input = "0";
2889        assert_eq!(
2890            from_bufstr(&mut buf, input),
2891            Ok((Thing::Uint(0), input.len()))
2892        );
2893        let input = "-1";
2894        assert_eq!(
2895            from_bufstr(&mut buf, input),
2896            Ok((Thing::Int(-1), input.len())));
2897        let input = r#""foo""#;
2898        assert_eq!(
2899            from_bufstr(&mut buf, input),
2900            Ok((Thing::Str("foo"), input.len())));
2901        let input = "18446744073709551615";
2902        assert_eq!(
2903            from_bufstr(&mut buf, input),
2904            Ok((Thing::LongUint(u64::MAX), input.len())));
2905        let input = "-9223372036854775808";
2906        assert_eq!(
2907            from_bufstr(&mut buf, input),
2908            Ok((Thing::LongInt(i64::MIN), input.len())));
2909        let input = "0.0";
2910        assert_eq!(
2911            from_bufstr(&mut buf, input),
2912            Ok((Thing::Float(0.0), input.len())));
2913        let input = "3.40282347E+38";
2914        #[cfg(feature = "de-any-f32")]
2915        assert_eq!(
2916            from_bufstr(&mut buf, input),
2917            Ok((Thing::Float(f32::MAX as f64), input.len())));
2918        #[cfg(not(feature = "de-any-f32"))]
2919        assert_eq!(
2920            from_bufstr(&mut buf, input),
2921            Ok((Thing::Float(3.40282347E+38), input.len())));
2922        let input = "1.7976931348623157e308";
2923        #[cfg(feature = "de-any-f32")]
2924        assert_eq!(
2925            from_bufstr(&mut buf, input),
2926            Ok((Thing::Float(f64::INFINITY), input.len())));
2927        #[cfg(not(feature = "de-any-f32"))]
2928        assert_eq!(
2929            from_bufstr(&mut buf, input),
2930            Ok((Thing::Float(f64::MAX), input.len())));
2931        let input = r#"["xy","abc"]"#;
2932        assert_eq!(
2933            from_bufstr(&mut buf, input),
2934            Ok((Thing::Array(["xy","abc"]), input.len())));
2935        let input = r#"{"a":126,"b":"zyx"}"#;
2936        assert_eq!(
2937            from_bufstr(&mut buf, input),
2938            Ok((Thing::Map{a:126,b:"zyx"}, input.len())));
2939        // error
2940        assert_eq!(from_bufstr::<Thing>(&mut buf, ""), Err(Error::UnexpectedEof));
2941        assert_eq!(from_bufstr::<Thing>(&mut buf, "x"), Err(Error::UnexpectedChar));
2942        assert_eq!(from_bufstr::<Thing>(&mut buf, "-"), Err(Error::InvalidNumber));
2943        assert_eq!(from_bufstr::<Thing>(&mut buf, "-+"), Err(Error::InvalidNumber));
2944        assert_eq!(from_bufstr::<Thing>(&mut buf, "2.+"), Err(Error::InvalidNumber));
2945        assert_eq!(from_bufstr::<Thing>(&mut buf, "2+"), Err(Error::InvalidNumber));
2946    }
2947
2948    #[cfg(any(feature = "std", feature = "alloc"))]
2949    #[test]
2950    fn test_de_error_string() {
2951        assert_eq!(&format!("{}", Error::UnexpectedEof), "Unexpected end of JSON input");
2952        assert_eq!(&format!("{}", Error::InvalidEscapeSequence), "Invalid JSON string escape sequence");
2953        assert_eq!(&format!("{}", Error::StringControlChar), "A control ASCII character found in a JSON string");
2954        assert_eq!(&format!("{}", Error::ExpectedArrayCommaOrEnd), "Expected `','` or `']'`");
2955        assert_eq!(&format!("{}", Error::ExpectedArrayEnd), "Expected ']'");
2956        assert_eq!(&format!("{}", Error::LeadingArrayComma), "JSON array content starts with a leading `','`");
2957        assert_eq!(&format!("{}", Error::TrailingArrayComma), "JSON array content ends with a trailing `','`");
2958        assert_eq!(&format!("{}", Error::ExpectedObjectCommaOrEnd), "Expected `','` or `'}'`");
2959        assert_eq!(&format!("{}", Error::ExpectedObjectEnd), "Expected `'}'`");
2960        assert_eq!(&format!("{}", Error::LeadingObjectComma), "JSON object content starts with a leading `','`");
2961        assert_eq!(&format!("{}", Error::TrailingObjectComma), "JSON object content ends with a trailing `','`");
2962        assert_eq!(&format!("{}", Error::ExpectedColon), "Expected `':'`");
2963        assert_eq!(&format!("{}", Error::ExpectedToken), "Expected either `true`, `false`, or `null`.");
2964        assert_eq!(&format!("{}", Error::ExpectedNull), "Expected `null`");
2965        assert_eq!(&format!("{}", Error::ExpectedString), r#"Expected `'"'`"#);
2966        assert_eq!(&format!("{}", Error::ExpectedArray), "Expeced a JSON array");
2967        assert_eq!(&format!("{}", Error::ExpectedObject), "Expected a JSON object");
2968        assert_eq!(&format!("{}", Error::ExpectedStruct), "Expected a JSON object or an array");
2969        assert_eq!(&format!("{}", Error::ExpectedEnumValue), r#"Expected this character to be `'"'` or `'{'`"#);
2970        assert_eq!(&format!("{}", Error::ExpectedEnumObjectEnd), "Expected this character to be `'}'`");
2971        assert_eq!(&format!("{}", Error::InvalidNumber), "Invalid number");
2972        assert_eq!(&format!("{}", Error::InvalidType), "Invalid type");
2973        assert_eq!(&format!("{}", Error::InvalidUnicodeCodePoint), "Invalid unicode code point");
2974        assert_eq!(&format!("{}", Error::KeyMustBeAString), "Object key is not a string");
2975        assert_eq!(&format!("{}", Error::TrailingCharacters), "JSON has non-whitespace trailing character after the value");
2976        assert_eq!(&format!("{}", Error::UnexpectedChar), "Unexpected token while parsing a JSON value");
2977        assert_eq!(&format!("{}", Error::InvalidLength), "Invalid length");
2978        let custom: Error = serde::de::Error::custom("xxx");
2979        assert_eq!(format!("{}", custom), "xxx while deserializing JSON");
2980    }
2981
2982    #[cfg(not(any(feature = "std", feature = "alloc")))]
2983    #[test]
2984    fn test_de_error_fmt() {
2985        use core::fmt::Write;
2986        let mut buf = [0u8;52];
2987        let mut writer = SliceWriter::new(&mut buf);
2988        let custom: Error = serde::de::Error::custom("xxx");
2989        write!(writer, "{}", custom).unwrap();
2990        assert_eq!(writer.as_ref(), "JSON does not match deserializer’s expected format".as_bytes());
2991    }
2992}