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