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
1586macro_rules! parse_ip_impl {
1587    (
1588        $(#[$attr:meta])*
1589        $ty:ty, $expecting:expr, $size:tt
1590    ) => {
1591        $(#[$attr])*
1592        impl<'de> Deserialize<'de> for $ty {
1593            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1594            where
1595                D: Deserializer<'de>,
1596            {
1597                if deserializer.is_human_readable() {
1598                    deserializer.deserialize_str(FromStrVisitor::new($expecting))
1599                } else {
1600                    <[u8; $size]>::deserialize(deserializer).map(<$ty>::from)
1601                }
1602            }
1603        }
1604    };
1605}
1606
1607#[cfg(feature = "std")]
1608macro_rules! variant_identifier {
1609    (
1610        $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*)
1611        $expecting_message:expr,
1612        $variants_name:ident
1613    ) => {
1614        enum $name_kind {
1615            $($variant),*
1616        }
1617
1618        static $variants_name: &[&str] = &[$(stringify!($variant)),*];
1619
1620        impl<'de> Deserialize<'de> for $name_kind {
1621            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1622            where
1623                D: Deserializer<'de>,
1624            {
1625                struct KindVisitor;
1626
1627                impl<'de> Visitor<'de> for KindVisitor {
1628                    type Value = $name_kind;
1629
1630                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1631                        formatter.write_str($expecting_message)
1632                    }
1633
1634                    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1635                    where
1636                        E: Error,
1637                    {
1638                        match value {
1639                            $(
1640                                $index => Ok($name_kind :: $variant),
1641                            )*
1642                            _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self),),
1643                        }
1644                    }
1645
1646                    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1647                    where
1648                        E: Error,
1649                    {
1650                        match value {
1651                            $(
1652                                stringify!($variant) => Ok($name_kind :: $variant),
1653                            )*
1654                            _ => Err(Error::unknown_variant(value, $variants_name)),
1655                        }
1656                    }
1657
1658                    fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
1659                    where
1660                        E: Error,
1661                    {
1662                        match value {
1663                            $(
1664                                $bytes => Ok($name_kind :: $variant),
1665                            )*
1666                            _ => {
1667                                match str::from_utf8(value) {
1668                                    Ok(value) => Err(Error::unknown_variant(value, $variants_name)),
1669                                    Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),
1670                                }
1671                            }
1672                        }
1673                    }
1674                }
1675
1676                deserializer.deserialize_identifier(KindVisitor)
1677            }
1678        }
1679    }
1680}
1681
1682#[cfg(feature = "std")]
1683macro_rules! deserialize_enum {
1684    (
1685        $name:ident $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*)
1686        $expecting_message:expr,
1687        $deserializer:expr
1688    ) => {
1689        variant_identifier! {
1690            $name_kind ($($variant; $bytes; $index),*)
1691            $expecting_message,
1692            VARIANTS
1693        }
1694
1695        struct EnumVisitor;
1696        impl<'de> Visitor<'de> for EnumVisitor {
1697            type Value = $name;
1698
1699            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1700                formatter.write_str(concat!("a ", stringify!($name)))
1701            }
1702
1703
1704            fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
1705            where
1706                A: EnumAccess<'de>,
1707            {
1708                match tri!(data.variant()) {
1709                    $(
1710                        ($name_kind :: $variant, v) => v.newtype_variant().map($name :: $variant),
1711                    )*
1712                }
1713            }
1714        }
1715        $deserializer.deserialize_enum(stringify!($name), VARIANTS, EnumVisitor)
1716    }
1717}
1718
1719#[cfg(feature = "std")]
1720#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1721impl<'de> Deserialize<'de> for net::IpAddr {
1722    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1723    where
1724        D: Deserializer<'de>,
1725    {
1726        if deserializer.is_human_readable() {
1727            deserializer.deserialize_str(FromStrVisitor::new("IP address"))
1728        } else {
1729            use crate::lib::net::IpAddr;
1730            deserialize_enum! {
1731                IpAddr IpAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)
1732                "`V4` or `V6`",
1733                deserializer
1734            }
1735        }
1736    }
1737}
1738
1739parse_ip_impl! {
1740    #[cfg(feature = "std")]
1741    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1742    net::Ipv4Addr, "IPv4 address", 4
1743}
1744
1745parse_ip_impl! {
1746    #[cfg(feature = "std")]
1747    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1748    net::Ipv6Addr, "IPv6 address", 16
1749}
1750
1751macro_rules! parse_socket_impl {
1752    (
1753        $(#[$attr:meta])*
1754        $ty:ty, $expecting:tt,
1755        $new:expr,
1756    ) => {
1757        $(#[$attr])*
1758        impl<'de> Deserialize<'de> for $ty {
1759            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1760            where
1761                D: Deserializer<'de>,
1762            {
1763                if deserializer.is_human_readable() {
1764                    deserializer.deserialize_str(FromStrVisitor::new($expecting))
1765                } else {
1766                    <(_, u16)>::deserialize(deserializer).map($new)
1767                }
1768            }
1769        }
1770    };
1771}
1772
1773#[cfg(feature = "std")]
1774#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1775impl<'de> Deserialize<'de> for net::SocketAddr {
1776    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1777    where
1778        D: Deserializer<'de>,
1779    {
1780        if deserializer.is_human_readable() {
1781            deserializer.deserialize_str(FromStrVisitor::new("socket address"))
1782        } else {
1783            use crate::lib::net::SocketAddr;
1784            deserialize_enum! {
1785                SocketAddr SocketAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)
1786                "`V4` or `V6`",
1787                deserializer
1788            }
1789        }
1790    }
1791}
1792
1793parse_socket_impl! {
1794    #[cfg(feature = "std")]
1795    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1796    net::SocketAddrV4, "IPv4 socket address",
1797    |(ip, port)| net::SocketAddrV4::new(ip, port),
1798}
1799
1800parse_socket_impl! {
1801    #[cfg(feature = "std")]
1802    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1803    net::SocketAddrV6, "IPv6 socket address",
1804    |(ip, port)| net::SocketAddrV6::new(ip, port, 0, 0),
1805}
1806
1807////////////////////////////////////////////////////////////////////////////////
1808
1809#[cfg(feature = "std")]
1810struct PathVisitor;
1811
1812#[cfg(feature = "std")]
1813impl<'a> Visitor<'a> for PathVisitor {
1814    type Value = &'a Path;
1815
1816    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1817        formatter.write_str("a borrowed path")
1818    }
1819
1820    fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
1821    where
1822        E: Error,
1823    {
1824        Ok(v.as_ref())
1825    }
1826
1827    fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
1828    where
1829        E: Error,
1830    {
1831        str::from_utf8(v)
1832            .map(AsRef::as_ref)
1833            .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
1834    }
1835}
1836
1837#[cfg(feature = "std")]
1838#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1839impl<'de: 'a, 'a> Deserialize<'de> for &'a Path {
1840    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1841    where
1842        D: Deserializer<'de>,
1843    {
1844        deserializer.deserialize_str(PathVisitor)
1845    }
1846}
1847
1848#[cfg(feature = "std")]
1849struct PathBufVisitor;
1850
1851#[cfg(feature = "std")]
1852impl<'de> Visitor<'de> for PathBufVisitor {
1853    type Value = PathBuf;
1854
1855    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1856        formatter.write_str("path string")
1857    }
1858
1859    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1860    where
1861        E: Error,
1862    {
1863        Ok(From::from(v))
1864    }
1865
1866    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1867    where
1868        E: Error,
1869    {
1870        Ok(From::from(v))
1871    }
1872
1873    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1874    where
1875        E: Error,
1876    {
1877        str::from_utf8(v)
1878            .map(From::from)
1879            .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
1880    }
1881
1882    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1883    where
1884        E: Error,
1885    {
1886        String::from_utf8(v)
1887            .map(From::from)
1888            .map_err(|e| Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self))
1889    }
1890}
1891
1892#[cfg(feature = "std")]
1893#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1894impl<'de> Deserialize<'de> for PathBuf {
1895    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1896    where
1897        D: Deserializer<'de>,
1898    {
1899        deserializer.deserialize_string(PathBufVisitor)
1900    }
1901}
1902
1903forwarded_impl! {
1904    #[cfg(feature = "std")]
1905    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1906    (), Box<Path>, PathBuf::into_boxed_path
1907}
1908
1909////////////////////////////////////////////////////////////////////////////////
1910
1911// If this were outside of the serde crate, it would just use:
1912//
1913//    #[derive(Deserialize)]
1914//    #[serde(variant_identifier)]
1915#[cfg(all(feature = "std", any(unix, windows)))]
1916variant_identifier! {
1917    OsStringKind (Unix; b"Unix"; 0, Windows; b"Windows"; 1)
1918    "`Unix` or `Windows`",
1919    OSSTR_VARIANTS
1920}
1921
1922#[cfg(all(feature = "std", any(unix, windows)))]
1923struct OsStringVisitor;
1924
1925#[cfg(all(feature = "std", any(unix, windows)))]
1926impl<'de> Visitor<'de> for OsStringVisitor {
1927    type Value = OsString;
1928
1929    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1930        formatter.write_str("os string")
1931    }
1932
1933    #[cfg(unix)]
1934    fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
1935    where
1936        A: EnumAccess<'de>,
1937    {
1938        use std::os::unix::ffi::OsStringExt;
1939
1940        match tri!(data.variant()) {
1941            (OsStringKind::Unix, v) => v.newtype_variant().map(OsString::from_vec),
1942            (OsStringKind::Windows, _) => Err(Error::custom(
1943                "cannot deserialize Windows OS string on Unix",
1944            )),
1945        }
1946    }
1947
1948    #[cfg(windows)]
1949    fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
1950    where
1951        A: EnumAccess<'de>,
1952    {
1953        use std::os::windows::ffi::OsStringExt;
1954
1955        match tri!(data.variant()) {
1956            (OsStringKind::Windows, v) => v
1957                .newtype_variant::<Vec<u16>>()
1958                .map(|vec| OsString::from_wide(&vec)),
1959            (OsStringKind::Unix, _) => Err(Error::custom(
1960                "cannot deserialize Unix OS string on Windows",
1961            )),
1962        }
1963    }
1964}
1965
1966#[cfg(all(feature = "std", any(unix, windows)))]
1967#[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))]
1968impl<'de> Deserialize<'de> for OsString {
1969    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1970    where
1971        D: Deserializer<'de>,
1972    {
1973        deserializer.deserialize_enum("OsString", OSSTR_VARIANTS, OsStringVisitor)
1974    }
1975}
1976
1977////////////////////////////////////////////////////////////////////////////////
1978
1979forwarded_impl! {
1980    #[cfg(any(feature = "std", feature = "alloc"))]
1981    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1982    (T), Box<T>, Box::new
1983}
1984
1985forwarded_impl! {
1986    #[cfg(any(feature = "std", feature = "alloc"))]
1987    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1988    (T), Box<[T]>, Vec::into_boxed_slice
1989}
1990
1991forwarded_impl! {
1992    #[cfg(any(feature = "std", feature = "alloc"))]
1993    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
1994    (), Box<str>, String::into_boxed_str
1995}
1996
1997forwarded_impl! {
1998    #[cfg(all(feature = "std", any(unix, windows)))]
1999    #[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))]
2000    (), Box<OsStr>, OsString::into_boxed_os_str
2001}
2002
2003#[cfg(any(feature = "std", feature = "alloc"))]
2004#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
2005impl<'de, 'a, T> Deserialize<'de> for Cow<'a, T>
2006where
2007    T: ?Sized + ToOwned,
2008    T::Owned: Deserialize<'de>,
2009{
2010    #[inline]
2011    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2012    where
2013        D: Deserializer<'de>,
2014    {
2015        T::Owned::deserialize(deserializer).map(Cow::Owned)
2016    }
2017}
2018
2019////////////////////////////////////////////////////////////////////////////////
2020
2021/// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting
2022/// `Weak<T>` has a reference count of 0 and cannot be upgraded.
2023///
2024/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
2025#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
2026#[cfg_attr(
2027    docsrs,
2028    doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc"))))
2029)]
2030impl<'de, T> Deserialize<'de> for RcWeak<T>
2031where
2032    T: Deserialize<'de>,
2033{
2034    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2035    where
2036        D: Deserializer<'de>,
2037    {
2038        tri!(Option::<T>::deserialize(deserializer));
2039        Ok(RcWeak::new())
2040    }
2041}
2042
2043/// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting
2044/// `Weak<T>` has a reference count of 0 and cannot be upgraded.
2045///
2046/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
2047#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
2048#[cfg_attr(
2049    docsrs,
2050    doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc"))))
2051)]
2052impl<'de, T> Deserialize<'de> for ArcWeak<T>
2053where
2054    T: Deserialize<'de>,
2055{
2056    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2057    where
2058        D: Deserializer<'de>,
2059    {
2060        tri!(Option::<T>::deserialize(deserializer));
2061        Ok(ArcWeak::new())
2062    }
2063}
2064
2065////////////////////////////////////////////////////////////////////////////////
2066
2067macro_rules! box_forwarded_impl {
2068    (
2069        $(#[$attr:meta])*
2070        $t:ident
2071    ) => {
2072        $(#[$attr])*
2073        impl<'de, T> Deserialize<'de> for $t<T>
2074        where
2075            T: ?Sized,
2076            Box<T>: Deserialize<'de>,
2077        {
2078            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2079            where
2080                D: Deserializer<'de>,
2081            {
2082                Box::deserialize(deserializer).map(Into::into)
2083            }
2084        }
2085    };
2086}
2087
2088box_forwarded_impl! {
2089    /// This impl requires the [`"rc"`] Cargo feature of Serde.
2090    ///
2091    /// Deserializing a data structure containing `Rc` will not attempt to
2092    /// deduplicate `Rc` references to the same data. Every deserialized `Rc`
2093    /// will end up with a strong count of 1.
2094    ///
2095    /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
2096    #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
2097    #[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))]
2098    Rc
2099}
2100
2101box_forwarded_impl! {
2102    /// This impl requires the [`"rc"`] Cargo feature of Serde.
2103    ///
2104    /// Deserializing a data structure containing `Arc` will not attempt to
2105    /// deduplicate `Arc` references to the same data. Every deserialized `Arc`
2106    /// will end up with a strong count of 1.
2107    ///
2108    /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
2109    #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
2110    #[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))]
2111    Arc
2112}
2113
2114////////////////////////////////////////////////////////////////////////////////
2115
2116impl<'de, T> Deserialize<'de> for Cell<T>
2117where
2118    T: Deserialize<'de> + Copy,
2119{
2120    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2121    where
2122        D: Deserializer<'de>,
2123    {
2124        T::deserialize(deserializer).map(Cell::new)
2125    }
2126}
2127
2128forwarded_impl! {
2129    (T), RefCell<T>, RefCell::new
2130}
2131
2132forwarded_impl! {
2133    #[cfg(feature = "std")]
2134    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2135    (T), Mutex<T>, Mutex::new
2136}
2137
2138forwarded_impl! {
2139    #[cfg(feature = "std")]
2140    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2141    (T), RwLock<T>, RwLock::new
2142}
2143
2144////////////////////////////////////////////////////////////////////////////////
2145
2146// This is a cleaned-up version of the impl generated by:
2147//
2148//     #[derive(Deserialize)]
2149//     #[serde(deny_unknown_fields)]
2150//     struct Duration {
2151//         secs: u64,
2152//         nanos: u32,
2153//     }
2154impl<'de> Deserialize<'de> for Duration {
2155    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2156    where
2157        D: Deserializer<'de>,
2158    {
2159        // If this were outside of the serde crate, it would just use:
2160        //
2161        //    #[derive(Deserialize)]
2162        //    #[serde(field_identifier, rename_all = "lowercase")]
2163        enum Field {
2164            Secs,
2165            Nanos,
2166        }
2167
2168        impl<'de> Deserialize<'de> for Field {
2169            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2170            where
2171                D: Deserializer<'de>,
2172            {
2173                struct FieldVisitor;
2174
2175                impl<'de> Visitor<'de> for FieldVisitor {
2176                    type Value = Field;
2177
2178                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2179                        formatter.write_str("`secs` or `nanos`")
2180                    }
2181
2182                    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2183                    where
2184                        E: Error,
2185                    {
2186                        match value {
2187                            "secs" => Ok(Field::Secs),
2188                            "nanos" => Ok(Field::Nanos),
2189                            _ => Err(Error::unknown_field(value, FIELDS)),
2190                        }
2191                    }
2192
2193                    fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2194                    where
2195                        E: Error,
2196                    {
2197                        match value {
2198                            b"secs" => Ok(Field::Secs),
2199                            b"nanos" => Ok(Field::Nanos),
2200                            _ => {
2201                                let value = crate::__private::from_utf8_lossy(value);
2202                                Err(Error::unknown_field(&*value, FIELDS))
2203                            }
2204                        }
2205                    }
2206                }
2207
2208                deserializer.deserialize_identifier(FieldVisitor)
2209            }
2210        }
2211
2212        fn check_overflow<E>(secs: u64, nanos: u32) -> Result<(), E>
2213        where
2214            E: Error,
2215        {
2216            static NANOS_PER_SEC: u32 = 1_000_000_000;
2217            match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
2218                Some(_) => Ok(()),
2219                None => Err(E::custom("overflow deserializing Duration")),
2220            }
2221        }
2222
2223        struct DurationVisitor;
2224
2225        impl<'de> Visitor<'de> for DurationVisitor {
2226            type Value = Duration;
2227
2228            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2229                formatter.write_str("struct Duration")
2230            }
2231
2232            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2233            where
2234                A: SeqAccess<'de>,
2235            {
2236                let secs: u64 = match tri!(seq.next_element()) {
2237                    Some(value) => value,
2238                    None => {
2239                        return Err(Error::invalid_length(0, &self));
2240                    }
2241                };
2242                let nanos: u32 = match tri!(seq.next_element()) {
2243                    Some(value) => value,
2244                    None => {
2245                        return Err(Error::invalid_length(1, &self));
2246                    }
2247                };
2248                tri!(check_overflow(secs, nanos));
2249                Ok(Duration::new(secs, nanos))
2250            }
2251
2252            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2253            where
2254                A: MapAccess<'de>,
2255            {
2256                let mut secs: Option<u64> = None;
2257                let mut nanos: Option<u32> = None;
2258                while let Some(key) = tri!(map.next_key()) {
2259                    match key {
2260                        Field::Secs => {
2261                            if secs.is_some() {
2262                                return Err(<A::Error as Error>::duplicate_field("secs"));
2263                            }
2264                            secs = Some(tri!(map.next_value()));
2265                        }
2266                        Field::Nanos => {
2267                            if nanos.is_some() {
2268                                return Err(<A::Error as Error>::duplicate_field("nanos"));
2269                            }
2270                            nanos = Some(tri!(map.next_value()));
2271                        }
2272                    }
2273                }
2274                let secs = match secs {
2275                    Some(secs) => secs,
2276                    None => return Err(<A::Error as Error>::missing_field("secs")),
2277                };
2278                let nanos = match nanos {
2279                    Some(nanos) => nanos,
2280                    None => return Err(<A::Error as Error>::missing_field("nanos")),
2281                };
2282                tri!(check_overflow(secs, nanos));
2283                Ok(Duration::new(secs, nanos))
2284            }
2285        }
2286
2287        const FIELDS: &[&str] = &["secs", "nanos"];
2288        deserializer.deserialize_struct("Duration", FIELDS, DurationVisitor)
2289    }
2290}
2291
2292////////////////////////////////////////////////////////////////////////////////
2293
2294#[cfg(feature = "std")]
2295#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2296impl<'de> Deserialize<'de> for SystemTime {
2297    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2298    where
2299        D: Deserializer<'de>,
2300    {
2301        // Reuse duration
2302        enum Field {
2303            Secs,
2304            Nanos,
2305        }
2306
2307        impl<'de> Deserialize<'de> for Field {
2308            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2309            where
2310                D: Deserializer<'de>,
2311            {
2312                struct FieldVisitor;
2313
2314                impl<'de> Visitor<'de> for FieldVisitor {
2315                    type Value = Field;
2316
2317                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2318                        formatter.write_str("`secs_since_epoch` or `nanos_since_epoch`")
2319                    }
2320
2321                    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2322                    where
2323                        E: Error,
2324                    {
2325                        match value {
2326                            "secs_since_epoch" => Ok(Field::Secs),
2327                            "nanos_since_epoch" => Ok(Field::Nanos),
2328                            _ => Err(Error::unknown_field(value, FIELDS)),
2329                        }
2330                    }
2331
2332                    fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2333                    where
2334                        E: Error,
2335                    {
2336                        match value {
2337                            b"secs_since_epoch" => Ok(Field::Secs),
2338                            b"nanos_since_epoch" => Ok(Field::Nanos),
2339                            _ => {
2340                                let value = String::from_utf8_lossy(value);
2341                                Err(Error::unknown_field(&value, FIELDS))
2342                            }
2343                        }
2344                    }
2345                }
2346
2347                deserializer.deserialize_identifier(FieldVisitor)
2348            }
2349        }
2350
2351        fn check_overflow<E>(secs: u64, nanos: u32) -> Result<(), E>
2352        where
2353            E: Error,
2354        {
2355            static NANOS_PER_SEC: u32 = 1_000_000_000;
2356            match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
2357                Some(_) => Ok(()),
2358                None => Err(E::custom("overflow deserializing SystemTime epoch offset")),
2359            }
2360        }
2361
2362        struct DurationVisitor;
2363
2364        impl<'de> Visitor<'de> for DurationVisitor {
2365            type Value = Duration;
2366
2367            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2368                formatter.write_str("struct SystemTime")
2369            }
2370
2371            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2372            where
2373                A: SeqAccess<'de>,
2374            {
2375                let secs: u64 = match tri!(seq.next_element()) {
2376                    Some(value) => value,
2377                    None => {
2378                        return Err(Error::invalid_length(0, &self));
2379                    }
2380                };
2381                let nanos: u32 = match tri!(seq.next_element()) {
2382                    Some(value) => value,
2383                    None => {
2384                        return Err(Error::invalid_length(1, &self));
2385                    }
2386                };
2387                tri!(check_overflow(secs, nanos));
2388                Ok(Duration::new(secs, nanos))
2389            }
2390
2391            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2392            where
2393                A: MapAccess<'de>,
2394            {
2395                let mut secs: Option<u64> = None;
2396                let mut nanos: Option<u32> = None;
2397                while let Some(key) = tri!(map.next_key()) {
2398                    match key {
2399                        Field::Secs => {
2400                            if secs.is_some() {
2401                                return Err(<A::Error as Error>::duplicate_field(
2402                                    "secs_since_epoch",
2403                                ));
2404                            }
2405                            secs = Some(tri!(map.next_value()));
2406                        }
2407                        Field::Nanos => {
2408                            if nanos.is_some() {
2409                                return Err(<A::Error as Error>::duplicate_field(
2410                                    "nanos_since_epoch",
2411                                ));
2412                            }
2413                            nanos = Some(tri!(map.next_value()));
2414                        }
2415                    }
2416                }
2417                let secs = match secs {
2418                    Some(secs) => secs,
2419                    None => return Err(<A::Error as Error>::missing_field("secs_since_epoch")),
2420                };
2421                let nanos = match nanos {
2422                    Some(nanos) => nanos,
2423                    None => return Err(<A::Error as Error>::missing_field("nanos_since_epoch")),
2424                };
2425                tri!(check_overflow(secs, nanos));
2426                Ok(Duration::new(secs, nanos))
2427            }
2428        }
2429
2430        const FIELDS: &[&str] = &["secs_since_epoch", "nanos_since_epoch"];
2431        let duration = tri!(deserializer.deserialize_struct("SystemTime", FIELDS, DurationVisitor));
2432        #[cfg(not(no_systemtime_checked_add))]
2433        let ret = UNIX_EPOCH
2434            .checked_add(duration)
2435            .ok_or_else(|| D::Error::custom("overflow deserializing SystemTime"));
2436        #[cfg(no_systemtime_checked_add)]
2437        let ret = Ok(UNIX_EPOCH + duration);
2438        ret
2439    }
2440}
2441
2442////////////////////////////////////////////////////////////////////////////////
2443
2444// Similar to:
2445//
2446//     #[derive(Deserialize)]
2447//     #[serde(deny_unknown_fields)]
2448//     struct Range<Idx> {
2449//         start: Idx,
2450//         end: Idx,
2451//     }
2452impl<'de, Idx> Deserialize<'de> for Range<Idx>
2453where
2454    Idx: Deserialize<'de>,
2455{
2456    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2457    where
2458        D: Deserializer<'de>,
2459    {
2460        let (start, end) = tri!(deserializer.deserialize_struct(
2461            "Range",
2462            range::FIELDS,
2463            range::RangeVisitor {
2464                expecting: "struct Range",
2465                phantom: PhantomData,
2466            },
2467        ));
2468        Ok(start..end)
2469    }
2470}
2471
2472impl<'de, Idx> Deserialize<'de> for RangeInclusive<Idx>
2473where
2474    Idx: Deserialize<'de>,
2475{
2476    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2477    where
2478        D: Deserializer<'de>,
2479    {
2480        let (start, end) = tri!(deserializer.deserialize_struct(
2481            "RangeInclusive",
2482            range::FIELDS,
2483            range::RangeVisitor {
2484                expecting: "struct RangeInclusive",
2485                phantom: PhantomData,
2486            },
2487        ));
2488        Ok(RangeInclusive::new(start, end))
2489    }
2490}
2491
2492mod range {
2493    use crate::lib::*;
2494
2495    use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor};
2496
2497    pub const FIELDS: &[&str] = &["start", "end"];
2498
2499    // If this were outside of the serde crate, it would just use:
2500    //
2501    //    #[derive(Deserialize)]
2502    //    #[serde(field_identifier, rename_all = "lowercase")]
2503    enum Field {
2504        Start,
2505        End,
2506    }
2507
2508    impl<'de> Deserialize<'de> for Field {
2509        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2510        where
2511            D: Deserializer<'de>,
2512        {
2513            struct FieldVisitor;
2514
2515            impl<'de> Visitor<'de> for FieldVisitor {
2516                type Value = Field;
2517
2518                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2519                    formatter.write_str("`start` or `end`")
2520                }
2521
2522                fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2523                where
2524                    E: Error,
2525                {
2526                    match value {
2527                        "start" => Ok(Field::Start),
2528                        "end" => Ok(Field::End),
2529                        _ => Err(Error::unknown_field(value, FIELDS)),
2530                    }
2531                }
2532
2533                fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2534                where
2535                    E: Error,
2536                {
2537                    match value {
2538                        b"start" => Ok(Field::Start),
2539                        b"end" => Ok(Field::End),
2540                        _ => {
2541                            let value = crate::__private::from_utf8_lossy(value);
2542                            Err(Error::unknown_field(&*value, FIELDS))
2543                        }
2544                    }
2545                }
2546            }
2547
2548            deserializer.deserialize_identifier(FieldVisitor)
2549        }
2550    }
2551
2552    pub struct RangeVisitor<Idx> {
2553        pub expecting: &'static str,
2554        pub phantom: PhantomData<Idx>,
2555    }
2556
2557    impl<'de, Idx> Visitor<'de> for RangeVisitor<Idx>
2558    where
2559        Idx: Deserialize<'de>,
2560    {
2561        type Value = (Idx, Idx);
2562
2563        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2564            formatter.write_str(self.expecting)
2565        }
2566
2567        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2568        where
2569            A: SeqAccess<'de>,
2570        {
2571            let start: Idx = match tri!(seq.next_element()) {
2572                Some(value) => value,
2573                None => {
2574                    return Err(Error::invalid_length(0, &self));
2575                }
2576            };
2577            let end: Idx = match tri!(seq.next_element()) {
2578                Some(value) => value,
2579                None => {
2580                    return Err(Error::invalid_length(1, &self));
2581                }
2582            };
2583            Ok((start, end))
2584        }
2585
2586        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2587        where
2588            A: MapAccess<'de>,
2589        {
2590            let mut start: Option<Idx> = None;
2591            let mut end: Option<Idx> = None;
2592            while let Some(key) = tri!(map.next_key()) {
2593                match key {
2594                    Field::Start => {
2595                        if start.is_some() {
2596                            return Err(<A::Error as Error>::duplicate_field("start"));
2597                        }
2598                        start = Some(tri!(map.next_value()));
2599                    }
2600                    Field::End => {
2601                        if end.is_some() {
2602                            return Err(<A::Error as Error>::duplicate_field("end"));
2603                        }
2604                        end = Some(tri!(map.next_value()));
2605                    }
2606                }
2607            }
2608            let start = match start {
2609                Some(start) => start,
2610                None => return Err(<A::Error as Error>::missing_field("start")),
2611            };
2612            let end = match end {
2613                Some(end) => end,
2614                None => return Err(<A::Error as Error>::missing_field("end")),
2615            };
2616            Ok((start, end))
2617        }
2618    }
2619}
2620
2621////////////////////////////////////////////////////////////////////////////////
2622
2623// Similar to:
2624//
2625//     #[derive(Deserialize)]
2626//     #[serde(deny_unknown_fields)]
2627//     struct RangeFrom<Idx> {
2628//         start: Idx,
2629//     }
2630impl<'de, Idx> Deserialize<'de> for RangeFrom<Idx>
2631where
2632    Idx: Deserialize<'de>,
2633{
2634    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2635    where
2636        D: Deserializer<'de>,
2637    {
2638        let start = tri!(deserializer.deserialize_struct(
2639            "RangeFrom",
2640            range_from::FIELDS,
2641            range_from::RangeFromVisitor {
2642                expecting: "struct RangeFrom",
2643                phantom: PhantomData,
2644            },
2645        ));
2646        Ok(start..)
2647    }
2648}
2649
2650mod range_from {
2651    use crate::lib::*;
2652
2653    use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor};
2654
2655    pub const FIELDS: &[&str] = &["start"];
2656
2657    // If this were outside of the serde crate, it would just use:
2658    //
2659    //    #[derive(Deserialize)]
2660    //    #[serde(field_identifier, rename_all = "lowercase")]
2661    enum Field {
2662        Start,
2663    }
2664
2665    impl<'de> Deserialize<'de> for Field {
2666        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2667        where
2668            D: Deserializer<'de>,
2669        {
2670            struct FieldVisitor;
2671
2672            impl<'de> Visitor<'de> for FieldVisitor {
2673                type Value = Field;
2674
2675                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2676                    formatter.write_str("`start`")
2677                }
2678
2679                fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2680                where
2681                    E: Error,
2682                {
2683                    match value {
2684                        "start" => Ok(Field::Start),
2685                        _ => Err(Error::unknown_field(value, FIELDS)),
2686                    }
2687                }
2688
2689                fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2690                where
2691                    E: Error,
2692                {
2693                    match value {
2694                        b"start" => Ok(Field::Start),
2695                        _ => {
2696                            let value = crate::__private::from_utf8_lossy(value);
2697                            Err(Error::unknown_field(&*value, FIELDS))
2698                        }
2699                    }
2700                }
2701            }
2702
2703            deserializer.deserialize_identifier(FieldVisitor)
2704        }
2705    }
2706
2707    pub struct RangeFromVisitor<Idx> {
2708        pub expecting: &'static str,
2709        pub phantom: PhantomData<Idx>,
2710    }
2711
2712    impl<'de, Idx> Visitor<'de> for RangeFromVisitor<Idx>
2713    where
2714        Idx: Deserialize<'de>,
2715    {
2716        type Value = Idx;
2717
2718        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2719            formatter.write_str(self.expecting)
2720        }
2721
2722        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2723        where
2724            A: SeqAccess<'de>,
2725        {
2726            let start: Idx = match tri!(seq.next_element()) {
2727                Some(value) => value,
2728                None => {
2729                    return Err(Error::invalid_length(0, &self));
2730                }
2731            };
2732            Ok(start)
2733        }
2734
2735        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2736        where
2737            A: MapAccess<'de>,
2738        {
2739            let mut start: Option<Idx> = None;
2740            while let Some(key) = tri!(map.next_key()) {
2741                match key {
2742                    Field::Start => {
2743                        if start.is_some() {
2744                            return Err(<A::Error as Error>::duplicate_field("start"));
2745                        }
2746                        start = Some(tri!(map.next_value()));
2747                    }
2748                }
2749            }
2750            let start = match start {
2751                Some(start) => start,
2752                None => return Err(<A::Error as Error>::missing_field("start")),
2753            };
2754            Ok(start)
2755        }
2756    }
2757}
2758
2759////////////////////////////////////////////////////////////////////////////////
2760
2761// Similar to:
2762//
2763//     #[derive(Deserialize)]
2764//     #[serde(deny_unknown_fields)]
2765//     struct RangeTo<Idx> {
2766//         end: Idx,
2767//     }
2768impl<'de, Idx> Deserialize<'de> for RangeTo<Idx>
2769where
2770    Idx: Deserialize<'de>,
2771{
2772    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2773    where
2774        D: Deserializer<'de>,
2775    {
2776        let end = tri!(deserializer.deserialize_struct(
2777            "RangeTo",
2778            range_to::FIELDS,
2779            range_to::RangeToVisitor {
2780                expecting: "struct RangeTo",
2781                phantom: PhantomData,
2782            },
2783        ));
2784        Ok(..end)
2785    }
2786}
2787
2788mod range_to {
2789    use crate::lib::*;
2790
2791    use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor};
2792
2793    pub const FIELDS: &[&str] = &["end"];
2794
2795    // If this were outside of the serde crate, it would just use:
2796    //
2797    //    #[derive(Deserialize)]
2798    //    #[serde(field_identifier, rename_all = "lowercase")]
2799    enum Field {
2800        End,
2801    }
2802
2803    impl<'de> Deserialize<'de> for Field {
2804        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2805        where
2806            D: Deserializer<'de>,
2807        {
2808            struct FieldVisitor;
2809
2810            impl<'de> Visitor<'de> for FieldVisitor {
2811                type Value = Field;
2812
2813                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2814                    formatter.write_str("`end`")
2815                }
2816
2817                fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2818                where
2819                    E: Error,
2820                {
2821                    match value {
2822                        "end" => Ok(Field::End),
2823                        _ => Err(Error::unknown_field(value, FIELDS)),
2824                    }
2825                }
2826
2827                fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2828                where
2829                    E: Error,
2830                {
2831                    match value {
2832                        b"end" => Ok(Field::End),
2833                        _ => {
2834                            let value = crate::__private::from_utf8_lossy(value);
2835                            Err(Error::unknown_field(&*value, FIELDS))
2836                        }
2837                    }
2838                }
2839            }
2840
2841            deserializer.deserialize_identifier(FieldVisitor)
2842        }
2843    }
2844
2845    pub struct RangeToVisitor<Idx> {
2846        pub expecting: &'static str,
2847        pub phantom: PhantomData<Idx>,
2848    }
2849
2850    impl<'de, Idx> Visitor<'de> for RangeToVisitor<Idx>
2851    where
2852        Idx: Deserialize<'de>,
2853    {
2854        type Value = Idx;
2855
2856        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2857            formatter.write_str(self.expecting)
2858        }
2859
2860        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2861        where
2862            A: SeqAccess<'de>,
2863        {
2864            let end: Idx = match tri!(seq.next_element()) {
2865                Some(value) => value,
2866                None => {
2867                    return Err(Error::invalid_length(0, &self));
2868                }
2869            };
2870            Ok(end)
2871        }
2872
2873        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2874        where
2875            A: MapAccess<'de>,
2876        {
2877            let mut end: Option<Idx> = None;
2878            while let Some(key) = tri!(map.next_key()) {
2879                match key {
2880                    Field::End => {
2881                        if end.is_some() {
2882                            return Err(<A::Error as Error>::duplicate_field("end"));
2883                        }
2884                        end = Some(tri!(map.next_value()));
2885                    }
2886                }
2887            }
2888            let end = match end {
2889                Some(end) => end,
2890                None => return Err(<A::Error as Error>::missing_field("end")),
2891            };
2892            Ok(end)
2893        }
2894    }
2895}
2896
2897////////////////////////////////////////////////////////////////////////////////
2898
2899impl<'de, T> Deserialize<'de> for Bound<T>
2900where
2901    T: Deserialize<'de>,
2902{
2903    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2904    where
2905        D: Deserializer<'de>,
2906    {
2907        enum Field {
2908            Unbounded,
2909            Included,
2910            Excluded,
2911        }
2912
2913        impl<'de> Deserialize<'de> for Field {
2914            #[inline]
2915            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2916            where
2917                D: Deserializer<'de>,
2918            {
2919                struct FieldVisitor;
2920
2921                impl<'de> Visitor<'de> for FieldVisitor {
2922                    type Value = Field;
2923
2924                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2925                        formatter.write_str("`Unbounded`, `Included` or `Excluded`")
2926                    }
2927
2928                    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
2929                    where
2930                        E: Error,
2931                    {
2932                        match value {
2933                            0 => Ok(Field::Unbounded),
2934                            1 => Ok(Field::Included),
2935                            2 => Ok(Field::Excluded),
2936                            _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self)),
2937                        }
2938                    }
2939
2940                    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2941                    where
2942                        E: Error,
2943                    {
2944                        match value {
2945                            "Unbounded" => Ok(Field::Unbounded),
2946                            "Included" => Ok(Field::Included),
2947                            "Excluded" => Ok(Field::Excluded),
2948                            _ => Err(Error::unknown_variant(value, VARIANTS)),
2949                        }
2950                    }
2951
2952                    fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2953                    where
2954                        E: Error,
2955                    {
2956                        match value {
2957                            b"Unbounded" => Ok(Field::Unbounded),
2958                            b"Included" => Ok(Field::Included),
2959                            b"Excluded" => Ok(Field::Excluded),
2960                            _ => match str::from_utf8(value) {
2961                                Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
2962                                Err(_) => {
2963                                    Err(Error::invalid_value(Unexpected::Bytes(value), &self))
2964                                }
2965                            },
2966                        }
2967                    }
2968                }
2969
2970                deserializer.deserialize_identifier(FieldVisitor)
2971            }
2972        }
2973
2974        struct BoundVisitor<T>(PhantomData<Bound<T>>);
2975
2976        impl<'de, T> Visitor<'de> for BoundVisitor<T>
2977        where
2978            T: Deserialize<'de>,
2979        {
2980            type Value = Bound<T>;
2981
2982            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2983                formatter.write_str("enum Bound")
2984            }
2985
2986            fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
2987            where
2988                A: EnumAccess<'de>,
2989            {
2990                match tri!(data.variant()) {
2991                    (Field::Unbounded, v) => v.unit_variant().map(|()| Bound::Unbounded),
2992                    (Field::Included, v) => v.newtype_variant().map(Bound::Included),
2993                    (Field::Excluded, v) => v.newtype_variant().map(Bound::Excluded),
2994                }
2995            }
2996        }
2997
2998        const VARIANTS: &[&str] = &["Unbounded", "Included", "Excluded"];
2999
3000        deserializer.deserialize_enum("Bound", VARIANTS, BoundVisitor(PhantomData))
3001    }
3002}
3003
3004////////////////////////////////////////////////////////////////////////////////
3005
3006impl<'de, T, E> Deserialize<'de> for Result<T, E>
3007where
3008    T: Deserialize<'de>,
3009    E: Deserialize<'de>,
3010{
3011    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3012    where
3013        D: Deserializer<'de>,
3014    {
3015        // If this were outside of the serde crate, it would just use:
3016        //
3017        //    #[derive(Deserialize)]
3018        //    #[serde(variant_identifier)]
3019        enum Field {
3020            Ok,
3021            Err,
3022        }
3023
3024        impl<'de> Deserialize<'de> for Field {
3025            #[inline]
3026            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3027            where
3028                D: Deserializer<'de>,
3029            {
3030                struct FieldVisitor;
3031
3032                impl<'de> Visitor<'de> for FieldVisitor {
3033                    type Value = Field;
3034
3035                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3036                        formatter.write_str("`Ok` or `Err`")
3037                    }
3038
3039                    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
3040                    where
3041                        E: Error,
3042                    {
3043                        match value {
3044                            0 => Ok(Field::Ok),
3045                            1 => Ok(Field::Err),
3046                            _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self)),
3047                        }
3048                    }
3049
3050                    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
3051                    where
3052                        E: Error,
3053                    {
3054                        match value {
3055                            "Ok" => Ok(Field::Ok),
3056                            "Err" => Ok(Field::Err),
3057                            _ => Err(Error::unknown_variant(value, VARIANTS)),
3058                        }
3059                    }
3060
3061                    fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
3062                    where
3063                        E: Error,
3064                    {
3065                        match value {
3066                            b"Ok" => Ok(Field::Ok),
3067                            b"Err" => Ok(Field::Err),
3068                            _ => match str::from_utf8(value) {
3069                                Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
3070                                Err(_) => {
3071                                    Err(Error::invalid_value(Unexpected::Bytes(value), &self))
3072                                }
3073                            },
3074                        }
3075                    }
3076                }
3077
3078                deserializer.deserialize_identifier(FieldVisitor)
3079            }
3080        }
3081
3082        struct ResultVisitor<T, E>(PhantomData<Result<T, E>>);
3083
3084        impl<'de, T, E> Visitor<'de> for ResultVisitor<T, E>
3085        where
3086            T: Deserialize<'de>,
3087            E: Deserialize<'de>,
3088        {
3089            type Value = Result<T, E>;
3090
3091            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3092                formatter.write_str("enum Result")
3093            }
3094
3095            fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
3096            where
3097                A: EnumAccess<'de>,
3098            {
3099                match tri!(data.variant()) {
3100                    (Field::Ok, v) => v.newtype_variant().map(Ok),
3101                    (Field::Err, v) => v.newtype_variant().map(Err),
3102                }
3103            }
3104        }
3105
3106        const VARIANTS: &[&str] = &["Ok", "Err"];
3107
3108        deserializer.deserialize_enum("Result", VARIANTS, ResultVisitor(PhantomData))
3109    }
3110}
3111
3112////////////////////////////////////////////////////////////////////////////////
3113
3114impl<'de, T> Deserialize<'de> for Wrapping<T>
3115where
3116    T: Deserialize<'de>,
3117{
3118    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3119    where
3120        D: Deserializer<'de>,
3121    {
3122        Deserialize::deserialize(deserializer).map(Wrapping)
3123    }
3124}
3125
3126#[cfg(all(feature = "std", not(no_std_atomic)))]
3127macro_rules! atomic_impl {
3128    ($($ty:ident $size:expr)*) => {
3129        $(
3130            #[cfg(any(no_target_has_atomic, target_has_atomic = $size))]
3131            #[cfg_attr(docsrs, doc(cfg(all(feature = "std", target_has_atomic = $size))))]
3132            impl<'de> Deserialize<'de> for $ty {
3133                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3134                where
3135                    D: Deserializer<'de>,
3136                {
3137                    Deserialize::deserialize(deserializer).map(Self::new)
3138                }
3139            }
3140        )*
3141    };
3142}
3143
3144#[cfg(all(feature = "std", not(no_std_atomic)))]
3145atomic_impl! {
3146    AtomicBool "8"
3147    AtomicI8 "8"
3148    AtomicI16 "16"
3149    AtomicI32 "32"
3150    AtomicIsize "ptr"
3151    AtomicU8 "8"
3152    AtomicU16 "16"
3153    AtomicU32 "32"
3154    AtomicUsize "ptr"
3155}
3156
3157#[cfg(all(feature = "std", not(no_std_atomic64)))]
3158atomic_impl! {
3159    AtomicI64 "64"
3160    AtomicU64 "64"
3161}
3162
3163#[cfg(feature = "std")]
3164struct FromStrVisitor<T> {
3165    expecting: &'static str,
3166    ty: PhantomData<T>,
3167}
3168
3169#[cfg(feature = "std")]
3170impl<T> FromStrVisitor<T> {
3171    fn new(expecting: &'static str) -> Self {
3172        FromStrVisitor {
3173            expecting,
3174            ty: PhantomData,
3175        }
3176    }
3177}
3178
3179#[cfg(feature = "std")]
3180impl<'de, T> Visitor<'de> for FromStrVisitor<T>
3181where
3182    T: str::FromStr,
3183    T::Err: fmt::Display,
3184{
3185    type Value = T;
3186
3187    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3188        formatter.write_str(self.expecting)
3189    }
3190
3191    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
3192    where
3193        E: Error,
3194    {
3195        s.parse().map_err(Error::custom)
3196    }
3197}