ser_write_msgpack/
de.rs

1//! MessagePack serde deserializer
2
3// use std::println;
4#[cfg(feature = "std")]
5use std::{string::{String, ToString}};
6
7#[cfg(all(feature = "alloc",not(feature = "std")))]
8use alloc::{string::{String, ToString}};
9
10use core::convert::Infallible;
11use core::num::{NonZeroUsize, TryFromIntError};
12use core::str::{Utf8Error, FromStr};
13use core::{fmt, str};
14use serde::de::{self, Visitor, SeqAccess, MapAccess, DeserializeSeed};
15
16use crate::magick::*;
17
18/// Deserialize an instance of type `T` from a slice of bytes in a MessagePack format.
19///
20/// Return a tuple with `(value, msgpack_len)`. `msgpack_len` <= `input.len()`.
21///
22/// Any `&str` or `&[u8]` in the returned type will contain references to the provided slice.
23pub fn from_slice<'a, T>(input: &'a[u8]) -> Result<(T, usize)>
24    where T: de::Deserialize<'a>
25{
26    let mut de = Deserializer::from_slice(input);
27    let value = de::Deserialize::deserialize(&mut de)?;
28    let tail_len = de.end()?;
29
30    Ok((value, input.len() - tail_len))
31}
32
33/// Deserialize an instance of type `T` from a slice of bytes in a MessagePack format.
34///
35/// Return a tuple with `(value, tail)`, where `tail` is the tail of the input beginning
36/// at the byte following the last byte of the serialized data.
37///
38/// Any `&str` or `&[u8]` in the returned type will contain references to the provided slice.
39pub fn from_slice_split_tail<'a, T>(input: &'a[u8]) -> Result<(T, &'a[u8])>
40    where T: de::Deserialize<'a>
41{
42    let (value, len) = from_slice(input)?;
43    Ok((value, &input[len..]))
44}
45
46/// Serde MessagePack deserializer.
47///
48/// * deserializes data from a slice,
49/// * deserializes borrowed references to `&str` and `&[u8]` types,
50/// * deserializes structs from MessagePack maps or arrays.
51/// * deserializes enum variants and struct fields from MessagePack strings or integers.
52/// * deserializes integers from any MessagePack integer type as long as the number can be casted safely
53/// * deserializes floats from any MessagePack integer or float types
54/// * deserializes floats as `NaN` from `nil`
55pub struct Deserializer<'de> {
56    input: &'de[u8],
57    index: usize
58}
59
60/// Deserialization result
61pub type Result<T> = core::result::Result<T, Error>;
62
63/// Deserialization error
64#[derive(Debug, PartialEq, Eq, Clone)]
65#[non_exhaustive]
66pub enum Error {
67    /// EOF while parsing
68    UnexpectedEof,
69    /// Reserved code was detected
70    ReservedCode,
71    /// Unsopported extension was detected
72    UnsupportedExt,
73    /// Number could not be coerced
74    InvalidInteger,
75    /// Invalid type
76    InvalidType,
77    /// Invalid unicode code point
78    InvalidUnicodeCodePoint,
79    /// Expected an integer type
80    ExpectedInteger,
81    /// Expected a number type
82    ExpectedNumber,
83    /// Expected a string
84    ExpectedString,
85    /// Expected a binary type
86    ExpectedBin,
87    /// Expected NIL type
88    ExpectedNil,
89    /// Expected an array type
90    ExpectedArray,
91    /// Expected a map type
92    ExpectedMap,
93    /// Expected a map or an array type
94    ExpectedStruct,
95    /// Expected struct or variant identifier
96    ExpectedIdentifier,
97    /// Trailing unserialized array elements
98    TrailingElements,
99    /// Invalid length
100    InvalidLength,
101    #[cfg(any(feature = "std", feature = "alloc"))]
102    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
103    /// An error passed down from a [`serde::de::Deserialize`] implementation
104    DeserializeError(String),
105    #[cfg(not(any(feature = "std", feature = "alloc")))]
106    DeserializeError
107}
108
109impl serde::de::StdError for Error {}
110
111#[cfg(any(feature = "std", feature = "alloc"))]
112impl de::Error for Error {
113    fn custom<T: fmt::Display>(msg: T) -> Self {
114        Error::DeserializeError(msg.to_string())
115    }
116}
117
118#[cfg(not(any(feature = "std", feature = "alloc")))]
119impl de::Error for Error {
120    fn custom<T: fmt::Display>(_msg: T) -> Self {
121        Error::DeserializeError
122    }
123}
124
125impl fmt::Display for Error {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        f.write_str(match self {
128            Error::UnexpectedEof => "Unexpected end of MessagePack input",
129            Error::ReservedCode => "Reserved MessagePack code in input",
130            Error::UnsupportedExt => "Unsupported MessagePack extension code in input",
131            Error::InvalidInteger => "Could not coerce integer to a deserialized type",
132            Error::InvalidType => "Invalid type",
133            Error::InvalidUnicodeCodePoint => "Invalid unicode code point",
134            Error::ExpectedInteger => "Expected MessagePack integer",
135            Error::ExpectedNumber => "Expected MessagePack number",
136            Error::ExpectedString => "Expected MessagePack string",
137            Error::ExpectedBin => "Expected MessagePack bin",
138            Error::ExpectedNil => "Expected MessagePack nil",
139            Error::ExpectedArray => "Expected MessagePack array",
140            Error::ExpectedMap => "Expected MessagePack map",
141            Error::ExpectedStruct => "Expected MessagePack map or array",
142            Error::ExpectedIdentifier => "Expected a struct field or enum variant identifier",
143            Error::TrailingElements => "Too many elements for a deserialized type",
144            Error::InvalidLength => "Invalid length",
145            #[cfg(any(feature = "std", feature = "alloc"))]
146            Error::DeserializeError(s) => return write!(f, "{} while deserializing MessagePack", s),
147            #[cfg(not(any(feature = "std", feature = "alloc")))]
148            Error::DeserializeError => "MessagePack does not match deserializer’s expected format",
149        })
150    }
151}
152
153impl From<TryFromIntError> for Error {
154    fn from(_err: TryFromIntError) -> Self {
155        Error::InvalidInteger
156    }
157}
158
159impl From<Infallible> for Error {
160    fn from(_err: Infallible) -> Self {
161        unreachable!()
162    }
163}
164
165impl From<Utf8Error> for Error {
166    fn from(_err: Utf8Error) -> Self {
167        Error::InvalidUnicodeCodePoint
168    }
169}
170
171enum MsgType {
172    Single(usize),
173    Array(usize),
174    Map(usize),
175}
176
177/// Methods in a `Deserializer` are made public, but expect them to be modified in future releases.
178impl<'de> Deserializer<'de> {
179    /// Provide a slice from which to deserialize
180    pub fn from_slice(input: &'de[u8]) -> Self {
181        Deserializer { input, index: 0, }
182    }
183
184    /// Consume deserializer and return the size of the remaining portion of the input slice
185    pub fn end(self) -> Result<usize> {
186        self.input.len()
187        .checked_sub(self.index)
188        .ok_or(Error::UnexpectedEof)
189    }
190
191    /// Peek at the next byte code, otherwise return `Err(Error::UnexpectedEof)`.
192    pub fn peek(&self) -> Result<u8> {
193        self.input.get(self.index).copied()
194        .ok_or(Error::UnexpectedEof)
195    }
196    /// Advance the input cursor by `len` characters.
197    ///
198    /// _Note_: this function only increases a cursor without any checks!
199    #[inline(always)]
200    pub fn eat_some(&mut self, len: usize) {
201        self.index += len;
202    }
203    /// Return a reference to the unparsed portion of the input slice on success.
204    /// Otherwise return `Err(Error::UnexpectedEof)`.
205    pub fn input_ref(&self) -> Result<&[u8]> {
206        self.input.get(self.index..).ok_or(Error::UnexpectedEof)
207    }
208    /// Split the unparsed portion of the input slice between `0..len` and on success
209    /// return it with the lifetime of the original slice container.
210    ///
211    /// The returned slice can be passed to `visit_borrowed_*` functions of a [`Visitor`].
212    ///
213    /// Drop already parsed bytes and the new unparsed input slice will begin at `len`.
214    ///
215    /// __Panics__ if `cursor` + `len` overflows `usize` integer capacity.
216    pub fn split_input(&mut self, len: usize) -> Result<&'de[u8]> {
217        let input = self.input.get(self.index..)
218                    .ok_or(Error::UnexpectedEof)?;
219        // let (res, input) = self.input.split_at_checked(len)
220        //             .ok_or(Error::UnexpectedEof)?;
221        let (res, input) = if len <= input.len() {
222           input.split_at(len)
223        }
224        else {
225            return Err(Error::UnexpectedEof)
226        };
227        self.input = input;
228        self.index = 0;
229        Ok(res)
230    }
231
232    /// Fetch the next byte from input or return an `Err::UnexpectedEof` error.
233    pub fn fetch(&mut self) -> Result<u8> {
234        let c = self.peek()?;
235        self.eat_some(1);
236        Ok(c)
237    }
238
239    fn fetch_array<const N: usize>(&mut self) -> Result<[u8;N]> {
240        let index = self.index;
241        let res = self.input.get(index..index+N)
242        .ok_or(Error::UnexpectedEof)?
243        .try_into().unwrap();
244        self.eat_some(N);
245        Ok(res)
246    }
247
248    fn fetch_u8(&mut self) -> Result<u8> {
249        Ok(u8::from_be_bytes(self.fetch_array()?))
250    }
251
252    fn fetch_i8(&mut self) -> Result<i8> {
253        Ok(i8::from_be_bytes(self.fetch_array()?))
254    }
255
256    fn fetch_u16(&mut self) -> Result<u16> {
257        Ok(u16::from_be_bytes(self.fetch_array()?))
258    }
259
260    fn fetch_i16(&mut self) -> Result<i16> {
261        Ok(i16::from_be_bytes(self.fetch_array()?))
262    }
263
264    fn fetch_u32(&mut self) -> Result<u32> {
265        Ok(u32::from_be_bytes(self.fetch_array()?))
266    }
267
268    fn fetch_i32(&mut self) -> Result<i32> {
269        Ok(i32::from_be_bytes(self.fetch_array()?))
270    }
271
272    fn fetch_u64(&mut self) -> Result<u64> {
273        Ok(u64::from_be_bytes(self.fetch_array()?))
274    }
275
276    fn fetch_i64(&mut self) -> Result<i64> {
277        Ok(i64::from_be_bytes(self.fetch_array()?))
278    }
279
280    fn fetch_f32(&mut self) -> Result<f32> {
281        Ok(f32::from_be_bytes(self.fetch_array()?))
282    }
283
284    fn fetch_f64(&mut self) -> Result<f64> {
285        Ok(f64::from_be_bytes(self.fetch_array()?))
286    }
287
288    fn parse_str(&mut self) -> Result<&'de str> {
289        let len: usize = match self.fetch()? {
290            c@(FIXSTR..=FIXSTR_MAX) => (c as usize) & MAX_FIXSTR_SIZE,
291            STR_8 => self.fetch_u8()?.into(),
292            STR_16 => self.fetch_u16()?.into(),
293            STR_32 => self.fetch_u32()?.try_into()?,
294            _ => return Err(Error::ExpectedString)
295        };
296        Ok(core::str::from_utf8(self.split_input(len)?)?)
297    }
298
299    fn parse_bytes(&mut self) -> Result<&'de[u8]> {
300        let len: usize = match self.fetch()? {
301            BIN_8 => self.fetch_u8()?.into(),
302            BIN_16 => self.fetch_u16()?.into(),
303            BIN_32 => self.fetch_u32()?.try_into()?,
304            _ => return Err(Error::ExpectedBin)
305        };
306        self.split_input(len)
307    }
308
309    fn parse_integer<N>(&mut self) -> Result<N>
310        where N: TryFrom<i8> + TryFrom<u8> +
311                 TryFrom<i16> + TryFrom<u16> +
312                 TryFrom<i32> + TryFrom<u32> +
313                 TryFrom<i64> + TryFrom<u64>,
314              Error: From<<N as TryFrom<i8>>::Error>,
315              Error: From<<N as TryFrom<u8>>::Error>,
316              Error: From<<N as TryFrom<i16>>::Error>,
317              Error: From<<N as TryFrom<u16>>::Error>,
318              Error: From<<N as TryFrom<i32>>::Error>,
319              Error: From<<N as TryFrom<u32>>::Error>,
320              Error: From<<N as TryFrom<i64>>::Error>,
321              Error: From<<N as TryFrom<u64>>::Error>,
322    {
323        let n: N = match self.fetch()? {
324            n@(MIN_POSFIXINT..=MAX_POSFIXINT|NEGFIXINT..=0xff) => {
325                (n as i8).try_into()?
326            }
327            UINT_8  => (self.fetch_u8()?).try_into()?,
328            UINT_16 => (self.fetch_u16()?).try_into()?,
329            UINT_32 => (self.fetch_u32()?).try_into()?,
330            UINT_64 => (self.fetch_u64()?).try_into()?,
331            INT_8   => (self.fetch_i8()?).try_into()?,
332            INT_16  => (self.fetch_i16()?).try_into()?,
333            INT_32  => (self.fetch_i32()?).try_into()?,
334            INT_64  => (self.fetch_i64()?).try_into()?,
335            _ => return Err(Error::ExpectedInteger)
336        };
337        Ok(n)
338    }
339
340    /// Attempts to consume a single MessagePack message from the input without fully decoding its content.
341    ///
342    /// Return `Ok(())` on success or `Err(Error::UnexpectedEof)` if there was not enough data
343    /// to fully decode a MessagePack item.
344    pub fn eat_message(&mut self) -> Result<()> {
345        use MsgType::*;
346        let mtyp = match self.fetch()? {
347            NIL|
348            FALSE|
349            TRUE|
350            MIN_POSFIXINT..=MAX_POSFIXINT|
351            NEGFIXINT..=0xff => Single(0),
352            c@(FIXMAP..=FIXMAP_MAX) => Map((c as usize) & MAX_FIXMAP_SIZE),
353            c@(FIXARRAY..=FIXARRAY_MAX) => Array((c as usize) & MAX_FIXARRAY_SIZE),
354            c@(FIXSTR..=FIXSTR_MAX) => Single((c as usize) & MAX_FIXSTR_SIZE),
355            RESERVED => return Err(Error::ReservedCode),
356            BIN_8|STR_8 => Single(self.fetch_u8()?.into()),
357            BIN_16|STR_16 => Single(self.fetch_u16()?.into()),
358            BIN_32|STR_32 => Single(self.fetch_u32()?.try_into()?),
359            EXT_8 => Single(1usize + usize::from(self.fetch_u8()?)),
360            EXT_16 => Single(1usize + usize::from(self.fetch_u16()?)),
361            EXT_32 => Single(1usize + usize::try_from(self.fetch_u32()?)?),
362            FLOAT_32 => Single(4),
363            FLOAT_64 => Single(8),
364            UINT_8 => Single(1),
365            UINT_16 => Single(2),
366            UINT_32 => Single(4),
367            UINT_64 => Single(8),
368            INT_8 => Single(1),
369            INT_16 => Single(2),
370            INT_32 => Single(4),
371            INT_64 => Single(8),
372            FIXEXT_1 => Single(2),
373            FIXEXT_2 => Single(3),
374            FIXEXT_4 => Single(5),
375            FIXEXT_8 => Single(9),
376            FIXEXT_16 => Single(17),
377            ARRAY_16 => Array(self.fetch_u16()?.into()),
378            ARRAY_32 => Array(self.fetch_u32()?.try_into()?),
379            MAP_16 => Map(self.fetch_u16()?.into()),
380            MAP_32 => Map(self.fetch_u32()?.try_into()?),
381        };
382        match mtyp {
383            Single(len) => {
384                let index = self.index + len;
385                if index > self.input.len() {
386                    return Err(Error::UnexpectedEof)
387                }
388                self.index = index;
389            }
390            Array(len) => self.eat_seq_items(len)?,
391            Map(len) => self.eat_map_items(len)?
392        }
393        Ok(())
394    }
395
396    fn eat_seq_items(&mut self, len: usize) -> Result<()> {
397        for _ in 0..len {
398            self.eat_message()?;
399        }
400        Ok(())
401    }
402
403    fn eat_map_items(&mut self, len: usize) -> Result<()> {
404        for _ in 0..len {
405            self.eat_message()?;
406            self.eat_message()?;
407        }
408        Ok(())
409    }
410
411}
412
413
414impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
415    type Error = Error;
416
417    fn is_human_readable(&self) -> bool {
418        false
419    }
420
421    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
422        where V: Visitor<'de>
423    {
424        match self.peek()? {
425            MIN_POSFIXINT..=MAX_POSFIXINT => self.deserialize_u8(visitor),
426            FIXMAP..=FIXMAP_MAX => self.deserialize_map(visitor),
427            FIXARRAY..=FIXARRAY_MAX => self.deserialize_seq(visitor),
428            FIXSTR..=FIXSTR_MAX => self.deserialize_str(visitor),
429            NIL => self.deserialize_unit(visitor),
430            RESERVED => Err(Error::ReservedCode),
431            FALSE|
432            TRUE => self.deserialize_bool(visitor),
433            BIN_8|
434            BIN_16|
435            BIN_32 => self.deserialize_bytes(visitor),
436            EXT_8|
437            EXT_16|
438            EXT_32 => Err(Error::UnsupportedExt),
439            FLOAT_32 => self.deserialize_f32(visitor),
440            FLOAT_64 => self.deserialize_f64(visitor),
441            UINT_8 => self.deserialize_u8(visitor),
442            UINT_16 => self.deserialize_u16(visitor),
443            UINT_32 => self.deserialize_u32(visitor),
444            UINT_64 => self.deserialize_u64(visitor),
445            INT_8 => self.deserialize_i8(visitor),
446            INT_16 => self.deserialize_i16(visitor),
447            INT_32 => self.deserialize_i32(visitor),
448            INT_64 => self.deserialize_i64(visitor),
449            FIXEXT_1|
450            FIXEXT_2|
451            FIXEXT_4|
452            FIXEXT_8|
453            FIXEXT_16 => Err(Error::UnsupportedExt),
454            STR_8|
455            STR_16|
456            STR_32 => self.deserialize_str(visitor),
457            ARRAY_16|
458            ARRAY_32 => self.deserialize_seq(visitor),
459            MAP_16|
460            MAP_32 => self.deserialize_map(visitor),
461            NEGFIXINT..=0xff => self.deserialize_i8(visitor),
462        }
463    }
464
465    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
466        where V: Visitor<'de>
467    {
468        let boolean = match self.fetch()? {
469            TRUE => true,
470            FALSE => false,
471            _ => return Err(Error::InvalidType)
472        };
473        visitor.visit_bool(boolean)
474    }
475
476    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
477        where V: Visitor<'de>
478    {
479        visitor.visit_i8(self.parse_integer()?)
480    }
481
482    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value>
483        where V: Visitor<'de>
484    {
485        visitor.visit_i16(self.parse_integer()?)
486    }
487
488    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value>
489        where V: Visitor<'de>
490    {
491        visitor.visit_i32(self.parse_integer()?)
492    }
493
494    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value>
495        where V: Visitor<'de>
496    {
497        visitor.visit_i64(self.parse_integer()?)
498    }
499
500    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
501        where V: Visitor<'de>
502    {
503        visitor.visit_u8(self.parse_integer()?)
504    }
505
506    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value>
507        where V: Visitor<'de>
508    {
509        visitor.visit_u16(self.parse_integer()?)
510    }
511
512    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value>
513        where V: Visitor<'de>
514    {
515        visitor.visit_u32(self.parse_integer()?)
516    }
517
518    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value>
519        where V: Visitor<'de>
520    {
521        visitor.visit_u64(self.parse_integer()?)
522    }
523
524    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value>
525        where V: Visitor<'de>
526    {
527        let f: f32 = match self.fetch()? {
528            FLOAT_32 => self.fetch_f32()?,
529            FLOAT_64 => self.fetch_f64()? as f32,
530            NIL => f32::NAN,
531            n@(MIN_POSFIXINT..=MAX_POSFIXINT|NEGFIXINT..=0xff) => {
532                (n as i8) as f32
533            }
534            UINT_8  => self.fetch_u8()?  as f32,
535            UINT_16 => self.fetch_u16()? as f32,
536            UINT_32 => self.fetch_u32()? as f32,
537            UINT_64 => self.fetch_u64()? as f32,
538            INT_8   => self.fetch_i8()?  as f32,
539            INT_16  => self.fetch_i16()? as f32,
540            INT_32  => self.fetch_i32()? as f32,
541            INT_64  => self.fetch_i64()? as f32,
542            _ => return Err(Error::ExpectedNumber)
543        };
544        visitor.visit_f32(f)
545    }
546
547    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value>
548        where V: Visitor<'de>
549    {
550        let f: f64 = match self.fetch()? {
551            FLOAT_64 => self.fetch_f64()?,
552            FLOAT_32 => self.fetch_f32()? as f64,
553            NIL => f64::NAN,
554            n@(MIN_POSFIXINT..=MAX_POSFIXINT|NEGFIXINT..=0xff) => {
555                (n as i8) as f64
556            }
557            UINT_8  => self.fetch_u8()?  as f64,
558            UINT_16 => self.fetch_u16()? as f64,
559            UINT_32 => self.fetch_u32()? as f64,
560            UINT_64 => self.fetch_u64()? as f64,
561            INT_8   => self.fetch_i8()?  as f64,
562            INT_16  => self.fetch_i16()? as f64,
563            INT_32  => self.fetch_i32()? as f64,
564            INT_64  => self.fetch_i64()? as f64,
565            _ => return Err(Error::ExpectedNumber)
566        };
567        visitor.visit_f64(f)
568    }
569
570    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
571        where V: Visitor<'de>
572    {
573        let s = self.parse_str()?;
574        let ch = char::from_str(s).map_err(|_| Error::InvalidLength)?;
575        visitor.visit_char(ch)
576    }
577
578    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
579        where V: Visitor<'de>
580    {
581        visitor.visit_borrowed_str(self.parse_str()?)
582    }
583
584    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
585        where V: Visitor<'de>
586    {
587        self.deserialize_str(visitor)
588    }
589
590    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
591        where V: Visitor<'de>
592    {
593        visitor.visit_borrowed_bytes(self.parse_bytes()?)
594    }
595
596    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
597        where V: Visitor<'de>
598    {
599        self.deserialize_bytes(visitor)
600    }
601
602    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
603        where V: Visitor<'de>
604    {
605        match self.peek()? {
606            NIL => {
607                self.eat_some(1);
608                visitor.visit_none()
609            }
610            _ => visitor.visit_some(self)
611        }
612    }
613
614    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
615        where V: Visitor<'de>
616    {
617        match self.fetch()? {
618            NIL => visitor.visit_unit(),
619            _ => Err(Error::ExpectedNil)
620        }
621    }
622
623    fn deserialize_unit_struct<V>(
624        self,
625        _name: &'static str,
626        visitor: V,
627    ) -> Result<V::Value>
628        where V: Visitor<'de>
629    {
630        self.deserialize_unit(visitor)
631    }
632
633    // As is done here, serializers are encouraged to treat newtype structs as
634    // insignificant wrappers around the data they contain. That means not
635    // parsing anything other than the contained value.
636    fn deserialize_newtype_struct<V>(
637        self,
638        _name: &'static str,
639        visitor: V,
640    ) -> Result<V::Value>
641        where V: Visitor<'de>
642    {
643        visitor.visit_newtype_struct(self)
644    }
645
646    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
647        where V: Visitor<'de>
648    {
649        let len: usize = match self.fetch()? {
650            c@(FIXARRAY..=FIXARRAY_MAX) => (c as usize) & MAX_FIXARRAY_SIZE,
651            ARRAY_16 => self.fetch_u16()?.into(),
652            ARRAY_32 => self.fetch_u32()?.try_into()?,
653            _ => return Err(Error::ExpectedArray)
654        };
655        let mut access = CountingAccess::new(self, len);
656        let value = visitor.visit_seq(&mut access)?;
657        if access.count.is_some() {
658            return Err(Error::TrailingElements)
659        }
660        Ok(value)
661    }
662
663    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value>
664        where V: Visitor<'de>
665    {
666        self.deserialize_seq(visitor)
667    }
668
669    fn deserialize_tuple_struct<V>(
670        self,
671        _name: &'static str,
672        _len: usize,
673        visitor: V,
674    ) -> Result<V::Value>
675        where V: Visitor<'de>
676    {
677        self.deserialize_seq(visitor)
678    }
679
680    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
681        where V: Visitor<'de>
682    {
683        let len: usize = match self.fetch()? {
684            c@(FIXMAP..=FIXMAP_MAX) => (c as usize) & MAX_FIXMAP_SIZE,
685            MAP_16 => self.fetch_u16()?.into(),
686            MAP_32 => self.fetch_u32()?.try_into()?,
687            _ => return Err(Error::ExpectedMap)
688        };
689        let mut access = CountingAccess::new(self, len);
690        let value = visitor.visit_map(&mut access)?;
691        if access.count.is_some() {
692            return Err(Error::TrailingElements)
693        }
694        Ok(value)
695    }
696
697    fn deserialize_struct<V>(
698        self,
699        _name: &'static str,
700        _fields: &'static [&'static str],
701        visitor: V,
702    ) -> Result<V::Value>
703        where V: Visitor<'de>
704    {
705        let (map, len): (bool, usize) = match self.fetch()? {
706            c@(FIXMAP..=FIXMAP_MAX) => (true, (c as usize) & MAX_FIXMAP_SIZE),
707            MAP_16 => (true, self.fetch_u16()?.into()),
708            MAP_32 => (true, self.fetch_u32()?.try_into()?),
709            c@(FIXARRAY..=FIXARRAY_MAX) => (false, (c as usize) & MAX_FIXARRAY_SIZE),
710            ARRAY_16 => (false, self.fetch_u16()?.into()),
711            ARRAY_32 => (false, self.fetch_u32()?.try_into()?),
712            _ => return Err(Error::ExpectedStruct)
713        };
714        let mut access = CountingAccess::new(self, len);
715        let value = if map {
716            visitor.visit_map(&mut access)?
717        }
718        else {
719            visitor.visit_seq(&mut access)?
720        };
721        if access.count.is_some() {
722            return Err(Error::TrailingElements)
723        }
724        Ok(value)
725    }
726
727    fn deserialize_enum<V>(
728        self,
729        _name: &'static str,
730        _variants: &'static [&'static str],
731        visitor: V,
732    ) -> Result<V::Value>
733        where V: Visitor<'de>
734    {
735        const FIXMAP_1: u8 = FIXMAP|1;
736        match self.peek()? {
737            FIXMAP_1 => {
738                self.eat_some(1);
739                visitor.visit_enum(VariantAccess { de: self })
740            }
741            _ => visitor.visit_enum(UnitVariantAccess { de: self })
742        }
743    }
744
745    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>
746        where V: Visitor<'de>
747    {
748        match self.peek()? {
749            MIN_POSFIXINT..=MAX_POSFIXINT|
750            UINT_8|
751            UINT_16|
752            UINT_32 => self.deserialize_u32(visitor),
753            FIXSTR..=FIXSTR_MAX|
754            STR_8|
755            STR_16|
756            STR_32  => self.deserialize_str(visitor),
757            _ => Err(Error::ExpectedIdentifier)
758        }
759    }
760
761    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
762        where V: Visitor<'de>
763    {
764        self.eat_message()?;
765        visitor.visit_unit()
766    }
767}
768
769struct CountingAccess<'a, 'de: 'a> {
770    de: &'a mut Deserializer<'de>,
771    count: Option<NonZeroUsize>,
772}
773
774impl<'a, 'de> CountingAccess<'a, 'de> {
775    fn new(de: &'a mut Deserializer<'de>, count: usize) -> Self {
776        CountingAccess {
777            de,
778            count: NonZeroUsize::new(count),
779        }
780    }
781}
782
783impl<'de, 'a> SeqAccess<'de> for CountingAccess<'a, 'de> {
784    type Error = Error;
785
786    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
787        where T: DeserializeSeed<'de>
788    {
789        if let Some(len) = self.count {
790            self.count = NonZeroUsize::new(len.get() - 1);
791            return seed.deserialize(&mut *self.de).map(Some)
792        }
793        Ok(None)
794    }
795
796    fn size_hint(&self) -> Option<usize> {
797        self.count.map(NonZeroUsize::get).or(Some(0))
798    }
799}
800
801impl<'a, 'de> MapAccess<'de> for CountingAccess<'a, 'de> {
802    type Error = Error;
803
804    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
805        where K: DeserializeSeed<'de>
806    {
807        if let Some(len) = self.count {
808            self.count = NonZeroUsize::new(len.get() - 1);
809            return seed.deserialize(&mut *self.de).map(Some)
810        }
811        Ok(None)
812    }
813
814    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
815        where V: DeserializeSeed<'de>
816    {
817        seed.deserialize(&mut *self.de)
818    }
819
820    fn size_hint(&self) -> Option<usize> {
821        self.count.map(NonZeroUsize::get).or(Some(0))
822    }
823}
824
825struct UnitVariantAccess<'a, 'de> {
826    de: &'a mut Deserializer<'de>,
827}
828
829impl<'a, 'de> de::EnumAccess<'de> for UnitVariantAccess<'a, 'de> {
830    type Error = Error;
831    type Variant = Self;
832
833    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)>
834        where V: de::DeserializeSeed<'de>
835    {
836        let variant = seed.deserialize(&mut *self.de)?;
837        Ok((variant, self))
838    }
839}
840
841impl<'a, 'de> de::VariantAccess<'de> for UnitVariantAccess<'a, 'de> {
842    type Error = Error;
843
844    fn unit_variant(self) -> Result<()> {
845        Ok(())
846    }
847
848    fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value>
849        where T: de::DeserializeSeed<'de>
850    {
851        Err(Error::InvalidType)
852    }
853
854    fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value>
855        where V: de::Visitor<'de>
856    {
857        Err(Error::InvalidType)
858    }
859
860    fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value>
861        where V: de::Visitor<'de>
862    {
863        Err(Error::InvalidType)
864    }
865}
866
867struct VariantAccess<'a, 'de> {
868    de: &'a mut Deserializer<'de>,
869}
870
871impl<'a, 'de> de::EnumAccess<'de> for VariantAccess<'a, 'de> {
872    type Error = Error;
873    type Variant = Self;
874
875    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)>
876        where V: de::DeserializeSeed<'de>
877    {
878        let variant = seed.deserialize(&mut *self.de)?;
879        Ok((variant, self))
880    }
881}
882
883impl<'a, 'de> de::VariantAccess<'de> for VariantAccess<'a, 'de> {
884    type Error = Error;
885
886    fn unit_variant(self) -> Result<()> {
887        Err(Error::InvalidType)
888    }
889
890    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
891        where T: de::DeserializeSeed<'de>
892    {
893        seed.deserialize(self.de)
894    }
895
896    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
897        where V: de::Visitor<'de>
898    {
899        de::Deserializer::deserialize_seq(self.de, visitor)
900    }
901
902    fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value>
903        where V: de::Visitor<'de>
904    {
905        de::Deserializer::deserialize_struct(self.de, "", fields, visitor)
906    }
907}
908
909
910#[cfg(test)]
911mod tests {
912    #[cfg(feature = "std")]
913    use std::{vec, vec::Vec, collections::BTreeMap, format};
914    #[cfg(all(feature = "alloc",not(feature = "std")))]
915    use alloc::{vec, vec::Vec, collections::BTreeMap, format};
916    use serde::Deserialize;
917    use super::*;
918
919    #[derive(Debug, Deserialize, PartialEq)]
920    struct Unit;
921    #[derive(Debug, Deserialize, PartialEq)]
922    struct Test {
923        compact: bool,
924        schema: u32,
925        unit: Unit
926    }
927
928    #[test]
929    fn test_deserializer() {
930        let input = [0xC0];
931        let mut de = Deserializer::from_slice(&input);
932        assert_eq!(serde::de::Deserializer::is_human_readable(&(&mut de)), false);
933        assert_eq!(de.input_ref().unwrap(), &[0xC0]);
934        assert_eq!(de.fetch().unwrap(), 0xC0);
935        assert_eq!(de.input_ref().unwrap(), &[]);
936        assert_eq!(de.split_input(2), Err(Error::UnexpectedEof));
937        de.eat_some(1);
938        assert_eq!(de.peek(), Err(Error::UnexpectedEof));
939        assert_eq!(de.fetch(), Err(Error::UnexpectedEof));
940        assert_eq!(de.input_ref(), Err(Error::UnexpectedEof));
941        assert_eq!(de.split_input(1), Err(Error::UnexpectedEof));
942    }
943
944    #[test]
945    fn test_de_msgpack() {
946        let test = Test {
947            compact: true,
948            schema: 0,
949            unit: Unit
950        };
951        assert_eq!(
952            from_slice(b"\x83\xA7compact\xC3\xA6schema\x00\xA4unit\xC0"),
953            Ok((test, 24))
954        );
955        assert_eq!(
956            from_slice::<()>(b"\xC1"),
957            Err(Error::ExpectedNil)
958        );
959        assert_eq!(
960            Deserializer::from_slice(b"\xC1").eat_message(),
961            Err(Error::ReservedCode)
962        );
963    }
964
965    #[test]
966    fn test_de_array() {
967        assert_eq!(from_slice::<[i32; 0]>(&[0x90]), Ok(([], 1)));
968        assert_eq!(from_slice(&[0x93, 0, 1, 2]), Ok(([0, 1, 2], 4)));
969        assert_eq!(from_slice(&[0x9F, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]),
970                              Ok(([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], 16)));
971        assert_eq!(from_slice(&[0xDC, 0, 3, 0, 1, 2]), Ok(([0, 1, 2], 6)));
972        assert_eq!(from_slice(&[0xDD, 0, 0, 0, 3, 0, 1, 2]), Ok(([0, 1, 2], 8)));
973
974        #[cfg(any(feature = "std", feature = "alloc"))]
975        {
976            let mut vec = vec![0xDC, 0xFF, 0xFF];
977            for _ in 0..65535 {
978                vec.push(0xC3);
979            }
980            let (res, len) = from_slice::<Vec<bool>>(&vec).unwrap();
981            assert_eq!(len, 65535+3);
982            assert_eq!(res.len(), 65535);
983            for i in 0..65535 {
984                assert_eq!(res[i], true);
985            }
986
987            let mut vec = vec![0xDD, 0x00, 0x01, 0x00, 0x00];
988            for _ in 0..65536 {
989                vec.push(0xC2);
990            }
991            let (res, len) = from_slice::<Vec<bool>>(&vec).unwrap();
992            assert_eq!(len, 65536+5);
993            assert_eq!(res.len(), 65536);
994            for i in 0..65536 {
995                assert_eq!(res[i], false);
996            }
997        }
998
999        // error
1000        assert_eq!(from_slice::<[i32; 2]>(&[0x80]), Err(Error::ExpectedArray));
1001        assert_eq!(from_slice::<[i32; 2]>(&[]), Err(Error::UnexpectedEof));
1002        assert_eq!(from_slice::<[i32; 2]>(&[0x91]), Err(Error::UnexpectedEof));
1003        assert_eq!(from_slice::<[i32; 2]>(&[0x92,0x00]), Err(Error::UnexpectedEof));
1004        assert_eq!(from_slice::<[i32; 2]>(&[0x92,0xC0]), Err(Error::ExpectedInteger));
1005        assert_eq!(from_slice::<[i32; 2]>(&[0xDC]), Err(Error::UnexpectedEof));
1006        assert_eq!(from_slice::<[i32; 2]>(&[0xDC,0x00,0x01]), Err(Error::UnexpectedEof));
1007        assert_eq!(from_slice::<[i32; 2]>(&[0xDD]), Err(Error::UnexpectedEof));
1008        assert_eq!(from_slice::<[i32; 2]>(&[0xDD,0x00,0x00,0x00,0x01]), Err(Error::UnexpectedEof));
1009    }
1010
1011    #[test]
1012    fn test_de_bool() {
1013        assert_eq!(from_slice(&[0xC2]), Ok((false, 1)));
1014        assert_eq!(from_slice(&[0xC3]), Ok((true, 1)));
1015        // error
1016        assert_eq!(from_slice::<bool>(&[]), Err(Error::UnexpectedEof));
1017        assert_eq!(from_slice::<bool>(&[0xC1]), Err(Error::InvalidType));
1018        assert_eq!(from_slice::<bool>(&[0xC0]), Err(Error::InvalidType));
1019    }
1020
1021    #[test]
1022    fn test_de_floating_point() {
1023        assert_eq!(from_slice(&[1]), Ok((1.0f64, 1)));
1024        assert_eq!(from_slice(&[-1i8 as _]), Ok((-1.0f64, 1)));
1025        assert_eq!(from_slice(&[0xCC, 1]), Ok((1.0f64, 2)));
1026        assert_eq!(from_slice(&[0xCD, 0, 1]), Ok((1.0f64, 3)));
1027        assert_eq!(from_slice(&[0xCE, 0, 0, 0, 1]), Ok((1.0f64, 5)));
1028        assert_eq!(from_slice(&[0xCF, 0, 0, 0, 0, 0, 0, 0, 1]), Ok((1.0f64, 9)));
1029        assert_eq!(from_slice(&[0xD0, 0xff]), Ok((-1.0f64, 2)));
1030        assert_eq!(from_slice(&[0xD1, 0xff, 0xff]), Ok((-1.0f64, 3)));
1031        assert_eq!(from_slice(&[0xD2, 0xff, 0xff, 0xff, 0xff]), Ok((-1.0f64, 5)));
1032        assert_eq!(from_slice(&[0xD3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), Ok((-1.0f64, 9)));
1033
1034        assert_eq!(from_slice(&[5]), Ok((5.0f32, 1)));
1035        assert_eq!(from_slice(&[0xCC, 1]), Ok((1.0f32, 2)));
1036        assert_eq!(from_slice(&[0xCD, 0, 1]), Ok((1.0f32, 3)));
1037        assert_eq!(from_slice(&[0xCE, 0, 0, 0, 1]), Ok((1.0f32, 5)));
1038        assert_eq!(from_slice(&[0xCF, 0, 0, 0, 0, 0, 0, 0, 1]), Ok((1.0f32, 9)));
1039        assert_eq!(from_slice(&[0xD0, 0xff]), Ok((-1.0f32, 2)));
1040        assert_eq!(from_slice(&[0xD1, 0xff, 0xff]), Ok((-1.0f32, 3)));
1041        assert_eq!(from_slice(&[0xD2, 0xff, 0xff, 0xff, 0xff]), Ok((-1.0f32, 5)));
1042        assert_eq!(from_slice(&[0xD3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), Ok((-1.0f32, 9)));
1043
1044        let mut input = [0xCA, 0, 0, 0, 0];
1045        input[1..].copy_from_slice(&(-2.5f32).to_be_bytes());
1046        assert_eq!(from_slice(&input), Ok((-2.5, 5)));
1047        assert_eq!(from_slice(&input), Ok((-2.5f32, 5)));
1048        let mut input = [0xCB, 0, 0, 0, 0, 0, 0, 0, 0];
1049        input[1..].copy_from_slice(&(-999.9f64).to_be_bytes());
1050        assert_eq!(from_slice(&input), Ok((-999.9, 9)));
1051        assert_eq!(from_slice(&input), Ok((-999.9f32, 9)));
1052        let (f, len) = from_slice::<f32>(&[0xC0]).unwrap();
1053        assert_eq!(len, 1);
1054        assert!(f.is_nan());
1055        let (f, len) = from_slice::<f64>(&[0xC0]).unwrap();
1056        assert_eq!(len, 1);
1057        assert!(f.is_nan());
1058        // error
1059        assert_eq!(from_slice::<f32>(&[0xc1]), Err(Error::ExpectedNumber));
1060        assert_eq!(from_slice::<f64>(&[0x90]), Err(Error::ExpectedNumber));
1061        assert_eq!(from_slice::<f32>(&[]), Err(Error::UnexpectedEof));
1062        assert_eq!(from_slice::<f64>(&[]), Err(Error::UnexpectedEof));
1063        assert_eq!(from_slice::<f32>(&[0xCA, 0]), Err(Error::UnexpectedEof));
1064        assert_eq!(from_slice::<f64>(&[0xCB, 0]), Err(Error::UnexpectedEof));
1065        for code in [0xCA, 0xCB, 
1066                     0xCC, 0xCD, 0xCE, 0xCF,
1067                     0xD0, 0xD1, 0xD2, 0xD3]
1068        {
1069            assert_eq!(from_slice::<f32>(&[code]), Err(Error::UnexpectedEof));
1070            assert_eq!(from_slice::<f64>(&[code]), Err(Error::UnexpectedEof));
1071        }
1072    }
1073
1074    #[test]
1075    fn test_de_integer() {
1076        macro_rules! test_integer {
1077            ($($ty:ty),*) => {$(
1078                assert_eq!(from_slice::<$ty>(&[1]), Ok((1, 1)));
1079                assert_eq!(from_slice::<$ty>(&[-1i8 as _]), Ok((-1, 1)));
1080                assert_eq!(from_slice::<$ty>(&[0xCC, 1]), Ok((1, 2)));
1081                assert_eq!(from_slice::<$ty>(&[0xCD, 0, 1]), Ok((1, 3)));
1082                assert_eq!(from_slice::<$ty>(&[0xCE, 0, 0, 0, 1]), Ok((1, 5)));
1083                assert_eq!(from_slice::<$ty>(&[0xCF, 0, 0, 0, 0, 0, 0, 0, 1]), Ok((1, 9)));
1084                assert_eq!(from_slice::<$ty>(&[0xD0, 0xff]), Ok((-1, 2)));
1085                assert_eq!(from_slice::<$ty>(&[0xD1, 0xff, 0xff]), Ok((-1, 3)));
1086                assert_eq!(from_slice::<$ty>(&[0xD2, 0xff, 0xff, 0xff, 0xff]), Ok((-1, 5)));
1087                assert_eq!(from_slice::<$ty>(&[0xD3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), Ok((-1, 9)));
1088
1089            )*};
1090        }
1091        macro_rules! test_unsigned {
1092            ($($ty:ty),*) => {$(
1093                assert_eq!(from_slice::<$ty>(&[1]), Ok((1, 1)));
1094                assert_eq!(from_slice::<$ty>(&[-1i8 as _]), Err(Error::InvalidInteger));
1095                assert_eq!(from_slice::<$ty>(&[0xCC, 1]), Ok((1, 2)));
1096                assert_eq!(from_slice::<$ty>(&[0xCD, 0, 1]), Ok((1, 3)));
1097                assert_eq!(from_slice::<$ty>(&[0xCE, 0, 0, 0, 1]), Ok((1, 5)));
1098                assert_eq!(from_slice::<$ty>(&[0xCF, 0, 0, 0, 0, 0, 0, 0, 1]), Ok((1, 9)));
1099                assert_eq!(from_slice::<$ty>(&[0xD0, 1]), Ok((1, 2)));
1100                assert_eq!(from_slice::<$ty>(&[0xD0, 0xff]), Err(Error::InvalidInteger));
1101                assert_eq!(from_slice::<$ty>(&[0xD1, 0, 1]), Ok((1, 3)));
1102                assert_eq!(from_slice::<$ty>(&[0xD1, 0xff, 0xff]), Err(Error::InvalidInteger));
1103                assert_eq!(from_slice::<$ty>(&[0xD2, 0, 0, 0, 1]), Ok((1, 5)));
1104                assert_eq!(from_slice::<$ty>(&[0xD2, 0xff, 0xff, 0xff, 0xff]), Err(Error::InvalidInteger));
1105                assert_eq!(from_slice::<$ty>(&[0xD3, 0, 0, 0, 0, 0, 0, 0, 1]), Ok((1, 9)));
1106                assert_eq!(from_slice::<$ty>(&[0xD3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), Err(Error::InvalidInteger));
1107            )*};
1108        }
1109        macro_rules! test_int_err {
1110            ($($ty:ty),*) => {$(
1111                assert_eq!(from_slice::<$ty>(&[0xC0]), Err(Error::ExpectedInteger));
1112                assert_eq!(from_slice::<$ty>(&[0xCC]), Err(Error::UnexpectedEof));
1113                assert_eq!(from_slice::<$ty>(&[0xCD]), Err(Error::UnexpectedEof));
1114                assert_eq!(from_slice::<$ty>(&[0xCE]), Err(Error::UnexpectedEof));
1115                assert_eq!(from_slice::<$ty>(&[0xCF]), Err(Error::UnexpectedEof));
1116                assert_eq!(from_slice::<$ty>(&[0xCD, 0]), Err(Error::UnexpectedEof));
1117                assert_eq!(from_slice::<$ty>(&[0xCE, 0]), Err(Error::UnexpectedEof));
1118                assert_eq!(from_slice::<$ty>(&[0xCF, 0]), Err(Error::UnexpectedEof));
1119                assert_eq!(from_slice::<$ty>(&[0xD0]), Err(Error::UnexpectedEof));
1120                assert_eq!(from_slice::<$ty>(&[0xD1]), Err(Error::UnexpectedEof));
1121                assert_eq!(from_slice::<$ty>(&[0xD2]), Err(Error::UnexpectedEof));
1122                assert_eq!(from_slice::<$ty>(&[0xD3]), Err(Error::UnexpectedEof));
1123                assert_eq!(from_slice::<$ty>(&[0xD1, 0]), Err(Error::UnexpectedEof));
1124                assert_eq!(from_slice::<$ty>(&[0xD2, 0]), Err(Error::UnexpectedEof));
1125                assert_eq!(from_slice::<$ty>(&[0xD3, 0]), Err(Error::UnexpectedEof));
1126            )*};
1127        }
1128        test_integer!(i8,i16,i32,i64);
1129        test_unsigned!(u8,u16,u32,u64);
1130        test_int_err!(i8,i16,i32,i64, u8,u16,u32,u64);
1131        assert_eq!(from_slice::<i8>(&[0xCC, 0x80]), Err(Error::InvalidInteger));
1132        assert_eq!(from_slice::<i16>(&[0xCD, 0x80, 0x00]), Err(Error::InvalidInteger));
1133        assert_eq!(from_slice::<i32>(&[0xCE, 0x80, 0x00, 0x00, 0x00]), Err(Error::InvalidInteger));
1134        assert_eq!(from_slice::<i64>(&[0xCF, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Err(Error::InvalidInteger));
1135    }
1136
1137    #[test]
1138    fn test_de_char() {
1139        assert_eq!(from_slice::<char>(&[0xA4,0xf0,0x9f,0x91,0x8f]), Ok(('👏', 5)));
1140        assert_eq!(from_slice::<char>(&[0xD9,4,0xf0,0x9f,0x91,0x8f]), Ok(('👏', 6)));
1141        assert_eq!(from_slice::<char>(&[0xDA,0,4,0xf0,0x9f,0x91,0x8f]), Ok(('👏', 7)));
1142        assert_eq!(from_slice::<char>(&[0xDB,0,0,0,4,0xf0,0x9f,0x91,0x8f]), Ok(('👏', 9)));
1143        assert_eq!(from_slice::<char>(b""), Err(Error::UnexpectedEof));
1144        assert_eq!(from_slice::<char>(b"\xC0"), Err(Error::ExpectedString));
1145        assert_eq!(from_slice::<char>(b"\xA0"), Err(Error::InvalidLength));
1146        assert_eq!(from_slice::<char>(b"\xA2ab"), Err(Error::InvalidLength));
1147        assert_eq!(from_slice::<char>(b"\xA1"), Err(Error::UnexpectedEof));
1148    }
1149
1150    #[cfg(any(feature = "std", feature = "alloc"))]
1151    #[test]
1152    fn test_de_string() {
1153        assert_eq!(from_slice::<String>(&[0xA0]), Ok(("".to_string(), 1)));
1154        assert_eq!(from_slice::<String>(&[0xD9,0]), Ok(("".to_string(), 2)));
1155        assert_eq!(from_slice::<String>(&[0xDA,0,0]), Ok(("".to_string(), 3)));
1156        assert_eq!(from_slice::<String>(&[0xDB,0,0,0,0]), Ok(("".to_string(), 5)));
1157        assert_eq!(from_slice::<String>(&[0xA1]), Err(Error::UnexpectedEof));
1158    }
1159
1160    #[test]
1161    fn test_de_str() {
1162        assert_eq!(from_slice(&[0xA0]), Ok(("", 1)));
1163        assert_eq!(from_slice(&[0xD9,0]), Ok(("", 2)));
1164        assert_eq!(from_slice(&[0xDA,0,0]), Ok(("", 3)));
1165        assert_eq!(from_slice(&[0xDB,0,0,0,0]), Ok(("", 5)));
1166        assert_eq!(from_slice(&[0xA4,0xf0,0x9f,0x91,0x8f]), Ok(("👏", 5)));
1167        assert_eq!(from_slice(&[0xD9,4,0xf0,0x9f,0x91,0x8f]), Ok(("👏", 6)));
1168        assert_eq!(from_slice(&[0xDA,0,4,0xf0,0x9f,0x91,0x8f]), Ok(("👏", 7)));
1169        assert_eq!(from_slice(&[0xDB,0,0,0,4,0xf0,0x9f,0x91,0x8f]), Ok(("👏", 9)));
1170        assert_eq!(from_slice(b"\xBF01234567890ABCDEFGHIJKLMNOPQRST"),
1171                   Ok(("01234567890ABCDEFGHIJKLMNOPQRST", 32)));
1172        let text = "O, mógłże sęp chlań wyjść furtką bździn";
1173        let mut input = [0u8;50];
1174        input[..2].copy_from_slice(&[0xd9, text.len() as u8]);
1175        input[2..].copy_from_slice(text.as_bytes());
1176        assert_eq!(from_slice(&input), Ok((text, 50)));
1177        // error
1178        assert_eq!(from_slice::<&str>(&[0xC4]), Err(Error::ExpectedString));
1179        assert_eq!(from_slice::<&str>(b"\xA2\xff\xfe"), Err(Error::InvalidUnicodeCodePoint));
1180        assert_eq!(from_slice::<&str>(&[]), Err(Error::UnexpectedEof));
1181        assert_eq!(from_slice::<&str>(&[0xA1]), Err(Error::UnexpectedEof));
1182        assert_eq!(from_slice::<&str>(&[0xA2, 0]), Err(Error::UnexpectedEof));
1183        assert_eq!(from_slice::<&str>(&[0xD9]), Err(Error::UnexpectedEof));
1184        assert_eq!(from_slice::<&str>(&[0xD9, 1]), Err(Error::UnexpectedEof));
1185        assert_eq!(from_slice::<&str>(&[0xDA, 0]), Err(Error::UnexpectedEof));
1186        assert_eq!(from_slice::<&str>(&[0xDA, 0, 1]), Err(Error::UnexpectedEof));
1187        assert_eq!(from_slice::<&str>(&[0xDB, 0, 0, 0]), Err(Error::UnexpectedEof));
1188        assert_eq!(from_slice::<&str>(&[0xDB, 0, 0, 0, 1]), Err(Error::UnexpectedEof));
1189    }
1190
1191    #[test]
1192    fn test_de_bytes() {
1193        assert_eq!(from_slice::<&[u8]>(&[0xC4,0]), Ok((&[][..], 2)));
1194        assert_eq!(from_slice::<&[u8]>(&[0xC5,0,0]), Ok((&[][..], 3)));
1195        assert_eq!(from_slice::<&[u8]>(&[0xC6,0,0,0,0]), Ok((&[][..], 5)));
1196        assert_eq!(from_slice::<&[u8]>(&[0xC4,1,0xff]), Ok((&[0xff][..], 3)));
1197        assert_eq!(from_slice::<&[u8]>(&[0xC5,0,1,0xff]), Ok((&[0xff][..], 4)));
1198        assert_eq!(from_slice::<&[u8]>(&[0xC6,0,0,0,1,0xff]), Ok((&[0xff][..], 6)));
1199        // error
1200        assert_eq!(from_slice::<&[u8]>(&[0xA0]), Err(Error::ExpectedBin));
1201        assert_eq!(from_slice::<&[u8]>(&[]), Err(Error::UnexpectedEof));
1202        assert_eq!(from_slice::<&[u8]>(&[0xC4]), Err(Error::UnexpectedEof));
1203        assert_eq!(from_slice::<&[u8]>(&[0xC4, 1]), Err(Error::UnexpectedEof));
1204        assert_eq!(from_slice::<&[u8]>(&[0xC5, 0]), Err(Error::UnexpectedEof));
1205        assert_eq!(from_slice::<&[u8]>(&[0xC5, 0, 1]), Err(Error::UnexpectedEof));
1206        assert_eq!(from_slice::<&[u8]>(&[0xC6, 0, 0, 0]), Err(Error::UnexpectedEof));
1207        assert_eq!(from_slice::<&[u8]>(&[0xC6, 0, 0, 0, 1]), Err(Error::UnexpectedEof));
1208    }
1209
1210    #[cfg(any(feature = "std", feature = "alloc"))]
1211    #[test]
1212    fn test_de_bytes_own() {
1213        #[derive(Debug, Deserialize, PartialEq)]
1214        struct Bytes(#[serde(with = "serde_bytes")] Vec<u8>);
1215        assert_eq!(from_slice::<Bytes>(&[0xC4,0]), Ok((Bytes(Vec::new()), 2)));
1216        assert_eq!(from_slice::<Bytes>(&[0xC5,0,0]), Ok((Bytes(Vec::new()), 3)));
1217        assert_eq!(from_slice::<Bytes>(&[0xC6,0,0,0,0]), Ok((Bytes(Vec::new()), 5)));
1218        assert_eq!(from_slice::<Bytes>(&[0xC4,1,0xff]), Ok((Bytes(vec![0xff]), 3)));
1219        assert_eq!(from_slice::<Bytes>(&[0xC5,0,1,0xff]), Ok((Bytes(vec![0xff]), 4)));
1220        assert_eq!(from_slice::<Bytes>(&[0xC6,0,0,0,1,0xff]), Ok((Bytes(vec![0xff]), 6)));
1221        // error
1222        assert_eq!(from_slice::<Bytes>(&[0xA0]), Err(Error::ExpectedBin));
1223        assert_eq!(from_slice::<Bytes>(&[]), Err(Error::UnexpectedEof));
1224        assert_eq!(from_slice::<Bytes>(&[0xC4]), Err(Error::UnexpectedEof));
1225        assert_eq!(from_slice::<Bytes>(&[0xC4, 1]), Err(Error::UnexpectedEof));
1226        assert_eq!(from_slice::<Bytes>(&[0xC5, 0]), Err(Error::UnexpectedEof));
1227        assert_eq!(from_slice::<Bytes>(&[0xC5, 0, 1]), Err(Error::UnexpectedEof));
1228        assert_eq!(from_slice::<Bytes>(&[0xC6, 0, 0, 0]), Err(Error::UnexpectedEof));
1229        assert_eq!(from_slice::<Bytes>(&[0xC6, 0, 0, 0, 1]), Err(Error::UnexpectedEof));
1230    }
1231
1232    #[derive(Debug, Deserialize, PartialEq)]
1233    enum Type {
1234        #[serde(rename = "boolean")]
1235        Boolean,
1236        #[serde(rename = "number")]
1237        Number,
1238        #[serde(rename = "thing")]
1239        Thing,
1240    }
1241
1242    #[test]
1243    fn test_de_enum_clike() {
1244        assert_eq!(from_slice(b"\xA7boolean"), Ok((Type::Boolean, 8)));
1245        assert_eq!(from_slice(b"\xA6number"), Ok((Type::Number, 7)));
1246        assert_eq!(from_slice(b"\xA5thing"), Ok((Type::Thing, 6)));
1247
1248        assert_eq!(from_slice(b"\x00"), Ok((Type::Boolean, 1)));
1249        assert_eq!(from_slice(b"\x01"), Ok((Type::Number, 1)));
1250        assert_eq!(from_slice(b"\x02"), Ok((Type::Thing, 1)));
1251        // error
1252        #[cfg(any(feature = "std", feature = "alloc"))]
1253        assert_eq!(from_slice::<Type>(b"\xA0"), Err(Error::DeserializeError(
1254            r#"unknown variant ``, expected one of `boolean`, `number`, `thing`"#.into())));
1255        #[cfg(not(any(feature = "std", feature = "alloc")))]
1256        assert_eq!(from_slice::<Type>(b"\xA0"), Err(Error::DeserializeError));
1257
1258        #[cfg(any(feature = "std", feature = "alloc"))]
1259        assert_eq!(from_slice::<Type>(b"\xA3xyz"), Err(Error::DeserializeError(
1260            r#"unknown variant `xyz`, expected one of `boolean`, `number`, `thing`"#.into())));
1261        #[cfg(not(any(feature = "std", feature = "alloc")))]
1262        assert_eq!(from_slice::<Type>(b"\xA3xyz"), Err(Error::DeserializeError));
1263
1264        #[cfg(any(feature = "std", feature = "alloc"))]
1265        assert_eq!(from_slice::<Type>(b"\x03"), Err(Error::DeserializeError(
1266            r#"invalid value: integer `3`, expected variant index 0 <= i < 3"#.into())));
1267        #[cfg(not(any(feature = "std", feature = "alloc")))]
1268        assert_eq!(from_slice::<Type>(b"\x03"), Err(Error::DeserializeError));
1269        assert_eq!(from_slice::<Type>(&[0xC0]), Err(Error::ExpectedIdentifier));
1270        assert_eq!(from_slice::<Type>(&[0x80]), Err(Error::ExpectedIdentifier));
1271        assert_eq!(from_slice::<Type>(&[0x90]), Err(Error::ExpectedIdentifier));
1272        assert_eq!(from_slice::<Type>(b""), Err(Error::UnexpectedEof));
1273        assert_eq!(from_slice::<Type>(b"\x81\xA7boolean\xC0"), Err(Error::InvalidType));
1274        assert_eq!(from_slice::<Type>(b"\x81\xA7boolean\x90"), Err(Error::InvalidType));
1275        assert_eq!(from_slice::<Type>(b"\x81\xA7boolean\x80"), Err(Error::InvalidType));
1276    }
1277
1278    #[cfg(any(feature = "std", feature = "alloc"))]
1279    #[test]
1280    fn test_de_map() {
1281        let (map, len) = from_slice::<BTreeMap<i32,&str>>(
1282            b"\x83\xff\xA1A\xfe\xA3wee\xD1\x01\xA4\xD9\x24Waltz, bad nymph, for quick jigs vex").unwrap();
1283        assert_eq!(len, 50);
1284        assert_eq!(map.len(), 3);
1285        assert_eq!(map[&-1], "A");
1286        assert_eq!(map[&-2], "wee");
1287        assert_eq!(map[&420], "Waltz, bad nymph, for quick jigs vex");
1288
1289        let (map, len) = from_slice::<BTreeMap<i32,bool>>(&[0x80]).unwrap();
1290        assert_eq!(len, 1);
1291        assert_eq!(map.len(), 0);
1292
1293        let (map, len) = from_slice::<BTreeMap<i32,bool>>(
1294            b"\x8F\x01\xC3\x02\xC3\x03\xC3\x04\xC3\x05\xC3\x06\xC3\x07\xC3\x08\xC3\x09\xC3\x0A\xC3\x0B\xC3\x0C\xC3\x0D\xC3\x0E\xC3\x0F\xC3").unwrap();
1295        assert_eq!(len, 31);
1296        assert_eq!(map.len(), 15);
1297        for i in 1..=15 {
1298            assert_eq!(map[&i], true);
1299        }
1300
1301        let mut vec = vec![0xDE, 0xFF, 0xFF];
1302        vec.reserve(65536*2);
1303        for i in 1..=65535u16 {
1304            if i < 128 {
1305                vec.push(i as u8);
1306            }
1307            else if i < 256 {
1308                vec.push(0xCC);
1309                vec.push(i as u8);
1310            }
1311            else {
1312                vec.push(0xCD);
1313                vec.extend_from_slice(&i.to_be_bytes());
1314            }
1315            vec.push(0xC3);
1316        }
1317        let (map, len) = from_slice::<BTreeMap<u32,bool>>(vec.as_slice()).unwrap();
1318        assert_eq!(len, vec.len());
1319        assert_eq!(map.len(), 65535);
1320        for i in 1..=65535 {
1321            assert!(map[&i]);
1322        }
1323
1324        let mut vec = vec![0xDF,0x00,0x01,0x00,0x00];
1325        vec.reserve(65536*2);
1326        for i in 1..=65536u32 {
1327            if i < 128 {
1328                vec.push(i as u8);
1329            }
1330            else if i < 256 {
1331                vec.push(0xCC);
1332                vec.push(i as u8);
1333            }
1334            else if i < 65536 {
1335                vec.push(0xCD);
1336                vec.extend_from_slice(&(i as u16).to_be_bytes());
1337            }
1338            else {
1339                vec.push(0xCE);
1340                vec.extend_from_slice(&i.to_be_bytes());
1341            }
1342            vec.push(0xC3);
1343        }
1344        let (map, len) = from_slice::<BTreeMap<u32,bool>>(vec.as_slice()).unwrap();
1345        assert_eq!(len, vec.len());
1346        assert_eq!(map.len(), 65536);
1347        for i in 1..=65536 {
1348            assert!(map[&i]);
1349        }
1350
1351        // error
1352        assert_eq!(from_slice::<BTreeMap<i32,bool>>(&[0x90]), Err(Error::ExpectedMap));
1353        assert_eq!(from_slice::<BTreeMap<i32,bool>>(&[]), Err(Error::UnexpectedEof));
1354        assert_eq!(from_slice::<BTreeMap<i32,bool>>(&[0x81]), Err(Error::UnexpectedEof));
1355        assert_eq!(from_slice::<BTreeMap<i32,bool>>(&[0x81,0x00]), Err(Error::UnexpectedEof));
1356        assert_eq!(from_slice::<BTreeMap<i32,bool>>(&[0x82,0x00,0xC2]), Err(Error::UnexpectedEof));
1357        assert_eq!(from_slice::<BTreeMap<i32,bool>>(&[0xDE]), Err(Error::UnexpectedEof));
1358        assert_eq!(from_slice::<BTreeMap<i32,bool>>(&[0xDE,0x00,0x01]), Err(Error::UnexpectedEof));
1359        assert_eq!(from_slice::<BTreeMap<i32,bool>>(&[0xDF]), Err(Error::UnexpectedEof));
1360        assert_eq!(from_slice::<BTreeMap<i32,bool>>(&[0xDF,0x00,0x00,0x00,0x01]), Err(Error::UnexpectedEof));
1361    }
1362
1363    #[test]
1364    fn test_de_map_err() {
1365        use core::marker::PhantomData;
1366        use serde::de::Deserializer;
1367        #[derive(Debug, PartialEq)]
1368        struct PhonyMap(Option<(i32,i32)>);
1369        struct PhonyMapVisitor(PhantomData<PhonyMap>);
1370        impl<'de> Visitor<'de> for PhonyMapVisitor {
1371            type Value = PhonyMap;
1372            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1373                formatter.write_str("a map")
1374            }
1375            fn visit_map<M: MapAccess<'de>>(self, mut access: M) -> core::result::Result<Self::Value, M::Error> {
1376                if let Some((k, v)) = access.next_entry()? {
1377                    return Ok(PhonyMap(Some((k,v))))
1378                }
1379                Ok(PhonyMap(None))
1380            }
1381        }
1382        impl<'de> Deserialize<'de> for PhonyMap {
1383            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> core::result::Result<Self, D::Error> {
1384                deserializer.deserialize_any(PhonyMapVisitor(PhantomData))
1385            }
1386        }
1387        assert_eq!(
1388            from_slice::<PhonyMap>(b"\x80"),
1389            Ok((PhonyMap(None), 1)));
1390        assert_eq!(
1391            from_slice::<PhonyMap>(b"\x81\x00\x01"),
1392            Ok((PhonyMap(Some((0,1))), 3)));
1393        assert_eq!(from_slice::<PhonyMap>(b""), Err(Error::UnexpectedEof));
1394        assert_eq!(from_slice::<PhonyMap>(b"\x81"), Err(Error::UnexpectedEof));
1395        assert_eq!(from_slice::<PhonyMap>(b"\x81\x00"), Err(Error::UnexpectedEof));
1396        assert_eq!(from_slice::<PhonyMap>(b"\x82\x00\x01"), Err(Error::TrailingElements));
1397        assert_eq!(from_slice::<PhonyMap>(b"\x82\x00\x01"), Err(Error::TrailingElements));
1398        assert!(from_slice::<PhonyMap>(b"\x90").is_err());
1399    }
1400
1401    #[test]
1402    fn test_de_struct() {
1403        #[derive(Default, Debug, Deserialize, PartialEq)]
1404        #[serde(default)]
1405        struct Test<'a> {
1406            foo: i8,
1407            bar: &'a str
1408        }
1409        assert_eq!(
1410            from_slice(&[0x82,
1411                0xA3, b'f', b'o', b'o', 0xff,
1412                0xA3, b'b', b'a', b'r', 0xA3, b'b', b'a', b'z']),
1413            Ok((Test { foo: -1, bar: "baz" }, 14))
1414        );
1415        assert_eq!(
1416            from_slice(&[0xDE,0x00,0x02,
1417                0xD9,0x03, b'f', b'o', b'o', 0xff,
1418                0xDA,0x00,0x03, b'b', b'a', b'r', 0xDB, 0x00, 0x00, 0x00, 0x03, b'b', b'a', b'z']),
1419            Ok((Test { foo: -1, bar: "baz" }, 23))
1420        );
1421        assert_eq!(
1422            from_slice(&[0xDF,0x00,0x00,0x00,0x02,
1423                0xD9,0x03, b'f', b'o', b'o', 0xff,
1424                0xDA,0x00,0x03, b'b', b'a', b'r', 0xDB, 0x00, 0x00, 0x00, 0x03, b'b', b'a', b'z']),
1425            Ok((Test { foo: -1, bar: "baz" }, 25))
1426        );
1427
1428        assert_eq!(
1429            from_slice(&[0x82,
1430                0x00, 0xff,
1431                0x01, 0xA3, b'b', b'a', b'z']),
1432            Ok((Test { foo: -1, bar: "baz" }, 8))
1433        );
1434
1435        assert_eq!(
1436            from_slice(&[0x92, 0xff, 0xA3, b'b', b'a', b'z']),
1437            Ok((Test { foo: -1, bar: "baz" }, 6))
1438        );
1439        assert_eq!(
1440            from_slice(&[0xDC,0x00,0x02, 0xff, 0xD9,0x03, b'b', b'a', b'z']),
1441            Ok((Test { foo: -1, bar: "baz" }, 9))
1442        );
1443        assert_eq!(
1444            from_slice(&[0xDD,0x00,0x00,0x00,0x02, 0xff, 0xDB, 0x00, 0x00, 0x00, 0x03, b'b', b'a', b'z']),
1445            Ok((Test { foo: -1, bar: "baz" }, 14))
1446        );
1447
1448        // error
1449        assert_eq!(
1450            from_slice::<Test>(&[0x93, 0xff, 0xA3, b'b', b'a', b'z', 0xC0]),
1451                Err(Error::TrailingElements));
1452
1453        #[cfg(any(feature = "std", feature = "alloc"))]
1454        assert_eq!(
1455            from_slice::<Test>(&[0x84,
1456                0x00, 0xff,
1457                0x01, 0xA3, b'b', b'a', b'z',
1458                0x02, 0xC0,
1459                0xA3, b'f', b'o', b'o', 0x01]),
1460            Err(Error::DeserializeError("duplicate field `foo`".into()))
1461        );
1462        #[cfg(not(any(feature = "std", feature = "alloc")))]
1463        assert_eq!(
1464            from_slice::<Test>(&[0x84,
1465                0x00, 0xff,
1466                0x01, 0xA3, b'b', b'a', b'z',
1467                0x02, 0xC0,
1468                0xA3, b'f', b'o', b'o', 0x01]),
1469            Err(Error::DeserializeError)
1470        );
1471        assert_eq!(from_slice::<Test>(b""), Err(Error::UnexpectedEof));
1472        assert_eq!(from_slice::<Test>(b"\xC0"), Err(Error::ExpectedStruct));
1473        assert_eq!(from_slice::<Test>(b"\x81"), Err(Error::UnexpectedEof));
1474        assert_eq!(from_slice::<Test>(b"\xDC"), Err(Error::UnexpectedEof));
1475        assert_eq!(from_slice::<Test>(b"\xDD"), Err(Error::UnexpectedEof));
1476        assert_eq!(from_slice::<Test>(b"\xDE"), Err(Error::UnexpectedEof));
1477        assert_eq!(from_slice::<Test>(b"\xDF"), Err(Error::UnexpectedEof));
1478    }
1479
1480    #[test]
1481    fn test_de_struct_bool() {
1482        #[derive(Debug, Deserialize, PartialEq)]
1483        struct Led {
1484            led: bool,
1485        }
1486
1487        assert_eq!(
1488            from_slice(b"\x81\xA3led\xC3"),
1489            Ok((Led { led: true }, 6)));
1490        assert_eq!(
1491            from_slice(b"\x81\x00\xC3"),
1492            Ok((Led { led: true }, 3)));
1493        assert_eq!(
1494            from_slice(b"\x91\xC3"),
1495            Ok((Led { led: true }, 2)));
1496        assert_eq!(
1497            from_slice(b"\x81\xA3led\xC2"),
1498            Ok((Led { led: false }, 6)));
1499        assert_eq!(
1500            from_slice(b"\x81\x00\xC2"),
1501            Ok((Led { led: false }, 3)));
1502        assert_eq!(
1503            from_slice(b"\x91\xC2"),
1504            Ok((Led { led: false }, 2)));
1505    }
1506
1507    #[test]
1508    fn test_de_struct_i8() {
1509        #[derive(Debug, Deserialize, PartialEq)]
1510        struct Temperature {
1511            temperature: i8,
1512        }
1513
1514        assert_eq!(
1515            from_slice(b"\x81\xABtemperature\xEF"),
1516            Ok((Temperature { temperature: -17 }, 14)));
1517        assert_eq!(
1518            from_slice(b"\x81\x00\xEF"),
1519            Ok((Temperature { temperature: -17 }, 3)));
1520        assert_eq!(
1521            from_slice(b"\x91\xEF"),
1522            Ok((Temperature { temperature: -17 }, 2)));
1523        // out of range
1524        assert_eq!(
1525            from_slice::<Temperature>(b"\x81\xABtemperature\xCC\x80"),
1526            Err(Error::InvalidInteger));
1527        assert_eq!(
1528            from_slice::<Temperature>(b"\x91\xD1\xff\x00"),
1529            Err(Error::InvalidInteger));
1530        // error
1531        assert_eq!(from_slice::<Temperature>(b"\x81\xABtemperature\xCA\x00\x00\x00\x00"), Err(Error::ExpectedInteger));
1532        assert_eq!(from_slice::<Temperature>(b"\x81\xABtemperature\xC0"), Err(Error::ExpectedInteger));
1533        assert_eq!(from_slice::<Temperature>(b"\x81\xABtemperature\xC2"), Err(Error::ExpectedInteger));
1534    }
1535
1536    #[test]
1537    fn test_de_struct_u8() {
1538        #[derive(Debug, Deserialize, PartialEq)]
1539        struct Temperature {
1540            temperature: u8,
1541        }
1542
1543        assert_eq!(
1544            from_slice(b"\x81\xABtemperature\x14"),
1545            Ok((Temperature { temperature: 20 }, 14)));
1546        assert_eq!(
1547            from_slice(b"\x81\x00\x14"),
1548            Ok((Temperature { temperature: 20 }, 3)));
1549        assert_eq!(
1550            from_slice(b"\x91\x14"),
1551            Ok((Temperature { temperature: 20 }, 2)));
1552        // out of range
1553        assert_eq!(
1554            from_slice::<Temperature>(b"\x81\xABtemperature\xCD\x01\x00"),
1555            Err(Error::InvalidInteger));
1556        assert_eq!(
1557            from_slice::<Temperature>(b"\x91\xff"),
1558            Err(Error::InvalidInteger));
1559        // error
1560        assert_eq!(from_slice::<Temperature>(b"\x81\xABtemperature\xCA\x00\x00\x00\x00"), Err(Error::ExpectedInteger));
1561        assert_eq!(from_slice::<Temperature>(b"\x81\xABtemperature\xC0"), Err(Error::ExpectedInteger));
1562        assert_eq!(from_slice::<Temperature>(b"\x81\xABtemperature\xC2"), Err(Error::ExpectedInteger));
1563    }
1564
1565    #[test]
1566    fn test_de_struct_f32() {
1567        #[derive(Debug, Deserialize, PartialEq)]
1568        struct Temperature {
1569            temperature: f32,
1570        }
1571
1572        assert_eq!(
1573            from_slice(b"\x81\xABtemperature\xEF"),
1574            Ok((Temperature { temperature: -17.0 }, 14)));
1575        assert_eq!(
1576            from_slice(b"\x81\x00\xEF"),
1577            Ok((Temperature { temperature: -17.0 }, 3)));
1578        assert_eq!(
1579            from_slice(b"\x91\xEF"),
1580            Ok((Temperature { temperature: -17.0 }, 2)));
1581
1582        assert_eq!(
1583            from_slice(b"\x81\xABtemperature\xCA\xc1\x89\x99\x9a"),
1584            Ok((Temperature { temperature: -17.2 }, 18))
1585        );
1586        assert_eq!(
1587            from_slice(b"\x91\xCB\xBF\x61\x34\x04\xEA\x4A\x8C\x15"),
1588            Ok((Temperature {temperature: -2.1e-3}, 10))
1589        );
1590        // NaNs will always compare unequal.
1591        let (r, n): (Temperature, usize) = from_slice(b"\x81\xABtemperature\xC0").unwrap();
1592        assert!(r.temperature.is_nan());
1593        assert_eq!(n, 14);
1594        // error
1595        assert_eq!(from_slice::<Temperature>(b"\x81\xABtemperature\xC2"), Err(Error::ExpectedNumber));
1596    }
1597
1598    #[test]
1599    fn test_de_struct_option() {
1600        #[derive(Default, Debug, Deserialize, PartialEq)]
1601        #[serde(default)]
1602        struct Property<'a> {
1603            description: Option<&'a str>,
1604            value: Option<u32>,
1605        }
1606
1607        assert_eq!(
1608            from_slice(b"\x81\xABdescription\xBDAn ambient temperature sensor"),
1609            Ok((Property {description: Some("An ambient temperature sensor"), value: None}, 43)));
1610        assert_eq!(
1611            from_slice(b"\x81\x00\xBDAn ambient temperature sensor"),
1612            Ok((Property {description: Some("An ambient temperature sensor"), value: None}, 32)));
1613        assert_eq!(
1614            from_slice(b"\x91\xBDAn ambient temperature sensor"),
1615            Ok((Property {description: Some("An ambient temperature sensor"), value: None}, 31)));
1616
1617        assert_eq!(
1618            from_slice(b"\x80"),
1619            Ok((Property { description: None, value: None }, 1)));
1620        assert_eq!(
1621            from_slice(b"\x81\xABdescription\xC0"),
1622            Ok((Property { description: None, value: None }, 14)));
1623        assert_eq!(
1624            from_slice(b"\x81\xA5value\xC0"),
1625            Ok((Property { description: None, value: None }, 8)));
1626        assert_eq!(
1627            from_slice(b"\x82\xABdescription\xC0\xA5value\xC0"),
1628            Ok((Property { description: None, value: None }, 21)));
1629        assert_eq!(
1630            from_slice(b"\x81\x00\xC0"),
1631            Ok((Property { description: None, value: None }, 3)));
1632        assert_eq!(
1633            from_slice(b"\x81\x01\xC0"),
1634            Ok((Property { description: None, value: None }, 3)));
1635        assert_eq!(
1636            from_slice(b"\x81\x01\x00"),
1637            Ok((Property { description: None, value: Some(0) }, 3)));
1638        assert_eq!(
1639            from_slice(b"\x81\x01\x7F"),
1640            Ok((Property { description: None, value: Some(127) }, 3)));
1641        assert_eq!(
1642            from_slice(b"\x82\x01\x7F\x00\xC0"),
1643            Ok((Property { description: None, value: Some(127) }, 5)));
1644
1645        assert_eq!(
1646            from_slice(b"\x90"),
1647            Ok((Property { description: None, value: None }, 1)));
1648        assert_eq!(
1649            from_slice(b"\x91\xC0"),
1650            Ok((Property { description: None, value: None }, 2)));
1651        assert_eq!(
1652            from_slice(b"\x92\xC0\xC0"),
1653            Ok((Property { description: None, value: None }, 3)));
1654        assert_eq!(
1655            from_slice(b"\x91\xBDAn ambient temperature sensor"),
1656            Ok((Property { description: Some("An ambient temperature sensor"), value: None }, 31)));
1657        assert_eq!(
1658            from_slice(b"\x92\xBDAn ambient temperature sensor\xC0"),
1659            Ok((Property { description: Some("An ambient temperature sensor"), value: None }, 32)));
1660        assert_eq!(
1661            from_slice(b"\x92\xBDAn ambient temperature sensor\x00"),
1662            Ok((Property { description: Some("An ambient temperature sensor"), value: Some(0) }, 32)));
1663        assert_eq!(
1664            from_slice(b"\x92\xC0\x00"),
1665            Ok((Property { description: None, value: Some(0) }, 3)));
1666        assert_eq!(from_slice::<Property>(b"\x91\x00"), Err(Error::ExpectedString));
1667        assert_eq!(from_slice::<Property>(b"\x92\xA1x"), Err(Error::UnexpectedEof));
1668    }
1669
1670    #[test]
1671    fn test_de_test_unit() {
1672        assert_eq!(from_slice(&[0xC0]), Ok(((), 1)));
1673        #[derive(Debug, Deserialize, PartialEq)]
1674        struct Unit;
1675        assert_eq!(from_slice(&[0xC0]), Ok((Unit, 1)));
1676    }
1677
1678    #[test]
1679    fn test_de_newtype_struct() {
1680        #[derive(Deserialize, Debug, PartialEq, Clone, Copy)]
1681        struct A(u32);
1682
1683        let a = A(54);
1684        assert_eq!(from_slice(&[54]), Ok((a, 1)));
1685        assert_eq!(from_slice(&[0xCC, 54]), Ok((a, 2)));
1686        assert_eq!(from_slice(&[0xCD, 0, 54]), Ok((a, 3)));
1687        assert_eq!(from_slice(&[0xCE, 0, 0, 0, 54]), Ok((a, 5)));
1688        assert_eq!(from_slice(&[0xCF, 0, 0, 0, 0, 0, 0, 0, 54]), Ok((a, 9)));
1689        assert_eq!(from_slice(&[0xD0, 54]), Ok((a, 2)));
1690        assert_eq!(from_slice(&[0xD1, 0, 54]), Ok((a, 3)));
1691        assert_eq!(from_slice(&[0xD2, 0, 0, 0, 54]), Ok((a, 5)));
1692        assert_eq!(from_slice(&[0xD3, 0, 0, 0, 0, 0, 0, 0, 54]), Ok((a, 9)));
1693        assert_eq!(from_slice::<A>(&[0xCA, 0x42, 0x58, 0, 0]), Err(Error::ExpectedInteger));
1694        assert_eq!(from_slice::<A>(&[0xCB, 0x40, 0x4B, 0, 0, 0, 0, 0, 0]), Err(Error::ExpectedInteger));
1695
1696        #[derive(Deserialize, Debug, PartialEq, Clone, Copy)]
1697        struct B(f32);
1698
1699        let b = B(54.0);
1700        assert_eq!(from_slice(&[54]), Ok((b, 1)));
1701        assert_eq!(from_slice(&[0xCC, 54]), Ok((b, 2)));
1702        assert_eq!(from_slice(&[0xCD, 0, 54]), Ok((b, 3)));
1703        assert_eq!(from_slice(&[0xCE, 0, 0, 0, 54]), Ok((b, 5)));
1704        assert_eq!(from_slice(&[0xCF, 0, 0, 0, 0, 0, 0, 0, 54]), Ok((b, 9)));
1705        assert_eq!(from_slice(&[0xD0, 54]), Ok((b, 2)));
1706        assert_eq!(from_slice(&[0xD1, 0, 54]), Ok((b, 3)));
1707        assert_eq!(from_slice(&[0xD2, 0, 0, 0, 54]), Ok((b, 5)));
1708        assert_eq!(from_slice(&[0xD3, 0, 0, 0, 0, 0, 0, 0, 54]), Ok((b, 9)));
1709        assert_eq!(from_slice(&[0xCA, 0x42, 0x58, 0, 0]), Ok((b, 5)));
1710        assert_eq!(from_slice(&[0xCB, 0x40, 0x4B, 0, 0, 0, 0, 0, 0]), Ok((b, 9)));
1711    }
1712
1713    #[test]
1714    fn test_de_newtype_variant() {
1715        #[derive(Deserialize, Debug, PartialEq, Clone, Copy)]
1716        enum A {
1717            A(u32),
1718        }
1719        let a = A::A(54);
1720        assert_eq!(from_slice::<A>(&[0x81,0xA1,b'A',54]), Ok((a, 4)));
1721        assert_eq!(from_slice::<A>(&[0x81,0x00,54]), Ok((a, 3)));
1722        // error
1723        assert_eq!(from_slice::<A>(&[]), Err(Error::UnexpectedEof));
1724        assert_eq!(from_slice::<A>(&[0x81]), Err(Error::UnexpectedEof));
1725        assert_eq!(from_slice::<A>(&[0x00]), Err(Error::InvalidType));
1726        assert_eq!(from_slice::<A>(&[0xA1,b'A']), Err(Error::InvalidType));
1727    }
1728
1729    #[test]
1730    fn test_de_struct_variant() {
1731        #[derive(Deserialize, Debug, PartialEq, Clone, Copy)]
1732        enum A {
1733            A { x: u32, y: u16 },
1734        }
1735        let a = A::A { x: 54, y: 720 };
1736        assert_eq!(from_slice(&[0x81,0xA1,b'A', 0x82, 0xA1,b'x',54, 0xA1,b'y',0xCD,2,208]), Ok((a, 12)));
1737        assert_eq!(from_slice(&[0x81,0x00, 0x82, 0xA1,b'x',54, 0xA1,b'y',0xCD,2,208]), Ok((a, 11)));
1738        assert_eq!(from_slice(&[0x81,0xA1,b'A', 0x82, 0x00,54, 0x01,0xCD,2,208]), Ok((a, 10)));
1739        assert_eq!(from_slice(&[0x81,0x00, 0x82, 0x00,54, 0x01,0xCD,2,208]), Ok((a, 9)));
1740        assert_eq!(from_slice(&[0x81,0xA1,b'A', 0x92 ,54, 0xCD,2,208]), Ok((a, 8)));
1741        assert_eq!(from_slice(&[0x81,0x00, 0x92 ,54, 0xCD,2,208]), Ok((a, 7)));
1742        // error
1743        assert_eq!(from_slice::<A>(&[]), Err(Error::UnexpectedEof));
1744        assert_eq!(from_slice::<A>(&[0x81]), Err(Error::UnexpectedEof));
1745        assert_eq!(from_slice::<A>(&[0x81,0xA1,b'A', 0x93 ,54, 0xCD,2,208, 0xC0]), Err(Error::TrailingElements));
1746        assert_eq!(from_slice::<A>(&[0x81,0x00, 0x93 ,54, 0xCD,2,208, 0xC0]), Err(Error::TrailingElements));
1747        assert_eq!(from_slice::<A>(&[0xA1,b'A']), Err(Error::InvalidType));
1748    }
1749
1750    #[test]
1751    fn test_de_tuple_variant() {
1752        #[derive(Deserialize, Debug, PartialEq, Clone, Copy)]
1753        enum A {
1754            A(i32,u16),
1755        }
1756        let a = A::A(-19,10000);
1757        assert_eq!(from_slice(&[0x81,0xA1,b'A', 0x92 ,0xED, 0xCD,0x27,0x10]), Ok((a, 8)));
1758        assert_eq!(from_slice(&[0x81,0x00, 0x92 ,0xED, 0xCD,0x27,0x10]), Ok((a, 7)));
1759        // error
1760        assert_eq!(from_slice::<A>(&[]), Err(Error::UnexpectedEof));
1761        assert_eq!(from_slice::<A>(&[0xA1,b'A']), Err(Error::InvalidType));
1762        assert_eq!(from_slice::<A>(&[0x81,0xA1,b'A', 0x80]), Err(Error::ExpectedArray));
1763        assert_eq!(from_slice::<A>(&[0x81,0x00, 0x80]), Err(Error::ExpectedArray));
1764        assert_eq!(from_slice::<A>(&[0x81,0x00, 0x93 ,0xED, 0xCD,0x27,0x10, 0xC0]), Err(Error::TrailingElements));
1765        assert_eq!(from_slice::<A>(&[0x81,0xA1,b'A', 0x93 ,0xED, 0xCD,0x27,0x10, 0xC0]), Err(Error::TrailingElements));
1766    }
1767
1768    #[test]
1769    fn test_de_struct_tuple() {
1770        #[derive(Debug, Deserialize, PartialEq)]
1771        struct Xy(u8, i8);
1772
1773        assert_eq!(from_slice(&[0x92,10,20]), Ok((Xy(10, 20), 3)));
1774        assert_eq!(from_slice(&[0x92,0xCC,200,-20i8 as _]), Ok((Xy(200, -20), 4)));
1775        assert_eq!(from_slice(&[0x92,10,0xD0,-77i8 as _]), Ok((Xy(10, -77), 4)));
1776        assert_eq!(from_slice(&[0x92,0xCC,200,0xD0,-77i8 as _]), Ok((Xy(200, -77), 5)));
1777
1778        // wrong number of args
1779        #[cfg(any(feature = "std", feature = "alloc"))]
1780        assert_eq!(
1781            from_slice::<Xy>(&[0x91,0x10]),
1782            Err(Error::DeserializeError(
1783                r#"invalid length 1, expected tuple struct Xy with 2 elements"#.to_string()))
1784        );
1785        #[cfg(not(any(feature = "std", feature = "alloc")))]
1786        assert_eq!(
1787            from_slice::<Xy>(&[0x91,0x10]),
1788            Err(Error::DeserializeError)
1789        );
1790        assert_eq!(
1791            from_slice::<Xy>(&[0x93,10,20,30]),
1792            Err(Error::TrailingElements)
1793        );
1794    }
1795
1796    #[test]
1797    fn test_de_struct_with_array_field() {
1798        #[derive(Debug, Deserialize, PartialEq)]
1799        struct Test {
1800            status: bool,
1801            point: [u32; 3],
1802        }
1803
1804        assert_eq!(
1805            from_slice(b"\x82\xA6status\xC3\xA5point\x93\x01\x02\x03"),
1806            Ok((
1807                Test {
1808                    status: true,
1809                    point: [1, 2, 3]
1810                },
1811                19
1812            ))
1813        );
1814        assert_eq!(
1815            from_slice(b"\x82\x00\xC3\x01\x93\x01\x02\x03"),
1816            Ok((
1817                Test {
1818                    status: true,
1819                    point: [1, 2, 3]
1820                },
1821                8
1822            ))
1823        );
1824        assert_eq!(
1825            from_slice(b"\x92\xC3\x93\x01\x02\x03"),
1826            Ok((
1827                Test {
1828                    status: true,
1829                    point: [1, 2, 3]
1830                },
1831                6
1832            ))
1833        );
1834    }
1835
1836    #[test]
1837    fn test_de_struct_with_tuple_field() {
1838        #[derive(Debug, Deserialize, PartialEq)]
1839        struct Test {
1840            status: bool,
1841            point: (u32, u32, u32),
1842        }
1843
1844        assert_eq!(
1845            from_slice(b"\x82\xA6status\xC3\xA5point\x93\x01\x02\x03"),
1846            Ok((
1847                Test {
1848                    status: true,
1849                    point: (1, 2, 3)
1850                },
1851                19
1852            ))
1853        );
1854        assert_eq!(
1855            from_slice(b"\x82\x00\xC3\x01\x93\x01\x02\x03"),
1856            Ok((
1857                Test {
1858                    status: true,
1859                    point: (1, 2, 3)
1860                },
1861                8
1862            ))
1863        );
1864        assert_eq!(
1865            from_slice(b"\x92\xC3\x93\x01\x02\x03"),
1866            Ok((
1867                Test {
1868                    status: true,
1869                    point: (1, 2, 3)
1870                },
1871                6
1872            ))
1873        );
1874    }
1875
1876    #[test]
1877    fn test_de_streaming() {
1878        let test = Test {
1879            compact: true,
1880            schema: 0,
1881            unit: Unit
1882        };
1883        let input = b"\xC0\xC2\x00\xA3ABC\xC4\x04_xyz\x83\xA7compact\xC3\xA6schema\x00\xA4unit\xC0\x93\x01\x02\x03\xC0";
1884        let (res, input) = from_slice_split_tail::<()>(input).unwrap();
1885        assert_eq!(res, ());
1886        let (res, input) = from_slice_split_tail::<bool>(input).unwrap();
1887        assert_eq!(res, false);
1888        let (res, input) = from_slice_split_tail::<i8>(input).unwrap();
1889        assert_eq!(res, 0);
1890        let (res, input) = from_slice_split_tail::<&str>(input).unwrap();
1891        assert_eq!(res, "ABC");
1892        let (res, input) = from_slice_split_tail::<&[u8]>(input).unwrap();
1893        assert_eq!(res, b"_xyz");
1894        let (res, input) = from_slice_split_tail::<Test>(input).unwrap();
1895        assert_eq!(res, test);
1896        let (res, input) = from_slice_split_tail::<[u32;3]>(input).unwrap();
1897        assert_eq!(res, [1,2,3]);
1898        let (res, input) = from_slice_split_tail::<Option<()>>(input).unwrap();
1899        assert_eq!(res, None);
1900        assert_eq!(input, b"");
1901        // error
1902        assert_eq!(from_slice_split_tail::<()>(input), Err(Error::UnexpectedEof));
1903    }
1904
1905    #[test]
1906    fn test_de_ignoring_extra_fields() {
1907        #[derive(Debug, Deserialize, PartialEq)]
1908        struct Temperature {
1909            temp: u32,
1910        }
1911        let input = &[
1912            0x8F,
1913            0xA4,b't',b'e',b'm',b'p', 20,
1914            0xA1,b'n', 0xC0,
1915            0xA1,b't', 0xC2,
1916            0xA1,b'f', 0xC3,
1917            0xA4,b'f',b'i',b'x',b'+', 0x7F,
1918            0xA4,b'f',b'i',b'x',b'-', -32i8 as _,
1919            0xA2,b'u',b'8',      0xCC,0xFF,
1920            0xA3,b'u',b'1',b'6', 0xCD,0xFF,0xFF,
1921            0xA3,b'u',b'3',b'2', 0xCE,0xFF,0xFF,0xFF,0xFF,
1922            0xA3,b'u',b'6',b'4', 0xCF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
1923            0xA2,b'i',b'8',      0xD0,0xFF,
1924            0xA3,b'i',b'1',b'6', 0xD1,0xFF,0xFF,
1925            0xA3,b'i',b'3',b'2', 0xD2,0xFF,0xFF,0xFF,0xFF,
1926            0xA3,b'i',b'6',b'4', 0xD3,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
1927            0xA3,b's',b't',b'r', 0xBF, b'J',b'a',b'c',b'k',b'd',b'a',b'w',b's',
1928                                       b'l',b'o',b'v',b'e',
1929                                       b'm',b'y',
1930                                       b'b',b'i',b'g',
1931                                       b's',b'p',b'h',b'i',b'n',b'x',
1932                                       b'o',b'f',
1933                                       b'q',b'u',b'a',b'r',b't',b'z'
1934        ];
1935        assert_eq!(
1936            from_slice(input),
1937            Ok((Temperature { temp: 20 }, input.len()))
1938        );
1939        let input = &[
1940            0x8F,
1941            0xA1,b'n', 0xC0,
1942            0xA1,b't', 0xC2,
1943            0xA1,b'f', 0xC3,
1944            0xA4,b'f',b'i',b'x',b'+', 0x7F,
1945            0xA4,b'f',b'i',b'x',b'-', -32i8 as _,
1946            0xA2,b'u',b'8',      0xCC,0xFF,
1947            0xA3,b'u',b'1',b'6', 0xCD,0xFF,0xFF,
1948            0xA3,b'u',b'3',b'2', 0xCE,0xFF,0xFF,0xFF,0xFF,
1949            0xA3,b'u',b'6',b'4', 0xCF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
1950            0xA2,b'i',b'8',      0xD0,0xFF,
1951            0xA3,b'i',b'1',b'6', 0xD1,0xFF,0xFF,
1952            0xA3,b'i',b'3',b'2', 0xD2,0xFF,0xFF,0xFF,0xFF,
1953            0xA3,b'i',b'6',b'4', 0xD3,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
1954            0xA3,b's',b't',b'r', 0xBF, b'J',b'a',b'c',b'k',b'd',b'a',b'w',b's',
1955                                       b'l',b'o',b'v',b'e',
1956                                       b'm',b'y',
1957                                       b'b',b'i',b'g',
1958                                       b's',b'p',b'h',b'i',b'n',b'x',
1959                                       b'o',b'f',
1960                                       b'q',b'u',b'a',b'r',b't',b'z',
1961            0xA4,b't',b'e',b'm',b'p', 20
1962        ];
1963        assert_eq!(
1964            from_slice(input),
1965            Ok((Temperature { temp: 20 }, input.len()))
1966        );
1967        let input = &[
1968            0x89,
1969            0xA4,b't',b'e',b'm',b'p', 0xCC, 220,
1970            0xA3,b'f',b'3',b'2', 0xCA,0x00,0x00,0x00,0x00,
1971            0xA3,b'f',b'6',b'4', 0xCB,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
1972            0xA2,b's',b'8', 0xD9,0x01,b'-',
1973            0xA3,b's',b'1',b'6', 0xDA,0x00,0x01,b'-',
1974            0xA3,b's',b'3',b'2', 0xDB,0x00,0x00,0x00,0x01,b'-',
1975            0xA2,b'b',b'8', 0xC4,0x01,0x80,
1976            0xA3,b'b',b'1',b'6', 0xC5,0x00,0x01,0x80,
1977            0xA3,b'b',b'3',b'2', 0xC6,0x00,0x00,0x00,0x01,0x80,
1978        ];
1979        assert_eq!(
1980            from_slice(input),
1981            Ok((Temperature { temp: 220 }, input.len()))
1982        );
1983        let input = &[
1984            0x89,
1985            0xA1,b'a', 0x90,
1986            0xA2,b'a',b'1', 0x91,0x00,
1987            0xA2,b'a',b's', 0xDC,0x00,0x02, 0xA0, 0xA3,b'1',b'2',b'3',
1988            0xA2,b'a',b'l', 0xDD,0x00,0x00,0x00,0x02, 0xA0, 0xA3,b'1',b'2',b'3',
1989            0xA1,b'm', 0x80,
1990            0xA2,b'm',b'1', 0x81,0x00,0xA0,
1991            0xA2,b'm',b's', 0xDE,0x00,0x02, 0x00,0xA0, 0x01,0xA3,b'1',b'2',b'3',
1992            0xA2,b'm',b'l', 0xDF,0x00,0x00,0x00,0x02, 0xA1,b'x', 0x92,0xC2,0xC3,
1993                                                      0xA1,b'y', 0x91,0xC0,
1994            0xA4,b't',b'e',b'm',b'p', 0xCC, 220,
1995        ];
1996        assert_eq!(
1997            from_slice(input),
1998            Ok((Temperature { temp: 220 }, input.len()))
1999        );
2000        let input = &[
2001            0x8B,
2002            0xA3,b'f',b'3',b'2', 0xCA,0x00,0x00,0x00,0x00,
2003            0xA3,b'f',b'6',b'4', 0xCB,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
2004            0xA2,b'e',b'8', 0xC7,0x01,0x7F,b'.',
2005            0xA3,b'e',b'1',b'6', 0xC8,0x00,0x01,0x7F,b'.',
2006            0xA3,b'e',b'3',b'2', 0xC9,0x00,0x00,0x00,0x01,0x7F,b'.',
2007            0xA2,b'x',b'1', 0xD4,0x7F,b'.',
2008            0xA2,b'x',b'2', 0xD5,0x7F,b'.',b'.',
2009            0xA2,b'x',b'4', 0xD6,0x7F,b'.',b'.',b'.',b'.',
2010            0xA2,b'x',b'8', 0xD7,0x7F,b'.',b'.',b'.',b'.',b'.',b'.',b'.',b'.',
2011            0xA3,b'x',b'1',b'6', 0xD8,0x7F,b'.',b'.',b'.',b'.',b'.',b'.',b'.',b'.',
2012                                           b'.',b'.',b'.',b'.',b'.',b'.',b'.',b'.',
2013            0xA4,b't',b'e',b'm',b'p', 0xCD,2,8,
2014        ];
2015        assert_eq!(
2016            from_slice(input),
2017            Ok((Temperature { temp: 520 }, input.len()))
2018        );
2019        assert_eq!(
2020            from_slice::<Temperature>(&[
2021                0x82,
2022                0xA4,b't',b'e',b'm',b'p', 20,
2023                0xA1,b'_', 0xC1
2024            ]),
2025            Err(Error::ReservedCode)
2026        );
2027    }
2028
2029    #[test]
2030    fn test_de_any() {
2031        #[derive(Debug, Deserialize, PartialEq)]
2032        #[serde(untagged)]
2033        enum Thing<'a> {
2034            Nope,
2035            Bool(bool),
2036            Str(&'a str),
2037            Bytes(&'a[u8]),
2038            Uint(u32),
2039            Int(i32),
2040            LongUint(u64),
2041            LongInt(i64),
2042            Float(f64),
2043            Array([&'a str;2]),
2044            Map{ a: u32, b: &'a str},
2045        }
2046        let input = b"\xC0";
2047        assert_eq!(
2048            from_slice(input),
2049            Ok((Thing::Nope, input.len()))
2050        );
2051        let input = b"\xC2";
2052        assert_eq!(
2053            from_slice(input),
2054            Ok((Thing::Bool(false), input.len()))
2055        );
2056        let input = b"\x00";
2057        assert_eq!(
2058            from_slice(input),
2059            Ok((Thing::Uint(0), input.len()))
2060        );
2061        let input = b"\xFF";
2062        assert_eq!(
2063            from_slice(input),
2064            Ok((Thing::Int(-1), input.len())));
2065        let input = b"\xA3foo";
2066        assert_eq!(
2067            from_slice(input),
2068            Ok((Thing::Str("foo"), input.len())));
2069        let input = b"\xD9\x03foo";
2070        assert_eq!(
2071            from_slice(input),
2072            Ok((Thing::Str("foo"), input.len())));
2073        let input = b"\xDA\x00\x03foo";
2074        assert_eq!(
2075            from_slice(input),
2076            Ok((Thing::Str("foo"), input.len())));
2077        let input = b"\xDB\x00\x00\x00\x03foo";
2078        assert_eq!(
2079            from_slice(input),
2080            Ok((Thing::Str("foo"), input.len())));
2081        let input = b"\xC4\x01\x80";
2082        assert_eq!(
2083            from_slice(input),
2084            Ok((Thing::Bytes(b"\x80"), input.len())));
2085        let input = b"\xCC\x00";
2086        assert_eq!(
2087            from_slice(input),
2088            Ok((Thing::Uint(0), input.len())));
2089        let input = b"\xCD\x00\x00";
2090        assert_eq!(
2091            from_slice(input),
2092            Ok((Thing::Uint(0), input.len())));
2093        let input = b"\xCE\x00\x00\x00\x00";
2094        assert_eq!(
2095            from_slice(input),
2096            Ok((Thing::Uint(0), input.len())));
2097        let input = b"\xCF\x00\x00\x00\x00\x00\x00\x00\x00";
2098        assert_eq!(
2099            from_slice(input),
2100            Ok((Thing::Uint(0), input.len())));
2101        let input = b"\xCF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF";
2102        assert_eq!(
2103            from_slice(input),
2104            Ok((Thing::LongUint(u64::MAX), input.len())));
2105        let input = b"\xD3\x00\x00\x00\x00\x00\x00\x00\x00";
2106        assert_eq!(
2107            from_slice(input),
2108            Ok((Thing::Uint(0), input.len())));
2109        let input = b"\xD0\xFF";
2110        assert_eq!(
2111            from_slice(input),
2112            Ok((Thing::Int(-1), input.len())));
2113        let input = b"\xD1\xFF\xFF";
2114        assert_eq!(
2115            from_slice(input),
2116            Ok((Thing::Int(-1), input.len())));
2117        let input = b"\xD2\xFF\xFF\xFF\xFF";
2118        assert_eq!(
2119            from_slice(input),
2120            Ok((Thing::Int(-1), input.len())));
2121        let input = b"\xD3\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF";
2122        assert_eq!(
2123            from_slice(input),
2124            Ok((Thing::Int(-1), input.len())));
2125        let input = b"\xD3\x80\x00\x00\x00\x00\x00\x00\x00";
2126        assert_eq!(
2127            from_slice(input),
2128            Ok((Thing::LongInt(i64::MIN), input.len())));
2129        let input = b"\xCA\x00\x00\x00\x00";
2130        assert_eq!(
2131            from_slice(input),
2132            Ok((Thing::Float(0.0), input.len())));
2133        let input = b"\xCB\x00\x00\x00\x00\x00\x00\x00\x00";
2134        assert_eq!(
2135            from_slice(input),
2136            Ok((Thing::Float(0.0), input.len())));
2137        let input = b"\xCB\x7F\xEF\xFF\xFF\xFF\xFF\xFF\xFF";
2138        assert_eq!(
2139            from_slice(input),
2140            Ok((Thing::Float(f64::MAX), input.len())));
2141        let input = b"\x92\xA2xy\xA3abc";
2142        assert_eq!(
2143            from_slice(input),
2144            Ok((Thing::Array(["xy","abc"]), input.len())));
2145        let input = b"\xDC\x00\x02\xA2xy\xA3abc";
2146        assert_eq!(
2147            from_slice(input),
2148            Ok((Thing::Array(["xy","abc"]), input.len())));
2149        let input = b"\xDD\x00\x00\x00\x02\xA2xy\xA3abc";
2150        assert_eq!(
2151            from_slice(input),
2152            Ok((Thing::Array(["xy","abc"]), input.len())));
2153        let input = b"\x82\xA1a\x7e\xA1b\xA3zyx";
2154        assert_eq!(
2155            from_slice(input),
2156            Ok((Thing::Map{a:126,b:"zyx"}, input.len())));
2157        let input = b"\xDE\x00\x02\xA1a\x7e\xA1b\xA3zyx";
2158        assert_eq!(
2159            from_slice(input),
2160            Ok((Thing::Map{a:126,b:"zyx"}, input.len())));
2161        let input = b"\xDF\x00\x00\x00\x02\xA1a\x7e\xA1b\xA3zyx";
2162        assert_eq!(
2163            from_slice(input),
2164            Ok((Thing::Map{a:126,b:"zyx"}, input.len())));
2165        // error
2166        assert_eq!(from_slice::<Thing>(b""), Err(Error::UnexpectedEof));
2167        assert_eq!(from_slice::<Thing>(b"\xC1"), Err(Error::ReservedCode));
2168        assert_eq!(from_slice::<Thing>(b"\xC7"), Err(Error::UnsupportedExt));
2169        assert_eq!(from_slice::<Thing>(b"\xC8"), Err(Error::UnsupportedExt));
2170        assert_eq!(from_slice::<Thing>(b"\xC9"), Err(Error::UnsupportedExt));
2171        assert_eq!(from_slice::<Thing>(b"\xD4"), Err(Error::UnsupportedExt));
2172        assert_eq!(from_slice::<Thing>(b"\xD5"), Err(Error::UnsupportedExt));
2173        assert_eq!(from_slice::<Thing>(b"\xD6"), Err(Error::UnsupportedExt));
2174        assert_eq!(from_slice::<Thing>(b"\xD7"), Err(Error::UnsupportedExt));
2175        assert_eq!(from_slice::<Thing>(b"\xD8"), Err(Error::UnsupportedExt));
2176    }
2177
2178    #[test]
2179    fn test_de_ignore_err() {
2180        assert_eq!(Deserializer::from_slice(b"").eat_message(), Err(Error::UnexpectedEof));
2181        assert_eq!(Deserializer::from_slice(b"\x81").eat_message(), Err(Error::UnexpectedEof));
2182        assert_eq!(Deserializer::from_slice(b"\x81\xC0").eat_message(), Err(Error::UnexpectedEof));
2183        assert_eq!(Deserializer::from_slice(b"\x91").eat_message(), Err(Error::UnexpectedEof));
2184        assert_eq!(Deserializer::from_slice(b"\xA1").eat_message(), Err(Error::UnexpectedEof));
2185        assert_eq!(Deserializer::from_slice(b"\xC4").eat_message(), Err(Error::UnexpectedEof));
2186        assert_eq!(Deserializer::from_slice(b"\xC4\x01").eat_message(), Err(Error::UnexpectedEof));
2187        assert_eq!(Deserializer::from_slice(b"\xC5\x00").eat_message(), Err(Error::UnexpectedEof));
2188        assert_eq!(Deserializer::from_slice(b"\xC5\x00\x01").eat_message(), Err(Error::UnexpectedEof));
2189        assert_eq!(Deserializer::from_slice(b"\xC6\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2190        assert_eq!(Deserializer::from_slice(b"\xC6\x00\x00\x00\x01").eat_message(), Err(Error::UnexpectedEof));
2191        assert_eq!(Deserializer::from_slice(b"\xC7").eat_message(), Err(Error::UnexpectedEof));
2192        assert_eq!(Deserializer::from_slice(b"\xC7\x00").eat_message(), Err(Error::UnexpectedEof));
2193        assert_eq!(Deserializer::from_slice(b"\xC7\x01\x7f").eat_message(), Err(Error::UnexpectedEof));
2194        assert_eq!(Deserializer::from_slice(b"\xC8").eat_message(), Err(Error::UnexpectedEof));
2195        assert_eq!(Deserializer::from_slice(b"\xC8\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2196        assert_eq!(Deserializer::from_slice(b"\xC8\x00\x01\x7f").eat_message(), Err(Error::UnexpectedEof));
2197        assert_eq!(Deserializer::from_slice(b"\xC9").eat_message(), Err(Error::UnexpectedEof));
2198        assert_eq!(Deserializer::from_slice(b"\xC9\x00\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2199        assert_eq!(Deserializer::from_slice(b"\xC9\x00\x00\x00\x01\x7f").eat_message(), Err(Error::UnexpectedEof));
2200        assert_eq!(Deserializer::from_slice(b"\xCA").eat_message(), Err(Error::UnexpectedEof));
2201        assert_eq!(Deserializer::from_slice(b"\xCA\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2202        assert_eq!(Deserializer::from_slice(b"\xCB").eat_message(), Err(Error::UnexpectedEof));
2203        assert_eq!(Deserializer::from_slice(b"\xCB\x00\x00\x00\x00\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2204        assert_eq!(Deserializer::from_slice(b"\xCC").eat_message(), Err(Error::UnexpectedEof));
2205        assert_eq!(Deserializer::from_slice(b"\xCD\x00").eat_message(), Err(Error::UnexpectedEof));
2206        assert_eq!(Deserializer::from_slice(b"\xCE\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2207        assert_eq!(Deserializer::from_slice(b"\xCF\x00\x00\x00\x00\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2208        assert_eq!(Deserializer::from_slice(b"\xD0").eat_message(), Err(Error::UnexpectedEof));
2209        assert_eq!(Deserializer::from_slice(b"\xD1\x00").eat_message(), Err(Error::UnexpectedEof));
2210        assert_eq!(Deserializer::from_slice(b"\xD2\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2211        assert_eq!(Deserializer::from_slice(b"\xD3\x00\x00\x00\x00\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2212        assert_eq!(Deserializer::from_slice(b"\xD4").eat_message(), Err(Error::UnexpectedEof));
2213        assert_eq!(Deserializer::from_slice(b"\xD4\x7f").eat_message(), Err(Error::UnexpectedEof));
2214        assert_eq!(Deserializer::from_slice(b"\xD5").eat_message(), Err(Error::UnexpectedEof));
2215        assert_eq!(Deserializer::from_slice(b"\xD5\x7f").eat_message(), Err(Error::UnexpectedEof));
2216        assert_eq!(Deserializer::from_slice(b"\xD5\x7f\x00").eat_message(), Err(Error::UnexpectedEof));
2217        assert_eq!(Deserializer::from_slice(b"\xD6").eat_message(), Err(Error::UnexpectedEof));
2218        assert_eq!(Deserializer::from_slice(b"\xD6\x7f").eat_message(), Err(Error::UnexpectedEof));
2219        assert_eq!(Deserializer::from_slice(b"\xD6\x7f\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2220        assert_eq!(Deserializer::from_slice(b"\xD7").eat_message(), Err(Error::UnexpectedEof));
2221        assert_eq!(Deserializer::from_slice(b"\xD7\x7f").eat_message(), Err(Error::UnexpectedEof));
2222        assert_eq!(Deserializer::from_slice(b"\xD7\x7f\x00\x00\x00\x00\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2223        assert_eq!(Deserializer::from_slice(b"\xD8").eat_message(), Err(Error::UnexpectedEof));
2224        assert_eq!(Deserializer::from_slice(b"\xD8\x7f").eat_message(), Err(Error::UnexpectedEof));
2225        assert_eq!(Deserializer::from_slice(b"\xD8\x7f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2226        assert_eq!(Deserializer::from_slice(b"\xD9").eat_message(), Err(Error::UnexpectedEof));
2227        assert_eq!(Deserializer::from_slice(b"\xD9\x01").eat_message(), Err(Error::UnexpectedEof));
2228        assert_eq!(Deserializer::from_slice(b"\xDA\x00").eat_message(), Err(Error::UnexpectedEof));
2229        assert_eq!(Deserializer::from_slice(b"\xDA\x00\x01").eat_message(), Err(Error::UnexpectedEof));
2230        assert_eq!(Deserializer::from_slice(b"\xDB\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2231        assert_eq!(Deserializer::from_slice(b"\xDB\x00\x00\x00\x01").eat_message(), Err(Error::UnexpectedEof));
2232        assert_eq!(Deserializer::from_slice(b"\xDC").eat_message(), Err(Error::UnexpectedEof));
2233        assert_eq!(Deserializer::from_slice(b"\xDC\x00").eat_message(), Err(Error::UnexpectedEof));
2234        assert_eq!(Deserializer::from_slice(b"\xDC\x00\x01").eat_message(), Err(Error::UnexpectedEof));
2235        assert_eq!(Deserializer::from_slice(b"\xDD").eat_message(), Err(Error::UnexpectedEof));
2236        assert_eq!(Deserializer::from_slice(b"\xDD\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2237        assert_eq!(Deserializer::from_slice(b"\xDD\x00\x00\x00\x01").eat_message(), Err(Error::UnexpectedEof));
2238        assert_eq!(Deserializer::from_slice(b"\xDE").eat_message(), Err(Error::UnexpectedEof));
2239        assert_eq!(Deserializer::from_slice(b"\xDE\x00").eat_message(), Err(Error::UnexpectedEof));
2240        assert_eq!(Deserializer::from_slice(b"\xDE\x00\x01").eat_message(), Err(Error::UnexpectedEof));
2241        assert_eq!(Deserializer::from_slice(b"\xDE\x00\x01\xC0").eat_message(), Err(Error::UnexpectedEof));
2242        assert_eq!(Deserializer::from_slice(b"\xDF").eat_message(), Err(Error::UnexpectedEof));
2243        assert_eq!(Deserializer::from_slice(b"\xDF\x00\x00\x00").eat_message(), Err(Error::UnexpectedEof));
2244        assert_eq!(Deserializer::from_slice(b"\xDF\x00\x00\x00\x01").eat_message(), Err(Error::UnexpectedEof));
2245        assert_eq!(Deserializer::from_slice(b"\xDF\x00\x00\x00\x01\xC0").eat_message(), Err(Error::UnexpectedEof));
2246    }
2247
2248    #[cfg(any(feature = "std", feature = "alloc"))]
2249    #[test]
2250    fn test_de_error_string() {
2251        assert_eq!(&format!("{}", Error::UnexpectedEof), "Unexpected end of MessagePack input");
2252        assert_eq!(&format!("{}", Error::ReservedCode), "Reserved MessagePack code in input");
2253        assert_eq!(&format!("{}", Error::UnsupportedExt), "Unsupported MessagePack extension code in input");
2254        assert_eq!(&format!("{}", Error::InvalidInteger), "Could not coerce integer to a deserialized type");
2255        assert_eq!(&format!("{}", Error::InvalidType), "Invalid type");
2256        assert_eq!(&format!("{}", Error::InvalidUnicodeCodePoint), "Invalid unicode code point");
2257        assert_eq!(&format!("{}", Error::ExpectedInteger), "Expected MessagePack integer");
2258        assert_eq!(&format!("{}", Error::ExpectedNumber), "Expected MessagePack number");
2259        assert_eq!(&format!("{}", Error::ExpectedString), "Expected MessagePack string");
2260        assert_eq!(&format!("{}", Error::ExpectedBin), "Expected MessagePack bin");
2261        assert_eq!(&format!("{}", Error::ExpectedNil), "Expected MessagePack nil");
2262        assert_eq!(&format!("{}", Error::ExpectedArray), "Expected MessagePack array");
2263        assert_eq!(&format!("{}", Error::ExpectedMap), "Expected MessagePack map");
2264        assert_eq!(&format!("{}", Error::ExpectedStruct), "Expected MessagePack map or array");
2265        assert_eq!(&format!("{}", Error::ExpectedIdentifier), "Expected a struct field or enum variant identifier");
2266        assert_eq!(&format!("{}", Error::TrailingElements), "Too many elements for a deserialized type");
2267        assert_eq!(&format!("{}", Error::InvalidLength), "Invalid length");
2268        let custom: Error = serde::de::Error::custom("xxx");
2269        assert_eq!(format!("{}", custom), "xxx while deserializing MessagePack");
2270    }
2271
2272    #[cfg(not(any(feature = "std", feature = "alloc")))]
2273    #[test]
2274    fn test_de_error_fmt() {
2275        use crate::ser_write::SliceWriter;
2276        use core::fmt::Write;
2277        let mut buf = [0u8;59];
2278        let mut writer = SliceWriter::new(&mut buf);
2279        let custom: Error = serde::de::Error::custom("xxx");
2280        write!(writer, "{}", custom).unwrap();
2281        assert_eq!(writer.as_ref(), "MessagePack does not match deserializer’s expected format".as_bytes());
2282    }
2283}