serde/de/
impls.rs

1use crate::lib::*;
2
3use crate::de::{
4    Deserialize, Deserializer, EnumAccess, Error, MapAccess, SeqAccess, Unexpected, VariantAccess,
5    Visitor,
6};
7
8use crate::seed::InPlaceSeed;
9
10#[cfg(any(feature = "std", feature = "alloc"))]
11use crate::de::size_hint;
12
13////////////////////////////////////////////////////////////////////////////////
14
15struct UnitVisitor;
16
17impl<'de> Visitor<'de> for UnitVisitor {
18    type Value = ();
19
20    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
21        formatter.write_str("unit")
22    }
23
24    fn visit_unit<E>(self) -> Result<Self::Value, E>
25    where
26        E: Error,
27    {
28        Ok(())
29    }
30}
31
32impl<'de> Deserialize<'de> for () {
33    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
34    where
35        D: Deserializer<'de>,
36    {
37        deserializer.deserialize_unit(UnitVisitor)
38    }
39}
40
41#[cfg(feature = "unstable")]
42#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
43impl<'de> Deserialize<'de> for ! {
44    fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
45    where
46        D: Deserializer<'de>,
47    {
48        Err(Error::custom("cannot deserialize `!`"))
49    }
50}
51
52////////////////////////////////////////////////////////////////////////////////
53
54struct BoolVisitor;
55
56impl<'de> Visitor<'de> for BoolVisitor {
57    type Value = bool;
58
59    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
60        formatter.write_str("a boolean")
61    }
62
63    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
64    where
65        E: Error,
66    {
67        Ok(v)
68    }
69}
70
71impl<'de> Deserialize<'de> for bool {
72    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
73    where
74        D: Deserializer<'de>,
75    {
76        deserializer.deserialize_bool(BoolVisitor)
77    }
78}
79
80////////////////////////////////////////////////////////////////////////////////
81
82macro_rules! impl_deserialize_num {
83    ($primitive:ident, $nonzero:ident $(cfg($($cfg:tt)*))*, $deserialize:ident $($method:ident!($($val:ident : $visit:ident)*);)*) => {
84        impl_deserialize_num!($primitive, $deserialize $($method!($($val : $visit)*);)*);
85
86        $(#[cfg($($cfg)*)])*
87        impl<'de> Deserialize<'de> for num::$nonzero {
88            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
89            where
90                D: Deserializer<'de>,
91            {
92                struct NonZeroVisitor;
93
94                impl<'de> Visitor<'de> for NonZeroVisitor {
95                    type Value = num::$nonzero;
96
97                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
98                        formatter.write_str(concat!("a nonzero ", stringify!($primitive)))
99                    }
100
101                    $($($method!(nonzero $primitive $val : $visit);)*)*
102                }
103
104                deserializer.$deserialize(NonZeroVisitor)
105            }
106        }
107
108        #[cfg(not(no_core_num_saturating))]
109        impl<'de> Deserialize<'de> for Saturating<$primitive> {
110            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
111            where
112                D: Deserializer<'de>,
113            {
114                struct SaturatingVisitor;
115
116                impl<'de> Visitor<'de> for SaturatingVisitor {
117                    type Value = Saturating<$primitive>;
118
119                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
120                        formatter.write_str("integer with support for saturating semantics")
121                    }
122
123                    $($($method!(saturating $primitive $val : $visit);)*)*
124                }
125
126                deserializer.$deserialize(SaturatingVisitor)
127            }
128        }
129    };
130
131    ($primitive:ident, $deserialize:ident $($method:ident!($($val:ident : $visit:ident)*);)*) => {
132        impl<'de> Deserialize<'de> for $primitive {
133            #[inline]
134            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
135            where
136                D: Deserializer<'de>,
137            {
138                struct PrimitiveVisitor;
139
140                impl<'de> Visitor<'de> for PrimitiveVisitor {
141                    type Value = $primitive;
142
143                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
144                        formatter.write_str(stringify!($primitive))
145                    }
146
147                    $($($method!($val : $visit);)*)*
148                }
149
150                deserializer.$deserialize(PrimitiveVisitor)
151            }
152        }
153    };
154}
155
156macro_rules! num_self {
157    ($ty:ident : $visit:ident) => {
158        #[inline]
159        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
160        where
161            E: Error,
162        {
163            Ok(v)
164        }
165    };
166
167    (nonzero $primitive:ident $ty:ident : $visit:ident) => {
168        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
169        where
170            E: Error,
171        {
172            if let Some(nonzero) = Self::Value::new(v) {
173                Ok(nonzero)
174            } else {
175                Err(Error::invalid_value(Unexpected::Unsigned(0), &self))
176            }
177        }
178    };
179
180    (saturating $primitive:ident $ty:ident : $visit:ident) => {
181        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
182        where
183            E: Error,
184        {
185            Ok(Saturating(v))
186        }
187    };
188}
189
190macro_rules! num_as_self {
191    ($ty:ident : $visit:ident) => {
192        #[inline]
193        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
194        where
195            E: Error,
196        {
197            Ok(v as Self::Value)
198        }
199    };
200
201    (nonzero $primitive:ident $ty:ident : $visit:ident) => {
202        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
203        where
204            E: Error,
205        {
206            if let Some(nonzero) = Self::Value::new(v as $primitive) {
207                Ok(nonzero)
208            } else {
209                Err(Error::invalid_value(Unexpected::Unsigned(0), &self))
210            }
211        }
212    };
213
214    (saturating $primitive:ident $ty:ident : $visit:ident) => {
215        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
216        where
217            E: Error,
218        {
219            Ok(Saturating(v as $primitive))
220        }
221    };
222}
223
224macro_rules! num_as_copysign_self {
225    ($ty:ident : $visit:ident) => {
226        #[inline]
227        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
228        where
229            E: Error,
230        {
231            #[cfg(any(no_float_copysign, not(feature = "std")))]
232            {
233                Ok(v as Self::Value)
234            }
235
236            #[cfg(all(not(no_float_copysign), feature = "std"))]
237            {
238                // Preserve sign of NaN. The `as` produces a nondeterministic sign.
239                let sign = if v.is_sign_positive() { 1.0 } else { -1.0 };
240                Ok((v as Self::Value).copysign(sign))
241            }
242        }
243    };
244}
245
246macro_rules! int_to_int {
247    ($ty:ident : $visit:ident) => {
248        #[inline]
249        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
250        where
251            E: Error,
252        {
253            if Self::Value::min_value() as i64 <= v as i64
254                && v as i64 <= Self::Value::max_value() as i64
255            {
256                Ok(v as Self::Value)
257            } else {
258                Err(Error::invalid_value(Unexpected::Signed(v as i64), &self))
259            }
260        }
261    };
262
263    (nonzero $primitive:ident $ty:ident : $visit:ident) => {
264        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
265        where
266            E: Error,
267        {
268            if $primitive::min_value() as i64 <= v as i64
269                && v as i64 <= $primitive::max_value() as i64
270            {
271                if let Some(nonzero) = Self::Value::new(v as $primitive) {
272                    return Ok(nonzero);
273                }
274            }
275            Err(Error::invalid_value(Unexpected::Signed(v as i64), &self))
276        }
277    };
278
279    (saturating $primitive:ident $ty:ident : $visit:ident) => {
280        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
281        where
282            E: Error,
283        {
284            if (v as i64) < $primitive::MIN as i64 {
285                Ok(Saturating($primitive::MIN))
286            } else if ($primitive::MAX as i64) < v as i64 {
287                Ok(Saturating($primitive::MAX))
288            } else {
289                Ok(Saturating(v as $primitive))
290            }
291        }
292    };
293}
294
295macro_rules! int_to_uint {
296    ($ty:ident : $visit:ident) => {
297        #[inline]
298        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
299        where
300            E: Error,
301        {
302            if 0 <= v && v as u64 <= Self::Value::max_value() as u64 {
303                Ok(v as Self::Value)
304            } else {
305                Err(Error::invalid_value(Unexpected::Signed(v as i64), &self))
306            }
307        }
308    };
309
310    (nonzero $primitive:ident $ty:ident : $visit:ident) => {
311        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
312        where
313            E: Error,
314        {
315            if 0 < v && v as u64 <= $primitive::max_value() as u64 {
316                if let Some(nonzero) = Self::Value::new(v as $primitive) {
317                    return Ok(nonzero);
318                }
319            }
320            Err(Error::invalid_value(Unexpected::Signed(v as i64), &self))
321        }
322    };
323
324    (saturating $primitive:ident $ty:ident : $visit:ident) => {
325        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
326        where
327            E: Error,
328        {
329            if v < 0 {
330                Ok(Saturating(0))
331            } else if ($primitive::MAX as u64) < v as u64 {
332                Ok(Saturating($primitive::MAX))
333            } else {
334                Ok(Saturating(v as $primitive))
335            }
336        }
337    };
338}
339
340macro_rules! uint_to_self {
341    ($ty:ident : $visit:ident) => {
342        #[inline]
343        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
344        where
345            E: Error,
346        {
347            if v as u64 <= Self::Value::max_value() as u64 {
348                Ok(v as Self::Value)
349            } else {
350                Err(Error::invalid_value(Unexpected::Unsigned(v as u64), &self))
351            }
352        }
353    };
354
355    (nonzero $primitive:ident $ty:ident : $visit:ident) => {
356        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
357        where
358            E: Error,
359        {
360            if v as u64 <= $primitive::max_value() as u64 {
361                if let Some(nonzero) = Self::Value::new(v as $primitive) {
362                    return Ok(nonzero);
363                }
364            }
365            Err(Error::invalid_value(Unexpected::Unsigned(v as u64), &self))
366        }
367    };
368
369    (saturating $primitive:ident $ty:ident : $visit:ident) => {
370        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
371        where
372            E: Error,
373        {
374            if v as u64 <= $primitive::MAX as u64 {
375                Ok(Saturating(v as $primitive))
376            } else {
377                Ok(Saturating($primitive::MAX))
378            }
379        }
380    };
381}
382
383impl_deserialize_num! {
384    i8, NonZeroI8 cfg(not(no_num_nonzero_signed)), deserialize_i8
385    num_self!(i8:visit_i8);
386    int_to_int!(i16:visit_i16 i32:visit_i32 i64:visit_i64);
387    uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
388}
389
390impl_deserialize_num! {
391    i16, NonZeroI16 cfg(not(no_num_nonzero_signed)), deserialize_i16
392    num_self!(i16:visit_i16);
393    num_as_self!(i8:visit_i8);
394    int_to_int!(i32:visit_i32 i64:visit_i64);
395    uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
396}
397
398impl_deserialize_num! {
399    i32, NonZeroI32 cfg(not(no_num_nonzero_signed)), deserialize_i32
400    num_self!(i32:visit_i32);
401    num_as_self!(i8:visit_i8 i16:visit_i16);
402    int_to_int!(i64:visit_i64);
403    uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
404}
405
406impl_deserialize_num! {
407    i64, NonZeroI64 cfg(not(no_num_nonzero_signed)), deserialize_i64
408    num_self!(i64:visit_i64);
409    num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32);
410    uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
411}
412
413impl_deserialize_num! {
414    isize, NonZeroIsize cfg(not(no_num_nonzero_signed)), deserialize_i64
415    num_as_self!(i8:visit_i8 i16:visit_i16);
416    int_to_int!(i32:visit_i32 i64:visit_i64);
417    uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
418}
419
420impl_deserialize_num! {
421    u8, NonZeroU8, deserialize_u8
422    num_self!(u8:visit_u8);
423    int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
424    uint_to_self!(u16:visit_u16 u32:visit_u32 u64:visit_u64);
425}
426
427impl_deserialize_num! {
428    u16, NonZeroU16, deserialize_u16
429    num_self!(u16:visit_u16);
430    num_as_self!(u8:visit_u8);
431    int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
432    uint_to_self!(u32:visit_u32 u64:visit_u64);
433}
434
435impl_deserialize_num! {
436    u32, NonZeroU32, deserialize_u32
437    num_self!(u32:visit_u32);
438    num_as_self!(u8:visit_u8 u16:visit_u16);
439    int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
440    uint_to_self!(u64:visit_u64);
441}
442
443impl_deserialize_num! {
444    u64, NonZeroU64, deserialize_u64
445    num_self!(u64:visit_u64);
446    num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32);
447    int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
448}
449
450impl_deserialize_num! {
451    usize, NonZeroUsize, deserialize_u64
452    num_as_self!(u8:visit_u8 u16:visit_u16);
453    int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
454    uint_to_self!(u32:visit_u32 u64:visit_u64);
455}
456
457impl_deserialize_num! {
458    f32, deserialize_f32
459    num_self!(f32:visit_f32);
460    num_as_copysign_self!(f64:visit_f64);
461    num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
462    num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
463}
464
465impl_deserialize_num! {
466    f64, deserialize_f64
467    num_self!(f64:visit_f64);
468    num_as_copysign_self!(f32:visit_f32);
469    num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
470    num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
471}
472
473macro_rules! num_128 {
474    ($ty:ident : $visit:ident) => {
475        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
476        where
477            E: Error,
478        {
479            if v as i128 >= Self::Value::min_value() as i128
480                && v as u128 <= Self::Value::max_value() as u128
481            {
482                Ok(v as Self::Value)
483            } else {
484                Err(Error::invalid_value(
485                    Unexpected::Other(stringify!($ty)),
486                    &self,
487                ))
488            }
489        }
490    };
491
492    (nonzero $primitive:ident $ty:ident : $visit:ident) => {
493        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
494        where
495            E: Error,
496        {
497            if v as i128 >= $primitive::min_value() as i128
498                && v as u128 <= $primitive::max_value() as u128
499            {
500                if let Some(nonzero) = Self::Value::new(v as $primitive) {
501                    Ok(nonzero)
502                } else {
503                    Err(Error::invalid_value(Unexpected::Unsigned(0), &self))
504                }
505            } else {
506                Err(Error::invalid_value(
507                    Unexpected::Other(stringify!($ty)),
508                    &self,
509                ))
510            }
511        }
512    };
513
514    (saturating $primitive:ident $ty:ident : $visit:ident) => {
515        fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
516        where
517            E: Error,
518        {
519            if (v as i128) < $primitive::MIN as i128 {
520                Ok(Saturating($primitive::MIN))
521            } else if ($primitive::MAX as u128) < v as u128 {
522                Ok(Saturating($primitive::MAX))
523            } else {
524                Ok(Saturating(v as $primitive))
525            }
526        }
527    };
528}
529
530impl_deserialize_num! {
531    i128, NonZeroI128 cfg(not(no_num_nonzero_signed)), deserialize_i128
532    num_self!(i128:visit_i128);
533    num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
534    num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
535    num_128!(u128:visit_u128);
536}
537
538impl_deserialize_num! {
539    u128, NonZeroU128, deserialize_u128
540    num_self!(u128:visit_u128);
541    num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
542    int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
543    num_128!(i128:visit_i128);
544}
545
546////////////////////////////////////////////////////////////////////////////////
547
548struct CharVisitor;
549
550impl<'de> Visitor<'de> for CharVisitor {
551    type Value = char;
552
553    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
554        formatter.write_str("a character")
555    }
556
557    #[inline]
558    fn visit_char<E>(self, v: char) -> Result<Self::Value, E>
559    where
560        E: Error,
561    {
562        Ok(v)
563    }
564
565    #[inline]
566    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
567    where
568        E: Error,
569    {
570        let mut iter = v.chars();
571        match (iter.next(), iter.next()) {
572            (Some(c), None) => Ok(c),
573            _ => Err(Error::invalid_value(Unexpected::Str(v), &self)),
574        }
575    }
576}
577
578impl<'de> Deserialize<'de> for char {
579    #[inline]
580    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
581    where
582        D: Deserializer<'de>,
583    {
584        deserializer.deserialize_char(CharVisitor)
585    }
586}
587
588////////////////////////////////////////////////////////////////////////////////
589
590#[cfg(any(feature = "std", feature = "alloc"))]
591struct StringVisitor;
592#[cfg(any(feature = "std", feature = "alloc"))]
593struct StringInPlaceVisitor<'a>(&'a mut String);
594
595#[cfg(any(feature = "std", feature = "alloc"))]
596impl<'de> Visitor<'de> for StringVisitor {
597    type Value = String;
598
599    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
600        formatter.write_str("a string")
601    }
602
603    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
604    where
605        E: Error,
606    {
607        Ok(v.to_owned())
608    }
609
610    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
611    where
612        E: Error,
613    {
614        Ok(v)
615    }
616
617    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
618    where
619        E: Error,
620    {
621        match str::from_utf8(v) {
622            Ok(s) => Ok(s.to_owned()),
623            Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
624        }
625    }
626
627    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
628    where
629        E: Error,
630    {
631        match String::from_utf8(v) {
632            Ok(s) => Ok(s),
633            Err(e) => Err(Error::invalid_value(
634                Unexpected::Bytes(&e.into_bytes()),
635                &self,
636            )),
637        }
638    }
639}
640
641#[cfg(any(feature = "std", feature = "alloc"))]
642impl<'a, 'de> Visitor<'de> for StringInPlaceVisitor<'a> {
643    type Value = ();
644
645    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
646        formatter.write_str("a string")
647    }
648
649    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
650    where
651        E: Error,
652    {
653        self.0.clear();
654        self.0.push_str(v);
655        Ok(())
656    }
657
658    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
659    where
660        E: Error,
661    {
662        *self.0 = v;
663        Ok(())
664    }
665
666    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
667    where
668        E: Error,
669    {
670        match str::from_utf8(v) {
671            Ok(s) => {
672                self.0.clear();
673                self.0.push_str(s);
674                Ok(())
675            }
676            Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
677        }
678    }
679
680    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
681    where
682        E: Error,
683    {
684        match String::from_utf8(v) {
685            Ok(s) => {
686                *self.0 = s;
687                Ok(())
688            }
689            Err(e) => Err(Error::invalid_value(
690                Unexpected::Bytes(&e.into_bytes()),
691                &self,
692            )),
693        }
694    }
695}
696
697#[cfg(any(feature = "std", feature = "alloc"))]
698#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
699impl<'de> Deserialize<'de> for String {
700    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
701    where
702        D: Deserializer<'de>,
703    {
704        deserializer.deserialize_string(StringVisitor)
705    }
706
707    fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
708    where
709        D: Deserializer<'de>,
710    {
711        deserializer.deserialize_string(StringInPlaceVisitor(place))
712    }
713}
714
715////////////////////////////////////////////////////////////////////////////////
716
717struct StrVisitor;
718
719impl<'a> Visitor<'a> for StrVisitor {
720    type Value = &'a str;
721
722    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
723        formatter.write_str("a borrowed string")
724    }
725
726    fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
727    where
728        E: Error,
729    {
730        Ok(v) // so easy
731    }
732
733    fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
734    where
735        E: Error,
736    {
737        str::from_utf8(v).map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
738    }
739}
740
741impl<'de: 'a, 'a> Deserialize<'de> for &'a str {
742    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
743    where
744        D: Deserializer<'de>,
745    {
746        deserializer.deserialize_str(StrVisitor)
747    }
748}
749
750////////////////////////////////////////////////////////////////////////////////
751
752struct BytesVisitor;
753
754impl<'a> Visitor<'a> for BytesVisitor {
755    type Value = &'a [u8];
756
757    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
758        formatter.write_str("a borrowed byte array")
759    }
760
761    fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
762    where
763        E: Error,
764    {
765        Ok(v)
766    }
767
768    fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
769    where
770        E: Error,
771    {
772        Ok(v.as_bytes())
773    }
774}
775
776impl<'de: 'a, 'a> Deserialize<'de> for &'a [u8] {
777    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
778    where
779        D: Deserializer<'de>,
780    {
781        deserializer.deserialize_bytes(BytesVisitor)
782    }
783}
784
785////////////////////////////////////////////////////////////////////////////////
786
787#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))]
788struct CStringVisitor;
789
790#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))]
791impl<'de> Visitor<'de> for CStringVisitor {
792    type Value = CString;
793
794    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
795        formatter.write_str("byte array")
796    }
797
798    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
799    where
800        A: SeqAccess<'de>,
801    {
802        let capacity = size_hint::cautious::<u8>(seq.size_hint());
803        let mut values = Vec::<u8>::with_capacity(capacity);
804
805        while let Some(value) = tri!(seq.next_element()) {
806            values.push(value);
807        }
808
809        CString::new(values).map_err(Error::custom)
810    }
811
812    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
813    where
814        E: Error,
815    {
816        CString::new(v).map_err(Error::custom)
817    }
818
819    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
820    where
821        E: Error,
822    {
823        CString::new(v).map_err(Error::custom)
824    }
825
826    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
827    where
828        E: Error,
829    {
830        CString::new(v).map_err(Error::custom)
831    }
832
833    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
834    where
835        E: Error,
836    {
837        CString::new(v).map_err(Error::custom)
838    }
839}
840
841#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))]
842#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
843impl<'de> Deserialize<'de> for CString {
844    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
845    where
846        D: Deserializer<'de>,
847    {
848        deserializer.deserialize_byte_buf(CStringVisitor)
849    }
850}
851
852macro_rules! forwarded_impl {
853    (
854        $(#[$attr:meta])*
855        ($($id:ident),*), $ty:ty, $func:expr
856    ) => {
857        $(#[$attr])*
858        impl<'de $(, $id : Deserialize<'de>,)*> Deserialize<'de> for $ty {
859            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
860            where
861                D: Deserializer<'de>,
862            {
863                Deserialize::deserialize(deserializer).map($func)
864            }
865        }
866    }
867}
868
869forwarded_impl! {
870    #[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))]
871    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
872    (), Box<CStr>, CString::into_boxed_c_str
873}
874
875forwarded_impl! {
876    (T), Reverse<T>, Reverse
877}
878
879////////////////////////////////////////////////////////////////////////////////
880
881struct OptionVisitor<T> {
882    marker: PhantomData<T>,
883}
884
885impl<'de, T> Visitor<'de> for OptionVisitor<T>
886where
887    T: Deserialize<'de>,
888{
889    type Value = Option<T>;
890
891    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
892        formatter.write_str("option")
893    }
894
895    #[inline]
896    fn visit_unit<E>(self) -> Result<Self::Value, E>
897    where
898        E: Error,
899    {
900        Ok(None)
901    }
902
903    #[inline]
904    fn visit_none<E>(self) -> Result<Self::Value, E>
905    where
906        E: Error,
907    {
908        Ok(None)
909    }
910
911    #[inline]
912    fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
913    where
914        D: Deserializer<'de>,
915    {
916        T::deserialize(deserializer).map(Some)
917    }
918
919    fn __private_visit_untagged_option<D>(self, deserializer: D) -> Result<Self::Value, ()>
920    where
921        D: Deserializer<'de>,
922    {
923        Ok(T::deserialize(deserializer).ok())
924    }
925}
926
927impl<'de, T> Deserialize<'de> for Option<T>
928where
929    T: Deserialize<'de>,
930{
931    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
932    where
933        D: Deserializer<'de>,
934    {
935        deserializer.deserialize_option(OptionVisitor {
936            marker: PhantomData,
937        })
938    }
939
940    // The Some variant's repr is opaque, so we can't play cute tricks with its
941    // tag to have deserialize_in_place build the content in place unconditionally.
942    //
943    // FIXME: investigate whether branching on the old value being Some to
944    // deserialize_in_place the value is profitable (probably data-dependent?)
945}
946
947////////////////////////////////////////////////////////////////////////////////
948
949struct PhantomDataVisitor<T: ?Sized> {
950    marker: PhantomData<T>,
951}
952
953impl<'de, T> Visitor<'de> for PhantomDataVisitor<T>
954where
955    T: ?Sized,
956{
957    type Value = PhantomData<T>;
958
959    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
960        formatter.write_str("unit")
961    }
962
963    #[inline]
964    fn visit_unit<E>(self) -> Result<Self::Value, E>
965    where
966        E: Error,
967    {
968        Ok(PhantomData)
969    }
970}
971
972impl<'de, T> Deserialize<'de> for PhantomData<T>
973where
974    T: ?Sized,
975{
976    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
977    where
978        D: Deserializer<'de>,
979    {
980        let visitor = PhantomDataVisitor {
981            marker: PhantomData,
982        };
983        deserializer.deserialize_unit_struct("PhantomData", visitor)
984    }
985}
986
987////////////////////////////////////////////////////////////////////////////////
988
989macro_rules! seq_impl {
990    (
991        $(#[$attr:meta])*
992        $ty:ident <T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)*>,
993        $access:ident,
994        $clear:expr,
995        $with_capacity:expr,
996        $reserve:expr,
997        $insert:expr
998    ) => {
999        $(#[$attr])*
1000        impl<'de, T $(, $typaram)*> Deserialize<'de> for $ty<T $(, $typaram)*>
1001        where
1002            T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*,
1003            $($typaram: $bound1 $(+ $bound2)*,)*
1004        {
1005            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1006            where
1007                D: Deserializer<'de>,
1008            {
1009                struct SeqVisitor<T $(, $typaram)*> {
1010                    marker: PhantomData<$ty<T $(, $typaram)*>>,
1011                }
1012
1013                impl<'de, T $(, $typaram)*> Visitor<'de> for SeqVisitor<T $(, $typaram)*>
1014                where
1015                    T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*,
1016                    $($typaram: $bound1 $(+ $bound2)*,)*
1017                {
1018                    type Value = $ty<T $(, $typaram)*>;
1019
1020                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1021                        formatter.write_str("a sequence")
1022                    }
1023
1024                    #[inline]
1025                    fn visit_seq<A>(self, mut $access: A) -> Result<Self::Value, A::Error>
1026                    where
1027                        A: SeqAccess<'de>,
1028                    {
1029                        let mut values = $with_capacity;
1030
1031                        while let Some(value) = tri!($access.next_element()) {
1032                            $insert(&mut values, value);
1033                        }
1034
1035                        Ok(values)
1036                    }
1037                }
1038
1039                let visitor = SeqVisitor { marker: PhantomData };
1040                deserializer.deserialize_seq(visitor)
1041            }
1042
1043            fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
1044            where
1045                D: Deserializer<'de>,
1046            {
1047                struct SeqInPlaceVisitor<'a, T: 'a $(, $typaram: 'a)*>(&'a mut $ty<T $(, $typaram)*>);
1048
1049                impl<'a, 'de, T $(, $typaram)*> Visitor<'de> for SeqInPlaceVisitor<'a, T $(, $typaram)*>
1050                where
1051                    T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*,
1052                    $($typaram: $bound1 $(+ $bound2)*,)*
1053                {
1054                    type Value = ();
1055
1056                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1057                        formatter.write_str("a sequence")
1058                    }
1059
1060                    #[inline]
1061                    fn visit_seq<A>(mut self, mut $access: A) -> Result<Self::Value, A::Error>
1062                    where
1063                        A: SeqAccess<'de>,
1064                    {
1065                        $clear(&mut self.0);
1066                        $reserve(&mut self.0, size_hint::cautious::<T>($access.size_hint()));
1067
1068                        // FIXME: try to overwrite old values here? (Vec, VecDeque, LinkedList)
1069                        while let Some(value) = tri!($access.next_element()) {
1070                            $insert(&mut self.0, value);
1071                        }
1072
1073                        Ok(())
1074                    }
1075                }
1076
1077                deserializer.deserialize_seq(SeqInPlaceVisitor(place))
1078            }
1079        }
1080    }
1081}
1082
1083// Dummy impl of reserve
1084#[cfg(any(feature = "std", feature = "alloc"))]
1085fn nop_reserve<T>(_seq: T, _n: usize) {}
1086
1087seq_impl!(
1088    #[cfg(any(feature = "std", feature = "alloc"))]
1089    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1090    BinaryHeap<T: Ord>,
1091    seq,
1092    BinaryHeap::clear,
1093    BinaryHeap::with_capacity(size_hint::cautious::<T>(seq.size_hint())),
1094    BinaryHeap::reserve,
1095    BinaryHeap::push
1096);
1097
1098seq_impl!(
1099    #[cfg(any(feature = "std", feature = "alloc"))]
1100    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1101    BTreeSet<T: Eq + Ord>,
1102    seq,
1103    BTreeSet::clear,
1104    BTreeSet::new(),
1105    nop_reserve,
1106    BTreeSet::insert
1107);
1108
1109seq_impl!(
1110    #[cfg(any(feature = "std", feature = "alloc"))]
1111    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1112    LinkedList<T>,
1113    seq,
1114    LinkedList::clear,
1115    LinkedList::new(),
1116    nop_reserve,
1117    LinkedList::push_back
1118);
1119
1120seq_impl!(
1121    #[cfg(feature = "std")]
1122    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1123    HashSet<T: Eq + Hash, S: BuildHasher + Default>,
1124    seq,
1125    HashSet::clear,
1126    HashSet::with_capacity_and_hasher(size_hint::cautious::<T>(seq.size_hint()), S::default()),
1127    HashSet::reserve,
1128    HashSet::insert
1129);
1130
1131seq_impl!(
1132    #[cfg(any(feature = "std", feature = "alloc"))]
1133    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1134    VecDeque<T>,
1135    seq,
1136    VecDeque::clear,
1137    VecDeque::with_capacity(size_hint::cautious::<T>(seq.size_hint())),
1138    VecDeque::reserve,
1139    VecDeque::push_back
1140);
1141
1142////////////////////////////////////////////////////////////////////////////////
1143
1144#[cfg(any(feature = "std", feature = "alloc"))]
1145#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1146impl<'de, T> Deserialize<'de> for Vec<T>
1147where
1148    T: Deserialize<'de>,
1149{
1150    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1151    where
1152        D: Deserializer<'de>,
1153    {
1154        struct VecVisitor<T> {
1155            marker: PhantomData<T>,
1156        }
1157
1158        impl<'de, T> Visitor<'de> for VecVisitor<T>
1159        where
1160            T: Deserialize<'de>,
1161        {
1162            type Value = Vec<T>;
1163
1164            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1165                formatter.write_str("a sequence")
1166            }
1167
1168            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1169            where
1170                A: SeqAccess<'de>,
1171            {
1172                let capacity = size_hint::cautious::<T>(seq.size_hint());
1173                let mut values = Vec::<T>::with_capacity(capacity);
1174
1175                while let Some(value) = tri!(seq.next_element()) {
1176                    values.push(value);
1177                }
1178
1179                Ok(values)
1180            }
1181        }
1182
1183        let visitor = VecVisitor {
1184            marker: PhantomData,
1185        };
1186        deserializer.deserialize_seq(visitor)
1187    }
1188
1189    fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
1190    where
1191        D: Deserializer<'de>,
1192    {
1193        struct VecInPlaceVisitor<'a, T: 'a>(&'a mut Vec<T>);
1194
1195        impl<'a, 'de, T> Visitor<'de> for VecInPlaceVisitor<'a, T>
1196        where
1197            T: Deserialize<'de>,
1198        {
1199            type Value = ();
1200
1201            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1202                formatter.write_str("a sequence")
1203            }
1204
1205            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1206            where
1207                A: SeqAccess<'de>,
1208            {
1209                let hint = size_hint::cautious::<T>(seq.size_hint());
1210                if let Some(additional) = hint.checked_sub(self.0.len()) {
1211                    self.0.reserve(additional);
1212                }
1213
1214                for i in 0..self.0.len() {
1215                    let next = {
1216                        let next_place = InPlaceSeed(&mut self.0[i]);
1217                        tri!(seq.next_element_seed(next_place))
1218                    };
1219                    if next.is_none() {
1220                        self.0.truncate(i);
1221                        return Ok(());
1222                    }
1223                }
1224
1225                while let Some(value) = tri!(seq.next_element()) {
1226                    self.0.push(value);
1227                }
1228
1229                Ok(())
1230            }
1231        }
1232
1233        deserializer.deserialize_seq(VecInPlaceVisitor(place))
1234    }
1235}
1236
1237////////////////////////////////////////////////////////////////////////////////
1238
1239struct ArrayVisitor<A> {
1240    marker: PhantomData<A>,
1241}
1242struct ArrayInPlaceVisitor<'a, A: 'a>(&'a mut A);
1243
1244impl<A> ArrayVisitor<A> {
1245    fn new() -> Self {
1246        ArrayVisitor {
1247            marker: PhantomData,
1248        }
1249    }
1250}
1251
1252impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]> {
1253    type Value = [T; 0];
1254
1255    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1256        formatter.write_str("an empty array")
1257    }
1258
1259    #[inline]
1260    fn visit_seq<A>(self, _: A) -> Result<Self::Value, A::Error>
1261    where
1262        A: SeqAccess<'de>,
1263    {
1264        Ok([])
1265    }
1266}
1267
1268// Does not require T: Deserialize<'de>.
1269impl<'de, T> Deserialize<'de> for [T; 0] {
1270    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1271    where
1272        D: Deserializer<'de>,
1273    {
1274        deserializer.deserialize_tuple(0, ArrayVisitor::<[T; 0]>::new())
1275    }
1276}
1277
1278macro_rules! array_impls {
1279    ($($len:expr => ($($n:tt)+))+) => {
1280        $(
1281            impl<'de, T> Visitor<'de> for ArrayVisitor<[T; $len]>
1282            where
1283                T: Deserialize<'de>,
1284            {
1285                type Value = [T; $len];
1286
1287                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1288                    formatter.write_str(concat!("an array of length ", $len))
1289                }
1290
1291                #[inline]
1292                fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1293                where
1294                    A: SeqAccess<'de>,
1295                {
1296                    Ok([$(
1297                        match tri!(seq.next_element()) {
1298                            Some(val) => val,
1299                            None => return Err(Error::invalid_length($n, &self)),
1300                        }
1301                    ),+])
1302                }
1303            }
1304
1305            impl<'a, 'de, T> Visitor<'de> for ArrayInPlaceVisitor<'a, [T; $len]>
1306            where
1307                T: Deserialize<'de>,
1308            {
1309                type Value = ();
1310
1311                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1312                    formatter.write_str(concat!("an array of length ", $len))
1313                }
1314
1315                #[inline]
1316                fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1317                where
1318                    A: SeqAccess<'de>,
1319                {
1320                    let mut fail_idx = None;
1321                    for (idx, dest) in self.0[..].iter_mut().enumerate() {
1322                        if tri!(seq.next_element_seed(InPlaceSeed(dest))).is_none() {
1323                            fail_idx = Some(idx);
1324                            break;
1325                        }
1326                    }
1327                    if let Some(idx) = fail_idx {
1328                        return Err(Error::invalid_length(idx, &self));
1329                    }
1330                    Ok(())
1331                }
1332            }
1333
1334            impl<'de, T> Deserialize<'de> for [T; $len]
1335            where
1336                T: Deserialize<'de>,
1337            {
1338                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1339                where
1340                    D: Deserializer<'de>,
1341                {
1342                    deserializer.deserialize_tuple($len, ArrayVisitor::<[T; $len]>::new())
1343                }
1344
1345                fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
1346                where
1347                    D: Deserializer<'de>,
1348                {
1349                    deserializer.deserialize_tuple($len, ArrayInPlaceVisitor(place))
1350                }
1351            }
1352        )+
1353    }
1354}
1355
1356array_impls! {
1357    1 => (0)
1358    2 => (0 1)
1359    3 => (0 1 2)
1360    4 => (0 1 2 3)
1361    5 => (0 1 2 3 4)
1362    6 => (0 1 2 3 4 5)
1363    7 => (0 1 2 3 4 5 6)
1364    8 => (0 1 2 3 4 5 6 7)
1365    9 => (0 1 2 3 4 5 6 7 8)
1366    10 => (0 1 2 3 4 5 6 7 8 9)
1367    11 => (0 1 2 3 4 5 6 7 8 9 10)
1368    12 => (0 1 2 3 4 5 6 7 8 9 10 11)
1369    13 => (0 1 2 3 4 5 6 7 8 9 10 11 12)
1370    14 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13)
1371    15 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14)
1372    16 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)
1373    17 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16)
1374    18 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17)
1375    19 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18)
1376    20 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19)
1377    21 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20)
1378    22 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21)
1379    23 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22)
1380    24 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23)
1381    25 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24)
1382    26 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25)
1383    27 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26)
1384    28 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27)
1385    29 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28)
1386    30 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29)
1387    31 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30)
1388    32 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31)
1389}
1390
1391////////////////////////////////////////////////////////////////////////////////
1392
1393macro_rules! tuple_impls {
1394    ($($len:tt => ($($n:tt $name:ident)+))+) => {
1395        $(
1396            #[cfg_attr(docsrs, doc(hidden))]
1397            impl<'de, $($name),+> Deserialize<'de> for ($($name,)+)
1398            where
1399                $($name: Deserialize<'de>,)+
1400            {
1401                tuple_impl_body!($len => ($($n $name)+));
1402            }
1403        )+
1404    };
1405}
1406
1407macro_rules! tuple_impl_body {
1408    ($len:tt => ($($n:tt $name:ident)+)) => {
1409        #[inline]
1410        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1411        where
1412            D: Deserializer<'de>,
1413        {
1414            struct TupleVisitor<$($name,)+> {
1415                marker: PhantomData<($($name,)+)>,
1416            }
1417
1418            impl<'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleVisitor<$($name,)+> {
1419                type Value = ($($name,)+);
1420
1421                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1422                    formatter.write_str(concat!("a tuple of size ", $len))
1423                }
1424
1425                #[inline]
1426                #[allow(non_snake_case)]
1427                fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1428                where
1429                    A: SeqAccess<'de>,
1430                {
1431                    $(
1432                        let $name = match tri!(seq.next_element()) {
1433                            Some(value) => value,
1434                            None => return Err(Error::invalid_length($n, &self)),
1435                        };
1436                    )+
1437
1438                    Ok(($($name,)+))
1439                }
1440            }
1441
1442            deserializer.deserialize_tuple($len, TupleVisitor { marker: PhantomData })
1443        }
1444
1445        #[inline]
1446        fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
1447        where
1448            D: Deserializer<'de>,
1449        {
1450            struct TupleInPlaceVisitor<'a, $($name: 'a,)+>(&'a mut ($($name,)+));
1451
1452            impl<'a, 'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleInPlaceVisitor<'a, $($name,)+> {
1453                type Value = ();
1454
1455                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1456                    formatter.write_str(concat!("a tuple of size ", $len))
1457                }
1458
1459                #[inline]
1460                #[allow(non_snake_case)]
1461                fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1462                where
1463                    A: SeqAccess<'de>,
1464                {
1465                    $(
1466                        if tri!(seq.next_element_seed(InPlaceSeed(&mut (self.0).$n))).is_none() {
1467                            return Err(Error::invalid_length($n, &self));
1468                        }
1469                    )+
1470
1471                    Ok(())
1472                }
1473            }
1474
1475            deserializer.deserialize_tuple($len, TupleInPlaceVisitor(place))
1476        }
1477    };
1478}
1479
1480#[cfg_attr(docsrs, doc(fake_variadic))]
1481#[cfg_attr(
1482    docsrs,
1483    doc = "This trait is implemented for tuples up to 16 items long."
1484)]
1485impl<'de, T> Deserialize<'de> for (T,)
1486where
1487    T: Deserialize<'de>,
1488{
1489    tuple_impl_body!(1 => (0 T));
1490}
1491
1492tuple_impls! {
1493    2  => (0 T0 1 T1)
1494    3  => (0 T0 1 T1 2 T2)
1495    4  => (0 T0 1 T1 2 T2 3 T3)
1496    5  => (0 T0 1 T1 2 T2 3 T3 4 T4)
1497    6  => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5)
1498    7  => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6)
1499    8  => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7)
1500    9  => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8)
1501    10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9)
1502    11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10)
1503    12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11)
1504    13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12)
1505    14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13)
1506    15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14)
1507    16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15)
1508}
1509
1510////////////////////////////////////////////////////////////////////////////////
1511
1512macro_rules! map_impl {
1513    (
1514        $(#[$attr:meta])*
1515        $ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)*>,
1516        $access:ident,
1517        $with_capacity:expr,
1518    ) => {
1519        $(#[$attr])*
1520        impl<'de, K, V $(, $typaram)*> Deserialize<'de> for $ty<K, V $(, $typaram)*>
1521        where
1522            K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*,
1523            V: Deserialize<'de>,
1524            $($typaram: $bound1 $(+ $bound2)*),*
1525        {
1526            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1527            where
1528                D: Deserializer<'de>,
1529            {
1530                struct MapVisitor<K, V $(, $typaram)*> {
1531                    marker: PhantomData<$ty<K, V $(, $typaram)*>>,
1532                }
1533
1534                impl<'de, K, V $(, $typaram)*> Visitor<'de> for MapVisitor<K, V $(, $typaram)*>
1535                where
1536                    K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*,
1537                    V: Deserialize<'de>,
1538                    $($typaram: $bound1 $(+ $bound2)*),*
1539                {
1540                    type Value = $ty<K, V $(, $typaram)*>;
1541
1542                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1543                        formatter.write_str("a map")
1544                    }
1545
1546                    #[inline]
1547                    fn visit_map<A>(self, mut $access: A) -> Result<Self::Value, A::Error>
1548                    where
1549                        A: MapAccess<'de>,
1550                    {
1551                        let mut values = $with_capacity;
1552
1553                        while let Some((key, value)) = tri!($access.next_entry()) {
1554                            values.insert(key, value);
1555                        }
1556
1557                        Ok(values)
1558                    }
1559                }
1560
1561                let visitor = MapVisitor { marker: PhantomData };
1562                deserializer.deserialize_map(visitor)
1563            }
1564        }
1565    }
1566}
1567
1568map_impl! {
1569    #[cfg(any(feature = "std", feature = "alloc"))]
1570    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1571    BTreeMap<K: Ord, V>,
1572    map,
1573    BTreeMap::new(),
1574}
1575
1576map_impl! {
1577    #[cfg(feature = "std")]
1578    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1579    HashMap<K: Eq + Hash, V, S: BuildHasher + Default>,
1580    map,
1581    HashMap::with_capacity_and_hasher(size_hint::cautious::<(K, V)>(map.size_hint()), S::default()),
1582}
1583
1584////////////////////////////////////////////////////////////////////////////////
1585
1586#[cfg(any(feature = "std", not(no_core_net)))]
1587macro_rules! parse_ip_impl {
1588    ($ty:ty, $expecting:expr, $size:tt) => {
1589        impl<'de> Deserialize<'de> for $ty {
1590            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1591            where
1592                D: Deserializer<'de>,
1593            {
1594                if deserializer.is_human_readable() {
1595                    deserializer.deserialize_str(FromStrVisitor::new($expecting))
1596                } else {
1597                    <[u8; $size]>::deserialize(deserializer).map(<$ty>::from)
1598                }
1599            }
1600        }
1601    };
1602}
1603
1604#[cfg(any(feature = "std", not(no_core_net)))]
1605macro_rules! variant_identifier {
1606    (
1607        $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*)
1608        $expecting_message:expr,
1609        $variants_name:ident
1610    ) => {
1611        enum $name_kind {
1612            $($variant),*
1613        }
1614
1615        static $variants_name: &[&str] = &[$(stringify!($variant)),*];
1616
1617        impl<'de> Deserialize<'de> for $name_kind {
1618            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1619            where
1620                D: Deserializer<'de>,
1621            {
1622                struct KindVisitor;
1623
1624                impl<'de> Visitor<'de> for KindVisitor {
1625                    type Value = $name_kind;
1626
1627                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1628                        formatter.write_str($expecting_message)
1629                    }
1630
1631                    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1632                    where
1633                        E: Error,
1634                    {
1635                        match value {
1636                            $(
1637                                $index => Ok($name_kind :: $variant),
1638                            )*
1639                            _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self),),
1640                        }
1641                    }
1642
1643                    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1644                    where
1645                        E: Error,
1646                    {
1647                        match value {
1648                            $(
1649                                stringify!($variant) => Ok($name_kind :: $variant),
1650                            )*
1651                            _ => Err(Error::unknown_variant(value, $variants_name)),
1652                        }
1653                    }
1654
1655                    fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
1656                    where
1657                        E: Error,
1658                    {
1659                        match value {
1660                            $(
1661                                $bytes => Ok($name_kind :: $variant),
1662                            )*
1663                            _ => {
1664                                match str::from_utf8(value) {
1665                                    Ok(value) => Err(Error::unknown_variant(value, $variants_name)),
1666                                    Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),
1667                                }
1668                            }
1669                        }
1670                    }
1671                }
1672
1673                deserializer.deserialize_identifier(KindVisitor)
1674            }
1675        }
1676    }
1677}
1678
1679#[cfg(any(feature = "std", not(no_core_net)))]
1680macro_rules! deserialize_enum {
1681    (
1682        $name:ident $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*)
1683        $expecting_message:expr,
1684        $deserializer:expr
1685    ) => {
1686        variant_identifier! {
1687            $name_kind ($($variant; $bytes; $index),*)
1688            $expecting_message,
1689            VARIANTS
1690        }
1691
1692        struct EnumVisitor;
1693        impl<'de> Visitor<'de> for EnumVisitor {
1694            type Value = $name;
1695
1696            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1697                formatter.write_str(concat!("a ", stringify!($name)))
1698            }
1699
1700
1701            fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
1702            where
1703                A: EnumAccess<'de>,
1704            {
1705                match tri!(data.variant()) {
1706                    $(
1707                        ($name_kind :: $variant, v) => v.newtype_variant().map($name :: $variant),
1708                    )*
1709                }
1710            }
1711        }
1712        $deserializer.deserialize_enum(stringify!($name), VARIANTS, EnumVisitor)
1713    }
1714}
1715
1716#[cfg(any(feature = "std", not(no_core_net)))]
1717impl<'de> Deserialize<'de> for net::IpAddr {
1718    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1719    where
1720        D: Deserializer<'de>,
1721    {
1722        if deserializer.is_human_readable() {
1723            deserializer.deserialize_str(FromStrVisitor::new("IP address"))
1724        } else {
1725            use crate::lib::net::IpAddr;
1726            deserialize_enum! {
1727                IpAddr IpAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)
1728                "`V4` or `V6`",
1729                deserializer
1730            }
1731        }
1732    }
1733}
1734
1735#[cfg(any(feature = "std", not(no_core_net)))]
1736parse_ip_impl!(net::Ipv4Addr, "IPv4 address", 4);
1737
1738#[cfg(any(feature = "std", not(no_core_net)))]
1739parse_ip_impl!(net::Ipv6Addr, "IPv6 address", 16);
1740
1741#[cfg(any(feature = "std", not(no_core_net)))]
1742macro_rules! parse_socket_impl {
1743    (
1744        $ty:ty, $expecting:tt,
1745        $new:expr,
1746    ) => {
1747        impl<'de> Deserialize<'de> for $ty {
1748            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1749            where
1750                D: Deserializer<'de>,
1751            {
1752                if deserializer.is_human_readable() {
1753                    deserializer.deserialize_str(FromStrVisitor::new($expecting))
1754                } else {
1755                    <(_, u16)>::deserialize(deserializer).map($new)
1756                }
1757            }
1758        }
1759    };
1760}
1761
1762#[cfg(any(feature = "std", not(no_core_net)))]
1763impl<'de> Deserialize<'de> for net::SocketAddr {
1764    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1765    where
1766        D: Deserializer<'de>,
1767    {
1768        if deserializer.is_human_readable() {
1769            deserializer.deserialize_str(FromStrVisitor::new("socket address"))
1770        } else {
1771            use crate::lib::net::SocketAddr;
1772            deserialize_enum! {
1773                SocketAddr SocketAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)
1774                "`V4` or `V6`",
1775                deserializer
1776            }
1777        }
1778    }
1779}
1780
1781#[cfg(any(feature = "std", not(no_core_net)))]
1782parse_socket_impl! {
1783    net::SocketAddrV4, "IPv4 socket address",
1784    |(ip, port)| net::SocketAddrV4::new(ip, port),
1785}
1786
1787#[cfg(any(feature = "std", not(no_core_net)))]
1788parse_socket_impl! {
1789    net::SocketAddrV6, "IPv6 socket address",
1790    |(ip, port)| net::SocketAddrV6::new(ip, port, 0, 0),
1791}
1792
1793////////////////////////////////////////////////////////////////////////////////
1794
1795#[cfg(feature = "std")]
1796struct PathVisitor;
1797
1798#[cfg(feature = "std")]
1799impl<'a> Visitor<'a> for PathVisitor {
1800    type Value = &'a Path;
1801
1802    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1803        formatter.write_str("a borrowed path")
1804    }
1805
1806    fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
1807    where
1808        E: Error,
1809    {
1810        Ok(v.as_ref())
1811    }
1812
1813    fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
1814    where
1815        E: Error,
1816    {
1817        str::from_utf8(v)
1818            .map(AsRef::as_ref)
1819            .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
1820    }
1821}
1822
1823#[cfg(feature = "std")]
1824#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1825impl<'de: 'a, 'a> Deserialize<'de> for &'a Path {
1826    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1827    where
1828        D: Deserializer<'de>,
1829    {
1830        deserializer.deserialize_str(PathVisitor)
1831    }
1832}
1833
1834#[cfg(feature = "std")]
1835struct PathBufVisitor;
1836
1837#[cfg(feature = "std")]
1838impl<'de> Visitor<'de> for PathBufVisitor {
1839    type Value = PathBuf;
1840
1841    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1842        formatter.write_str("path string")
1843    }
1844
1845    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1846    where
1847        E: Error,
1848    {
1849        Ok(From::from(v))
1850    }
1851
1852    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1853    where
1854        E: Error,
1855    {
1856        Ok(From::from(v))
1857    }
1858
1859    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1860    where
1861        E: Error,
1862    {
1863        str::from_utf8(v)
1864            .map(From::from)
1865            .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
1866    }
1867
1868    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1869    where
1870        E: Error,
1871    {
1872        String::from_utf8(v)
1873            .map(From::from)
1874            .map_err(|e| Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self))
1875    }
1876}
1877
1878#[cfg(feature = "std")]
1879#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1880impl<'de> Deserialize<'de> for PathBuf {
1881    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1882    where
1883        D: Deserializer<'de>,
1884    {
1885        deserializer.deserialize_string(PathBufVisitor)
1886    }
1887}
1888
1889forwarded_impl! {
1890    #[cfg(feature = "std")]
1891    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1892    (), Box<Path>, PathBuf::into_boxed_path
1893}
1894
1895////////////////////////////////////////////////////////////////////////////////
1896
1897// If this were outside of the serde crate, it would just use:
1898//
1899//    #[derive(Deserialize)]
1900//    #[serde(variant_identifier)]
1901#[cfg(all(feature = "std", any(unix, windows)))]
1902variant_identifier! {
1903    OsStringKind (Unix; b"Unix"; 0, Windows; b"Windows"; 1)
1904    "`Unix` or `Windows`",
1905    OSSTR_VARIANTS
1906}
1907
1908#[cfg(all(feature = "std", any(unix, windows)))]
1909struct OsStringVisitor;
1910
1911#[cfg(all(feature = "std", any(unix, windows)))]
1912impl<'de> Visitor<'de> for OsStringVisitor {
1913    type Value = OsString;
1914
1915    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1916        formatter.write_str("os string")
1917    }
1918
1919    #[cfg(unix)]
1920    fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
1921    where
1922        A: EnumAccess<'de>,
1923    {
1924        use std::os::unix::ffi::OsStringExt;
1925
1926        match tri!(data.variant()) {
1927            (OsStringKind::Unix, v) => v.newtype_variant().map(OsString::from_vec),
1928            (OsStringKind::Windows, _) => Err(Error::custom(
1929                "cannot deserialize Windows OS string on Unix",
1930            )),
1931        }
1932    }
1933
1934    #[cfg(windows)]
1935    fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
1936    where
1937        A: EnumAccess<'de>,
1938    {
1939        use std::os::windows::ffi::OsStringExt;
1940
1941        match tri!(data.variant()) {
1942            (OsStringKind::Windows, v) => v
1943                .newtype_variant::<Vec<u16>>()
1944                .map(|vec| OsString::from_wide(&vec)),
1945            (OsStringKind::Unix, _) => Err(Error::custom(
1946                "cannot deserialize Unix OS string on Windows",
1947            )),
1948        }
1949    }
1950}
1951
1952#[cfg(all(feature = "std", any(unix, windows)))]
1953#[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))]
1954impl<'de> Deserialize<'de> for OsString {
1955    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1956    where
1957        D: Deserializer<'de>,
1958    {
1959        deserializer.deserialize_enum("OsString", OSSTR_VARIANTS, OsStringVisitor)
1960    }
1961}
1962
1963////////////////////////////////////////////////////////////////////////////////
1964
1965forwarded_impl! {
1966    #[cfg(any(feature = "std", feature = "alloc"))]
1967    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1968    (T), Box<T>, Box::new
1969}
1970
1971forwarded_impl! {
1972    #[cfg(any(feature = "std", feature = "alloc"))]
1973    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1974    (T), Box<[T]>, Vec::into_boxed_slice
1975}
1976
1977forwarded_impl! {
1978    #[cfg(any(feature = "std", feature = "alloc"))]
1979    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1980    (), Box<str>, String::into_boxed_str
1981}
1982
1983forwarded_impl! {
1984    #[cfg(all(feature = "std", any(unix, windows)))]
1985    #[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))]
1986    (), Box<OsStr>, OsString::into_boxed_os_str
1987}
1988
1989#[cfg(any(feature = "std", feature = "alloc"))]
1990#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1991impl<'de, 'a, T> Deserialize<'de> for Cow<'a, T>
1992where
1993    T: ?Sized + ToOwned,
1994    T::Owned: Deserialize<'de>,
1995{
1996    #[inline]
1997    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1998    where
1999        D: Deserializer<'de>,
2000    {
2001        T::Owned::deserialize(deserializer).map(Cow::Owned)
2002    }
2003}
2004
2005////////////////////////////////////////////////////////////////////////////////
2006
2007/// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting
2008/// `Weak<T>` has a reference count of 0 and cannot be upgraded.
2009///
2010/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
2011#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
2012#[cfg_attr(
2013    docsrs,
2014    doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc"))))
2015)]
2016impl<'de, T> Deserialize<'de> for RcWeak<T>
2017where
2018    T: Deserialize<'de>,
2019{
2020    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2021    where
2022        D: Deserializer<'de>,
2023    {
2024        tri!(Option::<T>::deserialize(deserializer));
2025        Ok(RcWeak::new())
2026    }
2027}
2028
2029/// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting
2030/// `Weak<T>` has a reference count of 0 and cannot be upgraded.
2031///
2032/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
2033#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
2034#[cfg_attr(
2035    docsrs,
2036    doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc"))))
2037)]
2038impl<'de, T> Deserialize<'de> for ArcWeak<T>
2039where
2040    T: Deserialize<'de>,
2041{
2042    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2043    where
2044        D: Deserializer<'de>,
2045    {
2046        tri!(Option::<T>::deserialize(deserializer));
2047        Ok(ArcWeak::new())
2048    }
2049}
2050
2051////////////////////////////////////////////////////////////////////////////////
2052
2053macro_rules! box_forwarded_impl {
2054    (
2055        $(#[$attr:meta])*
2056        $t:ident
2057    ) => {
2058        $(#[$attr])*
2059        impl<'de, T> Deserialize<'de> for $t<T>
2060        where
2061            T: ?Sized,
2062            Box<T>: Deserialize<'de>,
2063        {
2064            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2065            where
2066                D: Deserializer<'de>,
2067            {
2068                Box::deserialize(deserializer).map(Into::into)
2069            }
2070        }
2071    };
2072}
2073
2074box_forwarded_impl! {
2075    /// This impl requires the [`"rc"`] Cargo feature of Serde.
2076    ///
2077    /// Deserializing a data structure containing `Rc` will not attempt to
2078    /// deduplicate `Rc` references to the same data. Every deserialized `Rc`
2079    /// will end up with a strong count of 1.
2080    ///
2081    /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
2082    #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
2083    #[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))]
2084    Rc
2085}
2086
2087box_forwarded_impl! {
2088    /// This impl requires the [`"rc"`] Cargo feature of Serde.
2089    ///
2090    /// Deserializing a data structure containing `Arc` will not attempt to
2091    /// deduplicate `Arc` references to the same data. Every deserialized `Arc`
2092    /// will end up with a strong count of 1.
2093    ///
2094    /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
2095    #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
2096    #[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))]
2097    Arc
2098}
2099
2100////////////////////////////////////////////////////////////////////////////////
2101
2102impl<'de, T> Deserialize<'de> for Cell<T>
2103where
2104    T: Deserialize<'de> + Copy,
2105{
2106    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2107    where
2108        D: Deserializer<'de>,
2109    {
2110        T::deserialize(deserializer).map(Cell::new)
2111    }
2112}
2113
2114forwarded_impl! {
2115    (T), RefCell<T>, RefCell::new
2116}
2117
2118forwarded_impl! {
2119    #[cfg(feature = "std")]
2120    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2121    (T), Mutex<T>, Mutex::new
2122}
2123
2124forwarded_impl! {
2125    #[cfg(feature = "std")]
2126    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2127    (T), RwLock<T>, RwLock::new
2128}
2129
2130////////////////////////////////////////////////////////////////////////////////
2131
2132// This is a cleaned-up version of the impl generated by:
2133//
2134//     #[derive(Deserialize)]
2135//     #[serde(deny_unknown_fields)]
2136//     struct Duration {
2137//         secs: u64,
2138//         nanos: u32,
2139//     }
2140impl<'de> Deserialize<'de> for Duration {
2141    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2142    where
2143        D: Deserializer<'de>,
2144    {
2145        // If this were outside of the serde crate, it would just use:
2146        //
2147        //    #[derive(Deserialize)]
2148        //    #[serde(field_identifier, rename_all = "lowercase")]
2149        enum Field {
2150            Secs,
2151            Nanos,
2152        }
2153
2154        impl<'de> Deserialize<'de> for Field {
2155            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2156            where
2157                D: Deserializer<'de>,
2158            {
2159                struct FieldVisitor;
2160
2161                impl<'de> Visitor<'de> for FieldVisitor {
2162                    type Value = Field;
2163
2164                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2165                        formatter.write_str("`secs` or `nanos`")
2166                    }
2167
2168                    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2169                    where
2170                        E: Error,
2171                    {
2172                        match value {
2173                            "secs" => Ok(Field::Secs),
2174                            "nanos" => Ok(Field::Nanos),
2175                            _ => Err(Error::unknown_field(value, FIELDS)),
2176                        }
2177                    }
2178
2179                    fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2180                    where
2181                        E: Error,
2182                    {
2183                        match value {
2184                            b"secs" => Ok(Field::Secs),
2185                            b"nanos" => Ok(Field::Nanos),
2186                            _ => {
2187                                let value = crate::__private::from_utf8_lossy(value);
2188                                Err(Error::unknown_field(&*value, FIELDS))
2189                            }
2190                        }
2191                    }
2192                }
2193
2194                deserializer.deserialize_identifier(FieldVisitor)
2195            }
2196        }
2197
2198        fn check_overflow<E>(secs: u64, nanos: u32) -> Result<(), E>
2199        where
2200            E: Error,
2201        {
2202            static NANOS_PER_SEC: u32 = 1_000_000_000;
2203            match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
2204                Some(_) => Ok(()),
2205                None => Err(E::custom("overflow deserializing Duration")),
2206            }
2207        }
2208
2209        struct DurationVisitor;
2210
2211        impl<'de> Visitor<'de> for DurationVisitor {
2212            type Value = Duration;
2213
2214            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2215                formatter.write_str("struct Duration")
2216            }
2217
2218            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2219            where
2220                A: SeqAccess<'de>,
2221            {
2222                let secs: u64 = match tri!(seq.next_element()) {
2223                    Some(value) => value,
2224                    None => {
2225                        return Err(Error::invalid_length(0, &self));
2226                    }
2227                };
2228                let nanos: u32 = match tri!(seq.next_element()) {
2229                    Some(value) => value,
2230                    None => {
2231                        return Err(Error::invalid_length(1, &self));
2232                    }
2233                };
2234                tri!(check_overflow(secs, nanos));
2235                Ok(Duration::new(secs, nanos))
2236            }
2237
2238            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2239            where
2240                A: MapAccess<'de>,
2241            {
2242                let mut secs: Option<u64> = None;
2243                let mut nanos: Option<u32> = None;
2244                while let Some(key) = tri!(map.next_key()) {
2245                    match key {
2246                        Field::Secs => {
2247                            if secs.is_some() {
2248                                return Err(<A::Error as Error>::duplicate_field("secs"));
2249                            }
2250                            secs = Some(tri!(map.next_value()));
2251                        }
2252                        Field::Nanos => {
2253                            if nanos.is_some() {
2254                                return Err(<A::Error as Error>::duplicate_field("nanos"));
2255                            }
2256                            nanos = Some(tri!(map.next_value()));
2257                        }
2258                    }
2259                }
2260                let secs = match secs {
2261                    Some(secs) => secs,
2262                    None => return Err(<A::Error as Error>::missing_field("secs")),
2263                };
2264                let nanos = match nanos {
2265                    Some(nanos) => nanos,
2266                    None => return Err(<A::Error as Error>::missing_field("nanos")),
2267                };
2268                tri!(check_overflow(secs, nanos));
2269                Ok(Duration::new(secs, nanos))
2270            }
2271        }
2272
2273        const FIELDS: &[&str] = &["secs", "nanos"];
2274        deserializer.deserialize_struct("Duration", FIELDS, DurationVisitor)
2275    }
2276}
2277
2278////////////////////////////////////////////////////////////////////////////////
2279
2280#[cfg(feature = "std")]
2281#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2282impl<'de> Deserialize<'de> for SystemTime {
2283    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2284    where
2285        D: Deserializer<'de>,
2286    {
2287        // Reuse duration
2288        enum Field {
2289            Secs,
2290            Nanos,
2291        }
2292
2293        impl<'de> Deserialize<'de> for Field {
2294            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2295            where
2296                D: Deserializer<'de>,
2297            {
2298                struct FieldVisitor;
2299
2300                impl<'de> Visitor<'de> for FieldVisitor {
2301                    type Value = Field;
2302
2303                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2304                        formatter.write_str("`secs_since_epoch` or `nanos_since_epoch`")
2305                    }
2306
2307                    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2308                    where
2309                        E: Error,
2310                    {
2311                        match value {
2312                            "secs_since_epoch" => Ok(Field::Secs),
2313                            "nanos_since_epoch" => Ok(Field::Nanos),
2314                            _ => Err(Error::unknown_field(value, FIELDS)),
2315                        }
2316                    }
2317
2318                    fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2319                    where
2320                        E: Error,
2321                    {
2322                        match value {
2323                            b"secs_since_epoch" => Ok(Field::Secs),
2324                            b"nanos_since_epoch" => Ok(Field::Nanos),
2325                            _ => {
2326                                let value = String::from_utf8_lossy(value);
2327                                Err(Error::unknown_field(&value, FIELDS))
2328                            }
2329                        }
2330                    }
2331                }
2332
2333                deserializer.deserialize_identifier(FieldVisitor)
2334            }
2335        }
2336
2337        fn check_overflow<E>(secs: u64, nanos: u32) -> Result<(), E>
2338        where
2339            E: Error,
2340        {
2341            static NANOS_PER_SEC: u32 = 1_000_000_000;
2342            match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
2343                Some(_) => Ok(()),
2344                None => Err(E::custom("overflow deserializing SystemTime epoch offset")),
2345            }
2346        }
2347
2348        struct DurationVisitor;
2349
2350        impl<'de> Visitor<'de> for DurationVisitor {
2351            type Value = Duration;
2352
2353            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2354                formatter.write_str("struct SystemTime")
2355            }
2356
2357            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2358            where
2359                A: SeqAccess<'de>,
2360            {
2361                let secs: u64 = match tri!(seq.next_element()) {
2362                    Some(value) => value,
2363                    None => {
2364                        return Err(Error::invalid_length(0, &self));
2365                    }
2366                };
2367                let nanos: u32 = match tri!(seq.next_element()) {
2368                    Some(value) => value,
2369                    None => {
2370                        return Err(Error::invalid_length(1, &self));
2371                    }
2372                };
2373                tri!(check_overflow(secs, nanos));
2374                Ok(Duration::new(secs, nanos))
2375            }
2376
2377            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2378            where
2379                A: MapAccess<'de>,
2380            {
2381                let mut secs: Option<u64> = None;
2382                let mut nanos: Option<u32> = None;
2383                while let Some(key) = tri!(map.next_key()) {
2384                    match key {
2385                        Field::Secs => {
2386                            if secs.is_some() {
2387                                return Err(<A::Error as Error>::duplicate_field(
2388                                    "secs_since_epoch",
2389                                ));
2390                            }
2391                            secs = Some(tri!(map.next_value()));
2392                        }
2393                        Field::Nanos => {
2394                            if nanos.is_some() {
2395                                return Err(<A::Error as Error>::duplicate_field(
2396                                    "nanos_since_epoch",
2397                                ));
2398                            }
2399                            nanos = Some(tri!(map.next_value()));
2400                        }
2401                    }
2402                }
2403                let secs = match secs {
2404                    Some(secs) => secs,
2405                    None => return Err(<A::Error as Error>::missing_field("secs_since_epoch")),
2406                };
2407                let nanos = match nanos {
2408                    Some(nanos) => nanos,
2409                    None => return Err(<A::Error as Error>::missing_field("nanos_since_epoch")),
2410                };
2411                tri!(check_overflow(secs, nanos));
2412                Ok(Duration::new(secs, nanos))
2413            }
2414        }
2415
2416        const FIELDS: &[&str] = &["secs_since_epoch", "nanos_since_epoch"];
2417        let duration = tri!(deserializer.deserialize_struct("SystemTime", FIELDS, DurationVisitor));
2418        #[cfg(not(no_systemtime_checked_add))]
2419        let ret = UNIX_EPOCH
2420            .checked_add(duration)
2421            .ok_or_else(|| D::Error::custom("overflow deserializing SystemTime"));
2422        #[cfg(no_systemtime_checked_add)]
2423        let ret = Ok(UNIX_EPOCH + duration);
2424        ret
2425    }
2426}
2427
2428////////////////////////////////////////////////////////////////////////////////
2429
2430// Similar to:
2431//
2432//     #[derive(Deserialize)]
2433//     #[serde(deny_unknown_fields)]
2434//     struct Range<Idx> {
2435//         start: Idx,
2436//         end: Idx,
2437//     }
2438impl<'de, Idx> Deserialize<'de> for Range<Idx>
2439where
2440    Idx: Deserialize<'de>,
2441{
2442    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2443    where
2444        D: Deserializer<'de>,
2445    {
2446        let (start, end) = tri!(deserializer.deserialize_struct(
2447            "Range",
2448            range::FIELDS,
2449            range::RangeVisitor {
2450                expecting: "struct Range",
2451                phantom: PhantomData,
2452            },
2453        ));
2454        Ok(start..end)
2455    }
2456}
2457
2458impl<'de, Idx> Deserialize<'de> for RangeInclusive<Idx>
2459where
2460    Idx: Deserialize<'de>,
2461{
2462    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2463    where
2464        D: Deserializer<'de>,
2465    {
2466        let (start, end) = tri!(deserializer.deserialize_struct(
2467            "RangeInclusive",
2468            range::FIELDS,
2469            range::RangeVisitor {
2470                expecting: "struct RangeInclusive",
2471                phantom: PhantomData,
2472            },
2473        ));
2474        Ok(RangeInclusive::new(start, end))
2475    }
2476}
2477
2478mod range {
2479    use crate::lib::*;
2480
2481    use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor};
2482
2483    pub const FIELDS: &[&str] = &["start", "end"];
2484
2485    // If this were outside of the serde crate, it would just use:
2486    //
2487    //    #[derive(Deserialize)]
2488    //    #[serde(field_identifier, rename_all = "lowercase")]
2489    enum Field {
2490        Start,
2491        End,
2492    }
2493
2494    impl<'de> Deserialize<'de> for Field {
2495        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2496        where
2497            D: Deserializer<'de>,
2498        {
2499            struct FieldVisitor;
2500
2501            impl<'de> Visitor<'de> for FieldVisitor {
2502                type Value = Field;
2503
2504                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2505                    formatter.write_str("`start` or `end`")
2506                }
2507
2508                fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2509                where
2510                    E: Error,
2511                {
2512                    match value {
2513                        "start" => Ok(Field::Start),
2514                        "end" => Ok(Field::End),
2515                        _ => Err(Error::unknown_field(value, FIELDS)),
2516                    }
2517                }
2518
2519                fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2520                where
2521                    E: Error,
2522                {
2523                    match value {
2524                        b"start" => Ok(Field::Start),
2525                        b"end" => Ok(Field::End),
2526                        _ => {
2527                            let value = crate::__private::from_utf8_lossy(value);
2528                            Err(Error::unknown_field(&*value, FIELDS))
2529                        }
2530                    }
2531                }
2532            }
2533
2534            deserializer.deserialize_identifier(FieldVisitor)
2535        }
2536    }
2537
2538    pub struct RangeVisitor<Idx> {
2539        pub expecting: &'static str,
2540        pub phantom: PhantomData<Idx>,
2541    }
2542
2543    impl<'de, Idx> Visitor<'de> for RangeVisitor<Idx>
2544    where
2545        Idx: Deserialize<'de>,
2546    {
2547        type Value = (Idx, Idx);
2548
2549        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2550            formatter.write_str(self.expecting)
2551        }
2552
2553        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2554        where
2555            A: SeqAccess<'de>,
2556        {
2557            let start: Idx = match tri!(seq.next_element()) {
2558                Some(value) => value,
2559                None => {
2560                    return Err(Error::invalid_length(0, &self));
2561                }
2562            };
2563            let end: Idx = match tri!(seq.next_element()) {
2564                Some(value) => value,
2565                None => {
2566                    return Err(Error::invalid_length(1, &self));
2567                }
2568            };
2569            Ok((start, end))
2570        }
2571
2572        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2573        where
2574            A: MapAccess<'de>,
2575        {
2576            let mut start: Option<Idx> = None;
2577            let mut end: Option<Idx> = None;
2578            while let Some(key) = tri!(map.next_key()) {
2579                match key {
2580                    Field::Start => {
2581                        if start.is_some() {
2582                            return Err(<A::Error as Error>::duplicate_field("start"));
2583                        }
2584                        start = Some(tri!(map.next_value()));
2585                    }
2586                    Field::End => {
2587                        if end.is_some() {
2588                            return Err(<A::Error as Error>::duplicate_field("end"));
2589                        }
2590                        end = Some(tri!(map.next_value()));
2591                    }
2592                }
2593            }
2594            let start = match start {
2595                Some(start) => start,
2596                None => return Err(<A::Error as Error>::missing_field("start")),
2597            };
2598            let end = match end {
2599                Some(end) => end,
2600                None => return Err(<A::Error as Error>::missing_field("end")),
2601            };
2602            Ok((start, end))
2603        }
2604    }
2605}
2606
2607////////////////////////////////////////////////////////////////////////////////
2608
2609// Similar to:
2610//
2611//     #[derive(Deserialize)]
2612//     #[serde(deny_unknown_fields)]
2613//     struct RangeFrom<Idx> {
2614//         start: Idx,
2615//     }
2616impl<'de, Idx> Deserialize<'de> for RangeFrom<Idx>
2617where
2618    Idx: Deserialize<'de>,
2619{
2620    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2621    where
2622        D: Deserializer<'de>,
2623    {
2624        let start = tri!(deserializer.deserialize_struct(
2625            "RangeFrom",
2626            range_from::FIELDS,
2627            range_from::RangeFromVisitor {
2628                expecting: "struct RangeFrom",
2629                phantom: PhantomData,
2630            },
2631        ));
2632        Ok(start..)
2633    }
2634}
2635
2636mod range_from {
2637    use crate::lib::*;
2638
2639    use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor};
2640
2641    pub const FIELDS: &[&str] = &["start"];
2642
2643    // If this were outside of the serde crate, it would just use:
2644    //
2645    //    #[derive(Deserialize)]
2646    //    #[serde(field_identifier, rename_all = "lowercase")]
2647    enum Field {
2648        Start,
2649    }
2650
2651    impl<'de> Deserialize<'de> for Field {
2652        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2653        where
2654            D: Deserializer<'de>,
2655        {
2656            struct FieldVisitor;
2657
2658            impl<'de> Visitor<'de> for FieldVisitor {
2659                type Value = Field;
2660
2661                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2662                    formatter.write_str("`start`")
2663                }
2664
2665                fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2666                where
2667                    E: Error,
2668                {
2669                    match value {
2670                        "start" => Ok(Field::Start),
2671                        _ => Err(Error::unknown_field(value, FIELDS)),
2672                    }
2673                }
2674
2675                fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2676                where
2677                    E: Error,
2678                {
2679                    match value {
2680                        b"start" => Ok(Field::Start),
2681                        _ => {
2682                            let value = crate::__private::from_utf8_lossy(value);
2683                            Err(Error::unknown_field(&*value, FIELDS))
2684                        }
2685                    }
2686                }
2687            }
2688
2689            deserializer.deserialize_identifier(FieldVisitor)
2690        }
2691    }
2692
2693    pub struct RangeFromVisitor<Idx> {
2694        pub expecting: &'static str,
2695        pub phantom: PhantomData<Idx>,
2696    }
2697
2698    impl<'de, Idx> Visitor<'de> for RangeFromVisitor<Idx>
2699    where
2700        Idx: Deserialize<'de>,
2701    {
2702        type Value = Idx;
2703
2704        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2705            formatter.write_str(self.expecting)
2706        }
2707
2708        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2709        where
2710            A: SeqAccess<'de>,
2711        {
2712            let start: Idx = match tri!(seq.next_element()) {
2713                Some(value) => value,
2714                None => {
2715                    return Err(Error::invalid_length(0, &self));
2716                }
2717            };
2718            Ok(start)
2719        }
2720
2721        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2722        where
2723            A: MapAccess<'de>,
2724        {
2725            let mut start: Option<Idx> = None;
2726            while let Some(key) = tri!(map.next_key()) {
2727                match key {
2728                    Field::Start => {
2729                        if start.is_some() {
2730                            return Err(<A::Error as Error>::duplicate_field("start"));
2731                        }
2732                        start = Some(tri!(map.next_value()));
2733                    }
2734                }
2735            }
2736            let start = match start {
2737                Some(start) => start,
2738                None => return Err(<A::Error as Error>::missing_field("start")),
2739            };
2740            Ok(start)
2741        }
2742    }
2743}
2744
2745////////////////////////////////////////////////////////////////////////////////
2746
2747// Similar to:
2748//
2749//     #[derive(Deserialize)]
2750//     #[serde(deny_unknown_fields)]
2751//     struct RangeTo<Idx> {
2752//         end: Idx,
2753//     }
2754impl<'de, Idx> Deserialize<'de> for RangeTo<Idx>
2755where
2756    Idx: Deserialize<'de>,
2757{
2758    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2759    where
2760        D: Deserializer<'de>,
2761    {
2762        let end = tri!(deserializer.deserialize_struct(
2763            "RangeTo",
2764            range_to::FIELDS,
2765            range_to::RangeToVisitor {
2766                expecting: "struct RangeTo",
2767                phantom: PhantomData,
2768            },
2769        ));
2770        Ok(..end)
2771    }
2772}
2773
2774mod range_to {
2775    use crate::lib::*;
2776
2777    use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor};
2778
2779    pub const FIELDS: &[&str] = &["end"];
2780
2781    // If this were outside of the serde crate, it would just use:
2782    //
2783    //    #[derive(Deserialize)]
2784    //    #[serde(field_identifier, rename_all = "lowercase")]
2785    enum Field {
2786        End,
2787    }
2788
2789    impl<'de> Deserialize<'de> for Field {
2790        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2791        where
2792            D: Deserializer<'de>,
2793        {
2794            struct FieldVisitor;
2795
2796            impl<'de> Visitor<'de> for FieldVisitor {
2797                type Value = Field;
2798
2799                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2800                    formatter.write_str("`end`")
2801                }
2802
2803                fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2804                where
2805                    E: Error,
2806                {
2807                    match value {
2808                        "end" => Ok(Field::End),
2809                        _ => Err(Error::unknown_field(value, FIELDS)),
2810                    }
2811                }
2812
2813                fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2814                where
2815                    E: Error,
2816                {
2817                    match value {
2818                        b"end" => Ok(Field::End),
2819                        _ => {
2820                            let value = crate::__private::from_utf8_lossy(value);
2821                            Err(Error::unknown_field(&*value, FIELDS))
2822                        }
2823                    }
2824                }
2825            }
2826
2827            deserializer.deserialize_identifier(FieldVisitor)
2828        }
2829    }
2830
2831    pub struct RangeToVisitor<Idx> {
2832        pub expecting: &'static str,
2833        pub phantom: PhantomData<Idx>,
2834    }
2835
2836    impl<'de, Idx> Visitor<'de> for RangeToVisitor<Idx>
2837    where
2838        Idx: Deserialize<'de>,
2839    {
2840        type Value = Idx;
2841
2842        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2843            formatter.write_str(self.expecting)
2844        }
2845
2846        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2847        where
2848            A: SeqAccess<'de>,
2849        {
2850            let end: Idx = match tri!(seq.next_element()) {
2851                Some(value) => value,
2852                None => {
2853                    return Err(Error::invalid_length(0, &self));
2854                }
2855            };
2856            Ok(end)
2857        }
2858
2859        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2860        where
2861            A: MapAccess<'de>,
2862        {
2863            let mut end: Option<Idx> = None;
2864            while let Some(key) = tri!(map.next_key()) {
2865                match key {
2866                    Field::End => {
2867                        if end.is_some() {
2868                            return Err(<A::Error as Error>::duplicate_field("end"));
2869                        }
2870                        end = Some(tri!(map.next_value()));
2871                    }
2872                }
2873            }
2874            let end = match end {
2875                Some(end) => end,
2876                None => return Err(<A::Error as Error>::missing_field("end")),
2877            };
2878            Ok(end)
2879        }
2880    }
2881}
2882
2883////////////////////////////////////////////////////////////////////////////////
2884
2885impl<'de, T> Deserialize<'de> for Bound<T>
2886where
2887    T: Deserialize<'de>,
2888{
2889    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2890    where
2891        D: Deserializer<'de>,
2892    {
2893        enum Field {
2894            Unbounded,
2895            Included,
2896            Excluded,
2897        }
2898
2899        impl<'de> Deserialize<'de> for Field {
2900            #[inline]
2901            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2902            where
2903                D: Deserializer<'de>,
2904            {
2905                struct FieldVisitor;
2906
2907                impl<'de> Visitor<'de> for FieldVisitor {
2908                    type Value = Field;
2909
2910                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2911                        formatter.write_str("`Unbounded`, `Included` or `Excluded`")
2912                    }
2913
2914                    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
2915                    where
2916                        E: Error,
2917                    {
2918                        match value {
2919                            0 => Ok(Field::Unbounded),
2920                            1 => Ok(Field::Included),
2921                            2 => Ok(Field::Excluded),
2922                            _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self)),
2923                        }
2924                    }
2925
2926                    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2927                    where
2928                        E: Error,
2929                    {
2930                        match value {
2931                            "Unbounded" => Ok(Field::Unbounded),
2932                            "Included" => Ok(Field::Included),
2933                            "Excluded" => Ok(Field::Excluded),
2934                            _ => Err(Error::unknown_variant(value, VARIANTS)),
2935                        }
2936                    }
2937
2938                    fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2939                    where
2940                        E: Error,
2941                    {
2942                        match value {
2943                            b"Unbounded" => Ok(Field::Unbounded),
2944                            b"Included" => Ok(Field::Included),
2945                            b"Excluded" => Ok(Field::Excluded),
2946                            _ => match str::from_utf8(value) {
2947                                Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
2948                                Err(_) => {
2949                                    Err(Error::invalid_value(Unexpected::Bytes(value), &self))
2950                                }
2951                            },
2952                        }
2953                    }
2954                }
2955
2956                deserializer.deserialize_identifier(FieldVisitor)
2957            }
2958        }
2959
2960        struct BoundVisitor<T>(PhantomData<Bound<T>>);
2961
2962        impl<'de, T> Visitor<'de> for BoundVisitor<T>
2963        where
2964            T: Deserialize<'de>,
2965        {
2966            type Value = Bound<T>;
2967
2968            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2969                formatter.write_str("enum Bound")
2970            }
2971
2972            fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
2973            where
2974                A: EnumAccess<'de>,
2975            {
2976                match tri!(data.variant()) {
2977                    (Field::Unbounded, v) => v.unit_variant().map(|()| Bound::Unbounded),
2978                    (Field::Included, v) => v.newtype_variant().map(Bound::Included),
2979                    (Field::Excluded, v) => v.newtype_variant().map(Bound::Excluded),
2980                }
2981            }
2982        }
2983
2984        const VARIANTS: &[&str] = &["Unbounded", "Included", "Excluded"];
2985
2986        deserializer.deserialize_enum("Bound", VARIANTS, BoundVisitor(PhantomData))
2987    }
2988}
2989
2990////////////////////////////////////////////////////////////////////////////////
2991
2992impl<'de, T, E> Deserialize<'de> for Result<T, E>
2993where
2994    T: Deserialize<'de>,
2995    E: Deserialize<'de>,
2996{
2997    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2998    where
2999        D: Deserializer<'de>,
3000    {
3001        // If this were outside of the serde crate, it would just use:
3002        //
3003        //    #[derive(Deserialize)]
3004        //    #[serde(variant_identifier)]
3005        enum Field {
3006            Ok,
3007            Err,
3008        }
3009
3010        impl<'de> Deserialize<'de> for Field {
3011            #[inline]
3012            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3013            where
3014                D: Deserializer<'de>,
3015            {
3016                struct FieldVisitor;
3017
3018                impl<'de> Visitor<'de> for FieldVisitor {
3019                    type Value = Field;
3020
3021                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3022                        formatter.write_str("`Ok` or `Err`")
3023                    }
3024
3025                    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
3026                    where
3027                        E: Error,
3028                    {
3029                        match value {
3030                            0 => Ok(Field::Ok),
3031                            1 => Ok(Field::Err),
3032                            _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self)),
3033                        }
3034                    }
3035
3036                    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
3037                    where
3038                        E: Error,
3039                    {
3040                        match value {
3041                            "Ok" => Ok(Field::Ok),
3042                            "Err" => Ok(Field::Err),
3043                            _ => Err(Error::unknown_variant(value, VARIANTS)),
3044                        }
3045                    }
3046
3047                    fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
3048                    where
3049                        E: Error,
3050                    {
3051                        match value {
3052                            b"Ok" => Ok(Field::Ok),
3053                            b"Err" => Ok(Field::Err),
3054                            _ => match str::from_utf8(value) {
3055                                Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
3056                                Err(_) => {
3057                                    Err(Error::invalid_value(Unexpected::Bytes(value), &self))
3058                                }
3059                            },
3060                        }
3061                    }
3062                }
3063
3064                deserializer.deserialize_identifier(FieldVisitor)
3065            }
3066        }
3067
3068        struct ResultVisitor<T, E>(PhantomData<Result<T, E>>);
3069
3070        impl<'de, T, E> Visitor<'de> for ResultVisitor<T, E>
3071        where
3072            T: Deserialize<'de>,
3073            E: Deserialize<'de>,
3074        {
3075            type Value = Result<T, E>;
3076
3077            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3078                formatter.write_str("enum Result")
3079            }
3080
3081            fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
3082            where
3083                A: EnumAccess<'de>,
3084            {
3085                match tri!(data.variant()) {
3086                    (Field::Ok, v) => v.newtype_variant().map(Ok),
3087                    (Field::Err, v) => v.newtype_variant().map(Err),
3088                }
3089            }
3090        }
3091
3092        const VARIANTS: &[&str] = &["Ok", "Err"];
3093
3094        deserializer.deserialize_enum("Result", VARIANTS, ResultVisitor(PhantomData))
3095    }
3096}
3097
3098////////////////////////////////////////////////////////////////////////////////
3099
3100impl<'de, T> Deserialize<'de> for Wrapping<T>
3101where
3102    T: Deserialize<'de>,
3103{
3104    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3105    where
3106        D: Deserializer<'de>,
3107    {
3108        Deserialize::deserialize(deserializer).map(Wrapping)
3109    }
3110}
3111
3112#[cfg(all(feature = "std", not(no_std_atomic)))]
3113macro_rules! atomic_impl {
3114    ($($ty:ident $size:expr)*) => {
3115        $(
3116            #[cfg(any(no_target_has_atomic, target_has_atomic = $size))]
3117            #[cfg_attr(docsrs, doc(cfg(all(feature = "std", target_has_atomic = $size))))]
3118            impl<'de> Deserialize<'de> for $ty {
3119                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3120                where
3121                    D: Deserializer<'de>,
3122                {
3123                    Deserialize::deserialize(deserializer).map(Self::new)
3124                }
3125            }
3126        )*
3127    };
3128}
3129
3130#[cfg(all(feature = "std", not(no_std_atomic)))]
3131atomic_impl! {
3132    AtomicBool "8"
3133    AtomicI8 "8"
3134    AtomicI16 "16"
3135    AtomicI32 "32"
3136    AtomicIsize "ptr"
3137    AtomicU8 "8"
3138    AtomicU16 "16"
3139    AtomicU32 "32"
3140    AtomicUsize "ptr"
3141}
3142
3143#[cfg(all(feature = "std", not(no_std_atomic64)))]
3144atomic_impl! {
3145    AtomicI64 "64"
3146    AtomicU64 "64"
3147}
3148
3149#[cfg(any(feature = "std", not(no_core_net)))]
3150struct FromStrVisitor<T> {
3151    expecting: &'static str,
3152    ty: PhantomData<T>,
3153}
3154
3155#[cfg(any(feature = "std", not(no_core_net)))]
3156impl<T> FromStrVisitor<T> {
3157    fn new(expecting: &'static str) -> Self {
3158        FromStrVisitor {
3159            expecting,
3160            ty: PhantomData,
3161        }
3162    }
3163}
3164
3165#[cfg(any(feature = "std", not(no_core_net)))]
3166impl<'de, T> Visitor<'de> for FromStrVisitor<T>
3167where
3168    T: str::FromStr,
3169    T::Err: fmt::Display,
3170{
3171    type Value = T;
3172
3173    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3174        formatter.write_str(self.expecting)
3175    }
3176
3177    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
3178    where
3179        E: Error,
3180    {
3181        s.parse().map_err(Error::custom)
3182    }
3183}