serde_implicit/
content.rs

1// This module is private and nothing here should be used outside of
2// generated code.
3//
4// We will iterate on the implementation for a few releases and only have to
5// worry about backward compatibility for the `untagged` and `tag` attributes
6// rather than for this entire mechanism.
7//
8// This issue is tracking making some of this stuff public:
9// https://github.com/serde-rs/serde/issues/741
10
11use std::fmt;
12use std::marker::PhantomData;
13
14use serde::de::value::{MapDeserializer, SeqDeserializer};
15use serde::de::{
16    self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, Expected, IgnoredAny, MapAccess,
17    SeqAccess, Unexpected, Visitor,
18};
19
20/// Used from generated code to buffer the contents of the Deserializer when
21/// deserializing untagged enums and internally tagged enums.
22///
23/// Not public API. Use serde-value instead.
24#[derive(Debug, Clone)]
25pub enum Content<'de> {
26    Bool(bool),
27
28    U8(u8),
29    U16(u16),
30    U32(u32),
31    U64(u64),
32
33    I8(i8),
34    I16(i16),
35    I32(i32),
36    I64(i64),
37
38    F32(f32),
39    F64(f64),
40
41    Char(char),
42    String(String),
43    Str(&'de str),
44    ByteBuf(Vec<u8>),
45    Bytes(&'de [u8]),
46
47    None,
48    Some(Box<Content<'de>>),
49
50    Unit,
51    Newtype(Box<Content<'de>>),
52    Seq(Vec<Content<'de>>),
53    Map(Vec<(Content<'de>, Content<'de>)>),
54}
55
56impl<'de> Content<'de> {
57    pub fn as_str(&self) -> Option<&str> {
58        match *self {
59            Content::Str(x) => Some(x),
60            Content::String(ref x) => Some(x),
61            Content::Bytes(x) => str::from_utf8(x).ok(),
62            Content::ByteBuf(ref x) => str::from_utf8(x).ok(),
63            _ => None,
64        }
65    }
66
67    #[cold]
68    fn unexpected(&self) -> Unexpected<'_> {
69        match *self {
70            Content::Bool(b) => Unexpected::Bool(b),
71            Content::U8(n) => Unexpected::Unsigned(n as u64),
72            Content::U16(n) => Unexpected::Unsigned(n as u64),
73            Content::U32(n) => Unexpected::Unsigned(n as u64),
74            Content::U64(n) => Unexpected::Unsigned(n),
75            Content::I8(n) => Unexpected::Signed(n as i64),
76            Content::I16(n) => Unexpected::Signed(n as i64),
77            Content::I32(n) => Unexpected::Signed(n as i64),
78            Content::I64(n) => Unexpected::Signed(n),
79            Content::F32(f) => Unexpected::Float(f as f64),
80            Content::F64(f) => Unexpected::Float(f),
81            Content::Char(c) => Unexpected::Char(c),
82            Content::String(ref s) => Unexpected::Str(s),
83            Content::Str(s) => Unexpected::Str(s),
84            Content::ByteBuf(ref b) => Unexpected::Bytes(b),
85            Content::Bytes(b) => Unexpected::Bytes(b),
86            Content::None | Content::Some(_) => Unexpected::Option,
87            Content::Unit => Unexpected::Unit,
88            Content::Newtype(_) => Unexpected::NewtypeStruct,
89            Content::Seq(_) => Unexpected::Seq,
90            Content::Map(_) => Unexpected::Map,
91        }
92    }
93}
94
95impl<'de> Deserialize<'de> for Content<'de> {
96    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
97    where
98        D: Deserializer<'de>,
99    {
100        // Untagged and internally tagged enums are only supported in
101        // self-describing formats.
102        let visitor = ContentVisitor { value: PhantomData };
103        deserializer.deserialize_any(visitor)
104    }
105}
106
107impl<'de, E> de::IntoDeserializer<'de, E> for Content<'de>
108where
109    E: de::Error,
110{
111    type Deserializer = ContentDeserializer<'de, E>;
112
113    fn into_deserializer(self) -> Self::Deserializer {
114        ContentDeserializer::new(self)
115    }
116}
117
118impl<'a, 'de, E> de::IntoDeserializer<'de, E> for &'a Content<'de>
119where
120    E: de::Error,
121{
122    type Deserializer = ContentRefDeserializer<'a, 'de, E>;
123
124    fn into_deserializer(self) -> Self::Deserializer {
125        ContentRefDeserializer::new(self)
126    }
127}
128
129/// Used to capture data in [`Content`] from other deserializers.
130/// Cannot capture externally tagged enums, `i128` and `u128`.
131struct ContentVisitor<'de> {
132    value: PhantomData<Content<'de>>,
133}
134
135impl<'de> ContentVisitor<'de> {
136    fn new() -> Self {
137        ContentVisitor { value: PhantomData }
138    }
139}
140
141macro_rules! tri {
142    ($e:expr) => {
143        $e?
144    };
145}
146
147impl<'de> Visitor<'de> for ContentVisitor<'de> {
148    type Value = Content<'de>;
149
150    fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
151        fmt.write_str("any value")
152    }
153
154    fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
155    where
156        F: de::Error,
157    {
158        Ok(Content::Bool(value))
159    }
160
161    fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
162    where
163        F: de::Error,
164    {
165        Ok(Content::I8(value))
166    }
167
168    fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
169    where
170        F: de::Error,
171    {
172        Ok(Content::I16(value))
173    }
174
175    fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
176    where
177        F: de::Error,
178    {
179        Ok(Content::I32(value))
180    }
181
182    fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
183    where
184        F: de::Error,
185    {
186        Ok(Content::I64(value))
187    }
188
189    fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
190    where
191        F: de::Error,
192    {
193        Ok(Content::U8(value))
194    }
195
196    fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
197    where
198        F: de::Error,
199    {
200        Ok(Content::U16(value))
201    }
202
203    fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
204    where
205        F: de::Error,
206    {
207        Ok(Content::U32(value))
208    }
209
210    fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
211    where
212        F: de::Error,
213    {
214        Ok(Content::U64(value))
215    }
216
217    fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
218    where
219        F: de::Error,
220    {
221        Ok(Content::F32(value))
222    }
223
224    fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
225    where
226        F: de::Error,
227    {
228        Ok(Content::F64(value))
229    }
230
231    fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
232    where
233        F: de::Error,
234    {
235        Ok(Content::Char(value))
236    }
237
238    fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
239    where
240        F: de::Error,
241    {
242        Ok(Content::String(value.into()))
243    }
244
245    fn visit_borrowed_str<F>(self, value: &'de str) -> Result<Self::Value, F>
246    where
247        F: de::Error,
248    {
249        Ok(Content::Str(value))
250    }
251
252    fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
253    where
254        F: de::Error,
255    {
256        Ok(Content::String(value))
257    }
258
259    fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
260    where
261        F: de::Error,
262    {
263        Ok(Content::ByteBuf(value.into()))
264    }
265
266    fn visit_borrowed_bytes<F>(self, value: &'de [u8]) -> Result<Self::Value, F>
267    where
268        F: de::Error,
269    {
270        Ok(Content::Bytes(value))
271    }
272
273    fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
274    where
275        F: de::Error,
276    {
277        Ok(Content::ByteBuf(value))
278    }
279
280    fn visit_unit<F>(self) -> Result<Self::Value, F>
281    where
282        F: de::Error,
283    {
284        Ok(Content::Unit)
285    }
286
287    fn visit_none<F>(self) -> Result<Self::Value, F>
288    where
289        F: de::Error,
290    {
291        Ok(Content::None)
292    }
293
294    fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
295    where
296        D: Deserializer<'de>,
297    {
298        let v = tri!(Deserialize::deserialize(deserializer));
299        Ok(Content::Some(Box::new(v)))
300    }
301
302    fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
303    where
304        D: Deserializer<'de>,
305    {
306        let v = tri!(Deserialize::deserialize(deserializer));
307        Ok(Content::Newtype(Box::new(v)))
308    }
309
310    fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
311    where
312        V: SeqAccess<'de>,
313    {
314        let mut vec = Vec::<Content>::with_capacity(visitor.size_hint().unwrap_or(0));
315        while let Some(e) = tri!(visitor.next_element()) {
316            vec.push(e);
317        }
318        Ok(Content::Seq(vec))
319    }
320
321    fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
322    where
323        V: MapAccess<'de>,
324    {
325        let mut vec = Vec::<(Content, Content)>::with_capacity(visitor.size_hint().unwrap_or(0));
326        while let Some(kv) = tri!(visitor.next_entry()) {
327            vec.push(kv);
328        }
329        Ok(Content::Map(vec))
330    }
331
332    fn visit_enum<V>(self, _visitor: V) -> Result<Self::Value, V::Error>
333    where
334        V: EnumAccess<'de>,
335    {
336        Err(de::Error::custom(
337            "untagged and internally tagged enums do not support enum input",
338        ))
339    }
340}
341
342/// This is the type of the map keys in an internally tagged enum.
343///
344/// Not public API.
345pub enum TagOrContent<'de> {
346    Tag,
347    Content(Content<'de>),
348}
349
350/// Serves as a seed for deserializing a key of internally tagged enum.
351/// Cannot capture externally tagged enums, `i128` and `u128`.
352struct TagOrContentVisitor<'de> {
353    name: &'static str,
354    value: PhantomData<TagOrContent<'de>>,
355}
356
357impl<'de> TagOrContentVisitor<'de> {
358    fn new(name: &'static str) -> Self {
359        TagOrContentVisitor {
360            name,
361            value: PhantomData,
362        }
363    }
364}
365
366impl<'de> DeserializeSeed<'de> for TagOrContentVisitor<'de> {
367    type Value = TagOrContent<'de>;
368
369    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
370    where
371        D: Deserializer<'de>,
372    {
373        // Internally tagged enums are only supported in self-describing
374        // formats.
375        deserializer.deserialize_any(self)
376    }
377}
378
379impl<'de> Visitor<'de> for TagOrContentVisitor<'de> {
380    type Value = TagOrContent<'de>;
381
382    fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
383        write!(fmt, "a type tag `{}` or any other value", self.name)
384    }
385
386    fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
387    where
388        F: de::Error,
389    {
390        ContentVisitor::new()
391            .visit_bool(value)
392            .map(TagOrContent::Content)
393    }
394
395    fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
396    where
397        F: de::Error,
398    {
399        ContentVisitor::new()
400            .visit_i8(value)
401            .map(TagOrContent::Content)
402    }
403
404    fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
405    where
406        F: de::Error,
407    {
408        ContentVisitor::new()
409            .visit_i16(value)
410            .map(TagOrContent::Content)
411    }
412
413    fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
414    where
415        F: de::Error,
416    {
417        ContentVisitor::new()
418            .visit_i32(value)
419            .map(TagOrContent::Content)
420    }
421
422    fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
423    where
424        F: de::Error,
425    {
426        ContentVisitor::new()
427            .visit_i64(value)
428            .map(TagOrContent::Content)
429    }
430
431    fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
432    where
433        F: de::Error,
434    {
435        ContentVisitor::new()
436            .visit_u8(value)
437            .map(TagOrContent::Content)
438    }
439
440    fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
441    where
442        F: de::Error,
443    {
444        ContentVisitor::new()
445            .visit_u16(value)
446            .map(TagOrContent::Content)
447    }
448
449    fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
450    where
451        F: de::Error,
452    {
453        ContentVisitor::new()
454            .visit_u32(value)
455            .map(TagOrContent::Content)
456    }
457
458    fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
459    where
460        F: de::Error,
461    {
462        ContentVisitor::new()
463            .visit_u64(value)
464            .map(TagOrContent::Content)
465    }
466
467    fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
468    where
469        F: de::Error,
470    {
471        ContentVisitor::new()
472            .visit_f32(value)
473            .map(TagOrContent::Content)
474    }
475
476    fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
477    where
478        F: de::Error,
479    {
480        ContentVisitor::new()
481            .visit_f64(value)
482            .map(TagOrContent::Content)
483    }
484
485    fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
486    where
487        F: de::Error,
488    {
489        ContentVisitor::new()
490            .visit_char(value)
491            .map(TagOrContent::Content)
492    }
493
494    fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
495    where
496        F: de::Error,
497    {
498        if value == self.name {
499            Ok(TagOrContent::Tag)
500        } else {
501            ContentVisitor::new()
502                .visit_str(value)
503                .map(TagOrContent::Content)
504        }
505    }
506
507    fn visit_borrowed_str<F>(self, value: &'de str) -> Result<Self::Value, F>
508    where
509        F: de::Error,
510    {
511        if value == self.name {
512            Ok(TagOrContent::Tag)
513        } else {
514            ContentVisitor::new()
515                .visit_borrowed_str(value)
516                .map(TagOrContent::Content)
517        }
518    }
519
520    fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
521    where
522        F: de::Error,
523    {
524        if value == self.name {
525            Ok(TagOrContent::Tag)
526        } else {
527            ContentVisitor::new()
528                .visit_string(value)
529                .map(TagOrContent::Content)
530        }
531    }
532
533    fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
534    where
535        F: de::Error,
536    {
537        if value == self.name.as_bytes() {
538            Ok(TagOrContent::Tag)
539        } else {
540            ContentVisitor::new()
541                .visit_bytes(value)
542                .map(TagOrContent::Content)
543        }
544    }
545
546    fn visit_borrowed_bytes<F>(self, value: &'de [u8]) -> Result<Self::Value, F>
547    where
548        F: de::Error,
549    {
550        if value == self.name.as_bytes() {
551            Ok(TagOrContent::Tag)
552        } else {
553            ContentVisitor::new()
554                .visit_borrowed_bytes(value)
555                .map(TagOrContent::Content)
556        }
557    }
558
559    fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
560    where
561        F: de::Error,
562    {
563        if value == self.name.as_bytes() {
564            Ok(TagOrContent::Tag)
565        } else {
566            ContentVisitor::new()
567                .visit_byte_buf(value)
568                .map(TagOrContent::Content)
569        }
570    }
571
572    fn visit_unit<F>(self) -> Result<Self::Value, F>
573    where
574        F: de::Error,
575    {
576        ContentVisitor::new()
577            .visit_unit()
578            .map(TagOrContent::Content)
579    }
580
581    fn visit_none<F>(self) -> Result<Self::Value, F>
582    where
583        F: de::Error,
584    {
585        ContentVisitor::new()
586            .visit_none()
587            .map(TagOrContent::Content)
588    }
589
590    fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
591    where
592        D: Deserializer<'de>,
593    {
594        ContentVisitor::new()
595            .visit_some(deserializer)
596            .map(TagOrContent::Content)
597    }
598
599    fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
600    where
601        D: Deserializer<'de>,
602    {
603        ContentVisitor::new()
604            .visit_newtype_struct(deserializer)
605            .map(TagOrContent::Content)
606    }
607
608    fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
609    where
610        V: SeqAccess<'de>,
611    {
612        ContentVisitor::new()
613            .visit_seq(visitor)
614            .map(TagOrContent::Content)
615    }
616
617    fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
618    where
619        V: MapAccess<'de>,
620    {
621        ContentVisitor::new()
622            .visit_map(visitor)
623            .map(TagOrContent::Content)
624    }
625
626    fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
627    where
628        V: EnumAccess<'de>,
629    {
630        ContentVisitor::new()
631            .visit_enum(visitor)
632            .map(TagOrContent::Content)
633    }
634}
635
636/// Used by generated code to deserialize an internally tagged enum.
637///
638/// Captures map or sequence from the original deserializer and searches
639/// a tag in it (in case of sequence, tag is the first element of sequence).
640///
641/// Not public API.
642pub struct TaggedContentVisitor<T> {
643    tag_name: &'static str,
644    expecting: &'static str,
645    value: PhantomData<T>,
646}
647
648impl<T> TaggedContentVisitor<T> {
649    /// Visitor for the content of an internally tagged enum with the given
650    /// tag name.
651    pub fn new(name: &'static str, expecting: &'static str) -> Self {
652        TaggedContentVisitor {
653            tag_name: name,
654            expecting,
655            value: PhantomData,
656        }
657    }
658}
659
660impl<'de, T> Visitor<'de> for TaggedContentVisitor<T>
661where
662    T: Deserialize<'de>,
663{
664    type Value = (T, Content<'de>);
665
666    fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
667        fmt.write_str(self.expecting)
668    }
669
670    fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
671    where
672        S: SeqAccess<'de>,
673    {
674        let tag = match tri!(seq.next_element()) {
675            Some(tag) => tag,
676            None => {
677                return Err(de::Error::missing_field(self.tag_name));
678            }
679        };
680        let rest = de::value::SeqAccessDeserializer::new(seq);
681        Ok((tag, tri!(Content::deserialize(rest))))
682    }
683
684    fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
685    where
686        M: MapAccess<'de>,
687    {
688        let mut tag = None;
689        let mut vec = Vec::<(Content, Content)>::with_capacity(map.size_hint().unwrap_or(0));
690        while let Some(k) = tri!(map.next_key_seed(TagOrContentVisitor::new(self.tag_name))) {
691            match k {
692                TagOrContent::Tag => {
693                    if tag.is_some() {
694                        return Err(de::Error::duplicate_field(self.tag_name));
695                    }
696                    tag = Some(tri!(map.next_value()));
697                }
698                TagOrContent::Content(k) => {
699                    let v = tri!(map.next_value());
700                    vec.push((k, v));
701                }
702            }
703        }
704        match tag {
705            None => Err(de::Error::missing_field(self.tag_name)),
706            Some(tag) => Ok((tag, Content::Map(vec))),
707        }
708    }
709}
710
711/// Used by generated code to deserialize an adjacently tagged enum.
712///
713/// Not public API.
714pub enum TagOrContentField {
715    Tag,
716    Content,
717}
718
719/// Not public API.
720pub struct TagOrContentFieldVisitor {
721    /// Name of the tag field of the adjacently tagged enum
722    pub tag: &'static str,
723    /// Name of the content field of the adjacently tagged enum
724    pub content: &'static str,
725}
726
727impl<'de> DeserializeSeed<'de> for TagOrContentFieldVisitor {
728    type Value = TagOrContentField;
729
730    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
731    where
732        D: Deserializer<'de>,
733    {
734        deserializer.deserialize_identifier(self)
735    }
736}
737
738impl<'de> Visitor<'de> for TagOrContentFieldVisitor {
739    type Value = TagOrContentField;
740
741    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
742        write!(formatter, "{:?} or {:?}", self.tag, self.content)
743    }
744
745    fn visit_u64<E>(self, field_index: u64) -> Result<Self::Value, E>
746    where
747        E: de::Error,
748    {
749        match field_index {
750            0 => Ok(TagOrContentField::Tag),
751            1 => Ok(TagOrContentField::Content),
752            _ => Err(de::Error::invalid_value(
753                Unexpected::Unsigned(field_index),
754                &self,
755            )),
756        }
757    }
758
759    fn visit_str<E>(self, field: &str) -> Result<Self::Value, E>
760    where
761        E: de::Error,
762    {
763        if field == self.tag {
764            Ok(TagOrContentField::Tag)
765        } else if field == self.content {
766            Ok(TagOrContentField::Content)
767        } else {
768            Err(de::Error::invalid_value(Unexpected::Str(field), &self))
769        }
770    }
771
772    fn visit_bytes<E>(self, field: &[u8]) -> Result<Self::Value, E>
773    where
774        E: de::Error,
775    {
776        if field == self.tag.as_bytes() {
777            Ok(TagOrContentField::Tag)
778        } else if field == self.content.as_bytes() {
779            Ok(TagOrContentField::Content)
780        } else {
781            Err(de::Error::invalid_value(Unexpected::Bytes(field), &self))
782        }
783    }
784}
785
786/// Used by generated code to deserialize an adjacently tagged enum when
787/// ignoring unrelated fields is allowed.
788///
789/// Not public API.
790pub enum TagContentOtherField {
791    Tag,
792    Content,
793    Other,
794}
795
796/// Not public API.
797pub struct TagContentOtherFieldVisitor {
798    /// Name of the tag field of the adjacently tagged enum
799    pub tag: &'static str,
800    /// Name of the content field of the adjacently tagged enum
801    pub content: &'static str,
802}
803
804impl<'de> DeserializeSeed<'de> for TagContentOtherFieldVisitor {
805    type Value = TagContentOtherField;
806
807    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
808    where
809        D: Deserializer<'de>,
810    {
811        deserializer.deserialize_identifier(self)
812    }
813}
814
815impl<'de> Visitor<'de> for TagContentOtherFieldVisitor {
816    type Value = TagContentOtherField;
817
818    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
819        write!(
820            formatter,
821            "{:?}, {:?}, or other ignored fields",
822            self.tag, self.content
823        )
824    }
825
826    fn visit_u64<E>(self, field_index: u64) -> Result<Self::Value, E>
827    where
828        E: de::Error,
829    {
830        match field_index {
831            0 => Ok(TagContentOtherField::Tag),
832            1 => Ok(TagContentOtherField::Content),
833            _ => Ok(TagContentOtherField::Other),
834        }
835    }
836
837    fn visit_str<E>(self, field: &str) -> Result<Self::Value, E>
838    where
839        E: de::Error,
840    {
841        self.visit_bytes(field.as_bytes())
842    }
843
844    fn visit_bytes<E>(self, field: &[u8]) -> Result<Self::Value, E>
845    where
846        E: de::Error,
847    {
848        if field == self.tag.as_bytes() {
849            Ok(TagContentOtherField::Tag)
850        } else if field == self.content.as_bytes() {
851            Ok(TagContentOtherField::Content)
852        } else {
853            Ok(TagContentOtherField::Other)
854        }
855    }
856}
857
858/// Not public API
859pub struct ContentDeserializer<'de, E> {
860    content: Content<'de>,
861    err: PhantomData<E>,
862}
863
864impl<'de, E> ContentDeserializer<'de, E>
865where
866    E: de::Error,
867{
868    #[cold]
869    fn invalid_type(self, exp: &dyn Expected) -> E {
870        de::Error::invalid_type(self.content.unexpected(), exp)
871    }
872
873    fn deserialize_integer<V>(self, visitor: V) -> Result<V::Value, E>
874    where
875        V: Visitor<'de>,
876    {
877        match self.content {
878            Content::U8(v) => visitor.visit_u8(v),
879            Content::U16(v) => visitor.visit_u16(v),
880            Content::U32(v) => visitor.visit_u32(v),
881            Content::U64(v) => visitor.visit_u64(v),
882            Content::I8(v) => visitor.visit_i8(v),
883            Content::I16(v) => visitor.visit_i16(v),
884            Content::I32(v) => visitor.visit_i32(v),
885            Content::I64(v) => visitor.visit_i64(v),
886            _ => Err(self.invalid_type(&visitor)),
887        }
888    }
889
890    fn deserialize_float<V>(self, visitor: V) -> Result<V::Value, E>
891    where
892        V: Visitor<'de>,
893    {
894        match self.content {
895            Content::F32(v) => visitor.visit_f32(v),
896            Content::F64(v) => visitor.visit_f64(v),
897            Content::U8(v) => visitor.visit_u8(v),
898            Content::U16(v) => visitor.visit_u16(v),
899            Content::U32(v) => visitor.visit_u32(v),
900            Content::U64(v) => visitor.visit_u64(v),
901            Content::I8(v) => visitor.visit_i8(v),
902            Content::I16(v) => visitor.visit_i16(v),
903            Content::I32(v) => visitor.visit_i32(v),
904            Content::I64(v) => visitor.visit_i64(v),
905            _ => Err(self.invalid_type(&visitor)),
906        }
907    }
908}
909
910fn visit_content_seq<'de, V, E>(content: Vec<Content<'de>>, visitor: V) -> Result<V::Value, E>
911where
912    V: Visitor<'de>,
913    E: de::Error,
914{
915    let mut seq_visitor = SeqDeserializer::new(content.into_iter());
916    let value = tri!(visitor.visit_seq(&mut seq_visitor));
917    tri!(seq_visitor.end());
918    Ok(value)
919}
920
921fn visit_content_map<'de, V, E>(
922    content: Vec<(Content<'de>, Content<'de>)>,
923    visitor: V,
924) -> Result<V::Value, E>
925where
926    V: Visitor<'de>,
927    E: de::Error,
928{
929    let mut map_visitor = MapDeserializer::new(content.into_iter());
930    let value = tri!(visitor.visit_map(&mut map_visitor));
931    tri!(map_visitor.end());
932    Ok(value)
933}
934
935/// Used when deserializing an internally tagged enum because the content
936/// will be used exactly once.
937impl<'de, E> Deserializer<'de> for ContentDeserializer<'de, E>
938where
939    E: de::Error,
940{
941    type Error = E;
942
943    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
944    where
945        V: Visitor<'de>,
946    {
947        match self.content {
948            Content::Bool(v) => visitor.visit_bool(v),
949            Content::U8(v) => visitor.visit_u8(v),
950            Content::U16(v) => visitor.visit_u16(v),
951            Content::U32(v) => visitor.visit_u32(v),
952            Content::U64(v) => visitor.visit_u64(v),
953            Content::I8(v) => visitor.visit_i8(v),
954            Content::I16(v) => visitor.visit_i16(v),
955            Content::I32(v) => visitor.visit_i32(v),
956            Content::I64(v) => visitor.visit_i64(v),
957            Content::F32(v) => visitor.visit_f32(v),
958            Content::F64(v) => visitor.visit_f64(v),
959            Content::Char(v) => visitor.visit_char(v),
960            Content::String(v) => visitor.visit_string(v),
961            Content::Str(v) => visitor.visit_borrowed_str(v),
962            Content::ByteBuf(v) => visitor.visit_byte_buf(v),
963            Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
964            Content::Unit => visitor.visit_unit(),
965            Content::None => visitor.visit_none(),
966            Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
967            Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)),
968            Content::Seq(v) => visit_content_seq(v, visitor),
969            Content::Map(v) => visit_content_map(v, visitor),
970        }
971    }
972
973    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
974    where
975        V: Visitor<'de>,
976    {
977        match self.content {
978            Content::Bool(v) => visitor.visit_bool(v),
979            _ => Err(self.invalid_type(&visitor)),
980        }
981    }
982
983    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
984    where
985        V: Visitor<'de>,
986    {
987        self.deserialize_integer(visitor)
988    }
989
990    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
991    where
992        V: Visitor<'de>,
993    {
994        self.deserialize_integer(visitor)
995    }
996
997    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
998    where
999        V: Visitor<'de>,
1000    {
1001        self.deserialize_integer(visitor)
1002    }
1003
1004    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1005    where
1006        V: Visitor<'de>,
1007    {
1008        self.deserialize_integer(visitor)
1009    }
1010
1011    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1012    where
1013        V: Visitor<'de>,
1014    {
1015        self.deserialize_integer(visitor)
1016    }
1017
1018    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1019    where
1020        V: Visitor<'de>,
1021    {
1022        self.deserialize_integer(visitor)
1023    }
1024
1025    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1026    where
1027        V: Visitor<'de>,
1028    {
1029        self.deserialize_integer(visitor)
1030    }
1031
1032    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1033    where
1034        V: Visitor<'de>,
1035    {
1036        self.deserialize_integer(visitor)
1037    }
1038
1039    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1040    where
1041        V: Visitor<'de>,
1042    {
1043        self.deserialize_float(visitor)
1044    }
1045
1046    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1047    where
1048        V: Visitor<'de>,
1049    {
1050        self.deserialize_float(visitor)
1051    }
1052
1053    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1054    where
1055        V: Visitor<'de>,
1056    {
1057        match self.content {
1058            Content::Char(v) => visitor.visit_char(v),
1059            Content::String(v) => visitor.visit_string(v),
1060            Content::Str(v) => visitor.visit_borrowed_str(v),
1061            _ => Err(self.invalid_type(&visitor)),
1062        }
1063    }
1064
1065    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1066    where
1067        V: Visitor<'de>,
1068    {
1069        self.deserialize_string(visitor)
1070    }
1071
1072    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1073    where
1074        V: Visitor<'de>,
1075    {
1076        match self.content {
1077            Content::String(v) => visitor.visit_string(v),
1078            Content::Str(v) => visitor.visit_borrowed_str(v),
1079            Content::ByteBuf(v) => visitor.visit_byte_buf(v),
1080            Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1081            _ => Err(self.invalid_type(&visitor)),
1082        }
1083    }
1084
1085    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1086    where
1087        V: Visitor<'de>,
1088    {
1089        self.deserialize_byte_buf(visitor)
1090    }
1091
1092    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1093    where
1094        V: Visitor<'de>,
1095    {
1096        match self.content {
1097            Content::String(v) => visitor.visit_string(v),
1098            Content::Str(v) => visitor.visit_borrowed_str(v),
1099            Content::ByteBuf(v) => visitor.visit_byte_buf(v),
1100            Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1101            Content::Seq(v) => visit_content_seq(v, visitor),
1102            _ => Err(self.invalid_type(&visitor)),
1103        }
1104    }
1105
1106    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1107    where
1108        V: Visitor<'de>,
1109    {
1110        match self.content {
1111            Content::None => visitor.visit_none(),
1112            Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
1113            Content::Unit => visitor.visit_unit(),
1114            _ => visitor.visit_some(self),
1115        }
1116    }
1117
1118    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1119    where
1120        V: Visitor<'de>,
1121    {
1122        match self.content {
1123            Content::Unit => visitor.visit_unit(),
1124
1125            // Allow deserializing newtype variant containing unit.
1126            //
1127            //     #[derive(Deserialize)]
1128            //     #[serde(tag = "result")]
1129            //     enum Response<T> {
1130            //         Success(T),
1131            //     }
1132            //
1133            // We want {"result":"Success"} to deserialize into Response<()>.
1134            Content::Map(ref v) if v.is_empty() => visitor.visit_unit(),
1135            _ => Err(self.invalid_type(&visitor)),
1136        }
1137    }
1138
1139    fn deserialize_unit_struct<V>(
1140        self,
1141        _name: &'static str,
1142        visitor: V,
1143    ) -> Result<V::Value, Self::Error>
1144    where
1145        V: Visitor<'de>,
1146    {
1147        match self.content {
1148            // As a special case, allow deserializing untagged newtype
1149            // variant containing unit struct.
1150            //
1151            //     #[derive(Deserialize)]
1152            //     struct Info;
1153            //
1154            //     #[derive(Deserialize)]
1155            //     #[serde(tag = "topic")]
1156            //     enum Message {
1157            //         Info(Info),
1158            //     }
1159            //
1160            // We want {"topic":"Info"} to deserialize even though
1161            // ordinarily unit structs do not deserialize from empty map/seq.
1162            Content::Map(ref v) if v.is_empty() => visitor.visit_unit(),
1163            Content::Seq(ref v) if v.is_empty() => visitor.visit_unit(),
1164            _ => self.deserialize_any(visitor),
1165        }
1166    }
1167
1168    fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
1169    where
1170        V: Visitor<'de>,
1171    {
1172        match self.content {
1173            Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)),
1174            _ => visitor.visit_newtype_struct(self),
1175        }
1176    }
1177
1178    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1179    where
1180        V: Visitor<'de>,
1181    {
1182        match self.content {
1183            Content::Seq(v) => visit_content_seq(v, visitor),
1184            _ => Err(self.invalid_type(&visitor)),
1185        }
1186    }
1187
1188    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
1189    where
1190        V: Visitor<'de>,
1191    {
1192        self.deserialize_seq(visitor)
1193    }
1194
1195    fn deserialize_tuple_struct<V>(
1196        self,
1197        _name: &'static str,
1198        _len: usize,
1199        visitor: V,
1200    ) -> Result<V::Value, Self::Error>
1201    where
1202        V: Visitor<'de>,
1203    {
1204        self.deserialize_seq(visitor)
1205    }
1206
1207    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1208    where
1209        V: Visitor<'de>,
1210    {
1211        match self.content {
1212            Content::Map(v) => visit_content_map(v, visitor),
1213            _ => Err(self.invalid_type(&visitor)),
1214        }
1215    }
1216
1217    fn deserialize_struct<V>(
1218        self,
1219        _name: &'static str,
1220        _fields: &'static [&'static str],
1221        visitor: V,
1222    ) -> Result<V::Value, Self::Error>
1223    where
1224        V: Visitor<'de>,
1225    {
1226        match self.content {
1227            Content::Seq(v) => visit_content_seq(v, visitor),
1228            Content::Map(v) => visit_content_map(v, visitor),
1229            _ => Err(self.invalid_type(&visitor)),
1230        }
1231    }
1232
1233    fn deserialize_enum<V>(
1234        self,
1235        _name: &str,
1236        _variants: &'static [&'static str],
1237        visitor: V,
1238    ) -> Result<V::Value, Self::Error>
1239    where
1240        V: Visitor<'de>,
1241    {
1242        let (variant, value) = match self.content {
1243            Content::Map(value) => {
1244                let mut iter = value.into_iter();
1245                let (variant, value) = match iter.next() {
1246                    Some(v) => v,
1247                    None => {
1248                        return Err(de::Error::invalid_value(
1249                            de::Unexpected::Map,
1250                            &"map with a single key",
1251                        ));
1252                    }
1253                };
1254                // enums are encoded in json as maps with a single key:value pair
1255                if iter.next().is_some() {
1256                    return Err(de::Error::invalid_value(
1257                        de::Unexpected::Map,
1258                        &"map with a single key",
1259                    ));
1260                }
1261                (variant, Some(value))
1262            }
1263            s @ Content::String(_) | s @ Content::Str(_) => (s, None),
1264            other => {
1265                return Err(de::Error::invalid_type(
1266                    other.unexpected(),
1267                    &"string or map",
1268                ));
1269            }
1270        };
1271
1272        visitor.visit_enum(EnumDeserializer::new(variant, value))
1273    }
1274
1275    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1276    where
1277        V: Visitor<'de>,
1278    {
1279        match self.content {
1280            Content::String(v) => visitor.visit_string(v),
1281            Content::Str(v) => visitor.visit_borrowed_str(v),
1282            Content::ByteBuf(v) => visitor.visit_byte_buf(v),
1283            Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1284            Content::U8(v) => visitor.visit_u8(v),
1285            Content::U64(v) => visitor.visit_u64(v),
1286            _ => Err(self.invalid_type(&visitor)),
1287        }
1288    }
1289
1290    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1291    where
1292        V: Visitor<'de>,
1293    {
1294        drop(self);
1295        visitor.visit_unit()
1296    }
1297}
1298
1299impl<'de, E> ContentDeserializer<'de, E> {
1300    /// private API, don't use
1301    pub fn new(content: Content<'de>) -> Self {
1302        ContentDeserializer {
1303            content,
1304            err: PhantomData,
1305        }
1306    }
1307}
1308
1309pub struct EnumDeserializer<'de, E>
1310where
1311    E: de::Error,
1312{
1313    variant: Content<'de>,
1314    value: Option<Content<'de>>,
1315    err: PhantomData<E>,
1316}
1317
1318impl<'de, E> EnumDeserializer<'de, E>
1319where
1320    E: de::Error,
1321{
1322    pub fn new(variant: Content<'de>, value: Option<Content<'de>>) -> EnumDeserializer<'de, E> {
1323        EnumDeserializer {
1324            variant,
1325            value,
1326            err: PhantomData,
1327        }
1328    }
1329}
1330
1331impl<'de, E> de::EnumAccess<'de> for EnumDeserializer<'de, E>
1332where
1333    E: de::Error,
1334{
1335    type Error = E;
1336    type Variant = VariantDeserializer<'de, Self::Error>;
1337
1338    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), E>
1339    where
1340        V: de::DeserializeSeed<'de>,
1341    {
1342        let visitor = VariantDeserializer {
1343            value: self.value,
1344            err: PhantomData,
1345        };
1346        seed.deserialize(ContentDeserializer::new(self.variant))
1347            .map(|v| (v, visitor))
1348    }
1349}
1350
1351pub struct VariantDeserializer<'de, E>
1352where
1353    E: de::Error,
1354{
1355    value: Option<Content<'de>>,
1356    err: PhantomData<E>,
1357}
1358
1359impl<'de, E> de::VariantAccess<'de> for VariantDeserializer<'de, E>
1360where
1361    E: de::Error,
1362{
1363    type Error = E;
1364
1365    fn unit_variant(self) -> Result<(), E> {
1366        match self.value {
1367            Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)),
1368            None => Ok(()),
1369        }
1370    }
1371
1372    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E>
1373    where
1374        T: de::DeserializeSeed<'de>,
1375    {
1376        match self.value {
1377            Some(value) => seed.deserialize(ContentDeserializer::new(value)),
1378            None => Err(de::Error::invalid_type(
1379                de::Unexpected::UnitVariant,
1380                &"newtype variant",
1381            )),
1382        }
1383    }
1384
1385    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
1386    where
1387        V: de::Visitor<'de>,
1388    {
1389        match self.value {
1390            Some(Content::Seq(v)) => {
1391                de::Deserializer::deserialize_any(SeqDeserializer::new(v.into_iter()), visitor)
1392            }
1393            Some(other) => Err(de::Error::invalid_type(
1394                other.unexpected(),
1395                &"tuple variant",
1396            )),
1397            None => Err(de::Error::invalid_type(
1398                de::Unexpected::UnitVariant,
1399                &"tuple variant",
1400            )),
1401        }
1402    }
1403
1404    fn struct_variant<V>(
1405        self,
1406        _fields: &'static [&'static str],
1407        visitor: V,
1408    ) -> Result<V::Value, Self::Error>
1409    where
1410        V: de::Visitor<'de>,
1411    {
1412        match self.value {
1413            Some(Content::Map(v)) => {
1414                de::Deserializer::deserialize_any(MapDeserializer::new(v.into_iter()), visitor)
1415            }
1416            Some(Content::Seq(v)) => {
1417                de::Deserializer::deserialize_any(SeqDeserializer::new(v.into_iter()), visitor)
1418            }
1419            Some(other) => Err(de::Error::invalid_type(
1420                other.unexpected(),
1421                &"struct variant",
1422            )),
1423            None => Err(de::Error::invalid_type(
1424                de::Unexpected::UnitVariant,
1425                &"struct variant",
1426            )),
1427        }
1428    }
1429}
1430
1431/// Not public API.
1432pub struct ContentRefDeserializer<'a, 'de: 'a, E> {
1433    content: &'a Content<'de>,
1434    err: PhantomData<E>,
1435}
1436
1437impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E>
1438where
1439    E: de::Error,
1440{
1441    #[cold]
1442    fn invalid_type(self, exp: &dyn Expected) -> E {
1443        de::Error::invalid_type(self.content.unexpected(), exp)
1444    }
1445
1446    fn deserialize_integer<V>(self, visitor: V) -> Result<V::Value, E>
1447    where
1448        V: Visitor<'de>,
1449    {
1450        match *self.content {
1451            Content::U8(v) => visitor.visit_u8(v),
1452            Content::U16(v) => visitor.visit_u16(v),
1453            Content::U32(v) => visitor.visit_u32(v),
1454            Content::U64(v) => visitor.visit_u64(v),
1455            Content::I8(v) => visitor.visit_i8(v),
1456            Content::I16(v) => visitor.visit_i16(v),
1457            Content::I32(v) => visitor.visit_i32(v),
1458            Content::I64(v) => visitor.visit_i64(v),
1459            _ => Err(self.invalid_type(&visitor)),
1460        }
1461    }
1462
1463    fn deserialize_float<V>(self, visitor: V) -> Result<V::Value, E>
1464    where
1465        V: Visitor<'de>,
1466    {
1467        match *self.content {
1468            Content::F32(v) => visitor.visit_f32(v),
1469            Content::F64(v) => visitor.visit_f64(v),
1470            Content::U8(v) => visitor.visit_u8(v),
1471            Content::U16(v) => visitor.visit_u16(v),
1472            Content::U32(v) => visitor.visit_u32(v),
1473            Content::U64(v) => visitor.visit_u64(v),
1474            Content::I8(v) => visitor.visit_i8(v),
1475            Content::I16(v) => visitor.visit_i16(v),
1476            Content::I32(v) => visitor.visit_i32(v),
1477            Content::I64(v) => visitor.visit_i64(v),
1478            _ => Err(self.invalid_type(&visitor)),
1479        }
1480    }
1481}
1482
1483fn visit_content_seq_ref<'a, 'de, V, E>(
1484    content: &'a [Content<'de>],
1485    visitor: V,
1486) -> Result<V::Value, E>
1487where
1488    V: Visitor<'de>,
1489    E: de::Error,
1490{
1491    let mut seq_visitor = SeqDeserializer::new(content.iter());
1492    let value = tri!(visitor.visit_seq(&mut seq_visitor));
1493    tri!(seq_visitor.end());
1494    Ok(value)
1495}
1496
1497fn visit_content_map_ref<'a, 'de, V, E>(
1498    content: &'a [(Content<'de>, Content<'de>)],
1499    visitor: V,
1500) -> Result<V::Value, E>
1501where
1502    V: Visitor<'de>,
1503    E: de::Error,
1504{
1505    fn content_ref_deserializer_pair<'a, 'de>(
1506        (k, v): &'a (Content<'de>, Content<'de>),
1507    ) -> (&'a Content<'de>, &'a Content<'de>) {
1508        (k, v)
1509    }
1510
1511    let map = content.iter().map(content_ref_deserializer_pair);
1512    let mut map_visitor = MapDeserializer::new(map);
1513    let value = tri!(visitor.visit_map(&mut map_visitor));
1514    tri!(map_visitor.end());
1515    Ok(value)
1516}
1517
1518/// Used when deserializing an untagged enum because the content may need
1519/// to be used more than once.
1520impl<'de, 'a, E> Deserializer<'de> for ContentRefDeserializer<'a, 'de, E>
1521where
1522    E: de::Error,
1523{
1524    type Error = E;
1525
1526    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, E>
1527    where
1528        V: Visitor<'de>,
1529    {
1530        match *self.content {
1531            Content::Bool(v) => visitor.visit_bool(v),
1532            Content::U8(v) => visitor.visit_u8(v),
1533            Content::U16(v) => visitor.visit_u16(v),
1534            Content::U32(v) => visitor.visit_u32(v),
1535            Content::U64(v) => visitor.visit_u64(v),
1536            Content::I8(v) => visitor.visit_i8(v),
1537            Content::I16(v) => visitor.visit_i16(v),
1538            Content::I32(v) => visitor.visit_i32(v),
1539            Content::I64(v) => visitor.visit_i64(v),
1540            Content::F32(v) => visitor.visit_f32(v),
1541            Content::F64(v) => visitor.visit_f64(v),
1542            Content::Char(v) => visitor.visit_char(v),
1543            Content::String(ref v) => visitor.visit_str(v),
1544            Content::Str(v) => visitor.visit_borrowed_str(v),
1545            Content::ByteBuf(ref v) => visitor.visit_bytes(v),
1546            Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1547            Content::Unit => visitor.visit_unit(),
1548            Content::None => visitor.visit_none(),
1549            Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
1550            Content::Newtype(ref v) => visitor.visit_newtype_struct(ContentRefDeserializer::new(v)),
1551            Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
1552            Content::Map(ref v) => visit_content_map_ref(v, visitor),
1553        }
1554    }
1555
1556    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1557    where
1558        V: Visitor<'de>,
1559    {
1560        match *self.content {
1561            Content::Bool(v) => visitor.visit_bool(v),
1562            _ => Err(self.invalid_type(&visitor)),
1563        }
1564    }
1565
1566    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1567    where
1568        V: Visitor<'de>,
1569    {
1570        self.deserialize_integer(visitor)
1571    }
1572
1573    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1574    where
1575        V: Visitor<'de>,
1576    {
1577        self.deserialize_integer(visitor)
1578    }
1579
1580    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1581    where
1582        V: Visitor<'de>,
1583    {
1584        self.deserialize_integer(visitor)
1585    }
1586
1587    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1588    where
1589        V: Visitor<'de>,
1590    {
1591        self.deserialize_integer(visitor)
1592    }
1593
1594    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1595    where
1596        V: Visitor<'de>,
1597    {
1598        self.deserialize_integer(visitor)
1599    }
1600
1601    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1602    where
1603        V: Visitor<'de>,
1604    {
1605        self.deserialize_integer(visitor)
1606    }
1607
1608    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1609    where
1610        V: Visitor<'de>,
1611    {
1612        self.deserialize_integer(visitor)
1613    }
1614
1615    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1616    where
1617        V: Visitor<'de>,
1618    {
1619        self.deserialize_integer(visitor)
1620    }
1621
1622    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1623    where
1624        V: Visitor<'de>,
1625    {
1626        self.deserialize_float(visitor)
1627    }
1628
1629    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1630    where
1631        V: Visitor<'de>,
1632    {
1633        self.deserialize_float(visitor)
1634    }
1635
1636    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1637    where
1638        V: Visitor<'de>,
1639    {
1640        match *self.content {
1641            Content::Char(v) => visitor.visit_char(v),
1642            Content::String(ref v) => visitor.visit_str(v),
1643            Content::Str(v) => visitor.visit_borrowed_str(v),
1644            _ => Err(self.invalid_type(&visitor)),
1645        }
1646    }
1647
1648    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1649    where
1650        V: Visitor<'de>,
1651    {
1652        match *self.content {
1653            Content::String(ref v) => visitor.visit_str(v),
1654            Content::Str(v) => visitor.visit_borrowed_str(v),
1655            Content::ByteBuf(ref v) => visitor.visit_bytes(v),
1656            Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1657            _ => Err(self.invalid_type(&visitor)),
1658        }
1659    }
1660
1661    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1662    where
1663        V: Visitor<'de>,
1664    {
1665        self.deserialize_str(visitor)
1666    }
1667
1668    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1669    where
1670        V: Visitor<'de>,
1671    {
1672        match *self.content {
1673            Content::String(ref v) => visitor.visit_str(v),
1674            Content::Str(v) => visitor.visit_borrowed_str(v),
1675            Content::ByteBuf(ref v) => visitor.visit_bytes(v),
1676            Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1677            Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
1678            _ => Err(self.invalid_type(&visitor)),
1679        }
1680    }
1681
1682    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1683    where
1684        V: Visitor<'de>,
1685    {
1686        self.deserialize_bytes(visitor)
1687    }
1688
1689    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E>
1690    where
1691        V: Visitor<'de>,
1692    {
1693        // Covered by tests/test_enum_untagged.rs
1694        //      with_optional_field::*
1695        match *self.content {
1696            Content::None => visitor.visit_none(),
1697            Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
1698            Content::Unit => visitor.visit_unit(),
1699            // This case is to support data formats which do not encode an
1700            // indication whether a value is optional. An example of such a
1701            // format is JSON, and a counterexample is RON. When requesting
1702            // `deserialize_any` in JSON, the data format never performs
1703            // `Visitor::visit_some` but we still must be able to
1704            // deserialize the resulting Content into data structures with
1705            // optional fields.
1706            _ => visitor.visit_some(self),
1707        }
1708    }
1709
1710    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1711    where
1712        V: Visitor<'de>,
1713    {
1714        match *self.content {
1715            Content::Unit => visitor.visit_unit(),
1716            _ => Err(self.invalid_type(&visitor)),
1717        }
1718    }
1719
1720    fn deserialize_unit_struct<V>(
1721        self,
1722        _name: &'static str,
1723        visitor: V,
1724    ) -> Result<V::Value, Self::Error>
1725    where
1726        V: Visitor<'de>,
1727    {
1728        self.deserialize_unit(visitor)
1729    }
1730
1731    fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, E>
1732    where
1733        V: Visitor<'de>,
1734    {
1735        // Covered by tests/test_enum_untagged.rs
1736        //      newtype_struct
1737        match *self.content {
1738            Content::Newtype(ref v) => visitor.visit_newtype_struct(ContentRefDeserializer::new(v)),
1739            // This case is to support data formats that encode newtype
1740            // structs and their underlying data the same, with no
1741            // indication whether a newtype wrapper was present. For example
1742            // JSON does this, while RON does not. In RON a newtype's name
1743            // is included in the serialized representation and it knows to
1744            // call `Visitor::visit_newtype_struct` from `deserialize_any`.
1745            // JSON's `deserialize_any` never calls `visit_newtype_struct`
1746            // but in this code we still must be able to deserialize the
1747            // resulting Content into newtypes.
1748            _ => visitor.visit_newtype_struct(self),
1749        }
1750    }
1751
1752    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1753    where
1754        V: Visitor<'de>,
1755    {
1756        match *self.content {
1757            Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
1758            _ => Err(self.invalid_type(&visitor)),
1759        }
1760    }
1761
1762    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
1763    where
1764        V: Visitor<'de>,
1765    {
1766        self.deserialize_seq(visitor)
1767    }
1768
1769    fn deserialize_tuple_struct<V>(
1770        self,
1771        _name: &'static str,
1772        _len: usize,
1773        visitor: V,
1774    ) -> Result<V::Value, Self::Error>
1775    where
1776        V: Visitor<'de>,
1777    {
1778        self.deserialize_seq(visitor)
1779    }
1780
1781    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1782    where
1783        V: Visitor<'de>,
1784    {
1785        match *self.content {
1786            Content::Map(ref v) => visit_content_map_ref(v, visitor),
1787            _ => Err(self.invalid_type(&visitor)),
1788        }
1789    }
1790
1791    fn deserialize_struct<V>(
1792        self,
1793        _name: &'static str,
1794        _fields: &'static [&'static str],
1795        visitor: V,
1796    ) -> Result<V::Value, Self::Error>
1797    where
1798        V: Visitor<'de>,
1799    {
1800        match *self.content {
1801            Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
1802            Content::Map(ref v) => visit_content_map_ref(v, visitor),
1803            _ => Err(self.invalid_type(&visitor)),
1804        }
1805    }
1806
1807    fn deserialize_enum<V>(
1808        self,
1809        _name: &str,
1810        _variants: &'static [&'static str],
1811        visitor: V,
1812    ) -> Result<V::Value, Self::Error>
1813    where
1814        V: Visitor<'de>,
1815    {
1816        let (variant, value) = match *self.content {
1817            Content::Map(ref value) => {
1818                let mut iter = value.iter();
1819                let (variant, value) = match iter.next() {
1820                    Some(v) => v,
1821                    None => {
1822                        return Err(de::Error::invalid_value(
1823                            de::Unexpected::Map,
1824                            &"map with a single key",
1825                        ));
1826                    }
1827                };
1828                // enums are encoded in json as maps with a single key:value pair
1829                if iter.next().is_some() {
1830                    return Err(de::Error::invalid_value(
1831                        de::Unexpected::Map,
1832                        &"map with a single key",
1833                    ));
1834                }
1835                (variant, Some(value))
1836            }
1837            ref s @ Content::String(_) | ref s @ Content::Str(_) => (s, None),
1838            ref other => {
1839                return Err(de::Error::invalid_type(
1840                    other.unexpected(),
1841                    &"string or map",
1842                ));
1843            }
1844        };
1845
1846        visitor.visit_enum(EnumRefDeserializer {
1847            variant,
1848            value,
1849            err: PhantomData,
1850        })
1851    }
1852
1853    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1854    where
1855        V: Visitor<'de>,
1856    {
1857        match *self.content {
1858            Content::String(ref v) => visitor.visit_str(v),
1859            Content::Str(v) => visitor.visit_borrowed_str(v),
1860            Content::ByteBuf(ref v) => visitor.visit_bytes(v),
1861            Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1862            Content::U8(v) => visitor.visit_u8(v),
1863            Content::U64(v) => visitor.visit_u64(v),
1864            _ => Err(self.invalid_type(&visitor)),
1865        }
1866    }
1867
1868    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1869    where
1870        V: Visitor<'de>,
1871    {
1872        visitor.visit_unit()
1873    }
1874}
1875
1876impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E> {
1877    /// private API, don't use
1878    pub fn new(content: &'a Content<'de>) -> Self {
1879        ContentRefDeserializer {
1880            content,
1881            err: PhantomData,
1882        }
1883    }
1884}
1885
1886impl<'a, 'de: 'a, E> Copy for ContentRefDeserializer<'a, 'de, E> {}
1887
1888impl<'a, 'de: 'a, E> Clone for ContentRefDeserializer<'a, 'de, E> {
1889    fn clone(&self) -> Self {
1890        *self
1891    }
1892}
1893
1894struct EnumRefDeserializer<'a, 'de: 'a, E>
1895where
1896    E: de::Error,
1897{
1898    variant: &'a Content<'de>,
1899    value: Option<&'a Content<'de>>,
1900    err: PhantomData<E>,
1901}
1902
1903impl<'de, 'a, E> de::EnumAccess<'de> for EnumRefDeserializer<'a, 'de, E>
1904where
1905    E: de::Error,
1906{
1907    type Error = E;
1908    type Variant = VariantRefDeserializer<'a, 'de, Self::Error>;
1909
1910    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
1911    where
1912        V: de::DeserializeSeed<'de>,
1913    {
1914        let visitor = VariantRefDeserializer {
1915            value: self.value,
1916            err: PhantomData,
1917        };
1918        seed.deserialize(ContentRefDeserializer::new(self.variant))
1919            .map(|v| (v, visitor))
1920    }
1921}
1922
1923struct VariantRefDeserializer<'a, 'de: 'a, E>
1924where
1925    E: de::Error,
1926{
1927    value: Option<&'a Content<'de>>,
1928    err: PhantomData<E>,
1929}
1930
1931impl<'de, 'a, E> de::VariantAccess<'de> for VariantRefDeserializer<'a, 'de, E>
1932where
1933    E: de::Error,
1934{
1935    type Error = E;
1936
1937    fn unit_variant(self) -> Result<(), E> {
1938        match self.value {
1939            Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)),
1940            // Covered by tests/test_annotations.rs
1941            //      test_partially_untagged_adjacently_tagged_enum
1942            // Covered by tests/test_enum_untagged.rs
1943            //      newtype_enum::unit
1944            None => Ok(()),
1945        }
1946    }
1947
1948    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E>
1949    where
1950        T: de::DeserializeSeed<'de>,
1951    {
1952        match self.value {
1953            // Covered by tests/test_annotations.rs
1954            //      test_partially_untagged_enum_desugared
1955            //      test_partially_untagged_enum_generic
1956            // Covered by tests/test_enum_untagged.rs
1957            //      newtype_enum::newtype
1958            Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
1959            None => Err(de::Error::invalid_type(
1960                de::Unexpected::UnitVariant,
1961                &"newtype variant",
1962            )),
1963        }
1964    }
1965
1966    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
1967    where
1968        V: de::Visitor<'de>,
1969    {
1970        match self.value {
1971            // Covered by tests/test_annotations.rs
1972            //      test_partially_untagged_enum
1973            //      test_partially_untagged_enum_desugared
1974            // Covered by tests/test_enum_untagged.rs
1975            //      newtype_enum::tuple0
1976            //      newtype_enum::tuple2
1977            Some(Content::Seq(v)) => visit_content_seq_ref(v, visitor),
1978            Some(other) => Err(de::Error::invalid_type(
1979                other.unexpected(),
1980                &"tuple variant",
1981            )),
1982            None => Err(de::Error::invalid_type(
1983                de::Unexpected::UnitVariant,
1984                &"tuple variant",
1985            )),
1986        }
1987    }
1988
1989    fn struct_variant<V>(
1990        self,
1991        _fields: &'static [&'static str],
1992        visitor: V,
1993    ) -> Result<V::Value, Self::Error>
1994    where
1995        V: de::Visitor<'de>,
1996    {
1997        match self.value {
1998            // Covered by tests/test_enum_untagged.rs
1999            //      newtype_enum::struct_from_map
2000            Some(Content::Map(v)) => visit_content_map_ref(v, visitor),
2001            // Covered by tests/test_enum_untagged.rs
2002            //      newtype_enum::struct_from_seq
2003            //      newtype_enum::empty_struct_from_seq
2004            Some(Content::Seq(v)) => visit_content_seq_ref(v, visitor),
2005            Some(other) => Err(de::Error::invalid_type(
2006                other.unexpected(),
2007                &"struct variant",
2008            )),
2009            None => Err(de::Error::invalid_type(
2010                de::Unexpected::UnitVariant,
2011                &"struct variant",
2012            )),
2013        }
2014    }
2015}
2016
2017impl<'de, E> de::IntoDeserializer<'de, E> for ContentDeserializer<'de, E>
2018where
2019    E: de::Error,
2020{
2021    type Deserializer = Self;
2022
2023    fn into_deserializer(self) -> Self {
2024        self
2025    }
2026}
2027
2028impl<'de, 'a, E> de::IntoDeserializer<'de, E> for ContentRefDeserializer<'a, 'de, E>
2029where
2030    E: de::Error,
2031{
2032    type Deserializer = Self;
2033
2034    fn into_deserializer(self) -> Self {
2035        self
2036    }
2037}
2038
2039/// Visitor for deserializing an internally tagged unit variant.
2040///
2041/// Not public API.
2042pub struct InternallyTaggedUnitVisitor<'a> {
2043    type_name: &'a str,
2044    variant_name: &'a str,
2045}
2046
2047impl<'a> InternallyTaggedUnitVisitor<'a> {
2048    /// Not public API.
2049    pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
2050        InternallyTaggedUnitVisitor {
2051            type_name,
2052            variant_name,
2053        }
2054    }
2055}
2056
2057impl<'de, 'a> Visitor<'de> for InternallyTaggedUnitVisitor<'a> {
2058    type Value = ();
2059
2060    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2061        write!(
2062            formatter,
2063            "unit variant {}::{}",
2064            self.type_name, self.variant_name
2065        )
2066    }
2067
2068    fn visit_seq<S>(self, _: S) -> Result<(), S::Error>
2069    where
2070        S: SeqAccess<'de>,
2071    {
2072        Ok(())
2073    }
2074
2075    fn visit_map<M>(self, mut access: M) -> Result<(), M::Error>
2076    where
2077        M: MapAccess<'de>,
2078    {
2079        while tri!(access.next_entry::<IgnoredAny, IgnoredAny>()).is_some() {}
2080        Ok(())
2081    }
2082}
2083
2084/// Visitor for deserializing an untagged unit variant.
2085///
2086/// Not public API.
2087pub struct UntaggedUnitVisitor<'a> {
2088    type_name: &'a str,
2089    variant_name: &'a str,
2090}
2091
2092impl<'a> UntaggedUnitVisitor<'a> {
2093    /// Not public API.
2094    pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
2095        UntaggedUnitVisitor {
2096            type_name,
2097            variant_name,
2098        }
2099    }
2100}
2101
2102impl<'de, 'a> Visitor<'de> for UntaggedUnitVisitor<'a> {
2103    type Value = ();
2104
2105    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2106        write!(
2107            formatter,
2108            "unit variant {}::{}",
2109            self.type_name, self.variant_name
2110        )
2111    }
2112
2113    fn visit_unit<E>(self) -> Result<(), E>
2114    where
2115        E: de::Error,
2116    {
2117        Ok(())
2118    }
2119
2120    fn visit_none<E>(self) -> Result<(), E>
2121    where
2122        E: de::Error,
2123    {
2124        Ok(())
2125    }
2126}