]> git.proxmox.com Git - rustc.git/blob - src/vendor/serde-0.9.15/src/de/value.rs
New upstream version 1.19.0+dfsg3
[rustc.git] / src / vendor / serde-0.9.15 / src / de / value.rs
1 //! This module supports deserializing from primitives with the `ValueDeserializer` trait.
2
3 #[cfg(feature = "std")]
4 use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map, btree_set, hash_map,
5 hash_set};
6 #[cfg(feature = "std")]
7 use std::borrow::Cow;
8 #[cfg(feature = "std")]
9 use std::vec;
10
11 #[cfg(all(feature = "collections", not(feature = "std")))]
12 use collections::{BTreeMap, BTreeSet, Vec, String, btree_map, btree_set, vec};
13 #[cfg(all(feature = "collections", not(feature = "std")))]
14 use collections::borrow::Cow;
15 #[cfg(all(feature = "collections", not(feature = "std")))]
16 use collections::boxed::Box;
17 #[cfg(all(feature = "collections", not(feature = "std")))]
18 use collections::string::ToString;
19
20 #[cfg(feature = "std")]
21 use core::hash::Hash;
22 #[cfg(feature = "std")]
23 use std::error;
24 #[cfg(not(feature = "std"))]
25 use error;
26
27 use core::fmt::{self, Display};
28 use core::iter::{self, Iterator};
29 use core::marker::PhantomData;
30
31 use de::{self, Expected, SeqVisitor};
32 use bytes;
33
34 ///////////////////////////////////////////////////////////////////////////////
35
36 /// This represents all the possible errors that can occur using the `ValueDeserializer`.
37 #[derive(Clone, Debug, PartialEq)]
38 pub struct Error {
39 err: ErrorImpl,
40 }
41
42 #[cfg(any(feature = "std", feature = "collections"))]
43 type ErrorImpl = Box<str>;
44 #[cfg(not(any(feature = "std", feature = "collections")))]
45 type ErrorImpl = ();
46
47 impl de::Error for Error {
48 #[cfg(any(feature = "std", feature = "collections"))]
49 fn custom<T: Display>(msg: T) -> Self {
50 Error { err: msg.to_string().into_boxed_str() }
51 }
52
53 #[cfg(not(any(feature = "std", feature = "collections")))]
54 fn custom<T: Display>(_msg: T) -> Self {
55 Error { err: () }
56 }
57 }
58
59 impl Display for Error {
60 #[cfg(any(feature = "std", feature = "collections"))]
61 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
62 formatter.write_str(&self.err)
63 }
64
65 #[cfg(not(any(feature = "std", feature = "collections")))]
66 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
67 formatter.write_str("Serde deserialization error")
68 }
69 }
70
71 impl error::Error for Error {
72 #[cfg(any(feature = "std", feature = "collections"))]
73 fn description(&self) -> &str {
74 &self.err
75 }
76
77 #[cfg(not(any(feature = "std", feature = "collections")))]
78 fn description(&self) -> &str {
79 "Serde deserialization error"
80 }
81 }
82
83 ///////////////////////////////////////////////////////////////////////////////
84
85 /// This trait converts primitive types into a deserializer.
86 pub trait ValueDeserializer<E: de::Error = Error> {
87 /// The actual deserializer type.
88 type Deserializer: de::Deserializer<Error = E>;
89
90 /// Convert this value into a deserializer.
91 fn into_deserializer(self) -> Self::Deserializer;
92 }
93
94 ///////////////////////////////////////////////////////////////////////////////
95
96 impl<E> ValueDeserializer<E> for ()
97 where E: de::Error
98 {
99 type Deserializer = UnitDeserializer<E>;
100
101 fn into_deserializer(self) -> UnitDeserializer<E> {
102 UnitDeserializer { marker: PhantomData }
103 }
104 }
105
106 /// A helper deserializer that deserializes a `()`.
107 pub struct UnitDeserializer<E> {
108 marker: PhantomData<E>,
109 }
110
111 impl<E> de::Deserializer for UnitDeserializer<E>
112 where E: de::Error
113 {
114 type Error = E;
115
116 forward_to_deserialize! {
117 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
118 seq_fixed_size bytes map unit_struct newtype_struct tuple_struct struct
119 struct_field tuple enum ignored_any byte_buf
120 }
121
122 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
123 where V: de::Visitor
124 {
125 visitor.visit_unit()
126 }
127
128 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
129 where V: de::Visitor
130 {
131 visitor.visit_none()
132 }
133 }
134
135 ///////////////////////////////////////////////////////////////////////////////
136
137 macro_rules! primitive_deserializer {
138 ($ty:ty, $name:ident, $method:ident $($cast:tt)*) => {
139 /// A helper deserializer that deserializes a number.
140 pub struct $name<E> {
141 value: $ty,
142 marker: PhantomData<E>
143 }
144
145 impl<E> ValueDeserializer<E> for $ty
146 where E: de::Error,
147 {
148 type Deserializer = $name<E>;
149
150 fn into_deserializer(self) -> $name<E> {
151 $name {
152 value: self,
153 marker: PhantomData,
154 }
155 }
156 }
157
158 impl<E> de::Deserializer for $name<E>
159 where E: de::Error,
160 {
161 type Error = E;
162
163 forward_to_deserialize! {
164 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit
165 option seq seq_fixed_size bytes map unit_struct newtype_struct
166 tuple_struct struct struct_field tuple enum ignored_any byte_buf
167 }
168
169 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
170 where V: de::Visitor,
171 {
172 visitor.$method(self.value $($cast)*)
173 }
174 }
175 }
176 }
177
178 primitive_deserializer!(bool, BoolDeserializer, visit_bool);
179 primitive_deserializer!(i8, I8Deserializer, visit_i8);
180 primitive_deserializer!(i16, I16Deserializer, visit_i16);
181 primitive_deserializer!(i32, I32Deserializer, visit_i32);
182 primitive_deserializer!(i64, I64Deserializer, visit_i64);
183 primitive_deserializer!(isize, IsizeDeserializer, visit_i64 as i64);
184 primitive_deserializer!(u8, U8Deserializer, visit_u8);
185 primitive_deserializer!(u16, U16Deserializer, visit_u16);
186 primitive_deserializer!(u64, U64Deserializer, visit_u64);
187 primitive_deserializer!(usize, UsizeDeserializer, visit_u64 as u64);
188 primitive_deserializer!(f32, F32Deserializer, visit_f32);
189 primitive_deserializer!(f64, F64Deserializer, visit_f64);
190 primitive_deserializer!(char, CharDeserializer, visit_char);
191
192 /// A helper deserializer that deserializes a number.
193 pub struct U32Deserializer<E> {
194 value: u32,
195 marker: PhantomData<E>,
196 }
197
198 impl<E> ValueDeserializer<E> for u32
199 where E: de::Error
200 {
201 type Deserializer = U32Deserializer<E>;
202
203 fn into_deserializer(self) -> U32Deserializer<E> {
204 U32Deserializer {
205 value: self,
206 marker: PhantomData,
207 }
208 }
209 }
210
211 impl<E> de::Deserializer for U32Deserializer<E>
212 where E: de::Error
213 {
214 type Error = E;
215
216 forward_to_deserialize! {
217 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
218 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
219 struct struct_field tuple ignored_any byte_buf
220 }
221
222 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
223 where V: de::Visitor
224 {
225 visitor.visit_u32(self.value)
226 }
227
228 fn deserialize_enum<V>(self,
229 _name: &str,
230 _variants: &'static [&'static str],
231 visitor: V)
232 -> Result<V::Value, Self::Error>
233 where V: de::Visitor
234 {
235 visitor.visit_enum(self)
236 }
237 }
238
239 impl<E> de::EnumVisitor for U32Deserializer<E>
240 where E: de::Error
241 {
242 type Error = E;
243 type Variant = private::UnitOnly<E>;
244
245 fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
246 where T: de::DeserializeSeed
247 {
248 seed.deserialize(self).map(private::unit_only)
249 }
250 }
251
252 ///////////////////////////////////////////////////////////////////////////////
253
254 /// A helper deserializer that deserializes a `&str`.
255 pub struct StrDeserializer<'a, E> {
256 value: &'a str,
257 marker: PhantomData<E>,
258 }
259
260 impl<'a, E> ValueDeserializer<E> for &'a str
261 where E: de::Error
262 {
263 type Deserializer = StrDeserializer<'a, E>;
264
265 fn into_deserializer(self) -> StrDeserializer<'a, E> {
266 StrDeserializer {
267 value: self,
268 marker: PhantomData,
269 }
270 }
271 }
272
273 impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
274 where E: de::Error
275 {
276 type Error = E;
277
278 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
279 where V: de::Visitor
280 {
281 visitor.visit_str(self.value)
282 }
283
284 fn deserialize_enum<V>(self,
285 _name: &str,
286 _variants: &'static [&'static str],
287 visitor: V)
288 -> Result<V::Value, Self::Error>
289 where V: de::Visitor
290 {
291 visitor.visit_enum(self)
292 }
293
294 forward_to_deserialize! {
295 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
296 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
297 struct struct_field tuple ignored_any byte_buf
298 }
299 }
300
301 impl<'a, E> de::EnumVisitor for StrDeserializer<'a, E>
302 where E: de::Error
303 {
304 type Error = E;
305 type Variant = private::UnitOnly<E>;
306
307 fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
308 where T: de::DeserializeSeed
309 {
310 seed.deserialize(self).map(private::unit_only)
311 }
312 }
313
314 ///////////////////////////////////////////////////////////////////////////////
315
316 /// A helper deserializer that deserializes a `String`.
317 #[cfg(any(feature = "std", feature = "collections"))]
318 pub struct StringDeserializer<E> {
319 value: String,
320 marker: PhantomData<E>,
321 }
322
323 #[cfg(any(feature = "std", feature = "collections"))]
324 impl<E> ValueDeserializer<E> for String
325 where E: de::Error
326 {
327 type Deserializer = StringDeserializer<E>;
328
329 fn into_deserializer(self) -> StringDeserializer<E> {
330 StringDeserializer {
331 value: self,
332 marker: PhantomData,
333 }
334 }
335 }
336
337 #[cfg(any(feature = "std", feature = "collections"))]
338 impl<E> de::Deserializer for StringDeserializer<E>
339 where E: de::Error
340 {
341 type Error = E;
342
343 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
344 where V: de::Visitor
345 {
346 visitor.visit_string(self.value)
347 }
348
349 fn deserialize_enum<V>(self,
350 _name: &str,
351 _variants: &'static [&'static str],
352 visitor: V)
353 -> Result<V::Value, Self::Error>
354 where V: de::Visitor
355 {
356 visitor.visit_enum(self)
357 }
358
359 forward_to_deserialize! {
360 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
361 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
362 struct struct_field tuple ignored_any byte_buf
363 }
364 }
365
366 #[cfg(any(feature = "std", feature = "collections"))]
367 impl<'a, E> de::EnumVisitor for StringDeserializer<E>
368 where E: de::Error
369 {
370 type Error = E;
371 type Variant = private::UnitOnly<E>;
372
373 fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
374 where T: de::DeserializeSeed
375 {
376 seed.deserialize(self).map(private::unit_only)
377 }
378 }
379
380 ///////////////////////////////////////////////////////////////////////////////
381
382 /// A helper deserializer that deserializes a `String`.
383 #[cfg(any(feature = "std", feature = "collections"))]
384 pub struct CowStrDeserializer<'a, E> {
385 value: Cow<'a, str>,
386 marker: PhantomData<E>,
387 }
388
389 #[cfg(any(feature = "std", feature = "collections"))]
390 impl<'a, E> ValueDeserializer<E> for Cow<'a, str>
391 where E: de::Error
392 {
393 type Deserializer = CowStrDeserializer<'a, E>;
394
395 fn into_deserializer(self) -> CowStrDeserializer<'a, E> {
396 CowStrDeserializer {
397 value: self,
398 marker: PhantomData,
399 }
400 }
401 }
402
403 #[cfg(any(feature = "std", feature = "collections"))]
404 impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
405 where E: de::Error
406 {
407 type Error = E;
408
409 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
410 where V: de::Visitor
411 {
412 match self.value {
413 Cow::Borrowed(string) => visitor.visit_str(string),
414 Cow::Owned(string) => visitor.visit_string(string),
415 }
416 }
417
418 fn deserialize_enum<V>(self,
419 _name: &str,
420 _variants: &'static [&'static str],
421 visitor: V)
422 -> Result<V::Value, Self::Error>
423 where V: de::Visitor
424 {
425 visitor.visit_enum(self)
426 }
427
428 forward_to_deserialize! {
429 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
430 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
431 struct struct_field tuple ignored_any byte_buf
432 }
433 }
434
435 #[cfg(any(feature = "std", feature = "collections"))]
436 impl<'a, E> de::EnumVisitor for CowStrDeserializer<'a, E>
437 where E: de::Error
438 {
439 type Error = E;
440 type Variant = private::UnitOnly<E>;
441
442 fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
443 where T: de::DeserializeSeed
444 {
445 seed.deserialize(self).map(private::unit_only)
446 }
447 }
448
449 ///////////////////////////////////////////////////////////////////////////////
450
451 /// A helper deserializer that deserializes a sequence.
452 pub struct SeqDeserializer<I, E> {
453 iter: iter::Fuse<I>,
454 count: usize,
455 marker: PhantomData<E>,
456 }
457
458 impl<I, E> SeqDeserializer<I, E>
459 where I: Iterator,
460 E: de::Error
461 {
462 /// Construct a new `SeqDeserializer<I>`.
463 pub fn new(iter: I) -> Self {
464 SeqDeserializer {
465 iter: iter.fuse(),
466 count: 0,
467 marker: PhantomData,
468 }
469 }
470
471 /// Check for remaining elements after passing a `SeqDeserializer` to
472 /// `Visitor::visit_seq`.
473 pub fn end(mut self) -> Result<(), E> {
474 let mut remaining = 0;
475 while self.iter.next().is_some() {
476 remaining += 1;
477 }
478 if remaining == 0 {
479 Ok(())
480 } else {
481 // First argument is the number of elements in the data, second
482 // argument is the number of elements expected by the Deserialize.
483 Err(de::Error::invalid_length(self.count + remaining, &ExpectedInSeq(self.count)))
484 }
485 }
486 }
487
488 impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
489 where I: Iterator<Item = T>,
490 T: ValueDeserializer<E>,
491 E: de::Error
492 {
493 type Error = E;
494
495 fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
496 where V: de::Visitor
497 {
498 let v = try!(visitor.visit_seq(&mut self));
499 try!(self.end());
500 Ok(v)
501 }
502
503 forward_to_deserialize! {
504 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
505 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
506 struct struct_field tuple enum ignored_any byte_buf
507 }
508 }
509
510 impl<I, T, E> de::SeqVisitor for SeqDeserializer<I, E>
511 where I: Iterator<Item = T>,
512 T: ValueDeserializer<E>,
513 E: de::Error
514 {
515 type Error = E;
516
517 fn visit_seed<V>(&mut self, seed: V) -> Result<Option<V::Value>, Self::Error>
518 where V: de::DeserializeSeed
519 {
520 match self.iter.next() {
521 Some(value) => {
522 self.count += 1;
523 seed.deserialize(value.into_deserializer()).map(Some)
524 }
525 None => Ok(None),
526 }
527 }
528
529 fn size_hint(&self) -> (usize, Option<usize>) {
530 self.iter.size_hint()
531 }
532 }
533
534 struct ExpectedInSeq(usize);
535
536 impl Expected for ExpectedInSeq {
537 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
538 if self.0 == 1 {
539 write!(formatter, "1 element in sequence")
540 } else {
541 write!(formatter, "{} elements in sequence", self.0)
542 }
543 }
544 }
545
546 ///////////////////////////////////////////////////////////////////////////////
547
548 #[cfg(any(feature = "std", feature = "collections"))]
549 impl<T, E> ValueDeserializer<E> for Vec<T>
550 where T: ValueDeserializer<E>,
551 E: de::Error
552 {
553 type Deserializer = SeqDeserializer<vec::IntoIter<T>, E>;
554
555 fn into_deserializer(self) -> Self::Deserializer {
556 SeqDeserializer::new(self.into_iter())
557 }
558 }
559
560 #[cfg(any(feature = "std", feature = "collections"))]
561 impl<T, E> ValueDeserializer<E> for BTreeSet<T>
562 where T: ValueDeserializer<E> + Eq + Ord,
563 E: de::Error
564 {
565 type Deserializer = SeqDeserializer<btree_set::IntoIter<T>, E>;
566
567 fn into_deserializer(self) -> Self::Deserializer {
568 SeqDeserializer::new(self.into_iter())
569 }
570 }
571
572 #[cfg(feature = "std")]
573 impl<T, E> ValueDeserializer<E> for HashSet<T>
574 where T: ValueDeserializer<E> + Eq + Hash,
575 E: de::Error
576 {
577 type Deserializer = SeqDeserializer<hash_set::IntoIter<T>, E>;
578
579 fn into_deserializer(self) -> Self::Deserializer {
580 SeqDeserializer::new(self.into_iter())
581 }
582 }
583
584 ///////////////////////////////////////////////////////////////////////////////
585
586 /// A helper deserializer that deserializes a sequence using a `SeqVisitor`.
587 pub struct SeqVisitorDeserializer<V_, E> {
588 visitor: V_,
589 marker: PhantomData<E>,
590 }
591
592 impl<V_, E> SeqVisitorDeserializer<V_, E>
593 where V_: de::SeqVisitor<Error = E>,
594 E: de::Error
595 {
596 /// Construct a new `SeqVisitorDeserializer<V_, E>`.
597 pub fn new(visitor: V_) -> Self {
598 SeqVisitorDeserializer {
599 visitor: visitor,
600 marker: PhantomData,
601 }
602 }
603 }
604
605 impl<V_, E> de::Deserializer for SeqVisitorDeserializer<V_, E>
606 where V_: de::SeqVisitor<Error = E>,
607 E: de::Error
608 {
609 type Error = E;
610
611 fn deserialize<V: de::Visitor>(self, visitor: V) -> Result<V::Value, Self::Error> {
612 visitor.visit_seq(self.visitor)
613 }
614
615 forward_to_deserialize! {
616 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
617 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
618 struct struct_field tuple enum ignored_any byte_buf
619 }
620 }
621
622 ///////////////////////////////////////////////////////////////////////////////
623
624 /// A helper deserializer that deserializes a map.
625 pub struct MapDeserializer<I, E>
626 where I: Iterator,
627 I::Item: private::Pair,
628 <I::Item as private::Pair>::First: ValueDeserializer<E>,
629 <I::Item as private::Pair>::Second: ValueDeserializer<E>,
630 E: de::Error
631 {
632 iter: iter::Fuse<I>,
633 value: Option<<I::Item as private::Pair>::Second>,
634 count: usize,
635 marker: PhantomData<E>,
636 }
637
638 impl<I, E> MapDeserializer<I, E>
639 where I: Iterator,
640 I::Item: private::Pair,
641 <I::Item as private::Pair>::First: ValueDeserializer<E>,
642 <I::Item as private::Pair>::Second: ValueDeserializer<E>,
643 E: de::Error
644 {
645 /// Construct a new `MapDeserializer<I, K, V, E>`.
646 pub fn new(iter: I) -> Self {
647 MapDeserializer {
648 iter: iter.fuse(),
649 value: None,
650 count: 0,
651 marker: PhantomData,
652 }
653 }
654
655 /// Check for remaining elements after passing a `MapDeserializer` to
656 /// `Visitor::visit_map`.
657 pub fn end(mut self) -> Result<(), E> {
658 let mut remaining = 0;
659 while self.iter.next().is_some() {
660 remaining += 1;
661 }
662 if remaining == 0 {
663 Ok(())
664 } else {
665 // First argument is the number of elements in the data, second
666 // argument is the number of elements expected by the Deserialize.
667 Err(de::Error::invalid_length(self.count + remaining, &ExpectedInMap(self.count)))
668 }
669 }
670
671 fn next_pair
672 (&mut self)
673 -> Option<(<I::Item as private::Pair>::First, <I::Item as private::Pair>::Second)> {
674 match self.iter.next() {
675 Some(kv) => {
676 self.count += 1;
677 Some(private::Pair::split(kv))
678 }
679 None => None,
680 }
681 }
682 }
683
684 impl<I, E> de::Deserializer for MapDeserializer<I, E>
685 where I: Iterator,
686 I::Item: private::Pair,
687 <I::Item as private::Pair>::First: ValueDeserializer<E>,
688 <I::Item as private::Pair>::Second: ValueDeserializer<E>,
689 E: de::Error
690 {
691 type Error = E;
692
693 fn deserialize<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error>
694 where V_: de::Visitor
695 {
696 let value = try!(visitor.visit_map(&mut self));
697 try!(self.end());
698 Ok(value)
699 }
700
701 fn deserialize_seq<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error>
702 where V_: de::Visitor
703 {
704 let value = try!(visitor.visit_seq(&mut self));
705 try!(self.end());
706 Ok(value)
707 }
708
709 fn deserialize_seq_fixed_size<V_>(self,
710 _len: usize,
711 visitor: V_)
712 -> Result<V_::Value, Self::Error>
713 where V_: de::Visitor
714 {
715 self.deserialize_seq(visitor)
716 }
717
718 forward_to_deserialize! {
719 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
720 bytes map unit_struct newtype_struct tuple_struct struct struct_field
721 tuple enum ignored_any byte_buf
722 }
723 }
724
725 impl<I, E> de::MapVisitor for MapDeserializer<I, E>
726 where I: Iterator,
727 I::Item: private::Pair,
728 <I::Item as private::Pair>::First: ValueDeserializer<E>,
729 <I::Item as private::Pair>::Second: ValueDeserializer<E>,
730 E: de::Error
731 {
732 type Error = E;
733
734 fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
735 where T: de::DeserializeSeed
736 {
737 match self.next_pair() {
738 Some((key, value)) => {
739 self.value = Some(value);
740 seed.deserialize(key.into_deserializer()).map(Some)
741 }
742 None => Ok(None),
743 }
744 }
745
746 fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
747 where T: de::DeserializeSeed
748 {
749 let value = self.value.take();
750 // Panic because this indicates a bug in the program rather than an
751 // expected failure.
752 let value = value.expect("MapVisitor::visit_value called before visit_key");
753 seed.deserialize(value.into_deserializer())
754 }
755
756 fn visit_seed<TK, TV>(&mut self,
757 kseed: TK,
758 vseed: TV)
759 -> Result<Option<(TK::Value, TV::Value)>, Self::Error>
760 where TK: de::DeserializeSeed,
761 TV: de::DeserializeSeed
762 {
763 match self.next_pair() {
764 Some((key, value)) => {
765 let key = try!(kseed.deserialize(key.into_deserializer()));
766 let value = try!(vseed.deserialize(value.into_deserializer()));
767 Ok(Some((key, value)))
768 }
769 None => Ok(None),
770 }
771 }
772
773 fn size_hint(&self) -> (usize, Option<usize>) {
774 self.iter.size_hint()
775 }
776 }
777
778 impl<I, E> de::SeqVisitor for MapDeserializer<I, E>
779 where I: Iterator,
780 I::Item: private::Pair,
781 <I::Item as private::Pair>::First: ValueDeserializer<E>,
782 <I::Item as private::Pair>::Second: ValueDeserializer<E>,
783 E: de::Error
784 {
785 type Error = E;
786
787 fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
788 where T: de::DeserializeSeed
789 {
790 match self.next_pair() {
791 Some((k, v)) => {
792 let de = PairDeserializer(k, v, PhantomData);
793 seed.deserialize(de).map(Some)
794 }
795 None => Ok(None),
796 }
797 }
798
799 fn size_hint(&self) -> (usize, Option<usize>) {
800 self.iter.size_hint()
801 }
802 }
803
804 // Used in the `impl SeqVisitor for MapDeserializer` to visit the map as a
805 // sequence of pairs.
806 struct PairDeserializer<A, B, E>(A, B, PhantomData<E>);
807
808 impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
809 where A: ValueDeserializer<E>,
810 B: ValueDeserializer<E>,
811 E: de::Error
812 {
813 type Error = E;
814
815 forward_to_deserialize! {
816 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
817 bytes map unit_struct newtype_struct tuple_struct struct struct_field
818 tuple enum ignored_any byte_buf
819 }
820
821 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
822 where V: de::Visitor
823 {
824 self.deserialize_seq(visitor)
825 }
826
827 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
828 where V: de::Visitor
829 {
830 let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData);
831 let pair = try!(visitor.visit_seq(&mut pair_visitor));
832 if pair_visitor.1.is_none() {
833 Ok(pair)
834 } else {
835 let remaining = pair_visitor.size_hint().0;
836 // First argument is the number of elements in the data, second
837 // argument is the number of elements expected by the Deserialize.
838 Err(de::Error::invalid_length(2, &ExpectedInSeq(2 - remaining)))
839 }
840 }
841
842 fn deserialize_seq_fixed_size<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
843 where V: de::Visitor
844 {
845 if len == 2 {
846 self.deserialize_seq(visitor)
847 } else {
848 // First argument is the number of elements in the data, second
849 // argument is the number of elements expected by the Deserialize.
850 Err(de::Error::invalid_length(2, &ExpectedInSeq(len)))
851 }
852 }
853 }
854
855 struct PairVisitor<A, B, E>(Option<A>, Option<B>, PhantomData<E>);
856
857 impl<A, B, E> de::SeqVisitor for PairVisitor<A, B, E>
858 where A: ValueDeserializer<E>,
859 B: ValueDeserializer<E>,
860 E: de::Error
861 {
862 type Error = E;
863
864 fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
865 where T: de::DeserializeSeed
866 {
867 if let Some(k) = self.0.take() {
868 seed.deserialize(k.into_deserializer()).map(Some)
869 } else if let Some(v) = self.1.take() {
870 seed.deserialize(v.into_deserializer()).map(Some)
871 } else {
872 Ok(None)
873 }
874 }
875
876 fn size_hint(&self) -> (usize, Option<usize>) {
877 let len = if self.0.is_some() {
878 2
879 } else if self.1.is_some() {
880 1
881 } else {
882 0
883 };
884 (len, Some(len))
885 }
886 }
887
888 struct ExpectedInMap(usize);
889
890 impl Expected for ExpectedInMap {
891 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
892 if self.0 == 1 {
893 write!(formatter, "1 element in map")
894 } else {
895 write!(formatter, "{} elements in map", self.0)
896 }
897 }
898 }
899
900 ///////////////////////////////////////////////////////////////////////////////
901
902 #[cfg(any(feature = "std", feature = "collections"))]
903 impl<K, V, E> ValueDeserializer<E> for BTreeMap<K, V>
904 where K: ValueDeserializer<E> + Eq + Ord,
905 V: ValueDeserializer<E>,
906 E: de::Error
907 {
908 type Deserializer = MapDeserializer<btree_map::IntoIter<K, V>, E>;
909
910 fn into_deserializer(self) -> Self::Deserializer {
911 MapDeserializer::new(self.into_iter())
912 }
913 }
914
915 #[cfg(feature = "std")]
916 impl<K, V, E> ValueDeserializer<E> for HashMap<K, V>
917 where K: ValueDeserializer<E> + Eq + Hash,
918 V: ValueDeserializer<E>,
919 E: de::Error
920 {
921 type Deserializer = MapDeserializer<hash_map::IntoIter<K, V>, E>;
922
923 fn into_deserializer(self) -> Self::Deserializer {
924 MapDeserializer::new(self.into_iter())
925 }
926 }
927
928 ///////////////////////////////////////////////////////////////////////////////
929
930 /// A helper deserializer that deserializes a map using a `MapVisitor`.
931 pub struct MapVisitorDeserializer<V_, E> {
932 visitor: V_,
933 marker: PhantomData<E>,
934 }
935
936 impl<V_, E> MapVisitorDeserializer<V_, E>
937 where V_: de::MapVisitor<Error = E>,
938 E: de::Error
939 {
940 /// Construct a new `MapVisitorDeserializer<V_, E>`.
941 pub fn new(visitor: V_) -> Self {
942 MapVisitorDeserializer {
943 visitor: visitor,
944 marker: PhantomData,
945 }
946 }
947 }
948
949 impl<V_, E> de::Deserializer for MapVisitorDeserializer<V_, E>
950 where V_: de::MapVisitor<Error = E>,
951 E: de::Error
952 {
953 type Error = E;
954
955 fn deserialize<V: de::Visitor>(self, visitor: V) -> Result<V::Value, Self::Error> {
956 visitor.visit_map(self.visitor)
957 }
958
959 forward_to_deserialize! {
960 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
961 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
962 struct struct_field tuple enum ignored_any byte_buf
963 }
964 }
965
966 ///////////////////////////////////////////////////////////////////////////////
967
968 impl<'a, E> ValueDeserializer<E> for bytes::Bytes<'a>
969 where E: de::Error
970 {
971 type Deserializer = BytesDeserializer<'a, E>;
972
973 fn into_deserializer(self) -> BytesDeserializer<'a, E> {
974 BytesDeserializer {
975 value: self.into(),
976 marker: PhantomData,
977 }
978 }
979 }
980
981 /// A helper deserializer that deserializes a `&[u8]`.
982 pub struct BytesDeserializer<'a, E> {
983 value: &'a [u8],
984 marker: PhantomData<E>,
985 }
986
987 impl<'a, E> de::Deserializer for BytesDeserializer<'a, E>
988 where E: de::Error
989 {
990 type Error = E;
991
992 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
993 where V: de::Visitor
994 {
995 visitor.visit_bytes(self.value)
996 }
997
998 forward_to_deserialize! {
999 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
1000 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
1001 struct struct_field tuple enum ignored_any byte_buf
1002 }
1003 }
1004
1005 ///////////////////////////////////////////////////////////////////////////////
1006
1007 #[cfg(any(feature = "std", feature = "collections"))]
1008 impl<E> ValueDeserializer<E> for bytes::ByteBuf
1009 where E: de::Error
1010 {
1011 type Deserializer = ByteBufDeserializer<E>;
1012
1013 fn into_deserializer(self) -> Self::Deserializer {
1014 ByteBufDeserializer {
1015 value: self.into(),
1016 marker: PhantomData,
1017 }
1018 }
1019 }
1020
1021 /// A helper deserializer that deserializes a `Vec<u8>`.
1022 #[cfg(any(feature = "std", feature = "collections"))]
1023 pub struct ByteBufDeserializer<E> {
1024 value: Vec<u8>,
1025 marker: PhantomData<E>,
1026 }
1027
1028 #[cfg(any(feature = "std", feature = "collections"))]
1029 impl<E> de::Deserializer for ByteBufDeserializer<E>
1030 where E: de::Error
1031 {
1032 type Error = E;
1033
1034 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1035 where V: de::Visitor
1036 {
1037 visitor.visit_byte_buf(self.value)
1038 }
1039
1040 forward_to_deserialize! {
1041 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
1042 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
1043 struct struct_field tuple enum ignored_any byte_buf
1044 }
1045 }
1046
1047 ///////////////////////////////////////////////////////////////////////////////
1048
1049 mod private {
1050 use de::{self, Unexpected};
1051 use core::marker::PhantomData;
1052
1053 pub struct UnitOnly<E> {
1054 marker: PhantomData<E>,
1055 }
1056
1057 pub fn unit_only<T, E>(t: T) -> (T, UnitOnly<E>) {
1058 (t, UnitOnly { marker: PhantomData })
1059 }
1060
1061 impl<E> de::VariantVisitor for UnitOnly<E>
1062 where E: de::Error
1063 {
1064 type Error = E;
1065
1066 fn visit_unit(self) -> Result<(), Self::Error> {
1067 Ok(())
1068 }
1069
1070 fn visit_newtype_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
1071 where T: de::DeserializeSeed
1072 {
1073 Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant"))
1074 }
1075
1076 fn visit_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
1077 where V: de::Visitor
1078 {
1079 Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"))
1080 }
1081
1082 fn visit_struct<V>(self,
1083 _fields: &'static [&'static str],
1084 _visitor: V)
1085 -> Result<V::Value, Self::Error>
1086 where V: de::Visitor
1087 {
1088 Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"))
1089 }
1090 }
1091
1092 /// Avoid having to restate the generic types on `MapDeserializer`. The
1093 /// `Iterator::Item` contains enough information to figure out K and V.
1094 pub trait Pair {
1095 type First;
1096 type Second;
1097 fn split(self) -> (Self::First, Self::Second);
1098 }
1099
1100 impl<A, B> Pair for (A, B) {
1101 type First = A;
1102 type Second = B;
1103 fn split(self) -> (A, B) {
1104 self
1105 }
1106 }
1107 }