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