serde/private/
de.rs

1use crate::lib::*;
2
3use crate::de::value::{BorrowedBytesDeserializer, BytesDeserializer};
4use crate::de::{
5    Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error, IntoDeserializer, VariantAccess,
6    Visitor,
7};
8
9#[cfg(any(feature = "std", feature = "alloc"))]
10use crate::de::{MapAccess, Unexpected};
11
12#[cfg(any(feature = "std", feature = "alloc"))]
13pub use self::content::{
14    Content, ContentDeserializer, ContentRefDeserializer, EnumDeserializer,
15    InternallyTaggedUnitVisitor, TagContentOtherField, TagContentOtherFieldVisitor,
16    TagOrContentField, TagOrContentFieldVisitor, TaggedContentVisitor, UntaggedUnitVisitor,
17};
18
19pub use crate::seed::InPlaceSeed;
20
21/// If the missing field is of type `Option<T>` then treat is as `None`,
22/// otherwise it is an error.
23pub fn missing_field<'de, V, E>(field: &'static str) -> Result<V, E>
24where
25    V: Deserialize<'de>,
26    E: Error,
27{
28    struct MissingFieldDeserializer<E>(&'static str, PhantomData<E>);
29
30    impl<'de, E> Deserializer<'de> for MissingFieldDeserializer<E>
31    where
32        E: Error,
33    {
34        type Error = E;
35
36        fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, E>
37        where
38            V: Visitor<'de>,
39        {
40            Err(Error::missing_field(self.0))
41        }
42
43        fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E>
44        where
45            V: Visitor<'de>,
46        {
47            visitor.visit_none()
48        }
49
50        forward_to_deserialize_any! {
51            bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
52            bytes byte_buf unit unit_struct newtype_struct seq tuple
53            tuple_struct map struct enum identifier ignored_any
54        }
55    }
56
57    let deserializer = MissingFieldDeserializer(field, PhantomData);
58    Deserialize::deserialize(deserializer)
59}
60
61#[cfg(any(feature = "std", feature = "alloc"))]
62pub fn borrow_cow_str<'de: 'a, 'a, D, R>(deserializer: D) -> Result<R, D::Error>
63where
64    D: Deserializer<'de>,
65    R: From<Cow<'a, str>>,
66{
67    struct CowStrVisitor;
68
69    impl<'a> Visitor<'a> for CowStrVisitor {
70        type Value = Cow<'a, str>;
71
72        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
73            formatter.write_str("a string")
74        }
75
76        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
77        where
78            E: Error,
79        {
80            Ok(Cow::Owned(v.to_owned()))
81        }
82
83        fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
84        where
85            E: Error,
86        {
87            Ok(Cow::Borrowed(v))
88        }
89
90        fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
91        where
92            E: Error,
93        {
94            Ok(Cow::Owned(v))
95        }
96
97        fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
98        where
99            E: Error,
100        {
101            match str::from_utf8(v) {
102                Ok(s) => Ok(Cow::Owned(s.to_owned())),
103                Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
104            }
105        }
106
107        fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
108        where
109            E: Error,
110        {
111            match str::from_utf8(v) {
112                Ok(s) => Ok(Cow::Borrowed(s)),
113                Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
114            }
115        }
116
117        fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
118        where
119            E: Error,
120        {
121            match String::from_utf8(v) {
122                Ok(s) => Ok(Cow::Owned(s)),
123                Err(e) => Err(Error::invalid_value(
124                    Unexpected::Bytes(&e.into_bytes()),
125                    &self,
126                )),
127            }
128        }
129    }
130
131    deserializer.deserialize_str(CowStrVisitor).map(From::from)
132}
133
134#[cfg(any(feature = "std", feature = "alloc"))]
135pub fn borrow_cow_bytes<'de: 'a, 'a, D, R>(deserializer: D) -> Result<R, D::Error>
136where
137    D: Deserializer<'de>,
138    R: From<Cow<'a, [u8]>>,
139{
140    struct CowBytesVisitor;
141
142    impl<'a> Visitor<'a> for CowBytesVisitor {
143        type Value = Cow<'a, [u8]>;
144
145        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
146            formatter.write_str("a byte array")
147        }
148
149        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
150        where
151            E: Error,
152        {
153            Ok(Cow::Owned(v.as_bytes().to_vec()))
154        }
155
156        fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
157        where
158            E: Error,
159        {
160            Ok(Cow::Borrowed(v.as_bytes()))
161        }
162
163        fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
164        where
165            E: Error,
166        {
167            Ok(Cow::Owned(v.into_bytes()))
168        }
169
170        fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
171        where
172            E: Error,
173        {
174            Ok(Cow::Owned(v.to_vec()))
175        }
176
177        fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
178        where
179            E: Error,
180        {
181            Ok(Cow::Borrowed(v))
182        }
183
184        fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
185        where
186            E: Error,
187        {
188            Ok(Cow::Owned(v))
189        }
190    }
191
192    deserializer
193        .deserialize_bytes(CowBytesVisitor)
194        .map(From::from)
195}
196
197#[cfg(any(feature = "std", feature = "alloc"))]
198mod content {
199    // This module is private and nothing here should be used outside of
200    // generated code.
201    //
202    // We will iterate on the implementation for a few releases and only have to
203    // worry about backward compatibility for the `untagged` and `tag` attributes
204    // rather than for this entire mechanism.
205    //
206    // This issue is tracking making some of this stuff public:
207    // https://github.com/serde-rs/serde/issues/741
208
209    use crate::lib::*;
210
211    use crate::actually_private;
212    use crate::de::value::{MapDeserializer, SeqDeserializer};
213    use crate::de::{
214        self, size_hint, Deserialize, DeserializeSeed, Deserializer, EnumAccess, Expected,
215        IgnoredAny, MapAccess, SeqAccess, Unexpected, Visitor,
216    };
217
218    /// Used from generated code to buffer the contents of the Deserializer when
219    /// deserializing untagged enums and internally tagged enums.
220    ///
221    /// Not public API. Use serde-value instead.
222    #[derive(Debug, Clone)]
223    pub enum Content<'de> {
224        Bool(bool),
225
226        U8(u8),
227        U16(u16),
228        U32(u32),
229        U64(u64),
230
231        I8(i8),
232        I16(i16),
233        I32(i32),
234        I64(i64),
235
236        F32(f32),
237        F64(f64),
238
239        Char(char),
240        String(String),
241        Str(&'de str),
242        ByteBuf(Vec<u8>),
243        Bytes(&'de [u8]),
244
245        None,
246        Some(Box<Content<'de>>),
247
248        Unit,
249        Newtype(Box<Content<'de>>),
250        Seq(Vec<Content<'de>>),
251        Map(Vec<(Content<'de>, Content<'de>)>),
252    }
253
254    impl<'de> Content<'de> {
255        pub fn as_str(&self) -> Option<&str> {
256            match *self {
257                Content::Str(x) => Some(x),
258                Content::String(ref x) => Some(x),
259                Content::Bytes(x) => str::from_utf8(x).ok(),
260                Content::ByteBuf(ref x) => str::from_utf8(x).ok(),
261                _ => None,
262            }
263        }
264
265        #[cold]
266        fn unexpected(&self) -> Unexpected {
267            match *self {
268                Content::Bool(b) => Unexpected::Bool(b),
269                Content::U8(n) => Unexpected::Unsigned(n as u64),
270                Content::U16(n) => Unexpected::Unsigned(n as u64),
271                Content::U32(n) => Unexpected::Unsigned(n as u64),
272                Content::U64(n) => Unexpected::Unsigned(n),
273                Content::I8(n) => Unexpected::Signed(n as i64),
274                Content::I16(n) => Unexpected::Signed(n as i64),
275                Content::I32(n) => Unexpected::Signed(n as i64),
276                Content::I64(n) => Unexpected::Signed(n),
277                Content::F32(f) => Unexpected::Float(f as f64),
278                Content::F64(f) => Unexpected::Float(f),
279                Content::Char(c) => Unexpected::Char(c),
280                Content::String(ref s) => Unexpected::Str(s),
281                Content::Str(s) => Unexpected::Str(s),
282                Content::ByteBuf(ref b) => Unexpected::Bytes(b),
283                Content::Bytes(b) => Unexpected::Bytes(b),
284                Content::None | Content::Some(_) => Unexpected::Option,
285                Content::Unit => Unexpected::Unit,
286                Content::Newtype(_) => Unexpected::NewtypeStruct,
287                Content::Seq(_) => Unexpected::Seq,
288                Content::Map(_) => Unexpected::Map,
289            }
290        }
291    }
292
293    impl<'de> Deserialize<'de> for Content<'de> {
294        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
295        where
296            D: Deserializer<'de>,
297        {
298            // Untagged and internally tagged enums are only supported in
299            // self-describing formats.
300            let visitor = ContentVisitor { value: PhantomData };
301            deserializer.__deserialize_content(actually_private::T, visitor)
302        }
303    }
304
305    impl<'de, E> de::IntoDeserializer<'de, E> for Content<'de>
306    where
307        E: de::Error,
308    {
309        type Deserializer = ContentDeserializer<'de, E>;
310
311        fn into_deserializer(self) -> Self::Deserializer {
312            ContentDeserializer::new(self)
313        }
314    }
315
316    /// Used to capture data in [`Content`] from other deserializers.
317    /// Cannot capture externally tagged enums, `i128` and `u128`.
318    struct ContentVisitor<'de> {
319        value: PhantomData<Content<'de>>,
320    }
321
322    impl<'de> ContentVisitor<'de> {
323        fn new() -> Self {
324            ContentVisitor { value: PhantomData }
325        }
326    }
327
328    impl<'de> Visitor<'de> for ContentVisitor<'de> {
329        type Value = Content<'de>;
330
331        fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
332            fmt.write_str("any value")
333        }
334
335        fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
336        where
337            F: de::Error,
338        {
339            Ok(Content::Bool(value))
340        }
341
342        fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
343        where
344            F: de::Error,
345        {
346            Ok(Content::I8(value))
347        }
348
349        fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
350        where
351            F: de::Error,
352        {
353            Ok(Content::I16(value))
354        }
355
356        fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
357        where
358            F: de::Error,
359        {
360            Ok(Content::I32(value))
361        }
362
363        fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
364        where
365            F: de::Error,
366        {
367            Ok(Content::I64(value))
368        }
369
370        fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
371        where
372            F: de::Error,
373        {
374            Ok(Content::U8(value))
375        }
376
377        fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
378        where
379            F: de::Error,
380        {
381            Ok(Content::U16(value))
382        }
383
384        fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
385        where
386            F: de::Error,
387        {
388            Ok(Content::U32(value))
389        }
390
391        fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
392        where
393            F: de::Error,
394        {
395            Ok(Content::U64(value))
396        }
397
398        fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
399        where
400            F: de::Error,
401        {
402            Ok(Content::F32(value))
403        }
404
405        fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
406        where
407            F: de::Error,
408        {
409            Ok(Content::F64(value))
410        }
411
412        fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
413        where
414            F: de::Error,
415        {
416            Ok(Content::Char(value))
417        }
418
419        fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
420        where
421            F: de::Error,
422        {
423            Ok(Content::String(value.into()))
424        }
425
426        fn visit_borrowed_str<F>(self, value: &'de str) -> Result<Self::Value, F>
427        where
428            F: de::Error,
429        {
430            Ok(Content::Str(value))
431        }
432
433        fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
434        where
435            F: de::Error,
436        {
437            Ok(Content::String(value))
438        }
439
440        fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
441        where
442            F: de::Error,
443        {
444            Ok(Content::ByteBuf(value.into()))
445        }
446
447        fn visit_borrowed_bytes<F>(self, value: &'de [u8]) -> Result<Self::Value, F>
448        where
449            F: de::Error,
450        {
451            Ok(Content::Bytes(value))
452        }
453
454        fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
455        where
456            F: de::Error,
457        {
458            Ok(Content::ByteBuf(value))
459        }
460
461        fn visit_unit<F>(self) -> Result<Self::Value, F>
462        where
463            F: de::Error,
464        {
465            Ok(Content::Unit)
466        }
467
468        fn visit_none<F>(self) -> Result<Self::Value, F>
469        where
470            F: de::Error,
471        {
472            Ok(Content::None)
473        }
474
475        fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
476        where
477            D: Deserializer<'de>,
478        {
479            Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v)))
480        }
481
482        fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
483        where
484            D: Deserializer<'de>,
485        {
486            Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v)))
487        }
488
489        fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
490        where
491            V: SeqAccess<'de>,
492        {
493            let mut vec =
494                Vec::<Content>::with_capacity(size_hint::cautious::<Content>(visitor.size_hint()));
495            while let Some(e) = tri!(visitor.next_element()) {
496                vec.push(e);
497            }
498            Ok(Content::Seq(vec))
499        }
500
501        fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
502        where
503            V: MapAccess<'de>,
504        {
505            let mut vec =
506                Vec::<(Content, Content)>::with_capacity(
507                    size_hint::cautious::<(Content, Content)>(visitor.size_hint()),
508                );
509            while let Some(kv) = tri!(visitor.next_entry()) {
510                vec.push(kv);
511            }
512            Ok(Content::Map(vec))
513        }
514
515        fn visit_enum<V>(self, _visitor: V) -> Result<Self::Value, V::Error>
516        where
517            V: EnumAccess<'de>,
518        {
519            Err(de::Error::custom(
520                "untagged and internally tagged enums do not support enum input",
521            ))
522        }
523    }
524
525    /// This is the type of the map keys in an internally tagged enum.
526    ///
527    /// Not public API.
528    pub enum TagOrContent<'de> {
529        Tag,
530        Content(Content<'de>),
531    }
532
533    /// Serves as a seed for deserializing a key of internally tagged enum.
534    /// Cannot capture externally tagged enums, `i128` and `u128`.
535    struct TagOrContentVisitor<'de> {
536        name: &'static str,
537        value: PhantomData<TagOrContent<'de>>,
538    }
539
540    impl<'de> TagOrContentVisitor<'de> {
541        fn new(name: &'static str) -> Self {
542            TagOrContentVisitor {
543                name,
544                value: PhantomData,
545            }
546        }
547    }
548
549    impl<'de> DeserializeSeed<'de> for TagOrContentVisitor<'de> {
550        type Value = TagOrContent<'de>;
551
552        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
553        where
554            D: Deserializer<'de>,
555        {
556            // Internally tagged enums are only supported in self-describing
557            // formats.
558            deserializer.deserialize_any(self)
559        }
560    }
561
562    impl<'de> Visitor<'de> for TagOrContentVisitor<'de> {
563        type Value = TagOrContent<'de>;
564
565        fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
566            write!(fmt, "a type tag `{}` or any other value", self.name)
567        }
568
569        fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
570        where
571            F: de::Error,
572        {
573            ContentVisitor::new()
574                .visit_bool(value)
575                .map(TagOrContent::Content)
576        }
577
578        fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
579        where
580            F: de::Error,
581        {
582            ContentVisitor::new()
583                .visit_i8(value)
584                .map(TagOrContent::Content)
585        }
586
587        fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
588        where
589            F: de::Error,
590        {
591            ContentVisitor::new()
592                .visit_i16(value)
593                .map(TagOrContent::Content)
594        }
595
596        fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
597        where
598            F: de::Error,
599        {
600            ContentVisitor::new()
601                .visit_i32(value)
602                .map(TagOrContent::Content)
603        }
604
605        fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
606        where
607            F: de::Error,
608        {
609            ContentVisitor::new()
610                .visit_i64(value)
611                .map(TagOrContent::Content)
612        }
613
614        fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
615        where
616            F: de::Error,
617        {
618            ContentVisitor::new()
619                .visit_u8(value)
620                .map(TagOrContent::Content)
621        }
622
623        fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
624        where
625            F: de::Error,
626        {
627            ContentVisitor::new()
628                .visit_u16(value)
629                .map(TagOrContent::Content)
630        }
631
632        fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
633        where
634            F: de::Error,
635        {
636            ContentVisitor::new()
637                .visit_u32(value)
638                .map(TagOrContent::Content)
639        }
640
641        fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
642        where
643            F: de::Error,
644        {
645            ContentVisitor::new()
646                .visit_u64(value)
647                .map(TagOrContent::Content)
648        }
649
650        fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
651        where
652            F: de::Error,
653        {
654            ContentVisitor::new()
655                .visit_f32(value)
656                .map(TagOrContent::Content)
657        }
658
659        fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
660        where
661            F: de::Error,
662        {
663            ContentVisitor::new()
664                .visit_f64(value)
665                .map(TagOrContent::Content)
666        }
667
668        fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
669        where
670            F: de::Error,
671        {
672            ContentVisitor::new()
673                .visit_char(value)
674                .map(TagOrContent::Content)
675        }
676
677        fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
678        where
679            F: de::Error,
680        {
681            if value == self.name {
682                Ok(TagOrContent::Tag)
683            } else {
684                ContentVisitor::new()
685                    .visit_str(value)
686                    .map(TagOrContent::Content)
687            }
688        }
689
690        fn visit_borrowed_str<F>(self, value: &'de str) -> Result<Self::Value, F>
691        where
692            F: de::Error,
693        {
694            if value == self.name {
695                Ok(TagOrContent::Tag)
696            } else {
697                ContentVisitor::new()
698                    .visit_borrowed_str(value)
699                    .map(TagOrContent::Content)
700            }
701        }
702
703        fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
704        where
705            F: de::Error,
706        {
707            if value == self.name {
708                Ok(TagOrContent::Tag)
709            } else {
710                ContentVisitor::new()
711                    .visit_string(value)
712                    .map(TagOrContent::Content)
713            }
714        }
715
716        fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
717        where
718            F: de::Error,
719        {
720            if value == self.name.as_bytes() {
721                Ok(TagOrContent::Tag)
722            } else {
723                ContentVisitor::new()
724                    .visit_bytes(value)
725                    .map(TagOrContent::Content)
726            }
727        }
728
729        fn visit_borrowed_bytes<F>(self, value: &'de [u8]) -> Result<Self::Value, F>
730        where
731            F: de::Error,
732        {
733            if value == self.name.as_bytes() {
734                Ok(TagOrContent::Tag)
735            } else {
736                ContentVisitor::new()
737                    .visit_borrowed_bytes(value)
738                    .map(TagOrContent::Content)
739            }
740        }
741
742        fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
743        where
744            F: de::Error,
745        {
746            if value == self.name.as_bytes() {
747                Ok(TagOrContent::Tag)
748            } else {
749                ContentVisitor::new()
750                    .visit_byte_buf(value)
751                    .map(TagOrContent::Content)
752            }
753        }
754
755        fn visit_unit<F>(self) -> Result<Self::Value, F>
756        where
757            F: de::Error,
758        {
759            ContentVisitor::new()
760                .visit_unit()
761                .map(TagOrContent::Content)
762        }
763
764        fn visit_none<F>(self) -> Result<Self::Value, F>
765        where
766            F: de::Error,
767        {
768            ContentVisitor::new()
769                .visit_none()
770                .map(TagOrContent::Content)
771        }
772
773        fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
774        where
775            D: Deserializer<'de>,
776        {
777            ContentVisitor::new()
778                .visit_some(deserializer)
779                .map(TagOrContent::Content)
780        }
781
782        fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
783        where
784            D: Deserializer<'de>,
785        {
786            ContentVisitor::new()
787                .visit_newtype_struct(deserializer)
788                .map(TagOrContent::Content)
789        }
790
791        fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
792        where
793            V: SeqAccess<'de>,
794        {
795            ContentVisitor::new()
796                .visit_seq(visitor)
797                .map(TagOrContent::Content)
798        }
799
800        fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
801        where
802            V: MapAccess<'de>,
803        {
804            ContentVisitor::new()
805                .visit_map(visitor)
806                .map(TagOrContent::Content)
807        }
808
809        fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
810        where
811            V: EnumAccess<'de>,
812        {
813            ContentVisitor::new()
814                .visit_enum(visitor)
815                .map(TagOrContent::Content)
816        }
817    }
818
819    /// Used by generated code to deserialize an internally tagged enum.
820    ///
821    /// Captures map or sequence from the original deserializer and searches
822    /// a tag in it (in case of sequence, tag is the first element of sequence).
823    ///
824    /// Not public API.
825    pub struct TaggedContentVisitor<T> {
826        tag_name: &'static str,
827        expecting: &'static str,
828        value: PhantomData<T>,
829    }
830
831    impl<T> TaggedContentVisitor<T> {
832        /// Visitor for the content of an internally tagged enum with the given
833        /// tag name.
834        pub fn new(name: &'static str, expecting: &'static str) -> Self {
835            TaggedContentVisitor {
836                tag_name: name,
837                expecting,
838                value: PhantomData,
839            }
840        }
841    }
842
843    impl<'de, T> Visitor<'de> for TaggedContentVisitor<T>
844    where
845        T: Deserialize<'de>,
846    {
847        type Value = (T, Content<'de>);
848
849        fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
850            fmt.write_str(self.expecting)
851        }
852
853        fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
854        where
855            S: SeqAccess<'de>,
856        {
857            let tag = match tri!(seq.next_element()) {
858                Some(tag) => tag,
859                None => {
860                    return Err(de::Error::missing_field(self.tag_name));
861                }
862            };
863            let rest = de::value::SeqAccessDeserializer::new(seq);
864            Ok((tag, tri!(Content::deserialize(rest))))
865        }
866
867        fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
868        where
869            M: MapAccess<'de>,
870        {
871            let mut tag = None;
872            let mut vec = Vec::<(Content, Content)>::with_capacity(size_hint::cautious::<(
873                Content,
874                Content,
875            )>(map.size_hint()));
876            while let Some(k) = tri!(map.next_key_seed(TagOrContentVisitor::new(self.tag_name))) {
877                match k {
878                    TagOrContent::Tag => {
879                        if tag.is_some() {
880                            return Err(de::Error::duplicate_field(self.tag_name));
881                        }
882                        tag = Some(tri!(map.next_value()));
883                    }
884                    TagOrContent::Content(k) => {
885                        let v = tri!(map.next_value());
886                        vec.push((k, v));
887                    }
888                }
889            }
890            match tag {
891                None => Err(de::Error::missing_field(self.tag_name)),
892                Some(tag) => Ok((tag, Content::Map(vec))),
893            }
894        }
895    }
896
897    /// Used by generated code to deserialize an adjacently tagged enum.
898    ///
899    /// Not public API.
900    pub enum TagOrContentField {
901        Tag,
902        Content,
903    }
904
905    /// Not public API.
906    pub struct TagOrContentFieldVisitor {
907        pub tag: &'static str,
908        pub content: &'static str,
909    }
910
911    impl<'de> DeserializeSeed<'de> for TagOrContentFieldVisitor {
912        type Value = TagOrContentField;
913
914        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
915        where
916            D: Deserializer<'de>,
917        {
918            deserializer.deserialize_identifier(self)
919        }
920    }
921
922    impl<'de> Visitor<'de> for TagOrContentFieldVisitor {
923        type Value = TagOrContentField;
924
925        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
926            write!(formatter, "{:?} or {:?}", self.tag, self.content)
927        }
928
929        fn visit_u64<E>(self, field_index: u64) -> Result<Self::Value, E>
930        where
931            E: de::Error,
932        {
933            match field_index {
934                0 => Ok(TagOrContentField::Tag),
935                1 => Ok(TagOrContentField::Content),
936                _ => Err(de::Error::invalid_value(
937                    Unexpected::Unsigned(field_index),
938                    &self,
939                )),
940            }
941        }
942
943        fn visit_str<E>(self, field: &str) -> Result<Self::Value, E>
944        where
945            E: de::Error,
946        {
947            if field == self.tag {
948                Ok(TagOrContentField::Tag)
949            } else if field == self.content {
950                Ok(TagOrContentField::Content)
951            } else {
952                Err(de::Error::invalid_value(Unexpected::Str(field), &self))
953            }
954        }
955
956        fn visit_bytes<E>(self, field: &[u8]) -> Result<Self::Value, E>
957        where
958            E: de::Error,
959        {
960            if field == self.tag.as_bytes() {
961                Ok(TagOrContentField::Tag)
962            } else if field == self.content.as_bytes() {
963                Ok(TagOrContentField::Content)
964            } else {
965                Err(de::Error::invalid_value(Unexpected::Bytes(field), &self))
966            }
967        }
968    }
969
970    /// Used by generated code to deserialize an adjacently tagged enum when
971    /// ignoring unrelated fields is allowed.
972    ///
973    /// Not public API.
974    pub enum TagContentOtherField {
975        Tag,
976        Content,
977        Other,
978    }
979
980    /// Not public API.
981    pub struct TagContentOtherFieldVisitor {
982        pub tag: &'static str,
983        pub content: &'static str,
984    }
985
986    impl<'de> DeserializeSeed<'de> for TagContentOtherFieldVisitor {
987        type Value = TagContentOtherField;
988
989        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
990        where
991            D: Deserializer<'de>,
992        {
993            deserializer.deserialize_identifier(self)
994        }
995    }
996
997    impl<'de> Visitor<'de> for TagContentOtherFieldVisitor {
998        type Value = TagContentOtherField;
999
1000        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1001            write!(
1002                formatter,
1003                "{:?}, {:?}, or other ignored fields",
1004                self.tag, self.content
1005            )
1006        }
1007
1008        fn visit_u64<E>(self, field_index: u64) -> Result<Self::Value, E>
1009        where
1010            E: de::Error,
1011        {
1012            match field_index {
1013                0 => Ok(TagContentOtherField::Tag),
1014                1 => Ok(TagContentOtherField::Content),
1015                _ => Ok(TagContentOtherField::Other),
1016            }
1017        }
1018
1019        fn visit_str<E>(self, field: &str) -> Result<Self::Value, E>
1020        where
1021            E: de::Error,
1022        {
1023            self.visit_bytes(field.as_bytes())
1024        }
1025
1026        fn visit_bytes<E>(self, field: &[u8]) -> Result<Self::Value, E>
1027        where
1028            E: de::Error,
1029        {
1030            if field == self.tag.as_bytes() {
1031                Ok(TagContentOtherField::Tag)
1032            } else if field == self.content.as_bytes() {
1033                Ok(TagContentOtherField::Content)
1034            } else {
1035                Ok(TagContentOtherField::Other)
1036            }
1037        }
1038    }
1039
1040    /// Not public API
1041    pub struct ContentDeserializer<'de, E> {
1042        content: Content<'de>,
1043        err: PhantomData<E>,
1044    }
1045
1046    impl<'de, E> ContentDeserializer<'de, E>
1047    where
1048        E: de::Error,
1049    {
1050        #[cold]
1051        fn invalid_type(self, exp: &Expected) -> E {
1052            de::Error::invalid_type(self.content.unexpected(), exp)
1053        }
1054
1055        fn deserialize_integer<V>(self, visitor: V) -> Result<V::Value, E>
1056        where
1057            V: Visitor<'de>,
1058        {
1059            match self.content {
1060                Content::U8(v) => visitor.visit_u8(v),
1061                Content::U16(v) => visitor.visit_u16(v),
1062                Content::U32(v) => visitor.visit_u32(v),
1063                Content::U64(v) => visitor.visit_u64(v),
1064                Content::I8(v) => visitor.visit_i8(v),
1065                Content::I16(v) => visitor.visit_i16(v),
1066                Content::I32(v) => visitor.visit_i32(v),
1067                Content::I64(v) => visitor.visit_i64(v),
1068                _ => Err(self.invalid_type(&visitor)),
1069            }
1070        }
1071
1072        fn deserialize_float<V>(self, visitor: V) -> Result<V::Value, E>
1073        where
1074            V: Visitor<'de>,
1075        {
1076            match self.content {
1077                Content::F32(v) => visitor.visit_f32(v),
1078                Content::F64(v) => visitor.visit_f64(v),
1079                Content::U8(v) => visitor.visit_u8(v),
1080                Content::U16(v) => visitor.visit_u16(v),
1081                Content::U32(v) => visitor.visit_u32(v),
1082                Content::U64(v) => visitor.visit_u64(v),
1083                Content::I8(v) => visitor.visit_i8(v),
1084                Content::I16(v) => visitor.visit_i16(v),
1085                Content::I32(v) => visitor.visit_i32(v),
1086                Content::I64(v) => visitor.visit_i64(v),
1087                _ => Err(self.invalid_type(&visitor)),
1088            }
1089        }
1090    }
1091
1092    fn visit_content_seq<'de, V, E>(content: Vec<Content<'de>>, visitor: V) -> Result<V::Value, E>
1093    where
1094        V: Visitor<'de>,
1095        E: de::Error,
1096    {
1097        let seq = content.into_iter().map(ContentDeserializer::new);
1098        let mut seq_visitor = SeqDeserializer::new(seq);
1099        let value = tri!(visitor.visit_seq(&mut seq_visitor));
1100        tri!(seq_visitor.end());
1101        Ok(value)
1102    }
1103
1104    fn visit_content_map<'de, V, E>(
1105        content: Vec<(Content<'de>, Content<'de>)>,
1106        visitor: V,
1107    ) -> Result<V::Value, E>
1108    where
1109        V: Visitor<'de>,
1110        E: de::Error,
1111    {
1112        let map = content
1113            .into_iter()
1114            .map(|(k, v)| (ContentDeserializer::new(k), ContentDeserializer::new(v)));
1115        let mut map_visitor = MapDeserializer::new(map);
1116        let value = tri!(visitor.visit_map(&mut map_visitor));
1117        tri!(map_visitor.end());
1118        Ok(value)
1119    }
1120
1121    /// Used when deserializing an internally tagged enum because the content
1122    /// will be used exactly once.
1123    impl<'de, E> Deserializer<'de> for ContentDeserializer<'de, E>
1124    where
1125        E: de::Error,
1126    {
1127        type Error = E;
1128
1129        fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1130        where
1131            V: Visitor<'de>,
1132        {
1133            match self.content {
1134                Content::Bool(v) => visitor.visit_bool(v),
1135                Content::U8(v) => visitor.visit_u8(v),
1136                Content::U16(v) => visitor.visit_u16(v),
1137                Content::U32(v) => visitor.visit_u32(v),
1138                Content::U64(v) => visitor.visit_u64(v),
1139                Content::I8(v) => visitor.visit_i8(v),
1140                Content::I16(v) => visitor.visit_i16(v),
1141                Content::I32(v) => visitor.visit_i32(v),
1142                Content::I64(v) => visitor.visit_i64(v),
1143                Content::F32(v) => visitor.visit_f32(v),
1144                Content::F64(v) => visitor.visit_f64(v),
1145                Content::Char(v) => visitor.visit_char(v),
1146                Content::String(v) => visitor.visit_string(v),
1147                Content::Str(v) => visitor.visit_borrowed_str(v),
1148                Content::ByteBuf(v) => visitor.visit_byte_buf(v),
1149                Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1150                Content::Unit => visitor.visit_unit(),
1151                Content::None => visitor.visit_none(),
1152                Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
1153                Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)),
1154                Content::Seq(v) => visit_content_seq(v, visitor),
1155                Content::Map(v) => visit_content_map(v, visitor),
1156            }
1157        }
1158
1159        fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1160        where
1161            V: Visitor<'de>,
1162        {
1163            match self.content {
1164                Content::Bool(v) => visitor.visit_bool(v),
1165                _ => Err(self.invalid_type(&visitor)),
1166            }
1167        }
1168
1169        fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1170        where
1171            V: Visitor<'de>,
1172        {
1173            self.deserialize_integer(visitor)
1174        }
1175
1176        fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1177        where
1178            V: Visitor<'de>,
1179        {
1180            self.deserialize_integer(visitor)
1181        }
1182
1183        fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1184        where
1185            V: Visitor<'de>,
1186        {
1187            self.deserialize_integer(visitor)
1188        }
1189
1190        fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1191        where
1192            V: Visitor<'de>,
1193        {
1194            self.deserialize_integer(visitor)
1195        }
1196
1197        fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1198        where
1199            V: Visitor<'de>,
1200        {
1201            self.deserialize_integer(visitor)
1202        }
1203
1204        fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1205        where
1206            V: Visitor<'de>,
1207        {
1208            self.deserialize_integer(visitor)
1209        }
1210
1211        fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1212        where
1213            V: Visitor<'de>,
1214        {
1215            self.deserialize_integer(visitor)
1216        }
1217
1218        fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1219        where
1220            V: Visitor<'de>,
1221        {
1222            self.deserialize_integer(visitor)
1223        }
1224
1225        fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1226        where
1227            V: Visitor<'de>,
1228        {
1229            self.deserialize_float(visitor)
1230        }
1231
1232        fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1233        where
1234            V: Visitor<'de>,
1235        {
1236            self.deserialize_float(visitor)
1237        }
1238
1239        fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1240        where
1241            V: Visitor<'de>,
1242        {
1243            match self.content {
1244                Content::Char(v) => visitor.visit_char(v),
1245                Content::String(v) => visitor.visit_string(v),
1246                Content::Str(v) => visitor.visit_borrowed_str(v),
1247                _ => Err(self.invalid_type(&visitor)),
1248            }
1249        }
1250
1251        fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1252        where
1253            V: Visitor<'de>,
1254        {
1255            self.deserialize_string(visitor)
1256        }
1257
1258        fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1259        where
1260            V: Visitor<'de>,
1261        {
1262            match self.content {
1263                Content::String(v) => visitor.visit_string(v),
1264                Content::Str(v) => visitor.visit_borrowed_str(v),
1265                Content::ByteBuf(v) => visitor.visit_byte_buf(v),
1266                Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1267                _ => Err(self.invalid_type(&visitor)),
1268            }
1269        }
1270
1271        fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1272        where
1273            V: Visitor<'de>,
1274        {
1275            self.deserialize_byte_buf(visitor)
1276        }
1277
1278        fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1279        where
1280            V: Visitor<'de>,
1281        {
1282            match self.content {
1283                Content::String(v) => visitor.visit_string(v),
1284                Content::Str(v) => visitor.visit_borrowed_str(v),
1285                Content::ByteBuf(v) => visitor.visit_byte_buf(v),
1286                Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1287                Content::Seq(v) => visit_content_seq(v, visitor),
1288                _ => Err(self.invalid_type(&visitor)),
1289            }
1290        }
1291
1292        fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1293        where
1294            V: Visitor<'de>,
1295        {
1296            match self.content {
1297                Content::None => visitor.visit_none(),
1298                Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
1299                Content::Unit => visitor.visit_unit(),
1300                _ => visitor.visit_some(self),
1301            }
1302        }
1303
1304        fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1305        where
1306            V: Visitor<'de>,
1307        {
1308            match self.content {
1309                Content::Unit => visitor.visit_unit(),
1310
1311                // Allow deserializing newtype variant containing unit.
1312                //
1313                //     #[derive(Deserialize)]
1314                //     #[serde(tag = "result")]
1315                //     enum Response<T> {
1316                //         Success(T),
1317                //     }
1318                //
1319                // We want {"result":"Success"} to deserialize into Response<()>.
1320                Content::Map(ref v) if v.is_empty() => visitor.visit_unit(),
1321                _ => Err(self.invalid_type(&visitor)),
1322            }
1323        }
1324
1325        fn deserialize_unit_struct<V>(
1326            self,
1327            _name: &'static str,
1328            visitor: V,
1329        ) -> Result<V::Value, Self::Error>
1330        where
1331            V: Visitor<'de>,
1332        {
1333            match self.content {
1334                // As a special case, allow deserializing untagged newtype
1335                // variant containing unit struct.
1336                //
1337                //     #[derive(Deserialize)]
1338                //     struct Info;
1339                //
1340                //     #[derive(Deserialize)]
1341                //     #[serde(tag = "topic")]
1342                //     enum Message {
1343                //         Info(Info),
1344                //     }
1345                //
1346                // We want {"topic":"Info"} to deserialize even though
1347                // ordinarily unit structs do not deserialize from empty map/seq.
1348                Content::Map(ref v) if v.is_empty() => visitor.visit_unit(),
1349                Content::Seq(ref v) if v.is_empty() => visitor.visit_unit(),
1350                _ => self.deserialize_any(visitor),
1351            }
1352        }
1353
1354        fn deserialize_newtype_struct<V>(
1355            self,
1356            _name: &str,
1357            visitor: V,
1358        ) -> Result<V::Value, Self::Error>
1359        where
1360            V: Visitor<'de>,
1361        {
1362            match self.content {
1363                Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)),
1364                _ => visitor.visit_newtype_struct(self),
1365            }
1366        }
1367
1368        fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1369        where
1370            V: Visitor<'de>,
1371        {
1372            match self.content {
1373                Content::Seq(v) => visit_content_seq(v, visitor),
1374                _ => Err(self.invalid_type(&visitor)),
1375            }
1376        }
1377
1378        fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
1379        where
1380            V: Visitor<'de>,
1381        {
1382            self.deserialize_seq(visitor)
1383        }
1384
1385        fn deserialize_tuple_struct<V>(
1386            self,
1387            _name: &'static str,
1388            _len: usize,
1389            visitor: V,
1390        ) -> Result<V::Value, Self::Error>
1391        where
1392            V: Visitor<'de>,
1393        {
1394            self.deserialize_seq(visitor)
1395        }
1396
1397        fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1398        where
1399            V: Visitor<'de>,
1400        {
1401            match self.content {
1402                Content::Map(v) => visit_content_map(v, visitor),
1403                _ => Err(self.invalid_type(&visitor)),
1404            }
1405        }
1406
1407        fn deserialize_struct<V>(
1408            self,
1409            _name: &'static str,
1410            _fields: &'static [&'static str],
1411            visitor: V,
1412        ) -> Result<V::Value, Self::Error>
1413        where
1414            V: Visitor<'de>,
1415        {
1416            match self.content {
1417                Content::Seq(v) => visit_content_seq(v, visitor),
1418                Content::Map(v) => visit_content_map(v, visitor),
1419                _ => Err(self.invalid_type(&visitor)),
1420            }
1421        }
1422
1423        fn deserialize_enum<V>(
1424            self,
1425            _name: &str,
1426            _variants: &'static [&'static str],
1427            visitor: V,
1428        ) -> Result<V::Value, Self::Error>
1429        where
1430            V: Visitor<'de>,
1431        {
1432            let (variant, value) = match self.content {
1433                Content::Map(value) => {
1434                    let mut iter = value.into_iter();
1435                    let (variant, value) = match iter.next() {
1436                        Some(v) => v,
1437                        None => {
1438                            return Err(de::Error::invalid_value(
1439                                de::Unexpected::Map,
1440                                &"map with a single key",
1441                            ));
1442                        }
1443                    };
1444                    // enums are encoded in json as maps with a single key:value pair
1445                    if iter.next().is_some() {
1446                        return Err(de::Error::invalid_value(
1447                            de::Unexpected::Map,
1448                            &"map with a single key",
1449                        ));
1450                    }
1451                    (variant, Some(value))
1452                }
1453                s @ Content::String(_) | s @ Content::Str(_) => (s, None),
1454                other => {
1455                    return Err(de::Error::invalid_type(
1456                        other.unexpected(),
1457                        &"string or map",
1458                    ));
1459                }
1460            };
1461
1462            visitor.visit_enum(EnumDeserializer::new(variant, value))
1463        }
1464
1465        fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1466        where
1467            V: Visitor<'de>,
1468        {
1469            match self.content {
1470                Content::String(v) => visitor.visit_string(v),
1471                Content::Str(v) => visitor.visit_borrowed_str(v),
1472                Content::ByteBuf(v) => visitor.visit_byte_buf(v),
1473                Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1474                Content::U8(v) => visitor.visit_u8(v),
1475                Content::U64(v) => visitor.visit_u64(v),
1476                _ => Err(self.invalid_type(&visitor)),
1477            }
1478        }
1479
1480        fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1481        where
1482            V: Visitor<'de>,
1483        {
1484            drop(self);
1485            visitor.visit_unit()
1486        }
1487
1488        fn __deserialize_content<V>(
1489            self,
1490            _: actually_private::T,
1491            visitor: V,
1492        ) -> Result<Content<'de>, Self::Error>
1493        where
1494            V: Visitor<'de, Value = Content<'de>>,
1495        {
1496            let _ = visitor;
1497            Ok(self.content)
1498        }
1499    }
1500
1501    impl<'de, E> ContentDeserializer<'de, E> {
1502        /// private API, don't use
1503        pub fn new(content: Content<'de>) -> Self {
1504            ContentDeserializer {
1505                content,
1506                err: PhantomData,
1507            }
1508        }
1509    }
1510
1511    pub struct EnumDeserializer<'de, E>
1512    where
1513        E: de::Error,
1514    {
1515        variant: Content<'de>,
1516        value: Option<Content<'de>>,
1517        err: PhantomData<E>,
1518    }
1519
1520    impl<'de, E> EnumDeserializer<'de, E>
1521    where
1522        E: de::Error,
1523    {
1524        pub fn new(variant: Content<'de>, value: Option<Content<'de>>) -> EnumDeserializer<'de, E> {
1525            EnumDeserializer {
1526                variant,
1527                value,
1528                err: PhantomData,
1529            }
1530        }
1531    }
1532
1533    impl<'de, E> de::EnumAccess<'de> for EnumDeserializer<'de, E>
1534    where
1535        E: de::Error,
1536    {
1537        type Error = E;
1538        type Variant = VariantDeserializer<'de, Self::Error>;
1539
1540        fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), E>
1541        where
1542            V: de::DeserializeSeed<'de>,
1543        {
1544            let visitor = VariantDeserializer {
1545                value: self.value,
1546                err: PhantomData,
1547            };
1548            seed.deserialize(ContentDeserializer::new(self.variant))
1549                .map(|v| (v, visitor))
1550        }
1551    }
1552
1553    pub struct VariantDeserializer<'de, E>
1554    where
1555        E: de::Error,
1556    {
1557        value: Option<Content<'de>>,
1558        err: PhantomData<E>,
1559    }
1560
1561    impl<'de, E> de::VariantAccess<'de> for VariantDeserializer<'de, E>
1562    where
1563        E: de::Error,
1564    {
1565        type Error = E;
1566
1567        fn unit_variant(self) -> Result<(), E> {
1568            match self.value {
1569                Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)),
1570                None => Ok(()),
1571            }
1572        }
1573
1574        fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E>
1575        where
1576            T: de::DeserializeSeed<'de>,
1577        {
1578            match self.value {
1579                Some(value) => seed.deserialize(ContentDeserializer::new(value)),
1580                None => Err(de::Error::invalid_type(
1581                    de::Unexpected::UnitVariant,
1582                    &"newtype variant",
1583                )),
1584            }
1585        }
1586
1587        fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
1588        where
1589            V: de::Visitor<'de>,
1590        {
1591            match self.value {
1592                Some(Content::Seq(v)) => {
1593                    de::Deserializer::deserialize_any(SeqDeserializer::new(v.into_iter()), visitor)
1594                }
1595                Some(other) => Err(de::Error::invalid_type(
1596                    other.unexpected(),
1597                    &"tuple variant",
1598                )),
1599                None => Err(de::Error::invalid_type(
1600                    de::Unexpected::UnitVariant,
1601                    &"tuple variant",
1602                )),
1603            }
1604        }
1605
1606        fn struct_variant<V>(
1607            self,
1608            _fields: &'static [&'static str],
1609            visitor: V,
1610        ) -> Result<V::Value, Self::Error>
1611        where
1612            V: de::Visitor<'de>,
1613        {
1614            match self.value {
1615                Some(Content::Map(v)) => {
1616                    de::Deserializer::deserialize_any(MapDeserializer::new(v.into_iter()), visitor)
1617                }
1618                Some(Content::Seq(v)) => {
1619                    de::Deserializer::deserialize_any(SeqDeserializer::new(v.into_iter()), visitor)
1620                }
1621                Some(other) => Err(de::Error::invalid_type(
1622                    other.unexpected(),
1623                    &"struct variant",
1624                )),
1625                None => Err(de::Error::invalid_type(
1626                    de::Unexpected::UnitVariant,
1627                    &"struct variant",
1628                )),
1629            }
1630        }
1631    }
1632
1633    /// Not public API.
1634    pub struct ContentRefDeserializer<'a, 'de: 'a, E> {
1635        content: &'a Content<'de>,
1636        err: PhantomData<E>,
1637    }
1638
1639    impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E>
1640    where
1641        E: de::Error,
1642    {
1643        #[cold]
1644        fn invalid_type(self, exp: &Expected) -> E {
1645            de::Error::invalid_type(self.content.unexpected(), exp)
1646        }
1647
1648        fn deserialize_integer<V>(self, visitor: V) -> Result<V::Value, E>
1649        where
1650            V: Visitor<'de>,
1651        {
1652            match *self.content {
1653                Content::U8(v) => visitor.visit_u8(v),
1654                Content::U16(v) => visitor.visit_u16(v),
1655                Content::U32(v) => visitor.visit_u32(v),
1656                Content::U64(v) => visitor.visit_u64(v),
1657                Content::I8(v) => visitor.visit_i8(v),
1658                Content::I16(v) => visitor.visit_i16(v),
1659                Content::I32(v) => visitor.visit_i32(v),
1660                Content::I64(v) => visitor.visit_i64(v),
1661                _ => Err(self.invalid_type(&visitor)),
1662            }
1663        }
1664
1665        fn deserialize_float<V>(self, visitor: V) -> Result<V::Value, E>
1666        where
1667            V: Visitor<'de>,
1668        {
1669            match *self.content {
1670                Content::F32(v) => visitor.visit_f32(v),
1671                Content::F64(v) => visitor.visit_f64(v),
1672                Content::U8(v) => visitor.visit_u8(v),
1673                Content::U16(v) => visitor.visit_u16(v),
1674                Content::U32(v) => visitor.visit_u32(v),
1675                Content::U64(v) => visitor.visit_u64(v),
1676                Content::I8(v) => visitor.visit_i8(v),
1677                Content::I16(v) => visitor.visit_i16(v),
1678                Content::I32(v) => visitor.visit_i32(v),
1679                Content::I64(v) => visitor.visit_i64(v),
1680                _ => Err(self.invalid_type(&visitor)),
1681            }
1682        }
1683    }
1684
1685    fn visit_content_seq_ref<'a, 'de, V, E>(
1686        content: &'a [Content<'de>],
1687        visitor: V,
1688    ) -> Result<V::Value, E>
1689    where
1690        V: Visitor<'de>,
1691        E: de::Error,
1692    {
1693        let seq = content.iter().map(ContentRefDeserializer::new);
1694        let mut seq_visitor = SeqDeserializer::new(seq);
1695        let value = tri!(visitor.visit_seq(&mut seq_visitor));
1696        tri!(seq_visitor.end());
1697        Ok(value)
1698    }
1699
1700    fn visit_content_map_ref<'a, 'de, V, E>(
1701        content: &'a [(Content<'de>, Content<'de>)],
1702        visitor: V,
1703    ) -> Result<V::Value, E>
1704    where
1705        V: Visitor<'de>,
1706        E: de::Error,
1707    {
1708        let map = content.iter().map(|(k, v)| {
1709            (
1710                ContentRefDeserializer::new(k),
1711                ContentRefDeserializer::new(v),
1712            )
1713        });
1714        let mut map_visitor = MapDeserializer::new(map);
1715        let value = tri!(visitor.visit_map(&mut map_visitor));
1716        tri!(map_visitor.end());
1717        Ok(value)
1718    }
1719
1720    /// Used when deserializing an untagged enum because the content may need
1721    /// to be used more than once.
1722    impl<'de, 'a, E> Deserializer<'de> for ContentRefDeserializer<'a, 'de, E>
1723    where
1724        E: de::Error,
1725    {
1726        type Error = E;
1727
1728        fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, E>
1729        where
1730            V: Visitor<'de>,
1731        {
1732            match *self.content {
1733                Content::Bool(v) => visitor.visit_bool(v),
1734                Content::U8(v) => visitor.visit_u8(v),
1735                Content::U16(v) => visitor.visit_u16(v),
1736                Content::U32(v) => visitor.visit_u32(v),
1737                Content::U64(v) => visitor.visit_u64(v),
1738                Content::I8(v) => visitor.visit_i8(v),
1739                Content::I16(v) => visitor.visit_i16(v),
1740                Content::I32(v) => visitor.visit_i32(v),
1741                Content::I64(v) => visitor.visit_i64(v),
1742                Content::F32(v) => visitor.visit_f32(v),
1743                Content::F64(v) => visitor.visit_f64(v),
1744                Content::Char(v) => visitor.visit_char(v),
1745                Content::String(ref v) => visitor.visit_str(v),
1746                Content::Str(v) => visitor.visit_borrowed_str(v),
1747                Content::ByteBuf(ref v) => visitor.visit_bytes(v),
1748                Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1749                Content::Unit => visitor.visit_unit(),
1750                Content::None => visitor.visit_none(),
1751                Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
1752                Content::Newtype(ref v) => {
1753                    visitor.visit_newtype_struct(ContentRefDeserializer::new(v))
1754                }
1755                Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
1756                Content::Map(ref v) => visit_content_map_ref(v, visitor),
1757            }
1758        }
1759
1760        fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1761        where
1762            V: Visitor<'de>,
1763        {
1764            match *self.content {
1765                Content::Bool(v) => visitor.visit_bool(v),
1766                _ => Err(self.invalid_type(&visitor)),
1767            }
1768        }
1769
1770        fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1771        where
1772            V: Visitor<'de>,
1773        {
1774            self.deserialize_integer(visitor)
1775        }
1776
1777        fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1778        where
1779            V: Visitor<'de>,
1780        {
1781            self.deserialize_integer(visitor)
1782        }
1783
1784        fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1785        where
1786            V: Visitor<'de>,
1787        {
1788            self.deserialize_integer(visitor)
1789        }
1790
1791        fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1792        where
1793            V: Visitor<'de>,
1794        {
1795            self.deserialize_integer(visitor)
1796        }
1797
1798        fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1799        where
1800            V: Visitor<'de>,
1801        {
1802            self.deserialize_integer(visitor)
1803        }
1804
1805        fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1806        where
1807            V: Visitor<'de>,
1808        {
1809            self.deserialize_integer(visitor)
1810        }
1811
1812        fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1813        where
1814            V: Visitor<'de>,
1815        {
1816            self.deserialize_integer(visitor)
1817        }
1818
1819        fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1820        where
1821            V: Visitor<'de>,
1822        {
1823            self.deserialize_integer(visitor)
1824        }
1825
1826        fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1827        where
1828            V: Visitor<'de>,
1829        {
1830            self.deserialize_float(visitor)
1831        }
1832
1833        fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1834        where
1835            V: Visitor<'de>,
1836        {
1837            self.deserialize_float(visitor)
1838        }
1839
1840        fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1841        where
1842            V: Visitor<'de>,
1843        {
1844            match *self.content {
1845                Content::Char(v) => visitor.visit_char(v),
1846                Content::String(ref v) => visitor.visit_str(v),
1847                Content::Str(v) => visitor.visit_borrowed_str(v),
1848                _ => Err(self.invalid_type(&visitor)),
1849            }
1850        }
1851
1852        fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1853        where
1854            V: Visitor<'de>,
1855        {
1856            match *self.content {
1857                Content::String(ref v) => visitor.visit_str(v),
1858                Content::Str(v) => visitor.visit_borrowed_str(v),
1859                Content::ByteBuf(ref v) => visitor.visit_bytes(v),
1860                Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1861                _ => Err(self.invalid_type(&visitor)),
1862            }
1863        }
1864
1865        fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1866        where
1867            V: Visitor<'de>,
1868        {
1869            self.deserialize_str(visitor)
1870        }
1871
1872        fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1873        where
1874            V: Visitor<'de>,
1875        {
1876            match *self.content {
1877                Content::String(ref v) => visitor.visit_str(v),
1878                Content::Str(v) => visitor.visit_borrowed_str(v),
1879                Content::ByteBuf(ref v) => visitor.visit_bytes(v),
1880                Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1881                Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
1882                _ => Err(self.invalid_type(&visitor)),
1883            }
1884        }
1885
1886        fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1887        where
1888            V: Visitor<'de>,
1889        {
1890            self.deserialize_bytes(visitor)
1891        }
1892
1893        fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E>
1894        where
1895            V: Visitor<'de>,
1896        {
1897            match *self.content {
1898                Content::None => visitor.visit_none(),
1899                Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
1900                Content::Unit => visitor.visit_unit(),
1901                _ => visitor.visit_some(self),
1902            }
1903        }
1904
1905        fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1906        where
1907            V: Visitor<'de>,
1908        {
1909            match *self.content {
1910                Content::Unit => visitor.visit_unit(),
1911                _ => Err(self.invalid_type(&visitor)),
1912            }
1913        }
1914
1915        fn deserialize_unit_struct<V>(
1916            self,
1917            _name: &'static str,
1918            visitor: V,
1919        ) -> Result<V::Value, Self::Error>
1920        where
1921            V: Visitor<'de>,
1922        {
1923            self.deserialize_unit(visitor)
1924        }
1925
1926        fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, E>
1927        where
1928            V: Visitor<'de>,
1929        {
1930            match *self.content {
1931                Content::Newtype(ref v) => {
1932                    visitor.visit_newtype_struct(ContentRefDeserializer::new(v))
1933                }
1934                _ => visitor.visit_newtype_struct(self),
1935            }
1936        }
1937
1938        fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1939        where
1940            V: Visitor<'de>,
1941        {
1942            match *self.content {
1943                Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
1944                _ => Err(self.invalid_type(&visitor)),
1945            }
1946        }
1947
1948        fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
1949        where
1950            V: Visitor<'de>,
1951        {
1952            self.deserialize_seq(visitor)
1953        }
1954
1955        fn deserialize_tuple_struct<V>(
1956            self,
1957            _name: &'static str,
1958            _len: usize,
1959            visitor: V,
1960        ) -> Result<V::Value, Self::Error>
1961        where
1962            V: Visitor<'de>,
1963        {
1964            self.deserialize_seq(visitor)
1965        }
1966
1967        fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1968        where
1969            V: Visitor<'de>,
1970        {
1971            match *self.content {
1972                Content::Map(ref v) => visit_content_map_ref(v, visitor),
1973                _ => Err(self.invalid_type(&visitor)),
1974            }
1975        }
1976
1977        fn deserialize_struct<V>(
1978            self,
1979            _name: &'static str,
1980            _fields: &'static [&'static str],
1981            visitor: V,
1982        ) -> Result<V::Value, Self::Error>
1983        where
1984            V: Visitor<'de>,
1985        {
1986            match *self.content {
1987                Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
1988                Content::Map(ref v) => visit_content_map_ref(v, visitor),
1989                _ => Err(self.invalid_type(&visitor)),
1990            }
1991        }
1992
1993        fn deserialize_enum<V>(
1994            self,
1995            _name: &str,
1996            _variants: &'static [&'static str],
1997            visitor: V,
1998        ) -> Result<V::Value, Self::Error>
1999        where
2000            V: Visitor<'de>,
2001        {
2002            let (variant, value) = match *self.content {
2003                Content::Map(ref value) => {
2004                    let mut iter = value.iter();
2005                    let (variant, value) = match iter.next() {
2006                        Some(v) => v,
2007                        None => {
2008                            return Err(de::Error::invalid_value(
2009                                de::Unexpected::Map,
2010                                &"map with a single key",
2011                            ));
2012                        }
2013                    };
2014                    // enums are encoded in json as maps with a single key:value pair
2015                    if iter.next().is_some() {
2016                        return Err(de::Error::invalid_value(
2017                            de::Unexpected::Map,
2018                            &"map with a single key",
2019                        ));
2020                    }
2021                    (variant, Some(value))
2022                }
2023                ref s @ Content::String(_) | ref s @ Content::Str(_) => (s, None),
2024                ref other => {
2025                    return Err(de::Error::invalid_type(
2026                        other.unexpected(),
2027                        &"string or map",
2028                    ));
2029                }
2030            };
2031
2032            visitor.visit_enum(EnumRefDeserializer {
2033                variant,
2034                value,
2035                err: PhantomData,
2036            })
2037        }
2038
2039        fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2040        where
2041            V: Visitor<'de>,
2042        {
2043            match *self.content {
2044                Content::String(ref v) => visitor.visit_str(v),
2045                Content::Str(v) => visitor.visit_borrowed_str(v),
2046                Content::ByteBuf(ref v) => visitor.visit_bytes(v),
2047                Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
2048                Content::U8(v) => visitor.visit_u8(v),
2049                Content::U64(v) => visitor.visit_u64(v),
2050                _ => Err(self.invalid_type(&visitor)),
2051            }
2052        }
2053
2054        fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2055        where
2056            V: Visitor<'de>,
2057        {
2058            visitor.visit_unit()
2059        }
2060
2061        fn __deserialize_content<V>(
2062            self,
2063            _: actually_private::T,
2064            visitor: V,
2065        ) -> Result<Content<'de>, Self::Error>
2066        where
2067            V: Visitor<'de, Value = Content<'de>>,
2068        {
2069            let _ = visitor;
2070            Ok(self.content.clone())
2071        }
2072    }
2073
2074    impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E> {
2075        /// private API, don't use
2076        pub fn new(content: &'a Content<'de>) -> Self {
2077            ContentRefDeserializer {
2078                content,
2079                err: PhantomData,
2080            }
2081        }
2082    }
2083
2084    impl<'a, 'de: 'a, E> Copy for ContentRefDeserializer<'a, 'de, E> {}
2085
2086    impl<'a, 'de: 'a, E> Clone for ContentRefDeserializer<'a, 'de, E> {
2087        fn clone(&self) -> Self {
2088            *self
2089        }
2090    }
2091
2092    struct EnumRefDeserializer<'a, 'de: 'a, E>
2093    where
2094        E: de::Error,
2095    {
2096        variant: &'a Content<'de>,
2097        value: Option<&'a Content<'de>>,
2098        err: PhantomData<E>,
2099    }
2100
2101    impl<'de, 'a, E> de::EnumAccess<'de> for EnumRefDeserializer<'a, 'de, E>
2102    where
2103        E: de::Error,
2104    {
2105        type Error = E;
2106        type Variant = VariantRefDeserializer<'a, 'de, Self::Error>;
2107
2108        fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
2109        where
2110            V: de::DeserializeSeed<'de>,
2111        {
2112            let visitor = VariantRefDeserializer {
2113                value: self.value,
2114                err: PhantomData,
2115            };
2116            seed.deserialize(ContentRefDeserializer::new(self.variant))
2117                .map(|v| (v, visitor))
2118        }
2119    }
2120
2121    struct VariantRefDeserializer<'a, 'de: 'a, E>
2122    where
2123        E: de::Error,
2124    {
2125        value: Option<&'a Content<'de>>,
2126        err: PhantomData<E>,
2127    }
2128
2129    impl<'de, 'a, E> de::VariantAccess<'de> for VariantRefDeserializer<'a, 'de, E>
2130    where
2131        E: de::Error,
2132    {
2133        type Error = E;
2134
2135        fn unit_variant(self) -> Result<(), E> {
2136            match self.value {
2137                Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)),
2138                None => Ok(()),
2139            }
2140        }
2141
2142        fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E>
2143        where
2144            T: de::DeserializeSeed<'de>,
2145        {
2146            match self.value {
2147                Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
2148                None => Err(de::Error::invalid_type(
2149                    de::Unexpected::UnitVariant,
2150                    &"newtype variant",
2151                )),
2152            }
2153        }
2154
2155        fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
2156        where
2157            V: de::Visitor<'de>,
2158        {
2159            match self.value {
2160                Some(Content::Seq(v)) => {
2161                    de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor)
2162                }
2163                Some(other) => Err(de::Error::invalid_type(
2164                    other.unexpected(),
2165                    &"tuple variant",
2166                )),
2167                None => Err(de::Error::invalid_type(
2168                    de::Unexpected::UnitVariant,
2169                    &"tuple variant",
2170                )),
2171            }
2172        }
2173
2174        fn struct_variant<V>(
2175            self,
2176            _fields: &'static [&'static str],
2177            visitor: V,
2178        ) -> Result<V::Value, Self::Error>
2179        where
2180            V: de::Visitor<'de>,
2181        {
2182            match self.value {
2183                Some(Content::Map(v)) => {
2184                    de::Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor)
2185                }
2186                Some(Content::Seq(v)) => {
2187                    de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor)
2188                }
2189                Some(other) => Err(de::Error::invalid_type(
2190                    other.unexpected(),
2191                    &"struct variant",
2192                )),
2193                None => Err(de::Error::invalid_type(
2194                    de::Unexpected::UnitVariant,
2195                    &"struct variant",
2196                )),
2197            }
2198        }
2199    }
2200
2201    struct SeqRefDeserializer<'a, 'de: 'a, E>
2202    where
2203        E: de::Error,
2204    {
2205        iter: <&'a [Content<'de>] as IntoIterator>::IntoIter,
2206        err: PhantomData<E>,
2207    }
2208
2209    impl<'a, 'de, E> SeqRefDeserializer<'a, 'de, E>
2210    where
2211        E: de::Error,
2212    {
2213        fn new(slice: &'a [Content<'de>]) -> Self {
2214            SeqRefDeserializer {
2215                iter: slice.iter(),
2216                err: PhantomData,
2217            }
2218        }
2219    }
2220
2221    impl<'de, 'a, E> de::Deserializer<'de> for SeqRefDeserializer<'a, 'de, E>
2222    where
2223        E: de::Error,
2224    {
2225        type Error = E;
2226
2227        #[inline]
2228        fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
2229        where
2230            V: de::Visitor<'de>,
2231        {
2232            let len = self.iter.len();
2233            if len == 0 {
2234                visitor.visit_unit()
2235            } else {
2236                let ret = tri!(visitor.visit_seq(&mut self));
2237                let remaining = self.iter.len();
2238                if remaining == 0 {
2239                    Ok(ret)
2240                } else {
2241                    Err(de::Error::invalid_length(len, &"fewer elements in array"))
2242                }
2243            }
2244        }
2245
2246        forward_to_deserialize_any! {
2247            bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
2248            bytes byte_buf option unit unit_struct newtype_struct seq tuple
2249            tuple_struct map struct enum identifier ignored_any
2250        }
2251    }
2252
2253    impl<'de, 'a, E> de::SeqAccess<'de> for SeqRefDeserializer<'a, 'de, E>
2254    where
2255        E: de::Error,
2256    {
2257        type Error = E;
2258
2259        fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
2260        where
2261            T: de::DeserializeSeed<'de>,
2262        {
2263            match self.iter.next() {
2264                Some(value) => seed
2265                    .deserialize(ContentRefDeserializer::new(value))
2266                    .map(Some),
2267                None => Ok(None),
2268            }
2269        }
2270
2271        fn size_hint(&self) -> Option<usize> {
2272            size_hint::from_bounds(&self.iter)
2273        }
2274    }
2275
2276    struct MapRefDeserializer<'a, 'de: 'a, E>
2277    where
2278        E: de::Error,
2279    {
2280        iter: <&'a [(Content<'de>, Content<'de>)] as IntoIterator>::IntoIter,
2281        value: Option<&'a Content<'de>>,
2282        err: PhantomData<E>,
2283    }
2284
2285    impl<'a, 'de, E> MapRefDeserializer<'a, 'de, E>
2286    where
2287        E: de::Error,
2288    {
2289        fn new(map: &'a [(Content<'de>, Content<'de>)]) -> Self {
2290            MapRefDeserializer {
2291                iter: map.iter(),
2292                value: None,
2293                err: PhantomData,
2294            }
2295        }
2296    }
2297
2298    impl<'de, 'a, E> de::MapAccess<'de> for MapRefDeserializer<'a, 'de, E>
2299    where
2300        E: de::Error,
2301    {
2302        type Error = E;
2303
2304        fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
2305        where
2306            T: de::DeserializeSeed<'de>,
2307        {
2308            match self.iter.next() {
2309                Some((key, value)) => {
2310                    self.value = Some(value);
2311                    seed.deserialize(ContentRefDeserializer::new(key)).map(Some)
2312                }
2313                None => Ok(None),
2314            }
2315        }
2316
2317        fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
2318        where
2319            T: de::DeserializeSeed<'de>,
2320        {
2321            match self.value.take() {
2322                Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
2323                None => Err(de::Error::custom("value is missing")),
2324            }
2325        }
2326
2327        fn size_hint(&self) -> Option<usize> {
2328            size_hint::from_bounds(&self.iter)
2329        }
2330    }
2331
2332    impl<'de, 'a, E> de::Deserializer<'de> for MapRefDeserializer<'a, 'de, E>
2333    where
2334        E: de::Error,
2335    {
2336        type Error = E;
2337
2338        #[inline]
2339        fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2340        where
2341            V: de::Visitor<'de>,
2342        {
2343            visitor.visit_map(self)
2344        }
2345
2346        forward_to_deserialize_any! {
2347            bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
2348            bytes byte_buf option unit unit_struct newtype_struct seq tuple
2349            tuple_struct map struct enum identifier ignored_any
2350        }
2351    }
2352
2353    impl<'de, E> de::IntoDeserializer<'de, E> for ContentDeserializer<'de, E>
2354    where
2355        E: de::Error,
2356    {
2357        type Deserializer = Self;
2358
2359        fn into_deserializer(self) -> Self {
2360            self
2361        }
2362    }
2363
2364    impl<'de, 'a, E> de::IntoDeserializer<'de, E> for ContentRefDeserializer<'a, 'de, E>
2365    where
2366        E: de::Error,
2367    {
2368        type Deserializer = Self;
2369
2370        fn into_deserializer(self) -> Self {
2371            self
2372        }
2373    }
2374
2375    /// Visitor for deserializing an internally tagged unit variant.
2376    ///
2377    /// Not public API.
2378    pub struct InternallyTaggedUnitVisitor<'a> {
2379        type_name: &'a str,
2380        variant_name: &'a str,
2381    }
2382
2383    impl<'a> InternallyTaggedUnitVisitor<'a> {
2384        /// Not public API.
2385        pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
2386            InternallyTaggedUnitVisitor {
2387                type_name,
2388                variant_name,
2389            }
2390        }
2391    }
2392
2393    impl<'de, 'a> Visitor<'de> for InternallyTaggedUnitVisitor<'a> {
2394        type Value = ();
2395
2396        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2397            write!(
2398                formatter,
2399                "unit variant {}::{}",
2400                self.type_name, self.variant_name
2401            )
2402        }
2403
2404        fn visit_seq<S>(self, _: S) -> Result<(), S::Error>
2405        where
2406            S: SeqAccess<'de>,
2407        {
2408            Ok(())
2409        }
2410
2411        fn visit_map<M>(self, mut access: M) -> Result<(), M::Error>
2412        where
2413            M: MapAccess<'de>,
2414        {
2415            while tri!(access.next_entry::<IgnoredAny, IgnoredAny>()).is_some() {}
2416            Ok(())
2417        }
2418    }
2419
2420    /// Visitor for deserializing an untagged unit variant.
2421    ///
2422    /// Not public API.
2423    pub struct UntaggedUnitVisitor<'a> {
2424        type_name: &'a str,
2425        variant_name: &'a str,
2426    }
2427
2428    impl<'a> UntaggedUnitVisitor<'a> {
2429        /// Not public API.
2430        pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
2431            UntaggedUnitVisitor {
2432                type_name,
2433                variant_name,
2434            }
2435        }
2436    }
2437
2438    impl<'de, 'a> Visitor<'de> for UntaggedUnitVisitor<'a> {
2439        type Value = ();
2440
2441        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2442            write!(
2443                formatter,
2444                "unit variant {}::{}",
2445                self.type_name, self.variant_name
2446            )
2447        }
2448
2449        fn visit_unit<E>(self) -> Result<(), E>
2450        where
2451            E: de::Error,
2452        {
2453            Ok(())
2454        }
2455
2456        fn visit_none<E>(self) -> Result<(), E>
2457        where
2458            E: de::Error,
2459        {
2460            Ok(())
2461        }
2462    }
2463}
2464
2465////////////////////////////////////////////////////////////////////////////////
2466
2467// Like `IntoDeserializer` but also implemented for `&[u8]`. This is used for
2468// the newtype fallthrough case of `field_identifier`.
2469//
2470//    #[derive(Deserialize)]
2471//    #[serde(field_identifier)]
2472//    enum F {
2473//        A,
2474//        B,
2475//        Other(String), // deserialized using IdentifierDeserializer
2476//    }
2477pub trait IdentifierDeserializer<'de, E: Error> {
2478    type Deserializer: Deserializer<'de, Error = E>;
2479
2480    fn from(self) -> Self::Deserializer;
2481}
2482
2483pub struct Borrowed<'de, T: 'de + ?Sized>(pub &'de T);
2484
2485impl<'de, E> IdentifierDeserializer<'de, E> for u64
2486where
2487    E: Error,
2488{
2489    type Deserializer = <u64 as IntoDeserializer<'de, E>>::Deserializer;
2490
2491    fn from(self) -> Self::Deserializer {
2492        self.into_deserializer()
2493    }
2494}
2495
2496pub struct StrDeserializer<'a, E> {
2497    value: &'a str,
2498    marker: PhantomData<E>,
2499}
2500
2501impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E>
2502where
2503    E: Error,
2504{
2505    type Error = E;
2506
2507    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2508    where
2509        V: Visitor<'de>,
2510    {
2511        visitor.visit_str(self.value)
2512    }
2513
2514    forward_to_deserialize_any! {
2515        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
2516        bytes byte_buf option unit unit_struct newtype_struct seq tuple
2517        tuple_struct map struct enum identifier ignored_any
2518    }
2519}
2520
2521pub struct BorrowedStrDeserializer<'de, E> {
2522    value: &'de str,
2523    marker: PhantomData<E>,
2524}
2525
2526impl<'de, E> Deserializer<'de> for BorrowedStrDeserializer<'de, E>
2527where
2528    E: Error,
2529{
2530    type Error = E;
2531
2532    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2533    where
2534        V: Visitor<'de>,
2535    {
2536        visitor.visit_borrowed_str(self.value)
2537    }
2538
2539    forward_to_deserialize_any! {
2540        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
2541        bytes byte_buf option unit unit_struct newtype_struct seq tuple
2542        tuple_struct map struct enum identifier ignored_any
2543    }
2544}
2545
2546impl<'a, E> IdentifierDeserializer<'a, E> for &'a str
2547where
2548    E: Error,
2549{
2550    type Deserializer = StrDeserializer<'a, E>;
2551
2552    fn from(self) -> Self::Deserializer {
2553        StrDeserializer {
2554            value: self,
2555            marker: PhantomData,
2556        }
2557    }
2558}
2559
2560impl<'de, E> IdentifierDeserializer<'de, E> for Borrowed<'de, str>
2561where
2562    E: Error,
2563{
2564    type Deserializer = BorrowedStrDeserializer<'de, E>;
2565
2566    fn from(self) -> Self::Deserializer {
2567        BorrowedStrDeserializer {
2568            value: self.0,
2569            marker: PhantomData,
2570        }
2571    }
2572}
2573
2574impl<'a, E> IdentifierDeserializer<'a, E> for &'a [u8]
2575where
2576    E: Error,
2577{
2578    type Deserializer = BytesDeserializer<'a, E>;
2579
2580    fn from(self) -> Self::Deserializer {
2581        BytesDeserializer::new(self)
2582    }
2583}
2584
2585impl<'de, E> IdentifierDeserializer<'de, E> for Borrowed<'de, [u8]>
2586where
2587    E: Error,
2588{
2589    type Deserializer = BorrowedBytesDeserializer<'de, E>;
2590
2591    fn from(self) -> Self::Deserializer {
2592        BorrowedBytesDeserializer::new(self.0)
2593    }
2594}
2595
2596#[cfg(any(feature = "std", feature = "alloc"))]
2597pub struct FlatMapDeserializer<'a, 'de: 'a, E>(
2598    pub &'a mut Vec<Option<(Content<'de>, Content<'de>)>>,
2599    pub PhantomData<E>,
2600);
2601
2602#[cfg(any(feature = "std", feature = "alloc"))]
2603impl<'a, 'de, E> FlatMapDeserializer<'a, 'de, E>
2604where
2605    E: Error,
2606{
2607    fn deserialize_other<V>() -> Result<V, E> {
2608        Err(Error::custom("can only flatten structs and maps"))
2609    }
2610}
2611
2612#[cfg(any(feature = "std", feature = "alloc"))]
2613macro_rules! forward_to_deserialize_other {
2614    ($($func:ident ($($arg:ty),*))*) => {
2615        $(
2616            fn $func<V>(self, $(_: $arg,)* _visitor: V) -> Result<V::Value, Self::Error>
2617            where
2618                V: Visitor<'de>,
2619            {
2620                Self::deserialize_other()
2621            }
2622        )*
2623    }
2624}
2625
2626#[cfg(any(feature = "std", feature = "alloc"))]
2627impl<'a, 'de, E> Deserializer<'de> for FlatMapDeserializer<'a, 'de, E>
2628where
2629    E: Error,
2630{
2631    type Error = E;
2632
2633    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2634    where
2635        V: Visitor<'de>,
2636    {
2637        self.deserialize_map(visitor)
2638    }
2639
2640    fn deserialize_enum<V>(
2641        self,
2642        name: &'static str,
2643        variants: &'static [&'static str],
2644        visitor: V,
2645    ) -> Result<V::Value, Self::Error>
2646    where
2647        V: Visitor<'de>,
2648    {
2649        for entry in self.0 {
2650            if let Some((key, value)) = flat_map_take_entry(entry, variants) {
2651                return visitor.visit_enum(EnumDeserializer::new(key, Some(value)));
2652            }
2653        }
2654
2655        Err(Error::custom(format_args!(
2656            "no variant of enum {} found in flattened data",
2657            name
2658        )))
2659    }
2660
2661    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2662    where
2663        V: Visitor<'de>,
2664    {
2665        visitor.visit_map(FlatMapAccess {
2666            iter: self.0.iter(),
2667            pending_content: None,
2668            _marker: PhantomData,
2669        })
2670    }
2671
2672    fn deserialize_struct<V>(
2673        self,
2674        _: &'static str,
2675        fields: &'static [&'static str],
2676        visitor: V,
2677    ) -> Result<V::Value, Self::Error>
2678    where
2679        V: Visitor<'de>,
2680    {
2681        visitor.visit_map(FlatStructAccess {
2682            iter: self.0.iter_mut(),
2683            pending_content: None,
2684            fields,
2685            _marker: PhantomData,
2686        })
2687    }
2688
2689    fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
2690    where
2691        V: Visitor<'de>,
2692    {
2693        visitor.visit_newtype_struct(self)
2694    }
2695
2696    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2697    where
2698        V: Visitor<'de>,
2699    {
2700        match visitor.__private_visit_untagged_option(self) {
2701            Ok(value) => Ok(value),
2702            Err(()) => Self::deserialize_other(),
2703        }
2704    }
2705
2706    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2707    where
2708        V: Visitor<'de>,
2709    {
2710        visitor.visit_unit()
2711    }
2712
2713    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2714    where
2715        V: Visitor<'de>,
2716    {
2717        visitor.visit_unit()
2718    }
2719
2720    forward_to_deserialize_other! {
2721        deserialize_bool()
2722        deserialize_i8()
2723        deserialize_i16()
2724        deserialize_i32()
2725        deserialize_i64()
2726        deserialize_u8()
2727        deserialize_u16()
2728        deserialize_u32()
2729        deserialize_u64()
2730        deserialize_f32()
2731        deserialize_f64()
2732        deserialize_char()
2733        deserialize_str()
2734        deserialize_string()
2735        deserialize_bytes()
2736        deserialize_byte_buf()
2737        deserialize_unit_struct(&'static str)
2738        deserialize_seq()
2739        deserialize_tuple(usize)
2740        deserialize_tuple_struct(&'static str, usize)
2741        deserialize_identifier()
2742    }
2743}
2744
2745#[cfg(any(feature = "std", feature = "alloc"))]
2746struct FlatMapAccess<'a, 'de: 'a, E> {
2747    iter: slice::Iter<'a, Option<(Content<'de>, Content<'de>)>>,
2748    pending_content: Option<&'a Content<'de>>,
2749    _marker: PhantomData<E>,
2750}
2751
2752#[cfg(any(feature = "std", feature = "alloc"))]
2753impl<'a, 'de, E> MapAccess<'de> for FlatMapAccess<'a, 'de, E>
2754where
2755    E: Error,
2756{
2757    type Error = E;
2758
2759    fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
2760    where
2761        T: DeserializeSeed<'de>,
2762    {
2763        for item in &mut self.iter {
2764            // Items in the vector are nulled out when used by a struct.
2765            if let Some((ref key, ref content)) = *item {
2766                // Do not take(), instead borrow this entry. The internally tagged
2767                // enum does its own buffering so we can't tell whether this entry
2768                // is going to be consumed. Borrowing here leaves the entry
2769                // available for later flattened fields.
2770                self.pending_content = Some(content);
2771                return seed.deserialize(ContentRefDeserializer::new(key)).map(Some);
2772            }
2773        }
2774        Ok(None)
2775    }
2776
2777    fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
2778    where
2779        T: DeserializeSeed<'de>,
2780    {
2781        match self.pending_content.take() {
2782            Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
2783            None => Err(Error::custom("value is missing")),
2784        }
2785    }
2786}
2787
2788#[cfg(any(feature = "std", feature = "alloc"))]
2789struct FlatStructAccess<'a, 'de: 'a, E> {
2790    iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>,
2791    pending_content: Option<Content<'de>>,
2792    fields: &'static [&'static str],
2793    _marker: PhantomData<E>,
2794}
2795
2796#[cfg(any(feature = "std", feature = "alloc"))]
2797impl<'a, 'de, E> MapAccess<'de> for FlatStructAccess<'a, 'de, E>
2798where
2799    E: Error,
2800{
2801    type Error = E;
2802
2803    fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
2804    where
2805        T: DeserializeSeed<'de>,
2806    {
2807        for entry in self.iter.by_ref() {
2808            if let Some((key, content)) = flat_map_take_entry(entry, self.fields) {
2809                self.pending_content = Some(content);
2810                return seed.deserialize(ContentDeserializer::new(key)).map(Some);
2811            }
2812        }
2813        Ok(None)
2814    }
2815
2816    fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
2817    where
2818        T: DeserializeSeed<'de>,
2819    {
2820        match self.pending_content.take() {
2821            Some(value) => seed.deserialize(ContentDeserializer::new(value)),
2822            None => Err(Error::custom("value is missing")),
2823        }
2824    }
2825}
2826
2827/// Claims one key-value pair from a FlatMapDeserializer's field buffer if the
2828/// field name matches any of the recognized ones.
2829#[cfg(any(feature = "std", feature = "alloc"))]
2830fn flat_map_take_entry<'de>(
2831    entry: &mut Option<(Content<'de>, Content<'de>)>,
2832    recognized: &[&str],
2833) -> Option<(Content<'de>, Content<'de>)> {
2834    // Entries in the FlatMapDeserializer buffer are nulled out as they get
2835    // claimed for deserialization. We only use an entry if it is still present
2836    // and if the field is one recognized by the current data structure.
2837    let is_recognized = match entry {
2838        None => false,
2839        Some((k, _v)) => k.as_str().map_or(false, |name| recognized.contains(&name)),
2840    };
2841
2842    if is_recognized {
2843        entry.take()
2844    } else {
2845        None
2846    }
2847}
2848
2849pub struct AdjacentlyTaggedEnumVariantSeed<F> {
2850    pub enum_name: &'static str,
2851    pub variants: &'static [&'static str],
2852    pub fields_enum: PhantomData<F>,
2853}
2854
2855pub struct AdjacentlyTaggedEnumVariantVisitor<F> {
2856    enum_name: &'static str,
2857    fields_enum: PhantomData<F>,
2858}
2859
2860impl<'de, F> Visitor<'de> for AdjacentlyTaggedEnumVariantVisitor<F>
2861where
2862    F: Deserialize<'de>,
2863{
2864    type Value = F;
2865
2866    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2867        write!(formatter, "variant of enum {}", self.enum_name)
2868    }
2869
2870    fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
2871    where
2872        A: EnumAccess<'de>,
2873    {
2874        let (variant, variant_access) = tri!(data.variant());
2875        tri!(variant_access.unit_variant());
2876        Ok(variant)
2877    }
2878}
2879
2880impl<'de, F> DeserializeSeed<'de> for AdjacentlyTaggedEnumVariantSeed<F>
2881where
2882    F: Deserialize<'de>,
2883{
2884    type Value = F;
2885
2886    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
2887    where
2888        D: Deserializer<'de>,
2889    {
2890        deserializer.deserialize_enum(
2891            self.enum_name,
2892            self.variants,
2893            AdjacentlyTaggedEnumVariantVisitor {
2894                enum_name: self.enum_name,
2895                fields_enum: PhantomData,
2896            },
2897        )
2898    }
2899}