Skip to main content

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