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