]> git.proxmox.com Git - cargo.git/blob - vendor/serde/src/private/de.rs
New upstream version 0.35.0
[cargo.git] / vendor / serde / src / private / de.rs
1 use lib::*;
2
3 use de::{Deserialize, DeserializeSeed, Deserializer, Error, IntoDeserializer, Visitor};
4
5 #[cfg(any(feature = "std", feature = "alloc"))]
6 use de::{MapAccess, Unexpected};
7
8 #[cfg(any(feature = "std", feature = "alloc"))]
9 pub 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.
17 pub fn missing_field<'de, V, E>(field: &'static str) -> Result<V, E>
18 where
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"))]
56 pub fn borrow_cow_str<'de: 'a, 'a, D>(deserializer: D) -> Result<Cow<'a, str>, D::Error>
57 where
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"))]
128 pub fn borrow_cow_bytes<'de: 'a, 'a, D>(deserializer: D) -> Result<Cow<'a, [u8]>, D::Error>
129 where
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
187 pub 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"))]
211 mod 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 _ => Err(self.invalid_type(&visitor)),
1424 }
1425 }
1426
1427 fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1428 where
1429 V: Visitor<'de>,
1430 {
1431 drop(self);
1432 visitor.visit_unit()
1433 }
1434 }
1435
1436 impl<'de, E> ContentDeserializer<'de, E> {
1437 /// private API, don't use
1438 pub fn new(content: Content<'de>) -> Self {
1439 ContentDeserializer {
1440 content: content,
1441 err: PhantomData,
1442 }
1443 }
1444 }
1445
1446 pub struct EnumDeserializer<'de, E>
1447 where
1448 E: de::Error,
1449 {
1450 variant: Content<'de>,
1451 value: Option<Content<'de>>,
1452 err: PhantomData<E>,
1453 }
1454
1455 impl<'de, E> EnumDeserializer<'de, E>
1456 where
1457 E: de::Error,
1458 {
1459 pub fn new(variant: Content<'de>, value: Option<Content<'de>>) -> EnumDeserializer<'de, E> {
1460 EnumDeserializer {
1461 variant: variant,
1462 value: value,
1463 err: PhantomData,
1464 }
1465 }
1466 }
1467
1468 impl<'de, E> de::EnumAccess<'de> for EnumDeserializer<'de, E>
1469 where
1470 E: de::Error,
1471 {
1472 type Error = E;
1473 type Variant = VariantDeserializer<'de, Self::Error>;
1474
1475 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), E>
1476 where
1477 V: de::DeserializeSeed<'de>,
1478 {
1479 let visitor = VariantDeserializer {
1480 value: self.value,
1481 err: PhantomData,
1482 };
1483 seed.deserialize(ContentDeserializer::new(self.variant))
1484 .map(|v| (v, visitor))
1485 }
1486 }
1487
1488 pub struct VariantDeserializer<'de, E>
1489 where
1490 E: de::Error,
1491 {
1492 value: Option<Content<'de>>,
1493 err: PhantomData<E>,
1494 }
1495
1496 impl<'de, E> de::VariantAccess<'de> for VariantDeserializer<'de, E>
1497 where
1498 E: de::Error,
1499 {
1500 type Error = E;
1501
1502 fn unit_variant(self) -> Result<(), E> {
1503 match self.value {
1504 Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)),
1505 None => Ok(()),
1506 }
1507 }
1508
1509 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E>
1510 where
1511 T: de::DeserializeSeed<'de>,
1512 {
1513 match self.value {
1514 Some(value) => seed.deserialize(ContentDeserializer::new(value)),
1515 None => Err(de::Error::invalid_type(
1516 de::Unexpected::UnitVariant,
1517 &"newtype variant",
1518 )),
1519 }
1520 }
1521
1522 fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
1523 where
1524 V: de::Visitor<'de>,
1525 {
1526 match self.value {
1527 Some(Content::Seq(v)) => {
1528 de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor)
1529 }
1530 Some(other) => Err(de::Error::invalid_type(
1531 other.unexpected(),
1532 &"tuple variant",
1533 )),
1534 None => Err(de::Error::invalid_type(
1535 de::Unexpected::UnitVariant,
1536 &"tuple variant",
1537 )),
1538 }
1539 }
1540
1541 fn struct_variant<V>(
1542 self,
1543 _fields: &'static [&'static str],
1544 visitor: V,
1545 ) -> Result<V::Value, Self::Error>
1546 where
1547 V: de::Visitor<'de>,
1548 {
1549 match self.value {
1550 Some(Content::Map(v)) => {
1551 de::Deserializer::deserialize_any(MapDeserializer::new(v), visitor)
1552 }
1553 Some(Content::Seq(v)) => {
1554 de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor)
1555 }
1556 Some(other) => Err(de::Error::invalid_type(
1557 other.unexpected(),
1558 &"struct variant",
1559 )),
1560 _ => Err(de::Error::invalid_type(
1561 de::Unexpected::UnitVariant,
1562 &"struct variant",
1563 )),
1564 }
1565 }
1566 }
1567
1568 struct SeqDeserializer<'de, E>
1569 where
1570 E: de::Error,
1571 {
1572 iter: <Vec<Content<'de>> as IntoIterator>::IntoIter,
1573 err: PhantomData<E>,
1574 }
1575
1576 impl<'de, E> SeqDeserializer<'de, E>
1577 where
1578 E: de::Error,
1579 {
1580 fn new(vec: Vec<Content<'de>>) -> Self {
1581 SeqDeserializer {
1582 iter: vec.into_iter(),
1583 err: PhantomData,
1584 }
1585 }
1586 }
1587
1588 impl<'de, E> de::Deserializer<'de> for SeqDeserializer<'de, E>
1589 where
1590 E: de::Error,
1591 {
1592 type Error = E;
1593
1594 #[inline]
1595 fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
1596 where
1597 V: de::Visitor<'de>,
1598 {
1599 let len = self.iter.len();
1600 if len == 0 {
1601 visitor.visit_unit()
1602 } else {
1603 let ret = try!(visitor.visit_seq(&mut self));
1604 let remaining = self.iter.len();
1605 if remaining == 0 {
1606 Ok(ret)
1607 } else {
1608 Err(de::Error::invalid_length(len, &"fewer elements in array"))
1609 }
1610 }
1611 }
1612
1613 forward_to_deserialize_any! {
1614 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
1615 bytes byte_buf option unit unit_struct newtype_struct seq tuple
1616 tuple_struct map struct enum identifier ignored_any
1617 }
1618 }
1619
1620 impl<'de, E> de::SeqAccess<'de> for SeqDeserializer<'de, E>
1621 where
1622 E: de::Error,
1623 {
1624 type Error = E;
1625
1626 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1627 where
1628 T: de::DeserializeSeed<'de>,
1629 {
1630 match self.iter.next() {
1631 Some(value) => seed.deserialize(ContentDeserializer::new(value)).map(Some),
1632 None => Ok(None),
1633 }
1634 }
1635
1636 fn size_hint(&self) -> Option<usize> {
1637 size_hint::from_bounds(&self.iter)
1638 }
1639 }
1640
1641 struct MapDeserializer<'de, E>
1642 where
1643 E: de::Error,
1644 {
1645 iter: <Vec<(Content<'de>, Content<'de>)> as IntoIterator>::IntoIter,
1646 value: Option<Content<'de>>,
1647 err: PhantomData<E>,
1648 }
1649
1650 impl<'de, E> MapDeserializer<'de, E>
1651 where
1652 E: de::Error,
1653 {
1654 fn new(map: Vec<(Content<'de>, Content<'de>)>) -> Self {
1655 MapDeserializer {
1656 iter: map.into_iter(),
1657 value: None,
1658 err: PhantomData,
1659 }
1660 }
1661 }
1662
1663 impl<'de, E> de::MapAccess<'de> for MapDeserializer<'de, E>
1664 where
1665 E: de::Error,
1666 {
1667 type Error = E;
1668
1669 fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1670 where
1671 T: de::DeserializeSeed<'de>,
1672 {
1673 match self.iter.next() {
1674 Some((key, value)) => {
1675 self.value = Some(value);
1676 seed.deserialize(ContentDeserializer::new(key)).map(Some)
1677 }
1678 None => Ok(None),
1679 }
1680 }
1681
1682 fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
1683 where
1684 T: de::DeserializeSeed<'de>,
1685 {
1686 match self.value.take() {
1687 Some(value) => seed.deserialize(ContentDeserializer::new(value)),
1688 None => Err(de::Error::custom("value is missing")),
1689 }
1690 }
1691
1692 fn size_hint(&self) -> Option<usize> {
1693 size_hint::from_bounds(&self.iter)
1694 }
1695 }
1696
1697 impl<'de, E> de::Deserializer<'de> for MapDeserializer<'de, E>
1698 where
1699 E: de::Error,
1700 {
1701 type Error = E;
1702
1703 #[inline]
1704 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1705 where
1706 V: de::Visitor<'de>,
1707 {
1708 visitor.visit_map(self)
1709 }
1710
1711 forward_to_deserialize_any! {
1712 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
1713 bytes byte_buf option unit unit_struct newtype_struct seq tuple
1714 tuple_struct map struct enum identifier ignored_any
1715 }
1716 }
1717
1718 /// Not public API.
1719 pub struct ContentRefDeserializer<'a, 'de: 'a, E> {
1720 content: &'a Content<'de>,
1721 err: PhantomData<E>,
1722 }
1723
1724 impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E>
1725 where
1726 E: de::Error,
1727 {
1728 #[cold]
1729 fn invalid_type(self, exp: &Expected) -> E {
1730 de::Error::invalid_type(self.content.unexpected(), exp)
1731 }
1732
1733 fn deserialize_integer<V>(self, visitor: V) -> Result<V::Value, E>
1734 where
1735 V: Visitor<'de>,
1736 {
1737 match *self.content {
1738 Content::U8(v) => visitor.visit_u8(v),
1739 Content::U16(v) => visitor.visit_u16(v),
1740 Content::U32(v) => visitor.visit_u32(v),
1741 Content::U64(v) => visitor.visit_u64(v),
1742 Content::I8(v) => visitor.visit_i8(v),
1743 Content::I16(v) => visitor.visit_i16(v),
1744 Content::I32(v) => visitor.visit_i32(v),
1745 Content::I64(v) => visitor.visit_i64(v),
1746 _ => Err(self.invalid_type(&visitor)),
1747 }
1748 }
1749 }
1750
1751 fn visit_content_seq_ref<'a, 'de, V, E>(
1752 content: &'a [Content<'de>],
1753 visitor: V,
1754 ) -> Result<V::Value, E>
1755 where
1756 V: Visitor<'de>,
1757 E: de::Error,
1758 {
1759 let seq = content.iter().map(ContentRefDeserializer::new);
1760 let mut seq_visitor = de::value::SeqDeserializer::new(seq);
1761 let value = try!(visitor.visit_seq(&mut seq_visitor));
1762 try!(seq_visitor.end());
1763 Ok(value)
1764 }
1765
1766 fn visit_content_map_ref<'a, 'de, V, E>(
1767 content: &'a [(Content<'de>, Content<'de>)],
1768 visitor: V,
1769 ) -> Result<V::Value, E>
1770 where
1771 V: Visitor<'de>,
1772 E: de::Error,
1773 {
1774 let map = content.iter().map(|&(ref k, ref v)| {
1775 (
1776 ContentRefDeserializer::new(k),
1777 ContentRefDeserializer::new(v),
1778 )
1779 });
1780 let mut map_visitor = de::value::MapDeserializer::new(map);
1781 let value = try!(visitor.visit_map(&mut map_visitor));
1782 try!(map_visitor.end());
1783 Ok(value)
1784 }
1785
1786 /// Used when deserializing an untagged enum because the content may need
1787 /// to be used more than once.
1788 impl<'de, 'a, E> Deserializer<'de> for ContentRefDeserializer<'a, 'de, E>
1789 where
1790 E: de::Error,
1791 {
1792 type Error = E;
1793
1794 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, E>
1795 where
1796 V: Visitor<'de>,
1797 {
1798 match *self.content {
1799 Content::Bool(v) => visitor.visit_bool(v),
1800 Content::U8(v) => visitor.visit_u8(v),
1801 Content::U16(v) => visitor.visit_u16(v),
1802 Content::U32(v) => visitor.visit_u32(v),
1803 Content::U64(v) => visitor.visit_u64(v),
1804 Content::I8(v) => visitor.visit_i8(v),
1805 Content::I16(v) => visitor.visit_i16(v),
1806 Content::I32(v) => visitor.visit_i32(v),
1807 Content::I64(v) => visitor.visit_i64(v),
1808 Content::F32(v) => visitor.visit_f32(v),
1809 Content::F64(v) => visitor.visit_f64(v),
1810 Content::Char(v) => visitor.visit_char(v),
1811 Content::String(ref v) => visitor.visit_str(v),
1812 Content::Str(v) => visitor.visit_borrowed_str(v),
1813 Content::ByteBuf(ref v) => visitor.visit_bytes(v),
1814 Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1815 Content::Unit => visitor.visit_unit(),
1816 Content::None => visitor.visit_none(),
1817 Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
1818 Content::Newtype(ref v) => {
1819 visitor.visit_newtype_struct(ContentRefDeserializer::new(v))
1820 }
1821 Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
1822 Content::Map(ref v) => visit_content_map_ref(v, visitor),
1823 }
1824 }
1825
1826 fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1827 where
1828 V: Visitor<'de>,
1829 {
1830 match *self.content {
1831 Content::Bool(v) => visitor.visit_bool(v),
1832 _ => Err(self.invalid_type(&visitor)),
1833 }
1834 }
1835
1836 fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1837 where
1838 V: Visitor<'de>,
1839 {
1840 self.deserialize_integer(visitor)
1841 }
1842
1843 fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1844 where
1845 V: Visitor<'de>,
1846 {
1847 self.deserialize_integer(visitor)
1848 }
1849
1850 fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1851 where
1852 V: Visitor<'de>,
1853 {
1854 self.deserialize_integer(visitor)
1855 }
1856
1857 fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1858 where
1859 V: Visitor<'de>,
1860 {
1861 self.deserialize_integer(visitor)
1862 }
1863
1864 fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1865 where
1866 V: Visitor<'de>,
1867 {
1868 self.deserialize_integer(visitor)
1869 }
1870
1871 fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1872 where
1873 V: Visitor<'de>,
1874 {
1875 self.deserialize_integer(visitor)
1876 }
1877
1878 fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1879 where
1880 V: Visitor<'de>,
1881 {
1882 self.deserialize_integer(visitor)
1883 }
1884
1885 fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1886 where
1887 V: Visitor<'de>,
1888 {
1889 self.deserialize_integer(visitor)
1890 }
1891
1892 fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1893 where
1894 V: Visitor<'de>,
1895 {
1896 match *self.content {
1897 Content::F32(v) => visitor.visit_f32(v),
1898 Content::F64(v) => visitor.visit_f64(v),
1899 Content::U64(v) => visitor.visit_u64(v),
1900 Content::I64(v) => visitor.visit_i64(v),
1901 _ => Err(self.invalid_type(&visitor)),
1902 }
1903 }
1904
1905 fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1906 where
1907 V: Visitor<'de>,
1908 {
1909 match *self.content {
1910 Content::F64(v) => visitor.visit_f64(v),
1911 Content::U64(v) => visitor.visit_u64(v),
1912 Content::I64(v) => visitor.visit_i64(v),
1913 _ => Err(self.invalid_type(&visitor)),
1914 }
1915 }
1916
1917 fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1918 where
1919 V: Visitor<'de>,
1920 {
1921 match *self.content {
1922 Content::Char(v) => visitor.visit_char(v),
1923 Content::String(ref v) => visitor.visit_str(v),
1924 Content::Str(v) => visitor.visit_borrowed_str(v),
1925 _ => Err(self.invalid_type(&visitor)),
1926 }
1927 }
1928
1929 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1930 where
1931 V: Visitor<'de>,
1932 {
1933 match *self.content {
1934 Content::String(ref v) => visitor.visit_str(v),
1935 Content::Str(v) => visitor.visit_borrowed_str(v),
1936 Content::ByteBuf(ref v) => visitor.visit_bytes(v),
1937 Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1938 _ => Err(self.invalid_type(&visitor)),
1939 }
1940 }
1941
1942 fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1943 where
1944 V: Visitor<'de>,
1945 {
1946 self.deserialize_str(visitor)
1947 }
1948
1949 fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1950 where
1951 V: Visitor<'de>,
1952 {
1953 match *self.content {
1954 Content::String(ref v) => visitor.visit_str(v),
1955 Content::Str(v) => visitor.visit_borrowed_str(v),
1956 Content::ByteBuf(ref v) => visitor.visit_bytes(v),
1957 Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1958 Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
1959 _ => Err(self.invalid_type(&visitor)),
1960 }
1961 }
1962
1963 fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1964 where
1965 V: Visitor<'de>,
1966 {
1967 self.deserialize_bytes(visitor)
1968 }
1969
1970 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E>
1971 where
1972 V: Visitor<'de>,
1973 {
1974 match *self.content {
1975 Content::None => visitor.visit_none(),
1976 Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
1977 Content::Unit => visitor.visit_unit(),
1978 _ => visitor.visit_some(self),
1979 }
1980 }
1981
1982 fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1983 where
1984 V: Visitor<'de>,
1985 {
1986 match *self.content {
1987 Content::Unit => visitor.visit_unit(),
1988 _ => Err(self.invalid_type(&visitor)),
1989 }
1990 }
1991
1992 fn deserialize_unit_struct<V>(
1993 self,
1994 _name: &'static str,
1995 visitor: V,
1996 ) -> Result<V::Value, Self::Error>
1997 where
1998 V: Visitor<'de>,
1999 {
2000 self.deserialize_unit(visitor)
2001 }
2002
2003 fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, E>
2004 where
2005 V: Visitor<'de>,
2006 {
2007 match *self.content {
2008 Content::Newtype(ref v) => {
2009 visitor.visit_newtype_struct(ContentRefDeserializer::new(v))
2010 }
2011 _ => visitor.visit_newtype_struct(self),
2012 }
2013 }
2014
2015 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2016 where
2017 V: Visitor<'de>,
2018 {
2019 match *self.content {
2020 Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
2021 _ => Err(self.invalid_type(&visitor)),
2022 }
2023 }
2024
2025 fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
2026 where
2027 V: Visitor<'de>,
2028 {
2029 self.deserialize_seq(visitor)
2030 }
2031
2032 fn deserialize_tuple_struct<V>(
2033 self,
2034 _name: &'static str,
2035 _len: usize,
2036 visitor: V,
2037 ) -> Result<V::Value, Self::Error>
2038 where
2039 V: Visitor<'de>,
2040 {
2041 self.deserialize_seq(visitor)
2042 }
2043
2044 fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2045 where
2046 V: Visitor<'de>,
2047 {
2048 match *self.content {
2049 Content::Map(ref v) => visit_content_map_ref(v, visitor),
2050 _ => Err(self.invalid_type(&visitor)),
2051 }
2052 }
2053
2054 fn deserialize_struct<V>(
2055 self,
2056 _name: &'static str,
2057 _fields: &'static [&'static str],
2058 visitor: V,
2059 ) -> Result<V::Value, Self::Error>
2060 where
2061 V: Visitor<'de>,
2062 {
2063 match *self.content {
2064 Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
2065 Content::Map(ref v) => visit_content_map_ref(v, visitor),
2066 _ => Err(self.invalid_type(&visitor)),
2067 }
2068 }
2069
2070 fn deserialize_enum<V>(
2071 self,
2072 _name: &str,
2073 _variants: &'static [&'static str],
2074 visitor: V,
2075 ) -> Result<V::Value, Self::Error>
2076 where
2077 V: Visitor<'de>,
2078 {
2079 let (variant, value) = match *self.content {
2080 Content::Map(ref value) => {
2081 let mut iter = value.iter();
2082 let &(ref variant, ref value) = match iter.next() {
2083 Some(v) => v,
2084 None => {
2085 return Err(de::Error::invalid_value(
2086 de::Unexpected::Map,
2087 &"map with a single key",
2088 ));
2089 }
2090 };
2091 // enums are encoded in json as maps with a single key:value pair
2092 if iter.next().is_some() {
2093 return Err(de::Error::invalid_value(
2094 de::Unexpected::Map,
2095 &"map with a single key",
2096 ));
2097 }
2098 (variant, Some(value))
2099 }
2100 ref s @ Content::String(_) | ref s @ Content::Str(_) => (s, None),
2101 ref other => {
2102 return Err(de::Error::invalid_type(
2103 other.unexpected(),
2104 &"string or map",
2105 ));
2106 }
2107 };
2108
2109 visitor.visit_enum(EnumRefDeserializer {
2110 variant: variant,
2111 value: value,
2112 err: PhantomData,
2113 })
2114 }
2115
2116 fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2117 where
2118 V: Visitor<'de>,
2119 {
2120 match *self.content {
2121 Content::String(ref v) => visitor.visit_str(v),
2122 Content::Str(v) => visitor.visit_borrowed_str(v),
2123 Content::ByteBuf(ref v) => visitor.visit_bytes(v),
2124 Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
2125 Content::U8(v) => visitor.visit_u8(v),
2126 _ => Err(self.invalid_type(&visitor)),
2127 }
2128 }
2129
2130 fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2131 where
2132 V: Visitor<'de>,
2133 {
2134 visitor.visit_unit()
2135 }
2136 }
2137
2138 impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E> {
2139 /// private API, don't use
2140 pub fn new(content: &'a Content<'de>) -> Self {
2141 ContentRefDeserializer {
2142 content: content,
2143 err: PhantomData,
2144 }
2145 }
2146 }
2147
2148 struct EnumRefDeserializer<'a, 'de: 'a, E>
2149 where
2150 E: de::Error,
2151 {
2152 variant: &'a Content<'de>,
2153 value: Option<&'a Content<'de>>,
2154 err: PhantomData<E>,
2155 }
2156
2157 impl<'de, 'a, E> de::EnumAccess<'de> for EnumRefDeserializer<'a, 'de, E>
2158 where
2159 E: de::Error,
2160 {
2161 type Error = E;
2162 type Variant = VariantRefDeserializer<'a, 'de, Self::Error>;
2163
2164 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
2165 where
2166 V: de::DeserializeSeed<'de>,
2167 {
2168 let visitor = VariantRefDeserializer {
2169 value: self.value,
2170 err: PhantomData,
2171 };
2172 seed.deserialize(ContentRefDeserializer::new(self.variant))
2173 .map(|v| (v, visitor))
2174 }
2175 }
2176
2177 struct VariantRefDeserializer<'a, 'de: 'a, E>
2178 where
2179 E: de::Error,
2180 {
2181 value: Option<&'a Content<'de>>,
2182 err: PhantomData<E>,
2183 }
2184
2185 impl<'de, 'a, E> de::VariantAccess<'de> for VariantRefDeserializer<'a, 'de, E>
2186 where
2187 E: de::Error,
2188 {
2189 type Error = E;
2190
2191 fn unit_variant(self) -> Result<(), E> {
2192 match self.value {
2193 Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)),
2194 None => Ok(()),
2195 }
2196 }
2197
2198 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E>
2199 where
2200 T: de::DeserializeSeed<'de>,
2201 {
2202 match self.value {
2203 Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
2204 None => Err(de::Error::invalid_type(
2205 de::Unexpected::UnitVariant,
2206 &"newtype variant",
2207 )),
2208 }
2209 }
2210
2211 fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
2212 where
2213 V: de::Visitor<'de>,
2214 {
2215 match self.value {
2216 Some(&Content::Seq(ref v)) => {
2217 de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor)
2218 }
2219 Some(other) => Err(de::Error::invalid_type(
2220 other.unexpected(),
2221 &"tuple variant",
2222 )),
2223 None => Err(de::Error::invalid_type(
2224 de::Unexpected::UnitVariant,
2225 &"tuple variant",
2226 )),
2227 }
2228 }
2229
2230 fn struct_variant<V>(
2231 self,
2232 _fields: &'static [&'static str],
2233 visitor: V,
2234 ) -> Result<V::Value, Self::Error>
2235 where
2236 V: de::Visitor<'de>,
2237 {
2238 match self.value {
2239 Some(&Content::Map(ref v)) => {
2240 de::Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor)
2241 }
2242 Some(&Content::Seq(ref v)) => {
2243 de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor)
2244 }
2245 Some(other) => Err(de::Error::invalid_type(
2246 other.unexpected(),
2247 &"struct variant",
2248 )),
2249 _ => Err(de::Error::invalid_type(
2250 de::Unexpected::UnitVariant,
2251 &"struct variant",
2252 )),
2253 }
2254 }
2255 }
2256
2257 struct SeqRefDeserializer<'a, 'de: 'a, E>
2258 where
2259 E: de::Error,
2260 {
2261 iter: <&'a [Content<'de>] as IntoIterator>::IntoIter,
2262 err: PhantomData<E>,
2263 }
2264
2265 impl<'a, 'de, E> SeqRefDeserializer<'a, 'de, E>
2266 where
2267 E: de::Error,
2268 {
2269 fn new(slice: &'a [Content<'de>]) -> Self {
2270 SeqRefDeserializer {
2271 iter: slice.iter(),
2272 err: PhantomData,
2273 }
2274 }
2275 }
2276
2277 impl<'de, 'a, E> de::Deserializer<'de> for SeqRefDeserializer<'a, 'de, E>
2278 where
2279 E: de::Error,
2280 {
2281 type Error = E;
2282
2283 #[inline]
2284 fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
2285 where
2286 V: de::Visitor<'de>,
2287 {
2288 let len = self.iter.len();
2289 if len == 0 {
2290 visitor.visit_unit()
2291 } else {
2292 let ret = try!(visitor.visit_seq(&mut self));
2293 let remaining = self.iter.len();
2294 if remaining == 0 {
2295 Ok(ret)
2296 } else {
2297 Err(de::Error::invalid_length(len, &"fewer elements in array"))
2298 }
2299 }
2300 }
2301
2302 forward_to_deserialize_any! {
2303 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
2304 bytes byte_buf option unit unit_struct newtype_struct seq tuple
2305 tuple_struct map struct enum identifier ignored_any
2306 }
2307 }
2308
2309 impl<'de, 'a, E> de::SeqAccess<'de> for SeqRefDeserializer<'a, 'de, E>
2310 where
2311 E: de::Error,
2312 {
2313 type Error = E;
2314
2315 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
2316 where
2317 T: de::DeserializeSeed<'de>,
2318 {
2319 match self.iter.next() {
2320 Some(value) => seed
2321 .deserialize(ContentRefDeserializer::new(value))
2322 .map(Some),
2323 None => Ok(None),
2324 }
2325 }
2326
2327 fn size_hint(&self) -> Option<usize> {
2328 size_hint::from_bounds(&self.iter)
2329 }
2330 }
2331
2332 struct MapRefDeserializer<'a, 'de: 'a, E>
2333 where
2334 E: de::Error,
2335 {
2336 iter: <&'a [(Content<'de>, Content<'de>)] as IntoIterator>::IntoIter,
2337 value: Option<&'a Content<'de>>,
2338 err: PhantomData<E>,
2339 }
2340
2341 impl<'a, 'de, E> MapRefDeserializer<'a, 'de, E>
2342 where
2343 E: de::Error,
2344 {
2345 fn new(map: &'a [(Content<'de>, Content<'de>)]) -> Self {
2346 MapRefDeserializer {
2347 iter: map.iter(),
2348 value: None,
2349 err: PhantomData,
2350 }
2351 }
2352 }
2353
2354 impl<'de, 'a, E> de::MapAccess<'de> for MapRefDeserializer<'a, 'de, E>
2355 where
2356 E: de::Error,
2357 {
2358 type Error = E;
2359
2360 fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
2361 where
2362 T: de::DeserializeSeed<'de>,
2363 {
2364 match self.iter.next() {
2365 Some(&(ref key, ref value)) => {
2366 self.value = Some(value);
2367 seed.deserialize(ContentRefDeserializer::new(key)).map(Some)
2368 }
2369 None => Ok(None),
2370 }
2371 }
2372
2373 fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
2374 where
2375 T: de::DeserializeSeed<'de>,
2376 {
2377 match self.value.take() {
2378 Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
2379 None => Err(de::Error::custom("value is missing")),
2380 }
2381 }
2382
2383 fn size_hint(&self) -> Option<usize> {
2384 size_hint::from_bounds(&self.iter)
2385 }
2386 }
2387
2388 impl<'de, 'a, E> de::Deserializer<'de> for MapRefDeserializer<'a, 'de, E>
2389 where
2390 E: de::Error,
2391 {
2392 type Error = E;
2393
2394 #[inline]
2395 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2396 where
2397 V: de::Visitor<'de>,
2398 {
2399 visitor.visit_map(self)
2400 }
2401
2402 forward_to_deserialize_any! {
2403 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
2404 bytes byte_buf option unit unit_struct newtype_struct seq tuple
2405 tuple_struct map struct enum identifier ignored_any
2406 }
2407 }
2408
2409 impl<'de, E> de::IntoDeserializer<'de, E> for ContentDeserializer<'de, E>
2410 where
2411 E: de::Error,
2412 {
2413 type Deserializer = Self;
2414
2415 fn into_deserializer(self) -> Self {
2416 self
2417 }
2418 }
2419
2420 impl<'de, 'a, E> de::IntoDeserializer<'de, E> for ContentRefDeserializer<'a, 'de, E>
2421 where
2422 E: de::Error,
2423 {
2424 type Deserializer = Self;
2425
2426 fn into_deserializer(self) -> Self {
2427 self
2428 }
2429 }
2430
2431 /// Visitor for deserializing an internally tagged unit variant.
2432 ///
2433 /// Not public API.
2434 pub struct InternallyTaggedUnitVisitor<'a> {
2435 type_name: &'a str,
2436 variant_name: &'a str,
2437 }
2438
2439 impl<'a> InternallyTaggedUnitVisitor<'a> {
2440 /// Not public API.
2441 pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
2442 InternallyTaggedUnitVisitor {
2443 type_name: type_name,
2444 variant_name: variant_name,
2445 }
2446 }
2447 }
2448
2449 impl<'de, 'a> Visitor<'de> for InternallyTaggedUnitVisitor<'a> {
2450 type Value = ();
2451
2452 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2453 write!(
2454 formatter,
2455 "unit variant {}::{}",
2456 self.type_name, self.variant_name
2457 )
2458 }
2459
2460 fn visit_seq<S>(self, _: S) -> Result<(), S::Error>
2461 where
2462 S: SeqAccess<'de>,
2463 {
2464 Ok(())
2465 }
2466
2467 fn visit_map<M>(self, mut access: M) -> Result<(), M::Error>
2468 where
2469 M: MapAccess<'de>,
2470 {
2471 while let Some(_) = try!(access.next_entry::<IgnoredAny, IgnoredAny>()) {}
2472 Ok(())
2473 }
2474 }
2475
2476 /// Visitor for deserializing an untagged unit variant.
2477 ///
2478 /// Not public API.
2479 pub struct UntaggedUnitVisitor<'a> {
2480 type_name: &'a str,
2481 variant_name: &'a str,
2482 }
2483
2484 impl<'a> UntaggedUnitVisitor<'a> {
2485 /// Not public API.
2486 pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
2487 UntaggedUnitVisitor {
2488 type_name: type_name,
2489 variant_name: variant_name,
2490 }
2491 }
2492 }
2493
2494 impl<'de, 'a> Visitor<'de> for UntaggedUnitVisitor<'a> {
2495 type Value = ();
2496
2497 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2498 write!(
2499 formatter,
2500 "unit variant {}::{}",
2501 self.type_name, self.variant_name
2502 )
2503 }
2504
2505 fn visit_unit<E>(self) -> Result<(), E>
2506 where
2507 E: de::Error,
2508 {
2509 Ok(())
2510 }
2511 }
2512 }
2513
2514 ////////////////////////////////////////////////////////////////////////////////
2515
2516 // Like `IntoDeserializer` but also implemented for `&[u8]`. This is used for
2517 // the newtype fallthrough case of `field_identifier`.
2518 //
2519 // #[derive(Deserialize)]
2520 // #[serde(field_identifier)]
2521 // enum F {
2522 // A,
2523 // B,
2524 // Other(String), // deserialized using IdentifierDeserializer
2525 // }
2526 pub trait IdentifierDeserializer<'de, E: Error> {
2527 type Deserializer: Deserializer<'de, Error = E>;
2528
2529 fn from(self) -> Self::Deserializer;
2530 }
2531
2532 impl<'de, E> IdentifierDeserializer<'de, E> for u32
2533 where
2534 E: Error,
2535 {
2536 type Deserializer = <u32 as IntoDeserializer<'de, E>>::Deserializer;
2537
2538 fn from(self) -> Self::Deserializer {
2539 self.into_deserializer()
2540 }
2541 }
2542
2543 pub struct StrDeserializer<'a, E> {
2544 value: &'a str,
2545 marker: PhantomData<E>,
2546 }
2547
2548 impl<'a, E> IdentifierDeserializer<'a, E> for &'a str
2549 where
2550 E: Error,
2551 {
2552 type Deserializer = StrDeserializer<'a, E>;
2553
2554 fn from(self) -> Self::Deserializer {
2555 StrDeserializer {
2556 value: self,
2557 marker: PhantomData,
2558 }
2559 }
2560 }
2561
2562 impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E>
2563 where
2564 E: Error,
2565 {
2566 type Error = E;
2567
2568 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2569 where
2570 V: Visitor<'de>,
2571 {
2572 visitor.visit_str(self.value)
2573 }
2574
2575 forward_to_deserialize_any! {
2576 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
2577 bytes byte_buf option unit unit_struct newtype_struct seq tuple
2578 tuple_struct map struct enum identifier ignored_any
2579 }
2580 }
2581
2582 pub struct BytesDeserializer<'a, E> {
2583 value: &'a [u8],
2584 marker: PhantomData<E>,
2585 }
2586
2587 impl<'a, E> IdentifierDeserializer<'a, E> for &'a [u8]
2588 where
2589 E: Error,
2590 {
2591 type Deserializer = BytesDeserializer<'a, E>;
2592
2593 fn from(self) -> Self::Deserializer {
2594 BytesDeserializer {
2595 value: self,
2596 marker: PhantomData,
2597 }
2598 }
2599 }
2600
2601 impl<'de, 'a, E> Deserializer<'de> for BytesDeserializer<'a, E>
2602 where
2603 E: Error,
2604 {
2605 type Error = E;
2606
2607 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2608 where
2609 V: Visitor<'de>,
2610 {
2611 visitor.visit_bytes(self.value)
2612 }
2613
2614 forward_to_deserialize_any! {
2615 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
2616 bytes byte_buf option unit unit_struct newtype_struct seq tuple
2617 tuple_struct map struct enum identifier ignored_any
2618 }
2619 }
2620
2621 /// A DeserializeSeed helper for implementing deserialize_in_place Visitors.
2622 ///
2623 /// Wraps a mutable reference and calls deserialize_in_place on it.
2624 pub struct InPlaceSeed<'a, T: 'a>(pub &'a mut T);
2625
2626 impl<'a, 'de, T> DeserializeSeed<'de> for InPlaceSeed<'a, T>
2627 where
2628 T: Deserialize<'de>,
2629 {
2630 type Value = ();
2631 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
2632 where
2633 D: Deserializer<'de>,
2634 {
2635 T::deserialize_in_place(deserializer, self.0)
2636 }
2637 }
2638
2639 #[cfg(any(feature = "std", feature = "alloc"))]
2640 pub struct FlatMapDeserializer<'a, 'de: 'a, E>(
2641 pub &'a mut Vec<Option<(Content<'de>, Content<'de>)>>,
2642 pub PhantomData<E>,
2643 );
2644
2645 #[cfg(any(feature = "std", feature = "alloc"))]
2646 impl<'a, 'de, E> FlatMapDeserializer<'a, 'de, E>
2647 where
2648 E: Error,
2649 {
2650 fn deserialize_other<V>() -> Result<V, E> {
2651 Err(Error::custom("can only flatten structs and maps"))
2652 }
2653 }
2654
2655 #[cfg(any(feature = "std", feature = "alloc"))]
2656 macro_rules! forward_to_deserialize_other {
2657 ($($func:ident ( $($arg:ty),* ))*) => {
2658 $(
2659 fn $func<V>(self, $(_: $arg,)* _visitor: V) -> Result<V::Value, Self::Error>
2660 where
2661 V: Visitor<'de>,
2662 {
2663 Self::deserialize_other()
2664 }
2665 )*
2666 }
2667 }
2668
2669 #[cfg(any(feature = "std", feature = "alloc"))]
2670 impl<'a, 'de, E> Deserializer<'de> for FlatMapDeserializer<'a, 'de, E>
2671 where
2672 E: Error,
2673 {
2674 type Error = E;
2675
2676 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2677 where
2678 V: Visitor<'de>,
2679 {
2680 visitor.visit_map(FlatInternallyTaggedAccess {
2681 iter: self.0.iter_mut(),
2682 pending: None,
2683 _marker: PhantomData,
2684 })
2685 }
2686
2687 fn deserialize_enum<V>(
2688 self,
2689 name: &'static str,
2690 variants: &'static [&'static str],
2691 visitor: V,
2692 ) -> Result<V::Value, Self::Error>
2693 where
2694 V: Visitor<'de>,
2695 {
2696 for item in self.0.iter_mut() {
2697 // items in the vector are nulled out when used. So we can only use
2698 // an item if it's still filled in and if the field is one we care
2699 // about.
2700 let use_item = match *item {
2701 None => false,
2702 Some((ref c, _)) => c.as_str().map_or(false, |x| variants.contains(&x)),
2703 };
2704
2705 if use_item {
2706 let (key, value) = item.take().unwrap();
2707 return visitor.visit_enum(EnumDeserializer::new(key, Some(value)));
2708 }
2709 }
2710
2711 Err(Error::custom(format_args!(
2712 "no variant of enum {} found in flattened data",
2713 name
2714 )))
2715 }
2716
2717 fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2718 where
2719 V: Visitor<'de>,
2720 {
2721 visitor.visit_map(FlatMapAccess::new(self.0.iter()))
2722 }
2723
2724 fn deserialize_struct<V>(
2725 self,
2726 _: &'static str,
2727 fields: &'static [&'static str],
2728 visitor: V,
2729 ) -> Result<V::Value, Self::Error>
2730 where
2731 V: Visitor<'de>,
2732 {
2733 visitor.visit_map(FlatStructAccess::new(self.0.iter_mut(), fields))
2734 }
2735
2736 fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
2737 where
2738 V: Visitor<'de>,
2739 {
2740 visitor.visit_newtype_struct(self)
2741 }
2742
2743 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
2744 where
2745 V: Visitor<'de>,
2746 {
2747 match visitor.__private_visit_untagged_option(self) {
2748 Ok(value) => Ok(value),
2749 Err(()) => Self::deserialize_other(),
2750 }
2751 }
2752
2753 forward_to_deserialize_other! {
2754 deserialize_bool()
2755 deserialize_i8()
2756 deserialize_i16()
2757 deserialize_i32()
2758 deserialize_i64()
2759 deserialize_u8()
2760 deserialize_u16()
2761 deserialize_u32()
2762 deserialize_u64()
2763 deserialize_f32()
2764 deserialize_f64()
2765 deserialize_char()
2766 deserialize_str()
2767 deserialize_string()
2768 deserialize_bytes()
2769 deserialize_byte_buf()
2770 deserialize_unit()
2771 deserialize_unit_struct(&'static str)
2772 deserialize_seq()
2773 deserialize_tuple(usize)
2774 deserialize_tuple_struct(&'static str, usize)
2775 deserialize_identifier()
2776 deserialize_ignored_any()
2777 }
2778 }
2779
2780 #[cfg(any(feature = "std", feature = "alloc"))]
2781 pub struct FlatMapAccess<'a, 'de: 'a, E> {
2782 iter: slice::Iter<'a, Option<(Content<'de>, Content<'de>)>>,
2783 pending_content: Option<&'a Content<'de>>,
2784 _marker: PhantomData<E>,
2785 }
2786
2787 #[cfg(any(feature = "std", feature = "alloc"))]
2788 impl<'a, 'de, E> FlatMapAccess<'a, 'de, E> {
2789 fn new(
2790 iter: slice::Iter<'a, Option<(Content<'de>, Content<'de>)>>,
2791 ) -> FlatMapAccess<'a, 'de, E> {
2792 FlatMapAccess {
2793 iter: iter,
2794 pending_content: None,
2795 _marker: PhantomData,
2796 }
2797 }
2798 }
2799
2800 #[cfg(any(feature = "std", feature = "alloc"))]
2801 impl<'a, 'de, E> MapAccess<'de> for FlatMapAccess<'a, 'de, E>
2802 where
2803 E: Error,
2804 {
2805 type Error = E;
2806
2807 fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
2808 where
2809 T: DeserializeSeed<'de>,
2810 {
2811 while let Some(item) = self.iter.next() {
2812 // Items in the vector are nulled out when used by a struct.
2813 if let Some((ref key, ref content)) = *item {
2814 self.pending_content = Some(content);
2815 return seed.deserialize(ContentRefDeserializer::new(key)).map(Some);
2816 }
2817 }
2818 Ok(None)
2819 }
2820
2821 fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
2822 where
2823 T: DeserializeSeed<'de>,
2824 {
2825 match self.pending_content.take() {
2826 Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
2827 None => Err(Error::custom("value is missing")),
2828 }
2829 }
2830 }
2831
2832 #[cfg(any(feature = "std", feature = "alloc"))]
2833 pub struct FlatStructAccess<'a, 'de: 'a, E> {
2834 iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>,
2835 pending_content: Option<Content<'de>>,
2836 fields: &'static [&'static str],
2837 _marker: PhantomData<E>,
2838 }
2839
2840 #[cfg(any(feature = "std", feature = "alloc"))]
2841 impl<'a, 'de, E> FlatStructAccess<'a, 'de, E> {
2842 fn new(
2843 iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>,
2844 fields: &'static [&'static str],
2845 ) -> FlatStructAccess<'a, 'de, E> {
2846 FlatStructAccess {
2847 iter: iter,
2848 pending_content: None,
2849 fields: fields,
2850 _marker: PhantomData,
2851 }
2852 }
2853 }
2854
2855 #[cfg(any(feature = "std", feature = "alloc"))]
2856 impl<'a, 'de, E> MapAccess<'de> for FlatStructAccess<'a, 'de, E>
2857 where
2858 E: Error,
2859 {
2860 type Error = E;
2861
2862 fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
2863 where
2864 T: DeserializeSeed<'de>,
2865 {
2866 while let Some(item) = self.iter.next() {
2867 // items in the vector are nulled out when used. So we can only use
2868 // an item if it's still filled in and if the field is one we care
2869 // about. In case we do not know which fields we want, we take them all.
2870 let use_item = match *item {
2871 None => false,
2872 Some((ref c, _)) => c.as_str().map_or(false, |key| self.fields.contains(&key)),
2873 };
2874
2875 if use_item {
2876 let (key, content) = item.take().unwrap();
2877 self.pending_content = Some(content);
2878 return seed.deserialize(ContentDeserializer::new(key)).map(Some);
2879 }
2880 }
2881 Ok(None)
2882 }
2883
2884 fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
2885 where
2886 T: DeserializeSeed<'de>,
2887 {
2888 match self.pending_content.take() {
2889 Some(value) => seed.deserialize(ContentDeserializer::new(value)),
2890 None => Err(Error::custom("value is missing")),
2891 }
2892 }
2893 }
2894
2895 #[cfg(any(feature = "std", feature = "alloc"))]
2896 pub struct FlatInternallyTaggedAccess<'a, 'de: 'a, E> {
2897 iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>,
2898 pending: Option<&'a Content<'de>>,
2899 _marker: PhantomData<E>,
2900 }
2901
2902 #[cfg(any(feature = "std", feature = "alloc"))]
2903 impl<'a, 'de, E> MapAccess<'de> for FlatInternallyTaggedAccess<'a, 'de, E>
2904 where
2905 E: Error,
2906 {
2907 type Error = E;
2908
2909 fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
2910 where
2911 T: DeserializeSeed<'de>,
2912 {
2913 while let Some(item) = self.iter.next() {
2914 if let Some((ref key, ref content)) = *item {
2915 // Do not take(), instead borrow this entry. The internally tagged
2916 // enum does its own buffering so we can't tell whether this entry
2917 // is going to be consumed. Borrowing here leaves the entry
2918 // available for later flattened fields.
2919 self.pending = Some(content);
2920 return seed.deserialize(ContentRefDeserializer::new(key)).map(Some);
2921 }
2922 }
2923 Ok(None)
2924 }
2925
2926 fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
2927 where
2928 T: DeserializeSeed<'de>,
2929 {
2930 match self.pending.take() {
2931 Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
2932 None => panic!("value is missing"),
2933 }
2934 }
2935 }