serde/private/
de.rs

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