]> git.proxmox.com Git - rustc.git/blame - src/vendor/serde/src/private/de.rs
New upstream version 1.23.0+dfsg1
[rustc.git] / src / vendor / serde / src / private / de.rs
CommitLineData
041b39d2
XL
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
9use lib::*;
10
11use de::{Deserialize, Deserializer, IntoDeserializer, Error, Visitor};
12
13#[cfg(any(feature = "std", feature = "alloc"))]
14use de::Unexpected;
15
16#[cfg(any(feature = "std", feature = "alloc"))]
17pub 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.
24pub fn missing_field<'de, V, E>(field: &'static str) -> Result<V, E>
25where
26 V: Deserialize<'de>,
27 E: Error,
28{
29 struct MissingFieldDeserializer<E>(&'static str, PhantomData<E>);
30
31 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"))]
63pub fn borrow_cow_str<'de: 'a, 'a, D>(deserializer: D) -> Result<Cow<'a, str>, D::Error>
64where
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"))]
132pub fn borrow_cow_bytes<'de: 'a, 'a, D>(deserializer: D) -> Result<Cow<'a, [u8]>, D::Error>
133where
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
191pub 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"))]
214mod 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 {
ea8adc8c 837 fmt.write_str("internally tagged enum")
041b39d2
XL
838 }
839
ea8adc8c 840 fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
041b39d2 841 where
ea8adc8c
XL
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>,
041b39d2
XL
860 {
861 let mut tag = None;
ea8adc8c 862 let mut vec = Vec::with_capacity(size_hint::cautious(map.size_hint()));
041b39d2 863 while let Some(k) =
ea8adc8c 864 try!(map.next_key_seed(TagOrContentVisitor::new(self.tag_name))) {
041b39d2
XL
865 match k {
866 TagOrContent::Tag => {
867 if tag.is_some() {
868 return Err(de::Error::duplicate_field(self.tag_name));
869 }
ea8adc8c 870 tag = Some(try!(map.next_value()));
041b39d2
XL
871 }
872 TagOrContent::Content(k) => {
ea8adc8c 873 let v = try!(map.next_value());
041b39d2
XL
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
abe05a73
XL
1117 fn deserialize_unit_struct<V>(
1118 self,
1119 _name: &'static str,
1120 visitor: V
1121 ) -> Result<V::Value, Self::Error>
1122 where
1123 V: Visitor<'de>,
1124 {
1125 match self.content {
1126 // As a special case, allow deserializing untagged newtype
1127 // variant containing unit struct.
1128 //
1129 // #[derive(Deserialize)]
1130 // struct Info;
1131 //
1132 // #[derive(Deserialize)]
1133 // #[serde(tag = "topic")]
1134 // enum Message {
1135 // Info(Info),
1136 // }
1137 //
1138 // We want {"topic":"Info"} to deserialize even though
1139 // ordinarily unit structs do not deserialize from empty map.
1140 Content::Map(ref v) if v.is_empty() => visitor.visit_unit(),
1141 _ => self.deserialize_any(visitor),
1142 }
1143 }
1144
041b39d2
XL
1145 forward_to_deserialize_any! {
1146 bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
abe05a73
XL
1147 byte_buf unit seq tuple tuple_struct map struct identifier
1148 ignored_any
041b39d2
XL
1149 }
1150 }
1151
1152 impl<'de, E> ContentDeserializer<'de, E> {
1153 /// private API, don't use
1154 pub fn new(content: Content<'de>) -> Self {
1155 ContentDeserializer {
1156 content: content,
1157 err: PhantomData,
1158 }
1159 }
1160 }
1161
1162 struct EnumDeserializer<'de, E>
1163 where
1164 E: de::Error,
1165 {
1166 variant: Content<'de>,
1167 value: Option<Content<'de>>,
1168 err: PhantomData<E>,
1169 }
1170
1171 impl<'de, E> de::EnumAccess<'de> for EnumDeserializer<'de, E>
1172 where
1173 E: de::Error,
1174 {
1175 type Error = E;
1176 type Variant = VariantDeserializer<'de, Self::Error>;
1177
1178 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), E>
1179 where
1180 V: de::DeserializeSeed<'de>,
1181 {
1182 let visitor = VariantDeserializer {
1183 value: self.value,
1184 err: PhantomData,
1185 };
1186 seed.deserialize(ContentDeserializer::new(self.variant))
1187 .map(|v| (v, visitor))
1188 }
1189 }
1190
1191 struct VariantDeserializer<'de, E>
1192 where
1193 E: de::Error,
1194 {
1195 value: Option<Content<'de>>,
1196 err: PhantomData<E>,
1197 }
1198
1199 impl<'de, E> de::VariantAccess<'de> for VariantDeserializer<'de, E>
1200 where
1201 E: de::Error,
1202 {
1203 type Error = E;
1204
1205 fn unit_variant(self) -> Result<(), E> {
1206 match self.value {
1207 Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)),
1208 None => Ok(()),
1209 }
1210 }
1211
1212 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E>
1213 where
1214 T: de::DeserializeSeed<'de>,
1215 {
1216 match self.value {
1217 Some(value) => seed.deserialize(ContentDeserializer::new(value)),
1218 None => {
1219 Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"newtype variant"),)
1220 }
1221 }
1222 }
1223
1224 fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
1225 where
1226 V: de::Visitor<'de>,
1227 {
1228 match self.value {
1229 Some(Content::Seq(v)) => {
1230 de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor)
1231 }
1232 Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant"),),
1233 None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"tuple variant"),),
1234 }
1235 }
1236
1237 fn struct_variant<V>(
1238 self,
1239 _fields: &'static [&'static str],
1240 visitor: V,
1241 ) -> Result<V::Value, Self::Error>
1242 where
1243 V: de::Visitor<'de>,
1244 {
1245 match self.value {
1246 Some(Content::Map(v)) => {
1247 de::Deserializer::deserialize_any(MapDeserializer::new(v), visitor)
1248 }
abe05a73
XL
1249 Some(Content::Seq(v)) => {
1250 de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor)
1251 }
041b39d2
XL
1252 Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant"),),
1253 _ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"struct variant"),),
1254 }
1255 }
1256 }
1257
1258 struct SeqDeserializer<'de, E>
1259 where
1260 E: de::Error,
1261 {
1262 iter: <Vec<Content<'de>> as IntoIterator>::IntoIter,
1263 err: PhantomData<E>,
1264 }
1265
1266 impl<'de, E> SeqDeserializer<'de, E>
1267 where
1268 E: de::Error,
1269 {
1270 fn new(vec: Vec<Content<'de>>) -> Self {
1271 SeqDeserializer {
1272 iter: vec.into_iter(),
1273 err: PhantomData,
1274 }
1275 }
1276 }
1277
1278 impl<'de, E> de::Deserializer<'de> for SeqDeserializer<'de, E>
1279 where
1280 E: de::Error,
1281 {
1282 type Error = E;
1283
1284 #[inline]
1285 fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
1286 where
1287 V: de::Visitor<'de>,
1288 {
1289 let len = self.iter.len();
1290 if len == 0 {
1291 visitor.visit_unit()
1292 } else {
1293 let ret = try!(visitor.visit_seq(&mut self));
1294 let remaining = self.iter.len();
1295 if remaining == 0 {
1296 Ok(ret)
1297 } else {
1298 Err(de::Error::invalid_length(len, &"fewer elements in array"))
1299 }
1300 }
1301 }
1302
1303 forward_to_deserialize_any! {
1304 bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
1305 byte_buf option unit unit_struct newtype_struct seq tuple
1306 tuple_struct map struct enum identifier ignored_any
1307 }
1308 }
1309
1310 impl<'de, E> de::SeqAccess<'de> for SeqDeserializer<'de, E>
1311 where
1312 E: de::Error,
1313 {
1314 type Error = E;
1315
1316 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1317 where
1318 T: de::DeserializeSeed<'de>,
1319 {
1320 match self.iter.next() {
1321 Some(value) => {
1322 seed.deserialize(ContentDeserializer::new(value))
1323 .map(Some)
1324 }
1325 None => Ok(None),
1326 }
1327 }
1328
1329 fn size_hint(&self) -> Option<usize> {
1330 size_hint::from_bounds(&self.iter)
1331 }
1332 }
1333
1334 struct MapDeserializer<'de, E>
1335 where
1336 E: de::Error,
1337 {
1338 iter: <Vec<(Content<'de>, Content<'de>)> as IntoIterator>::IntoIter,
1339 value: Option<Content<'de>>,
1340 err: PhantomData<E>,
1341 }
1342
1343 impl<'de, E> MapDeserializer<'de, E>
1344 where
1345 E: de::Error,
1346 {
1347 fn new(map: Vec<(Content<'de>, Content<'de>)>) -> Self {
1348 MapDeserializer {
1349 iter: map.into_iter(),
1350 value: None,
1351 err: PhantomData,
1352 }
1353 }
1354 }
1355
1356 impl<'de, E> de::MapAccess<'de> for MapDeserializer<'de, E>
1357 where
1358 E: de::Error,
1359 {
1360 type Error = E;
1361
1362 fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1363 where
1364 T: de::DeserializeSeed<'de>,
1365 {
1366 match self.iter.next() {
1367 Some((key, value)) => {
1368 self.value = Some(value);
1369 seed.deserialize(ContentDeserializer::new(key)).map(Some)
1370 }
1371 None => Ok(None),
1372 }
1373 }
1374
1375 fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
1376 where
1377 T: de::DeserializeSeed<'de>,
1378 {
1379 match self.value.take() {
1380 Some(value) => seed.deserialize(ContentDeserializer::new(value)),
1381 None => Err(de::Error::custom("value is missing")),
1382 }
1383 }
1384
1385 fn size_hint(&self) -> Option<usize> {
1386 size_hint::from_bounds(&self.iter)
1387 }
1388 }
1389
1390 impl<'de, E> de::Deserializer<'de> for MapDeserializer<'de, E>
1391 where
1392 E: de::Error,
1393 {
1394 type Error = E;
1395
1396 #[inline]
1397 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1398 where
1399 V: de::Visitor<'de>,
1400 {
1401 visitor.visit_map(self)
1402 }
1403
1404 forward_to_deserialize_any! {
1405 bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
1406 byte_buf option unit unit_struct newtype_struct seq tuple
1407 tuple_struct map struct enum identifier ignored_any
1408 }
1409 }
1410
1411 /// Not public API.
1412 pub struct ContentRefDeserializer<'a, 'de: 'a, E> {
1413 content: &'a Content<'de>,
1414 err: PhantomData<E>,
1415 }
1416
1417 /// Used when deserializing an untagged enum because the content may need to be
1418 /// used more than once.
1419 impl<'de, 'a, E> Deserializer<'de> for ContentRefDeserializer<'a, 'de, E>
1420 where
1421 E: de::Error,
1422 {
1423 type Error = E;
1424
1425 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, E>
1426 where
1427 V: Visitor<'de>,
1428 {
1429 match *self.content {
1430 Content::Bool(v) => visitor.visit_bool(v),
1431 Content::U8(v) => visitor.visit_u8(v),
1432 Content::U16(v) => visitor.visit_u16(v),
1433 Content::U32(v) => visitor.visit_u32(v),
1434 Content::U64(v) => visitor.visit_u64(v),
1435 Content::I8(v) => visitor.visit_i8(v),
1436 Content::I16(v) => visitor.visit_i16(v),
1437 Content::I32(v) => visitor.visit_i32(v),
1438 Content::I64(v) => visitor.visit_i64(v),
1439 Content::F32(v) => visitor.visit_f32(v),
1440 Content::F64(v) => visitor.visit_f64(v),
1441 Content::Char(v) => visitor.visit_char(v),
1442 Content::String(ref v) => visitor.visit_str(v),
1443 Content::Str(v) => visitor.visit_borrowed_str(v),
1444 Content::ByteBuf(ref v) => visitor.visit_bytes(v),
1445 Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
1446 Content::Unit => visitor.visit_unit(),
1447 Content::None => visitor.visit_none(),
1448 Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
1449 Content::Newtype(ref v) => {
1450 visitor.visit_newtype_struct(ContentRefDeserializer::new(v))
1451 }
1452 Content::Seq(ref v) => {
1453 let seq = v.into_iter().map(ContentRefDeserializer::new);
1454 let mut seq_visitor = de::value::SeqDeserializer::new(seq);
1455 let value = try!(visitor.visit_seq(&mut seq_visitor));
1456 try!(seq_visitor.end());
1457 Ok(value)
1458 }
1459 Content::Map(ref v) => {
1460 let map = v.into_iter()
1461 .map(
1462 |&(ref k, ref v)| {
1463 (ContentRefDeserializer::new(k), ContentRefDeserializer::new(v))
1464 },
1465 );
1466 let mut map_visitor = de::value::MapDeserializer::new(map);
1467 let value = try!(visitor.visit_map(&mut map_visitor));
1468 try!(map_visitor.end());
1469 Ok(value)
1470 }
1471 }
1472 }
1473
1474 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E>
1475 where
1476 V: Visitor<'de>,
1477 {
1478 match *self.content {
1479 Content::None => visitor.visit_none(),
1480 Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
1481 Content::Unit => visitor.visit_unit(),
1482 _ => visitor.visit_some(self),
1483 }
1484 }
1485
1486 fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, E>
1487 where
1488 V: Visitor<'de>,
1489 {
1490 visitor.visit_newtype_struct(self)
1491 }
1492
1493 fn deserialize_enum<V>(
1494 self,
1495 _name: &str,
1496 _variants: &'static [&'static str],
1497 visitor: V,
1498 ) -> Result<V::Value, Self::Error>
1499 where
1500 V: Visitor<'de>,
1501 {
1502 let (variant, value) = match *self.content {
1503 Content::Map(ref value) => {
1504 let mut iter = value.into_iter();
1505 let &(ref variant, ref value) = match iter.next() {
1506 Some(v) => v,
1507 None => {
1508 return Err(
1509 de::Error::invalid_value(
1510 de::Unexpected::Map,
1511 &"map with a single key",
1512 ),
1513 );
1514 }
1515 };
1516 // enums are encoded in json as maps with a single key:value pair
1517 if iter.next().is_some() {
1518 return Err(
1519 de::Error::invalid_value(
1520 de::Unexpected::Map,
1521 &"map with a single key",
1522 ),
1523 );
1524 }
1525 (variant, Some(value))
1526 }
1527 ref s @ Content::String(_) | ref s @ Content::Str(_) => (s, None),
1528 ref other => {
1529 return Err(de::Error::invalid_type(other.unexpected(), &"string or map"),);
1530 }
1531 };
1532
1533 visitor.visit_enum(
1534 EnumRefDeserializer {
1535 variant: variant,
1536 value: value,
1537 err: PhantomData,
1538 },
1539 )
1540 }
1541
1542 forward_to_deserialize_any! {
1543 bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
1544 byte_buf unit unit_struct seq tuple tuple_struct map struct
1545 identifier ignored_any
1546 }
1547 }
1548
1549 impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E> {
1550 /// private API, don't use
1551 pub fn new(content: &'a Content<'de>) -> Self {
1552 ContentRefDeserializer {
1553 content: content,
1554 err: PhantomData,
1555 }
1556 }
1557 }
1558
1559 struct EnumRefDeserializer<'a, 'de: 'a, E>
1560 where
1561 E: de::Error,
1562 {
1563 variant: &'a Content<'de>,
1564 value: Option<&'a Content<'de>>,
1565 err: PhantomData<E>,
1566 }
1567
1568 impl<'de, 'a, E> de::EnumAccess<'de> for EnumRefDeserializer<'a, 'de, E>
1569 where
1570 E: de::Error,
1571 {
1572 type Error = E;
1573 type Variant = VariantRefDeserializer<'a, 'de, Self::Error>;
1574
1575 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
1576 where
1577 V: de::DeserializeSeed<'de>,
1578 {
1579 let visitor = VariantRefDeserializer {
1580 value: self.value,
1581 err: PhantomData,
1582 };
1583 seed.deserialize(ContentRefDeserializer::new(self.variant))
1584 .map(|v| (v, visitor))
1585 }
1586 }
1587
1588 struct VariantRefDeserializer<'a, 'de: 'a, E>
1589 where
1590 E: de::Error,
1591 {
1592 value: Option<&'a Content<'de>>,
1593 err: PhantomData<E>,
1594 }
1595
1596 impl<'de, 'a, E> de::VariantAccess<'de> for VariantRefDeserializer<'a, 'de, E>
1597 where
1598 E: de::Error,
1599 {
1600 type Error = E;
1601
1602 fn unit_variant(self) -> Result<(), E> {
1603 match self.value {
1604 Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)),
1605 None => Ok(()),
1606 }
1607 }
1608
1609 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E>
1610 where
1611 T: de::DeserializeSeed<'de>,
1612 {
1613 match self.value {
1614 Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
1615 None => {
1616 Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"newtype variant"),)
1617 }
1618 }
1619 }
1620
1621 fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
1622 where
1623 V: de::Visitor<'de>,
1624 {
1625 match self.value {
1626 Some(&Content::Seq(ref v)) => {
1627 de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor)
1628 }
1629 Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant"),),
1630 None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"tuple variant"),),
1631 }
1632 }
1633
1634 fn struct_variant<V>(
1635 self,
1636 _fields: &'static [&'static str],
1637 visitor: V,
1638 ) -> Result<V::Value, Self::Error>
1639 where
1640 V: de::Visitor<'de>,
1641 {
1642 match self.value {
1643 Some(&Content::Map(ref v)) => {
1644 de::Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor)
1645 }
abe05a73
XL
1646 Some(&Content::Seq(ref v)) => {
1647 de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor)
1648 }
041b39d2
XL
1649 Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant"),),
1650 _ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"struct variant"),),
1651 }
1652 }
1653 }
1654
1655 struct SeqRefDeserializer<'a, 'de: 'a, E>
1656 where
1657 E: de::Error,
1658 {
1659 iter: <&'a [Content<'de>] as IntoIterator>::IntoIter,
1660 err: PhantomData<E>,
1661 }
1662
1663 impl<'a, 'de, E> SeqRefDeserializer<'a, 'de, E>
1664 where
1665 E: de::Error,
1666 {
1667 fn new(vec: &'a [Content<'de>]) -> Self {
1668 SeqRefDeserializer {
1669 iter: vec.into_iter(),
1670 err: PhantomData,
1671 }
1672 }
1673 }
1674
1675 impl<'de, 'a, E> de::Deserializer<'de> for SeqRefDeserializer<'a, 'de, E>
1676 where
1677 E: de::Error,
1678 {
1679 type Error = E;
1680
1681 #[inline]
1682 fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
1683 where
1684 V: de::Visitor<'de>,
1685 {
1686 let len = self.iter.len();
1687 if len == 0 {
1688 visitor.visit_unit()
1689 } else {
1690 let ret = try!(visitor.visit_seq(&mut self));
1691 let remaining = self.iter.len();
1692 if remaining == 0 {
1693 Ok(ret)
1694 } else {
1695 Err(de::Error::invalid_length(len, &"fewer elements in array"))
1696 }
1697 }
1698 }
1699
1700 forward_to_deserialize_any! {
1701 bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
1702 byte_buf option unit unit_struct newtype_struct seq tuple
1703 tuple_struct map struct enum identifier ignored_any
1704 }
1705 }
1706
1707 impl<'de, 'a, E> de::SeqAccess<'de> for SeqRefDeserializer<'a, 'de, E>
1708 where
1709 E: de::Error,
1710 {
1711 type Error = E;
1712
1713 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1714 where
1715 T: de::DeserializeSeed<'de>,
1716 {
1717 match self.iter.next() {
1718 Some(value) => {
1719 seed.deserialize(ContentRefDeserializer::new(value))
1720 .map(Some)
1721 }
1722 None => Ok(None),
1723 }
1724 }
1725
1726 fn size_hint(&self) -> Option<usize> {
1727 size_hint::from_bounds(&self.iter)
1728 }
1729 }
1730
1731 struct MapRefDeserializer<'a, 'de: 'a, E>
1732 where
1733 E: de::Error,
1734 {
1735 iter: <&'a [(Content<'de>, Content<'de>)] as IntoIterator>::IntoIter,
1736 value: Option<&'a Content<'de>>,
1737 err: PhantomData<E>,
1738 }
1739
1740 impl<'a, 'de, E> MapRefDeserializer<'a, 'de, E>
1741 where
1742 E: de::Error,
1743 {
1744 fn new(map: &'a [(Content<'de>, Content<'de>)]) -> Self {
1745 MapRefDeserializer {
1746 iter: map.into_iter(),
1747 value: None,
1748 err: PhantomData,
1749 }
1750 }
1751 }
1752
1753 impl<'de, 'a, E> de::MapAccess<'de> for MapRefDeserializer<'a, 'de, E>
1754 where
1755 E: de::Error,
1756 {
1757 type Error = E;
1758
1759 fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1760 where
1761 T: de::DeserializeSeed<'de>,
1762 {
1763 match self.iter.next() {
1764 Some(&(ref key, ref value)) => {
1765 self.value = Some(value);
1766 seed.deserialize(ContentRefDeserializer::new(key))
1767 .map(Some)
1768 }
1769 None => Ok(None),
1770 }
1771 }
1772
1773 fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
1774 where
1775 T: de::DeserializeSeed<'de>,
1776 {
1777 match self.value.take() {
1778 Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
1779 None => Err(de::Error::custom("value is missing")),
1780 }
1781 }
1782
1783 fn size_hint(&self) -> Option<usize> {
1784 size_hint::from_bounds(&self.iter)
1785 }
1786 }
1787
1788 impl<'de, 'a, E> de::Deserializer<'de> for MapRefDeserializer<'a, 'de, E>
1789 where
1790 E: de::Error,
1791 {
1792 type Error = E;
1793
1794 #[inline]
1795 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1796 where
1797 V: de::Visitor<'de>,
1798 {
1799 visitor.visit_map(self)
1800 }
1801
1802 forward_to_deserialize_any! {
1803 bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
1804 byte_buf option unit unit_struct newtype_struct seq tuple
1805 tuple_struct map struct enum identifier ignored_any
1806 }
1807 }
1808
1809 impl<'de, E> de::IntoDeserializer<'de, E> for ContentDeserializer<'de, E>
1810 where
1811 E: de::Error,
1812 {
1813 type Deserializer = Self;
1814
1815 fn into_deserializer(self) -> Self {
1816 self
1817 }
1818 }
1819
1820 impl<'de, 'a, E> de::IntoDeserializer<'de, E> for ContentRefDeserializer<'a, 'de, E>
1821 where
1822 E: de::Error,
1823 {
1824 type Deserializer = Self;
1825
1826 fn into_deserializer(self) -> Self {
1827 self
1828 }
1829 }
1830
1831 /// Visitor for deserializing an internally tagged unit variant.
1832 ///
1833 /// Not public API.
1834 pub struct InternallyTaggedUnitVisitor<'a> {
1835 type_name: &'a str,
1836 variant_name: &'a str,
1837 }
1838
1839 impl<'a> InternallyTaggedUnitVisitor<'a> {
1840 /// Not public API.
1841 pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
1842 InternallyTaggedUnitVisitor {
1843 type_name: type_name,
1844 variant_name: variant_name,
1845 }
1846 }
1847 }
1848
1849 impl<'de, 'a> Visitor<'de> for InternallyTaggedUnitVisitor<'a> {
1850 type Value = ();
1851
1852 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1853 write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name)
1854 }
1855
ea8adc8c 1856 fn visit_seq<S>(self, _: S) -> Result<(), S::Error>
041b39d2 1857 where
ea8adc8c
XL
1858 S: SeqAccess<'de>,
1859 {
1860 Ok(())
1861 }
1862
1863 fn visit_map<M>(self, _: M) -> Result<(), M::Error>
1864 where
1865 M: MapAccess<'de>,
041b39d2
XL
1866 {
1867 Ok(())
1868 }
1869 }
1870
1871 /// Visitor for deserializing an untagged unit variant.
1872 ///
1873 /// Not public API.
1874 pub struct UntaggedUnitVisitor<'a> {
1875 type_name: &'a str,
1876 variant_name: &'a str,
1877 }
1878
1879 impl<'a> UntaggedUnitVisitor<'a> {
1880 /// Not public API.
1881 pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
1882 UntaggedUnitVisitor {
1883 type_name: type_name,
1884 variant_name: variant_name,
1885 }
1886 }
1887 }
1888
1889 impl<'de, 'a> Visitor<'de> for UntaggedUnitVisitor<'a> {
1890 type Value = ();
1891
1892 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1893 write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name)
1894 }
1895
1896 fn visit_unit<E>(self) -> Result<(), E>
1897 where
1898 E: de::Error,
1899 {
1900 Ok(())
1901 }
1902 }
1903}
1904
1905////////////////////////////////////////////////////////////////////////////////
1906
1907// Like `IntoDeserializer` but also implemented for `&[u8]`. This is used for
1908// the newtype fallthrough case of `field_identifier`.
1909//
1910// #[derive(Deserialize)]
1911// #[serde(field_identifier)]
1912// enum F {
1913// A,
1914// B,
1915// Other(String), // deserialized using IdentifierDeserializer
1916// }
1917pub trait IdentifierDeserializer<'de, E: Error> {
1918 type Deserializer: Deserializer<'de, Error = E>;
1919
1920 fn from(self) -> Self::Deserializer;
1921}
1922
1923impl<'de, E> IdentifierDeserializer<'de, E> for u32
1924where
1925 E: Error,
1926{
1927 type Deserializer = <u32 as IntoDeserializer<'de, E>>::Deserializer;
1928
1929 fn from(self) -> Self::Deserializer {
1930 self.into_deserializer()
1931 }
1932}
1933
1934pub struct StrDeserializer<'a, E> {
1935 value: &'a str,
1936 marker: PhantomData<E>,
1937}
1938
1939impl<'a, E> IdentifierDeserializer<'a, E> for &'a str
1940where
1941 E: Error,
1942{
1943 type Deserializer = StrDeserializer<'a, E>;
1944
1945 fn from(self) -> Self::Deserializer {
1946 StrDeserializer {
1947 value: self,
1948 marker: PhantomData,
1949 }
1950 }
1951}
1952
1953impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E>
1954where
1955 E: Error,
1956{
1957 type Error = E;
1958
1959 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1960 where
1961 V: Visitor<'de>,
1962 {
1963 visitor.visit_str(self.value)
1964 }
1965
1966 forward_to_deserialize_any! {
1967 bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
1968 byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
1969 map struct enum identifier ignored_any
1970 }
1971}
1972
1973pub struct BytesDeserializer<'a, E> {
1974 value: &'a [u8],
1975 marker: PhantomData<E>,
1976}
1977
1978impl<'a, E> IdentifierDeserializer<'a, E> for &'a [u8]
1979where
1980 E: Error,
1981{
1982 type Deserializer = BytesDeserializer<'a, E>;
1983
1984 fn from(self) -> Self::Deserializer {
1985 BytesDeserializer {
1986 value: self,
1987 marker: PhantomData,
1988 }
1989 }
1990}
1991
1992impl<'de, 'a, E> Deserializer<'de> for BytesDeserializer<'a, E>
1993where
1994 E: Error,
1995{
1996 type Error = E;
1997
1998 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1999 where
2000 V: Visitor<'de>,
2001 {
2002 visitor.visit_bytes(self.value)
2003 }
2004
2005 forward_to_deserialize_any! {
2006 bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
2007 byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
2008 map struct enum identifier ignored_any
2009 }
2010}