]> git.proxmox.com Git - rustc.git/blob - src/vendor/serde/src/de/value.rs
New upstream version 1.17.0+dfsg1
[rustc.git] / src / vendor / serde / 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!(u32, U32Deserializer, visit_u32);
187 primitive_deserializer!(u64, U64Deserializer, visit_u64);
188 primitive_deserializer!(usize, UsizeDeserializer, visit_u64 as u64);
189 primitive_deserializer!(f32, F32Deserializer, visit_f32);
190 primitive_deserializer!(f64, F64Deserializer, visit_f64);
191 primitive_deserializer!(char, CharDeserializer, visit_char);
192
193 ///////////////////////////////////////////////////////////////////////////////
194
195 /// A helper deserializer that deserializes a `&str`.
196 pub struct StrDeserializer<'a, E> {
197 value: &'a str,
198 marker: PhantomData<E>,
199 }
200
201 impl<'a, E> ValueDeserializer<E> for &'a str
202 where E: de::Error
203 {
204 type Deserializer = StrDeserializer<'a, E>;
205
206 fn into_deserializer(self) -> StrDeserializer<'a, E> {
207 StrDeserializer {
208 value: self,
209 marker: PhantomData,
210 }
211 }
212 }
213
214 impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
215 where E: de::Error
216 {
217 type Error = E;
218
219 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
220 where V: de::Visitor
221 {
222 visitor.visit_str(self.value)
223 }
224
225 fn deserialize_enum<V>(self,
226 _name: &str,
227 _variants: &'static [&'static str],
228 visitor: V)
229 -> Result<V::Value, Self::Error>
230 where V: de::Visitor
231 {
232 visitor.visit_enum(self)
233 }
234
235 forward_to_deserialize! {
236 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
237 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
238 struct struct_field tuple ignored_any byte_buf
239 }
240 }
241
242 impl<'a, E> de::EnumVisitor for StrDeserializer<'a, E>
243 where E: de::Error
244 {
245 type Error = E;
246 type Variant = private::UnitOnly<E>;
247
248 fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
249 where T: de::DeserializeSeed
250 {
251 seed.deserialize(self).map(private::unit_only)
252 }
253 }
254
255 ///////////////////////////////////////////////////////////////////////////////
256
257 /// A helper deserializer that deserializes a `String`.
258 #[cfg(any(feature = "std", feature = "collections"))]
259 pub struct StringDeserializer<E> {
260 value: String,
261 marker: PhantomData<E>,
262 }
263
264 #[cfg(any(feature = "std", feature = "collections"))]
265 impl<E> ValueDeserializer<E> for String
266 where E: de::Error
267 {
268 type Deserializer = StringDeserializer<E>;
269
270 fn into_deserializer(self) -> StringDeserializer<E> {
271 StringDeserializer {
272 value: self,
273 marker: PhantomData,
274 }
275 }
276 }
277
278 #[cfg(any(feature = "std", feature = "collections"))]
279 impl<E> de::Deserializer for StringDeserializer<E>
280 where E: de::Error
281 {
282 type Error = E;
283
284 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
285 where V: de::Visitor
286 {
287 visitor.visit_string(self.value)
288 }
289
290 fn deserialize_enum<V>(self,
291 _name: &str,
292 _variants: &'static [&'static str],
293 visitor: V)
294 -> Result<V::Value, Self::Error>
295 where V: de::Visitor
296 {
297 visitor.visit_enum(self)
298 }
299
300 forward_to_deserialize! {
301 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
302 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
303 struct struct_field tuple ignored_any byte_buf
304 }
305 }
306
307 #[cfg(any(feature = "std", feature = "collections"))]
308 impl<'a, E> de::EnumVisitor for StringDeserializer<E>
309 where E: de::Error
310 {
311 type Error = E;
312 type Variant = private::UnitOnly<E>;
313
314 fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
315 where T: de::DeserializeSeed
316 {
317 seed.deserialize(self).map(private::unit_only)
318 }
319 }
320
321 ///////////////////////////////////////////////////////////////////////////////
322
323 /// A helper deserializer that deserializes a `String`.
324 #[cfg(any(feature = "std", feature = "collections"))]
325 pub struct CowStrDeserializer<'a, E> {
326 value: Cow<'a, str>,
327 marker: PhantomData<E>,
328 }
329
330 #[cfg(any(feature = "std", feature = "collections"))]
331 impl<'a, E> ValueDeserializer<E> for Cow<'a, str>
332 where E: de::Error
333 {
334 type Deserializer = CowStrDeserializer<'a, E>;
335
336 fn into_deserializer(self) -> CowStrDeserializer<'a, E> {
337 CowStrDeserializer {
338 value: self,
339 marker: PhantomData,
340 }
341 }
342 }
343
344 #[cfg(any(feature = "std", feature = "collections"))]
345 impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
346 where E: de::Error
347 {
348 type Error = E;
349
350 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
351 where V: de::Visitor
352 {
353 match self.value {
354 Cow::Borrowed(string) => visitor.visit_str(string),
355 Cow::Owned(string) => visitor.visit_string(string),
356 }
357 }
358
359 fn deserialize_enum<V>(self,
360 _name: &str,
361 _variants: &'static [&'static str],
362 visitor: V)
363 -> Result<V::Value, Self::Error>
364 where V: de::Visitor
365 {
366 visitor.visit_enum(self)
367 }
368
369 forward_to_deserialize! {
370 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
371 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
372 struct struct_field tuple ignored_any byte_buf
373 }
374 }
375
376 #[cfg(any(feature = "std", feature = "collections"))]
377 impl<'a, E> de::EnumVisitor for CowStrDeserializer<'a, E>
378 where E: de::Error
379 {
380 type Error = E;
381 type Variant = private::UnitOnly<E>;
382
383 fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
384 where T: de::DeserializeSeed
385 {
386 seed.deserialize(self).map(private::unit_only)
387 }
388 }
389
390 ///////////////////////////////////////////////////////////////////////////////
391
392 /// A helper deserializer that deserializes a sequence.
393 pub struct SeqDeserializer<I, E> {
394 iter: iter::Fuse<I>,
395 count: usize,
396 marker: PhantomData<E>,
397 }
398
399 impl<I, E> SeqDeserializer<I, E>
400 where I: Iterator,
401 E: de::Error
402 {
403 /// Construct a new `SeqDeserializer<I>`.
404 pub fn new(iter: I) -> Self {
405 SeqDeserializer {
406 iter: iter.fuse(),
407 count: 0,
408 marker: PhantomData,
409 }
410 }
411
412 /// Check for remaining elements after passing a `SeqDeserializer` to
413 /// `Visitor::visit_seq`.
414 pub fn end(mut self) -> Result<(), E> {
415 let mut remaining = 0;
416 while self.iter.next().is_some() {
417 remaining += 1;
418 }
419 if remaining == 0 {
420 Ok(())
421 } else {
422 // First argument is the number of elements in the data, second
423 // argument is the number of elements expected by the Deserialize.
424 Err(de::Error::invalid_length(self.count + remaining, &ExpectedInSeq(self.count)))
425 }
426 }
427 }
428
429 impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
430 where I: Iterator<Item = T>,
431 T: ValueDeserializer<E>,
432 E: de::Error
433 {
434 type Error = E;
435
436 fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
437 where V: de::Visitor
438 {
439 let v = try!(visitor.visit_seq(&mut self));
440 try!(self.end());
441 Ok(v)
442 }
443
444 forward_to_deserialize! {
445 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
446 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
447 struct struct_field tuple enum ignored_any byte_buf
448 }
449 }
450
451 impl<I, T, E> de::SeqVisitor for SeqDeserializer<I, E>
452 where I: Iterator<Item = T>,
453 T: ValueDeserializer<E>,
454 E: de::Error
455 {
456 type Error = E;
457
458 fn visit_seed<V>(&mut self, seed: V) -> Result<Option<V::Value>, Self::Error>
459 where V: de::DeserializeSeed
460 {
461 match self.iter.next() {
462 Some(value) => {
463 self.count += 1;
464 seed.deserialize(value.into_deserializer()).map(Some)
465 }
466 None => Ok(None),
467 }
468 }
469
470 fn size_hint(&self) -> (usize, Option<usize>) {
471 self.iter.size_hint()
472 }
473 }
474
475 struct ExpectedInSeq(usize);
476
477 impl Expected for ExpectedInSeq {
478 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
479 if self.0 == 1 {
480 write!(formatter, "1 element in sequence")
481 } else {
482 write!(formatter, "{} elements in sequence", self.0)
483 }
484 }
485 }
486
487 ///////////////////////////////////////////////////////////////////////////////
488
489 #[cfg(any(feature = "std", feature = "collections"))]
490 impl<T, E> ValueDeserializer<E> for Vec<T>
491 where T: ValueDeserializer<E>,
492 E: de::Error
493 {
494 type Deserializer = SeqDeserializer<vec::IntoIter<T>, E>;
495
496 fn into_deserializer(self) -> Self::Deserializer {
497 SeqDeserializer::new(self.into_iter())
498 }
499 }
500
501 #[cfg(any(feature = "std", feature = "collections"))]
502 impl<T, E> ValueDeserializer<E> for BTreeSet<T>
503 where T: ValueDeserializer<E> + Eq + Ord,
504 E: de::Error
505 {
506 type Deserializer = SeqDeserializer<btree_set::IntoIter<T>, E>;
507
508 fn into_deserializer(self) -> Self::Deserializer {
509 SeqDeserializer::new(self.into_iter())
510 }
511 }
512
513 #[cfg(feature = "std")]
514 impl<T, E> ValueDeserializer<E> for HashSet<T>
515 where T: ValueDeserializer<E> + Eq + Hash,
516 E: de::Error
517 {
518 type Deserializer = SeqDeserializer<hash_set::IntoIter<T>, E>;
519
520 fn into_deserializer(self) -> Self::Deserializer {
521 SeqDeserializer::new(self.into_iter())
522 }
523 }
524
525 ///////////////////////////////////////////////////////////////////////////////
526
527 /// A helper deserializer that deserializes a sequence using a `SeqVisitor`.
528 pub struct SeqVisitorDeserializer<V_, E> {
529 visitor: V_,
530 marker: PhantomData<E>,
531 }
532
533 impl<V_, E> SeqVisitorDeserializer<V_, E>
534 where V_: de::SeqVisitor<Error = E>,
535 E: de::Error
536 {
537 /// Construct a new `SeqVisitorDeserializer<V_, E>`.
538 pub fn new(visitor: V_) -> Self {
539 SeqVisitorDeserializer {
540 visitor: visitor,
541 marker: PhantomData,
542 }
543 }
544 }
545
546 impl<V_, E> de::Deserializer for SeqVisitorDeserializer<V_, E>
547 where V_: de::SeqVisitor<Error = E>,
548 E: de::Error
549 {
550 type Error = E;
551
552 fn deserialize<V: de::Visitor>(self, visitor: V) -> Result<V::Value, Self::Error> {
553 visitor.visit_seq(self.visitor)
554 }
555
556 forward_to_deserialize! {
557 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
558 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
559 struct struct_field tuple enum ignored_any byte_buf
560 }
561 }
562
563 ///////////////////////////////////////////////////////////////////////////////
564
565 /// A helper deserializer that deserializes a map.
566 pub struct MapDeserializer<I, E>
567 where I: Iterator,
568 I::Item: private::Pair,
569 <I::Item as private::Pair>::First: ValueDeserializer<E>,
570 <I::Item as private::Pair>::Second: ValueDeserializer<E>,
571 E: de::Error
572 {
573 iter: iter::Fuse<I>,
574 value: Option<<I::Item as private::Pair>::Second>,
575 count: usize,
576 marker: PhantomData<E>,
577 }
578
579 impl<I, E> MapDeserializer<I, E>
580 where I: Iterator,
581 I::Item: private::Pair,
582 <I::Item as private::Pair>::First: ValueDeserializer<E>,
583 <I::Item as private::Pair>::Second: ValueDeserializer<E>,
584 E: de::Error
585 {
586 /// Construct a new `MapDeserializer<I, K, V, E>`.
587 pub fn new(iter: I) -> Self {
588 MapDeserializer {
589 iter: iter.fuse(),
590 value: None,
591 count: 0,
592 marker: PhantomData,
593 }
594 }
595
596 /// Check for remaining elements after passing a `MapDeserializer` to
597 /// `Visitor::visit_map`.
598 pub fn end(mut self) -> Result<(), E> {
599 let mut remaining = 0;
600 while self.iter.next().is_some() {
601 remaining += 1;
602 }
603 if remaining == 0 {
604 Ok(())
605 } else {
606 // First argument is the number of elements in the data, second
607 // argument is the number of elements expected by the Deserialize.
608 Err(de::Error::invalid_length(self.count + remaining, &ExpectedInMap(self.count)))
609 }
610 }
611
612 fn next_pair
613 (&mut self)
614 -> Option<(<I::Item as private::Pair>::First, <I::Item as private::Pair>::Second)> {
615 match self.iter.next() {
616 Some(kv) => {
617 self.count += 1;
618 Some(private::Pair::split(kv))
619 }
620 None => None,
621 }
622 }
623 }
624
625 impl<I, E> de::Deserializer for 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 type Error = E;
633
634 fn deserialize<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error>
635 where V_: de::Visitor
636 {
637 let value = try!(visitor.visit_map(&mut self));
638 try!(self.end());
639 Ok(value)
640 }
641
642 fn deserialize_seq<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error>
643 where V_: de::Visitor
644 {
645 let value = try!(visitor.visit_seq(&mut self));
646 try!(self.end());
647 Ok(value)
648 }
649
650 fn deserialize_seq_fixed_size<V_>(self,
651 _len: usize,
652 visitor: V_)
653 -> Result<V_::Value, Self::Error>
654 where V_: de::Visitor
655 {
656 self.deserialize_seq(visitor)
657 }
658
659 forward_to_deserialize! {
660 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
661 bytes map unit_struct newtype_struct tuple_struct struct struct_field
662 tuple enum ignored_any byte_buf
663 }
664 }
665
666 impl<I, E> de::MapVisitor for MapDeserializer<I, E>
667 where I: Iterator,
668 I::Item: private::Pair,
669 <I::Item as private::Pair>::First: ValueDeserializer<E>,
670 <I::Item as private::Pair>::Second: ValueDeserializer<E>,
671 E: de::Error
672 {
673 type Error = E;
674
675 fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
676 where T: de::DeserializeSeed
677 {
678 match self.next_pair() {
679 Some((key, value)) => {
680 self.value = Some(value);
681 seed.deserialize(key.into_deserializer()).map(Some)
682 }
683 None => Ok(None),
684 }
685 }
686
687 fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
688 where T: de::DeserializeSeed
689 {
690 let value = self.value.take();
691 // Panic because this indicates a bug in the program rather than an
692 // expected failure.
693 let value = value.expect("MapVisitor::visit_value called before visit_key");
694 seed.deserialize(value.into_deserializer())
695 }
696
697 fn visit_seed<TK, TV>(&mut self,
698 kseed: TK,
699 vseed: TV)
700 -> Result<Option<(TK::Value, TV::Value)>, Self::Error>
701 where TK: de::DeserializeSeed,
702 TV: de::DeserializeSeed
703 {
704 match self.next_pair() {
705 Some((key, value)) => {
706 let key = try!(kseed.deserialize(key.into_deserializer()));
707 let value = try!(vseed.deserialize(value.into_deserializer()));
708 Ok(Some((key, value)))
709 }
710 None => Ok(None),
711 }
712 }
713
714 fn size_hint(&self) -> (usize, Option<usize>) {
715 self.iter.size_hint()
716 }
717 }
718
719 impl<I, E> de::SeqVisitor for MapDeserializer<I, E>
720 where I: Iterator,
721 I::Item: private::Pair,
722 <I::Item as private::Pair>::First: ValueDeserializer<E>,
723 <I::Item as private::Pair>::Second: ValueDeserializer<E>,
724 E: de::Error
725 {
726 type Error = E;
727
728 fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
729 where T: de::DeserializeSeed
730 {
731 match self.next_pair() {
732 Some((k, v)) => {
733 let de = PairDeserializer(k, v, PhantomData);
734 seed.deserialize(de).map(Some)
735 }
736 None => Ok(None),
737 }
738 }
739
740 fn size_hint(&self) -> (usize, Option<usize>) {
741 self.iter.size_hint()
742 }
743 }
744
745 // Used in the `impl SeqVisitor for MapDeserializer` to visit the map as a
746 // sequence of pairs.
747 struct PairDeserializer<A, B, E>(A, B, PhantomData<E>);
748
749 impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
750 where A: ValueDeserializer<E>,
751 B: ValueDeserializer<E>,
752 E: de::Error
753 {
754 type Error = E;
755
756 forward_to_deserialize! {
757 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
758 bytes map unit_struct newtype_struct tuple_struct struct struct_field
759 tuple enum ignored_any byte_buf
760 }
761
762 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
763 where V: de::Visitor
764 {
765 self.deserialize_seq(visitor)
766 }
767
768 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
769 where V: de::Visitor
770 {
771 let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData);
772 let pair = try!(visitor.visit_seq(&mut pair_visitor));
773 if pair_visitor.1.is_none() {
774 Ok(pair)
775 } else {
776 let remaining = pair_visitor.size_hint().0;
777 // First argument is the number of elements in the data, second
778 // argument is the number of elements expected by the Deserialize.
779 Err(de::Error::invalid_length(2, &ExpectedInSeq(2 - remaining)))
780 }
781 }
782
783 fn deserialize_seq_fixed_size<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
784 where V: de::Visitor
785 {
786 if len == 2 {
787 self.deserialize_seq(visitor)
788 } else {
789 // First argument is the number of elements in the data, second
790 // argument is the number of elements expected by the Deserialize.
791 Err(de::Error::invalid_length(2, &ExpectedInSeq(len)))
792 }
793 }
794 }
795
796 struct PairVisitor<A, B, E>(Option<A>, Option<B>, PhantomData<E>);
797
798 impl<A, B, E> de::SeqVisitor for PairVisitor<A, B, E>
799 where A: ValueDeserializer<E>,
800 B: ValueDeserializer<E>,
801 E: de::Error
802 {
803 type Error = E;
804
805 fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
806 where T: de::DeserializeSeed
807 {
808 if let Some(k) = self.0.take() {
809 seed.deserialize(k.into_deserializer()).map(Some)
810 } else if let Some(v) = self.1.take() {
811 seed.deserialize(v.into_deserializer()).map(Some)
812 } else {
813 Ok(None)
814 }
815 }
816
817 fn size_hint(&self) -> (usize, Option<usize>) {
818 let len = if self.0.is_some() {
819 2
820 } else if self.1.is_some() {
821 1
822 } else {
823 0
824 };
825 (len, Some(len))
826 }
827 }
828
829 struct ExpectedInMap(usize);
830
831 impl Expected for ExpectedInMap {
832 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
833 if self.0 == 1 {
834 write!(formatter, "1 element in map")
835 } else {
836 write!(formatter, "{} elements in map", self.0)
837 }
838 }
839 }
840
841 ///////////////////////////////////////////////////////////////////////////////
842
843 #[cfg(any(feature = "std", feature = "collections"))]
844 impl<K, V, E> ValueDeserializer<E> for BTreeMap<K, V>
845 where K: ValueDeserializer<E> + Eq + Ord,
846 V: ValueDeserializer<E>,
847 E: de::Error
848 {
849 type Deserializer = MapDeserializer<btree_map::IntoIter<K, V>, E>;
850
851 fn into_deserializer(self) -> Self::Deserializer {
852 MapDeserializer::new(self.into_iter())
853 }
854 }
855
856 #[cfg(feature = "std")]
857 impl<K, V, E> ValueDeserializer<E> for HashMap<K, V>
858 where K: ValueDeserializer<E> + Eq + Hash,
859 V: ValueDeserializer<E>,
860 E: de::Error
861 {
862 type Deserializer = MapDeserializer<hash_map::IntoIter<K, V>, E>;
863
864 fn into_deserializer(self) -> Self::Deserializer {
865 MapDeserializer::new(self.into_iter())
866 }
867 }
868
869 ///////////////////////////////////////////////////////////////////////////////
870
871 /// A helper deserializer that deserializes a map using a `MapVisitor`.
872 pub struct MapVisitorDeserializer<V_, E> {
873 visitor: V_,
874 marker: PhantomData<E>,
875 }
876
877 impl<V_, E> MapVisitorDeserializer<V_, E>
878 where V_: de::MapVisitor<Error = E>,
879 E: de::Error
880 {
881 /// Construct a new `MapVisitorDeserializer<V_, E>`.
882 pub fn new(visitor: V_) -> Self {
883 MapVisitorDeserializer {
884 visitor: visitor,
885 marker: PhantomData,
886 }
887 }
888 }
889
890 impl<V_, E> de::Deserializer for MapVisitorDeserializer<V_, E>
891 where V_: de::MapVisitor<Error = E>,
892 E: de::Error
893 {
894 type Error = E;
895
896 fn deserialize<V: de::Visitor>(self, visitor: V) -> Result<V::Value, Self::Error> {
897 visitor.visit_map(self.visitor)
898 }
899
900 forward_to_deserialize! {
901 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
902 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
903 struct struct_field tuple enum ignored_any byte_buf
904 }
905 }
906
907 ///////////////////////////////////////////////////////////////////////////////
908
909 impl<'a, E> ValueDeserializer<E> for bytes::Bytes<'a>
910 where E: de::Error
911 {
912 type Deserializer = BytesDeserializer<'a, E>;
913
914 fn into_deserializer(self) -> BytesDeserializer<'a, E> {
915 BytesDeserializer {
916 value: self.into(),
917 marker: PhantomData,
918 }
919 }
920 }
921
922 /// A helper deserializer that deserializes a `&[u8]`.
923 pub struct BytesDeserializer<'a, E> {
924 value: &'a [u8],
925 marker: PhantomData<E>,
926 }
927
928 impl<'a, E> de::Deserializer for BytesDeserializer<'a, E>
929 where E: de::Error
930 {
931 type Error = E;
932
933 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
934 where V: de::Visitor
935 {
936 visitor.visit_bytes(self.value)
937 }
938
939 forward_to_deserialize! {
940 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
941 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
942 struct struct_field tuple enum ignored_any byte_buf
943 }
944 }
945
946 ///////////////////////////////////////////////////////////////////////////////
947
948 #[cfg(any(feature = "std", feature = "collections"))]
949 impl<E> ValueDeserializer<E> for bytes::ByteBuf
950 where E: de::Error
951 {
952 type Deserializer = ByteBufDeserializer<E>;
953
954 fn into_deserializer(self) -> Self::Deserializer {
955 ByteBufDeserializer {
956 value: self.into(),
957 marker: PhantomData,
958 }
959 }
960 }
961
962 /// A helper deserializer that deserializes a `Vec<u8>`.
963 #[cfg(any(feature = "std", feature = "collections"))]
964 pub struct ByteBufDeserializer<E> {
965 value: Vec<u8>,
966 marker: PhantomData<E>,
967 }
968
969 #[cfg(any(feature = "std", feature = "collections"))]
970 impl<E> de::Deserializer for ByteBufDeserializer<E>
971 where E: de::Error
972 {
973 type Error = E;
974
975 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
976 where V: de::Visitor
977 {
978 visitor.visit_byte_buf(self.value)
979 }
980
981 forward_to_deserialize! {
982 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
983 seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
984 struct struct_field tuple enum ignored_any byte_buf
985 }
986 }
987
988 ///////////////////////////////////////////////////////////////////////////////
989
990 mod private {
991 use de::{self, Unexpected};
992 use core::marker::PhantomData;
993
994 pub struct UnitOnly<E> {
995 marker: PhantomData<E>,
996 }
997
998 pub fn unit_only<T, E>(t: T) -> (T, UnitOnly<E>) {
999 (t, UnitOnly { marker: PhantomData })
1000 }
1001
1002 impl<E> de::VariantVisitor for UnitOnly<E>
1003 where E: de::Error
1004 {
1005 type Error = E;
1006
1007 fn visit_unit(self) -> Result<(), Self::Error> {
1008 Ok(())
1009 }
1010
1011 fn visit_newtype_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
1012 where T: de::DeserializeSeed
1013 {
1014 Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant"))
1015 }
1016
1017 fn visit_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
1018 where V: de::Visitor
1019 {
1020 Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"))
1021 }
1022
1023 fn visit_struct<V>(self,
1024 _fields: &'static [&'static str],
1025 _visitor: V)
1026 -> Result<V::Value, Self::Error>
1027 where V: de::Visitor
1028 {
1029 Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"))
1030 }
1031 }
1032
1033 /// Avoid having to restate the generic types on `MapDeserializer`. The
1034 /// `Iterator::Item` contains enough information to figure out K and V.
1035 pub trait Pair {
1036 type First;
1037 type Second;
1038 fn split(self) -> (Self::First, Self::Second);
1039 }
1040
1041 impl<A, B> Pair for (A, B) {
1042 type First = A;
1043 type Second = B;
1044 fn split(self) -> (A, B) {
1045 self
1046 }
1047 }
1048 }