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