1//! Building blocks for deserializing basic values using the `IntoDeserializer`
2//! trait.
3//!
4//! ```edition2021
5//! use serde::de::{value, Deserialize, IntoDeserializer};
6//! use serde_derive::Deserialize;
7//! use std::str::FromStr;
8//!
9//! #[derive(Deserialize)]
10//! enum Setting {
11//! On,
12//! Off,
13//! }
14//!
15//! impl FromStr for Setting {
16//! type Err = value::Error;
17//!
18//! fn from_str(s: &str) -> Result<Self, Self::Err> {
19//! Self::deserialize(s.into_deserializer())
20//! }
21//! }
22//! ```
23
24use crate::lib::*;
25
26use self::private::{First, Second};
27use crate::de::{self, size_hint, Deserializer, Expected, IntoDeserializer, SeqAccess, Visitor};
28use crate::ser;
29
30////////////////////////////////////////////////////////////////////////////////
31
32// For structs that contain a PhantomData. We do not want the trait
33// bound `E: Clone` inferred by derive(Clone).
34macro_rules! impl_copy_clone {
35 ($ty:ident $(<$lifetime:tt>)*) => {
36 impl<$($lifetime,)* E> Copy for $ty<$($lifetime,)* E> {}
37
38 impl<$($lifetime,)* E> Clone for $ty<$($lifetime,)* E> {
39 fn clone(&self) -> Self {
40 *self
41 }
42 }
43 };
44}
45
46////////////////////////////////////////////////////////////////////////////////
47
48/// A minimal representation of all possible errors that can occur using the
49/// `IntoDeserializer` trait.
50#[derive(Clone, PartialEq)]
51pub struct Error {
52 err: ErrorImpl,
53}
54
55#[cfg(any(feature = "std", feature = "alloc"))]
56type ErrorImpl = Box<str>;
57#[cfg(not(any(feature = "std", feature = "alloc")))]
58type ErrorImpl = ();
59
60impl de::Error for Error {
61 #[cfg(any(feature = "std", feature = "alloc"))]
62 #[cold]
63 fn custom<T>(msg: T) -> Self
64 where
65 T: Display,
66 {
67 Error {
68 err: msg.to_string().into_boxed_str(),
69 }
70 }
71
72 #[cfg(not(any(feature = "std", feature = "alloc")))]
73 #[cold]
74 fn custom<T>(msg: T) -> Self
75 where
76 T: Display,
77 {
78 let _ = msg;
79 Error { err: () }
80 }
81}
82
83impl ser::Error for Error {
84 #[cold]
85 fn custom<T>(msg: T) -> Self
86 where
87 T: Display,
88 {
89 de::Error::custom(msg)
90 }
91}
92
93impl Display for Error {
94 #[cfg(any(feature = "std", feature = "alloc"))]
95 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
96 formatter.write_str(&self.err)
97 }
98
99 #[cfg(not(any(feature = "std", feature = "alloc")))]
100 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
101 formatter.write_str("Serde deserialization error")
102 }
103}
104
105impl Debug for Error {
106 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
107 let mut debug: DebugTuple<'_, '_> = formatter.debug_tuple(name:"Error");
108 #[cfg(any(feature = "std", feature = "alloc"))]
109 debug.field(&self.err);
110 debug.finish()
111 }
112}
113
114#[cfg(feature = "std")]
115impl error::Error for Error {
116 fn description(&self) -> &str {
117 &self.err
118 }
119}
120
121////////////////////////////////////////////////////////////////////////////////
122
123impl<'de, E> IntoDeserializer<'de, E> for ()
124where
125 E: de::Error,
126{
127 type Deserializer = UnitDeserializer<E>;
128
129 fn into_deserializer(self) -> UnitDeserializer<E> {
130 UnitDeserializer::new()
131 }
132}
133
134/// A deserializer holding a `()`.
135pub struct UnitDeserializer<E> {
136 marker: PhantomData<E>,
137}
138
139impl_copy_clone!(UnitDeserializer);
140
141impl<E> UnitDeserializer<E> {
142 #[allow(missing_docs)]
143 pub fn new() -> Self {
144 UnitDeserializer {
145 marker: PhantomData,
146 }
147 }
148}
149
150impl<'de, E> de::Deserializer<'de> for UnitDeserializer<E>
151where
152 E: de::Error,
153{
154 type Error = E;
155
156 forward_to_deserialize_any! {
157 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
158 bytes byte_buf unit unit_struct newtype_struct seq tuple tuple_struct
159 map struct enum identifier ignored_any
160 }
161
162 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
163 where
164 V: de::Visitor<'de>,
165 {
166 visitor.visit_unit()
167 }
168
169 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
170 where
171 V: de::Visitor<'de>,
172 {
173 visitor.visit_none()
174 }
175}
176
177impl<E> Debug for UnitDeserializer<E> {
178 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
179 formatter.debug_struct(name:"UnitDeserializer").finish()
180 }
181}
182
183////////////////////////////////////////////////////////////////////////////////
184
185/// A deserializer that cannot be instantiated.
186#[cfg(feature = "unstable")]
187pub struct NeverDeserializer<E> {
188 never: !,
189 marker: PhantomData<E>,
190}
191
192#[cfg(feature = "unstable")]
193impl<'de, E> IntoDeserializer<'de, E> for !
194where
195 E: de::Error,
196{
197 type Deserializer = NeverDeserializer<E>;
198
199 fn into_deserializer(self) -> Self::Deserializer {
200 self
201 }
202}
203
204#[cfg(feature = "unstable")]
205impl<'de, E> de::Deserializer<'de> for NeverDeserializer<E>
206where
207 E: de::Error,
208{
209 type Error = E;
210
211 fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
212 where
213 V: de::Visitor<'de>,
214 {
215 self.never
216 }
217
218 forward_to_deserialize_any! {
219 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
220 bytes byte_buf option unit unit_struct newtype_struct seq tuple
221 tuple_struct map struct enum identifier ignored_any
222 }
223}
224
225////////////////////////////////////////////////////////////////////////////////
226
227macro_rules! primitive_deserializer {
228 ($ty:ty, $doc:tt, $name:ident, $method:ident $($cast:tt)*) => {
229 #[doc = "A deserializer holding"]
230 #[doc = $doc]
231 pub struct $name<E> {
232 value: $ty,
233 marker: PhantomData<E>
234 }
235
236 impl_copy_clone!($name);
237
238 impl<'de, E> IntoDeserializer<'de, E> for $ty
239 where
240 E: de::Error,
241 {
242 type Deserializer = $name<E>;
243
244 fn into_deserializer(self) -> $name<E> {
245 $name::new(self)
246 }
247 }
248
249 impl<E> $name<E> {
250 #[allow(missing_docs)]
251 pub fn new(value: $ty) -> Self {
252 $name {
253 value,
254 marker: PhantomData,
255 }
256 }
257 }
258
259 impl<'de, E> de::Deserializer<'de> for $name<E>
260 where
261 E: de::Error,
262 {
263 type Error = E;
264
265 forward_to_deserialize_any! {
266 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str
267 string bytes byte_buf option unit unit_struct newtype_struct seq
268 tuple tuple_struct map struct enum identifier ignored_any
269 }
270
271 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
272 where
273 V: de::Visitor<'de>,
274 {
275 visitor.$method(self.value $($cast)*)
276 }
277 }
278
279 impl<E> Debug for $name<E> {
280 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
281 formatter
282 .debug_struct(stringify!($name))
283 .field("value", &self.value)
284 .finish()
285 }
286 }
287 }
288}
289
290primitive_deserializer!(bool, "a `bool`.", BoolDeserializer, visit_bool);
291primitive_deserializer!(i8, "an `i8`.", I8Deserializer, visit_i8);
292primitive_deserializer!(i16, "an `i16`.", I16Deserializer, visit_i16);
293primitive_deserializer!(i32, "an `i32`.", I32Deserializer, visit_i32);
294primitive_deserializer!(i64, "an `i64`.", I64Deserializer, visit_i64);
295primitive_deserializer!(isize, "an `isize`.", IsizeDeserializer, visit_i64 as i64);
296primitive_deserializer!(u8, "a `u8`.", U8Deserializer, visit_u8);
297primitive_deserializer!(u16, "a `u16`.", U16Deserializer, visit_u16);
298primitive_deserializer!(u64, "a `u64`.", U64Deserializer, visit_u64);
299primitive_deserializer!(usize, "a `usize`.", UsizeDeserializer, visit_u64 as u64);
300primitive_deserializer!(f32, "an `f32`.", F32Deserializer, visit_f32);
301primitive_deserializer!(f64, "an `f64`.", F64Deserializer, visit_f64);
302primitive_deserializer!(char, "a `char`.", CharDeserializer, visit_char);
303
304serde_if_integer128! {
305 primitive_deserializer!(i128, "an `i128`.", I128Deserializer, visit_i128);
306 primitive_deserializer!(u128, "a `u128`.", U128Deserializer, visit_u128);
307}
308
309/// A deserializer holding a `u32`.
310pub struct U32Deserializer<E> {
311 value: u32,
312 marker: PhantomData<E>,
313}
314
315impl_copy_clone!(U32Deserializer);
316
317impl<'de, E> IntoDeserializer<'de, E> for u32
318where
319 E: de::Error,
320{
321 type Deserializer = U32Deserializer<E>;
322
323 fn into_deserializer(self) -> U32Deserializer<E> {
324 U32Deserializer::new(self)
325 }
326}
327
328impl<E> U32Deserializer<E> {
329 #[allow(missing_docs)]
330 pub fn new(value: u32) -> Self {
331 U32Deserializer {
332 value,
333 marker: PhantomData,
334 }
335 }
336}
337
338impl<'de, E> de::Deserializer<'de> for U32Deserializer<E>
339where
340 E: de::Error,
341{
342 type Error = E;
343
344 forward_to_deserialize_any! {
345 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
346 bytes byte_buf option unit unit_struct newtype_struct seq tuple
347 tuple_struct map struct identifier ignored_any
348 }
349
350 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
351 where
352 V: de::Visitor<'de>,
353 {
354 visitor.visit_u32(self.value)
355 }
356
357 fn deserialize_enum<V>(
358 self,
359 name: &str,
360 variants: &'static [&'static str],
361 visitor: V,
362 ) -> Result<V::Value, Self::Error>
363 where
364 V: de::Visitor<'de>,
365 {
366 let _ = name;
367 let _ = variants;
368 visitor.visit_enum(self)
369 }
370}
371
372impl<'de, E> de::EnumAccess<'de> for U32Deserializer<E>
373where
374 E: de::Error,
375{
376 type Error = E;
377 type Variant = private::UnitOnly<E>;
378
379 fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
380 where
381 T: de::DeserializeSeed<'de>,
382 {
383 seed.deserialize(self).map(op:private::unit_only)
384 }
385}
386
387impl<E> Debug for U32Deserializer<E> {
388 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
389 formatter&mut DebugStruct<'_, '_>
390 .debug_struct("U32Deserializer")
391 .field(name:"value", &self.value)
392 .finish()
393 }
394}
395
396////////////////////////////////////////////////////////////////////////////////
397
398/// A deserializer holding a `&str`.
399pub struct StrDeserializer<'a, E> {
400 value: &'a str,
401 marker: PhantomData<E>,
402}
403
404impl_copy_clone!(StrDeserializer<'de>);
405
406impl<'de, 'a, E> IntoDeserializer<'de, E> for &'a str
407where
408 E: de::Error,
409{
410 type Deserializer = StrDeserializer<'a, E>;
411
412 fn into_deserializer(self) -> StrDeserializer<'a, E> {
413 StrDeserializer::new(self)
414 }
415}
416
417impl<'a, E> StrDeserializer<'a, E> {
418 #[allow(missing_docs)]
419 pub fn new(value: &'a str) -> Self {
420 StrDeserializer {
421 value,
422 marker: PhantomData,
423 }
424 }
425}
426
427impl<'de, 'a, E> de::Deserializer<'de> for StrDeserializer<'a, E>
428where
429 E: de::Error,
430{
431 type Error = E;
432
433 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
434 where
435 V: de::Visitor<'de>,
436 {
437 visitor.visit_str(self.value)
438 }
439
440 fn deserialize_enum<V>(
441 self,
442 name: &str,
443 variants: &'static [&'static str],
444 visitor: V,
445 ) -> Result<V::Value, Self::Error>
446 where
447 V: de::Visitor<'de>,
448 {
449 let _ = name;
450 let _ = variants;
451 visitor.visit_enum(self)
452 }
453
454 forward_to_deserialize_any! {
455 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
456 bytes byte_buf option unit unit_struct newtype_struct seq tuple
457 tuple_struct map struct identifier ignored_any
458 }
459}
460
461impl<'de, 'a, E> de::EnumAccess<'de> for StrDeserializer<'a, E>
462where
463 E: de::Error,
464{
465 type Error = E;
466 type Variant = private::UnitOnly<E>;
467
468 fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
469 where
470 T: de::DeserializeSeed<'de>,
471 {
472 seed.deserialize(self).map(op:private::unit_only)
473 }
474}
475
476impl<'a, E> Debug for StrDeserializer<'a, E> {
477 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
478 formatter&mut DebugStruct<'_, '_>
479 .debug_struct("StrDeserializer")
480 .field(name:"value", &self.value)
481 .finish()
482 }
483}
484
485////////////////////////////////////////////////////////////////////////////////
486
487/// A deserializer holding a `&str` with a lifetime tied to another
488/// deserializer.
489pub struct BorrowedStrDeserializer<'de, E> {
490 value: &'de str,
491 marker: PhantomData<E>,
492}
493
494impl_copy_clone!(BorrowedStrDeserializer<'de>);
495
496impl<'de, E> BorrowedStrDeserializer<'de, E> {
497 /// Create a new borrowed deserializer from the given string.
498 pub fn new(value: &'de str) -> BorrowedStrDeserializer<'de, E> {
499 BorrowedStrDeserializer {
500 value,
501 marker: PhantomData,
502 }
503 }
504}
505
506impl<'de, E> de::Deserializer<'de> for BorrowedStrDeserializer<'de, E>
507where
508 E: de::Error,
509{
510 type Error = E;
511
512 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
513 where
514 V: de::Visitor<'de>,
515 {
516 visitor.visit_borrowed_str(self.value)
517 }
518
519 fn deserialize_enum<V>(
520 self,
521 name: &str,
522 variants: &'static [&'static str],
523 visitor: V,
524 ) -> Result<V::Value, Self::Error>
525 where
526 V: de::Visitor<'de>,
527 {
528 let _ = name;
529 let _ = variants;
530 visitor.visit_enum(self)
531 }
532
533 forward_to_deserialize_any! {
534 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
535 bytes byte_buf option unit unit_struct newtype_struct seq tuple
536 tuple_struct map struct identifier ignored_any
537 }
538}
539
540impl<'de, E> de::EnumAccess<'de> for BorrowedStrDeserializer<'de, E>
541where
542 E: de::Error,
543{
544 type Error = E;
545 type Variant = private::UnitOnly<E>;
546
547 fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
548 where
549 T: de::DeserializeSeed<'de>,
550 {
551 seed.deserialize(self).map(op:private::unit_only)
552 }
553}
554
555impl<'de, E> Debug for BorrowedStrDeserializer<'de, E> {
556 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
557 formatter&mut DebugStruct<'_, '_>
558 .debug_struct("BorrowedStrDeserializer")
559 .field(name:"value", &self.value)
560 .finish()
561 }
562}
563
564////////////////////////////////////////////////////////////////////////////////
565
566/// A deserializer holding a `String`.
567#[cfg(any(feature = "std", feature = "alloc"))]
568pub struct StringDeserializer<E> {
569 value: String,
570 marker: PhantomData<E>,
571}
572
573#[cfg(any(feature = "std", feature = "alloc"))]
574impl<E> Clone for StringDeserializer<E> {
575 fn clone(&self) -> Self {
576 StringDeserializer {
577 value: self.value.clone(),
578 marker: PhantomData,
579 }
580 }
581}
582
583#[cfg(any(feature = "std", feature = "alloc"))]
584impl<'de, E> IntoDeserializer<'de, E> for String
585where
586 E: de::Error,
587{
588 type Deserializer = StringDeserializer<E>;
589
590 fn into_deserializer(self) -> StringDeserializer<E> {
591 StringDeserializer::new(self)
592 }
593}
594
595#[cfg(any(feature = "std", feature = "alloc"))]
596impl<E> StringDeserializer<E> {
597 #[allow(missing_docs)]
598 pub fn new(value: String) -> Self {
599 StringDeserializer {
600 value,
601 marker: PhantomData,
602 }
603 }
604}
605
606#[cfg(any(feature = "std", feature = "alloc"))]
607impl<'de, E> de::Deserializer<'de> for StringDeserializer<E>
608where
609 E: de::Error,
610{
611 type Error = E;
612
613 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
614 where
615 V: de::Visitor<'de>,
616 {
617 visitor.visit_string(self.value)
618 }
619
620 fn deserialize_enum<V>(
621 self,
622 name: &str,
623 variants: &'static [&'static str],
624 visitor: V,
625 ) -> Result<V::Value, Self::Error>
626 where
627 V: de::Visitor<'de>,
628 {
629 let _ = name;
630 let _ = variants;
631 visitor.visit_enum(self)
632 }
633
634 forward_to_deserialize_any! {
635 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
636 bytes byte_buf option unit unit_struct newtype_struct seq tuple
637 tuple_struct map struct identifier ignored_any
638 }
639}
640
641#[cfg(any(feature = "std", feature = "alloc"))]
642impl<'de, E> de::EnumAccess<'de> for StringDeserializer<E>
643where
644 E: de::Error,
645{
646 type Error = E;
647 type Variant = private::UnitOnly<E>;
648
649 fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
650 where
651 T: de::DeserializeSeed<'de>,
652 {
653 seed.deserialize(self).map(op:private::unit_only)
654 }
655}
656
657#[cfg(any(feature = "std", feature = "alloc"))]
658impl<E> Debug for StringDeserializer<E> {
659 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
660 formatter&mut DebugStruct<'_, '_>
661 .debug_struct("StringDeserializer")
662 .field(name:"value", &self.value)
663 .finish()
664 }
665}
666
667////////////////////////////////////////////////////////////////////////////////
668
669/// A deserializer holding a `Cow<str>`.
670#[cfg(any(feature = "std", feature = "alloc"))]
671pub struct CowStrDeserializer<'a, E> {
672 value: Cow<'a, str>,
673 marker: PhantomData<E>,
674}
675
676#[cfg(any(feature = "std", feature = "alloc"))]
677impl<'a, E> Clone for CowStrDeserializer<'a, E> {
678 fn clone(&self) -> Self {
679 CowStrDeserializer {
680 value: self.value.clone(),
681 marker: PhantomData,
682 }
683 }
684}
685
686#[cfg(any(feature = "std", feature = "alloc"))]
687impl<'de, 'a, E> IntoDeserializer<'de, E> for Cow<'a, str>
688where
689 E: de::Error,
690{
691 type Deserializer = CowStrDeserializer<'a, E>;
692
693 fn into_deserializer(self) -> CowStrDeserializer<'a, E> {
694 CowStrDeserializer::new(self)
695 }
696}
697
698#[cfg(any(feature = "std", feature = "alloc"))]
699impl<'a, E> CowStrDeserializer<'a, E> {
700 #[allow(missing_docs)]
701 pub fn new(value: Cow<'a, str>) -> Self {
702 CowStrDeserializer {
703 value,
704 marker: PhantomData,
705 }
706 }
707}
708
709#[cfg(any(feature = "std", feature = "alloc"))]
710impl<'de, 'a, E> de::Deserializer<'de> for CowStrDeserializer<'a, E>
711where
712 E: de::Error,
713{
714 type Error = E;
715
716 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
717 where
718 V: de::Visitor<'de>,
719 {
720 match self.value {
721 Cow::Borrowed(string) => visitor.visit_str(string),
722 Cow::Owned(string) => visitor.visit_string(string),
723 }
724 }
725
726 fn deserialize_enum<V>(
727 self,
728 name: &str,
729 variants: &'static [&'static str],
730 visitor: V,
731 ) -> Result<V::Value, Self::Error>
732 where
733 V: de::Visitor<'de>,
734 {
735 let _ = name;
736 let _ = variants;
737 visitor.visit_enum(self)
738 }
739
740 forward_to_deserialize_any! {
741 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
742 bytes byte_buf option unit unit_struct newtype_struct seq tuple
743 tuple_struct map struct identifier ignored_any
744 }
745}
746
747#[cfg(any(feature = "std", feature = "alloc"))]
748impl<'de, 'a, E> de::EnumAccess<'de> for CowStrDeserializer<'a, E>
749where
750 E: de::Error,
751{
752 type Error = E;
753 type Variant = private::UnitOnly<E>;
754
755 fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
756 where
757 T: de::DeserializeSeed<'de>,
758 {
759 seed.deserialize(self).map(op:private::unit_only)
760 }
761}
762
763#[cfg(any(feature = "std", feature = "alloc"))]
764impl<'a, E> Debug for CowStrDeserializer<'a, E> {
765 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
766 formatter&mut DebugStruct<'_, '_>
767 .debug_struct("CowStrDeserializer")
768 .field(name:"value", &self.value)
769 .finish()
770 }
771}
772
773////////////////////////////////////////////////////////////////////////////////
774
775/// A deserializer holding a `&[u8]`. Always calls [`Visitor::visit_bytes`].
776pub struct BytesDeserializer<'a, E> {
777 value: &'a [u8],
778 marker: PhantomData<E>,
779}
780
781impl<'a, E> BytesDeserializer<'a, E> {
782 /// Create a new deserializer from the given bytes.
783 pub fn new(value: &'a [u8]) -> Self {
784 BytesDeserializer {
785 value,
786 marker: PhantomData,
787 }
788 }
789}
790
791impl_copy_clone!(BytesDeserializer<'a>);
792
793impl<'de, 'a, E> IntoDeserializer<'de, E> for &'a [u8]
794where
795 E: de::Error,
796{
797 type Deserializer = BytesDeserializer<'a, E>;
798
799 fn into_deserializer(self) -> BytesDeserializer<'a, E> {
800 BytesDeserializer::new(self)
801 }
802}
803
804impl<'de, 'a, E> Deserializer<'de> for BytesDeserializer<'a, E>
805where
806 E: de::Error,
807{
808 type Error = E;
809
810 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
811 where
812 V: Visitor<'de>,
813 {
814 visitor.visit_bytes(self.value)
815 }
816
817 forward_to_deserialize_any! {
818 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
819 bytes byte_buf option unit unit_struct newtype_struct seq tuple
820 tuple_struct map struct enum identifier ignored_any
821 }
822}
823
824impl<'a, E> Debug for BytesDeserializer<'a, E> {
825 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
826 formatter&mut DebugStruct<'_, '_>
827 .debug_struct("BytesDeserializer")
828 .field(name:"value", &self.value)
829 .finish()
830 }
831}
832
833/// A deserializer holding a `&[u8]` with a lifetime tied to another
834/// deserializer. Always calls [`Visitor::visit_borrowed_bytes`].
835pub struct BorrowedBytesDeserializer<'de, E> {
836 value: &'de [u8],
837 marker: PhantomData<E>,
838}
839
840impl<'de, E> BorrowedBytesDeserializer<'de, E> {
841 /// Create a new borrowed deserializer from the given borrowed bytes.
842 pub fn new(value: &'de [u8]) -> Self {
843 BorrowedBytesDeserializer {
844 value,
845 marker: PhantomData,
846 }
847 }
848}
849
850impl_copy_clone!(BorrowedBytesDeserializer<'de>);
851
852impl<'de, E> Deserializer<'de> for BorrowedBytesDeserializer<'de, E>
853where
854 E: de::Error,
855{
856 type Error = E;
857
858 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
859 where
860 V: Visitor<'de>,
861 {
862 visitor.visit_borrowed_bytes(self.value)
863 }
864
865 forward_to_deserialize_any! {
866 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
867 bytes byte_buf option unit unit_struct newtype_struct seq tuple
868 tuple_struct map struct enum identifier ignored_any
869 }
870}
871
872impl<'de, E> Debug for BorrowedBytesDeserializer<'de, E> {
873 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
874 formatter&mut DebugStruct<'_, '_>
875 .debug_struct("BorrowedBytesDeserializer")
876 .field(name:"value", &self.value)
877 .finish()
878 }
879}
880
881////////////////////////////////////////////////////////////////////////////////
882
883/// A deserializer that iterates over a sequence.
884#[derive(Clone)]
885pub struct SeqDeserializer<I, E> {
886 iter: iter::Fuse<I>,
887 count: usize,
888 marker: PhantomData<E>,
889}
890
891impl<I, E> SeqDeserializer<I, E>
892where
893 I: Iterator,
894{
895 /// Construct a new `SeqDeserializer<I, E>`.
896 pub fn new(iter: I) -> Self {
897 SeqDeserializer {
898 iter: iter.fuse(),
899 count: 0,
900 marker: PhantomData,
901 }
902 }
903}
904
905impl<I, E> SeqDeserializer<I, E>
906where
907 I: Iterator,
908 E: de::Error,
909{
910 /// Check for remaining elements after passing a `SeqDeserializer` to
911 /// `Visitor::visit_seq`.
912 pub fn end(self) -> Result<(), E> {
913 let remaining: usize = self.iter.count();
914 if remaining == 0 {
915 Ok(())
916 } else {
917 // First argument is the number of elements in the data, second
918 // argument is the number of elements expected by the Deserialize.
919 Err(de::Error::invalid_length(
920 self.count + remaining,
921 &ExpectedInSeq(self.count),
922 ))
923 }
924 }
925}
926
927impl<'de, I, T, E> de::Deserializer<'de> for SeqDeserializer<I, E>
928where
929 I: Iterator<Item = T>,
930 T: IntoDeserializer<'de, E>,
931 E: de::Error,
932{
933 type Error = E;
934
935 fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
936 where
937 V: de::Visitor<'de>,
938 {
939 let v: ::Value = tri!(visitor.visit_seq(&mut self));
940 tri!(self.end());
941 Ok(v)
942 }
943
944 forward_to_deserialize_any! {
945 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
946 bytes byte_buf option unit unit_struct newtype_struct seq tuple
947 tuple_struct map struct enum identifier ignored_any
948 }
949}
950
951impl<'de, I, T, E> de::SeqAccess<'de> for SeqDeserializer<I, E>
952where
953 I: Iterator<Item = T>,
954 T: IntoDeserializer<'de, E>,
955 E: de::Error,
956{
957 type Error = E;
958
959 fn next_element_seed<V>(&mut self, seed: V) -> Result<Option<V::Value>, Self::Error>
960 where
961 V: de::DeserializeSeed<'de>,
962 {
963 match self.iter.next() {
964 Some(value: T) => {
965 self.count += 1;
966 seed.deserialize(value.into_deserializer()).map(op:Some)
967 }
968 None => Ok(None),
969 }
970 }
971
972 fn size_hint(&self) -> Option<usize> {
973 size_hint::from_bounds(&self.iter)
974 }
975}
976
977struct ExpectedInSeq(usize);
978
979impl Expected for ExpectedInSeq {
980 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
981 if self.0 == 1 {
982 write!(formatter, "1 element in sequence")
983 } else {
984 write!(formatter, "{} elements in sequence", self.0)
985 }
986 }
987}
988
989impl<I, E> Debug for SeqDeserializer<I, E>
990where
991 I: Debug,
992{
993 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
994 formatter&mut DebugStruct<'_, '_>
995 .debug_struct("SeqDeserializer")
996 .field("iter", &self.iter)
997 .field(name:"count", &self.count)
998 .finish()
999 }
1000}
1001
1002////////////////////////////////////////////////////////////////////////////////
1003
1004#[cfg(any(feature = "std", feature = "alloc"))]
1005impl<'de, T, E> IntoDeserializer<'de, E> for Vec<T>
1006where
1007 T: IntoDeserializer<'de, E>,
1008 E: de::Error,
1009{
1010 type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>;
1011
1012 fn into_deserializer(self) -> Self::Deserializer {
1013 SeqDeserializer::new(self.into_iter())
1014 }
1015}
1016
1017#[cfg(any(feature = "std", feature = "alloc"))]
1018impl<'de, T, E> IntoDeserializer<'de, E> for BTreeSet<T>
1019where
1020 T: IntoDeserializer<'de, E> + Eq + Ord,
1021 E: de::Error,
1022{
1023 type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>;
1024
1025 fn into_deserializer(self) -> Self::Deserializer {
1026 SeqDeserializer::new(self.into_iter())
1027 }
1028}
1029
1030#[cfg(feature = "std")]
1031impl<'de, T, S, E> IntoDeserializer<'de, E> for HashSet<T, S>
1032where
1033 T: IntoDeserializer<'de, E> + Eq + Hash,
1034 S: BuildHasher,
1035 E: de::Error,
1036{
1037 type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>;
1038
1039 fn into_deserializer(self) -> Self::Deserializer {
1040 SeqDeserializer::new(self.into_iter())
1041 }
1042}
1043
1044////////////////////////////////////////////////////////////////////////////////
1045
1046/// A deserializer holding a `SeqAccess`.
1047#[derive(Clone, Debug)]
1048pub struct SeqAccessDeserializer<A> {
1049 seq: A,
1050}
1051
1052impl<A> SeqAccessDeserializer<A> {
1053 /// Construct a new `SeqAccessDeserializer<A>`.
1054 pub fn new(seq: A) -> Self {
1055 SeqAccessDeserializer { seq }
1056 }
1057}
1058
1059impl<'de, A> de::Deserializer<'de> for SeqAccessDeserializer<A>
1060where
1061 A: de::SeqAccess<'de>,
1062{
1063 type Error = A::Error;
1064
1065 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1066 where
1067 V: de::Visitor<'de>,
1068 {
1069 visitor.visit_seq(self.seq)
1070 }
1071
1072 forward_to_deserialize_any! {
1073 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
1074 bytes byte_buf option unit unit_struct newtype_struct seq tuple
1075 tuple_struct map struct enum identifier ignored_any
1076 }
1077}
1078
1079////////////////////////////////////////////////////////////////////////////////
1080
1081/// A deserializer that iterates over a map.
1082pub struct MapDeserializer<'de, I, E>
1083where
1084 I: Iterator,
1085 I::Item: private::Pair,
1086{
1087 iter: iter::Fuse<I>,
1088 value: Option<Second<I::Item>>,
1089 count: usize,
1090 lifetime: PhantomData<&'de ()>,
1091 error: PhantomData<E>,
1092}
1093
1094impl<'de, I, E> MapDeserializer<'de, I, E>
1095where
1096 I: Iterator,
1097 I::Item: private::Pair,
1098{
1099 /// Construct a new `MapDeserializer<I, E>`.
1100 pub fn new(iter: I) -> Self {
1101 MapDeserializer {
1102 iter: iter.fuse(),
1103 value: None,
1104 count: 0,
1105 lifetime: PhantomData,
1106 error: PhantomData,
1107 }
1108 }
1109}
1110
1111impl<'de, I, E> MapDeserializer<'de, I, E>
1112where
1113 I: Iterator,
1114 I::Item: private::Pair,
1115 E: de::Error,
1116{
1117 /// Check for remaining elements after passing a `MapDeserializer` to
1118 /// `Visitor::visit_map`.
1119 pub fn end(self) -> Result<(), E> {
1120 let remaining: usize = self.iter.count();
1121 if remaining == 0 {
1122 Ok(())
1123 } else {
1124 // First argument is the number of elements in the data, second
1125 // argument is the number of elements expected by the Deserialize.
1126 Err(de::Error::invalid_length(
1127 self.count + remaining,
1128 &ExpectedInMap(self.count),
1129 ))
1130 }
1131 }
1132}
1133
1134impl<'de, I, E> MapDeserializer<'de, I, E>
1135where
1136 I: Iterator,
1137 I::Item: private::Pair,
1138{
1139 fn next_pair(&mut self) -> Option<(First<I::Item>, Second<I::Item>)> {
1140 match self.iter.next() {
1141 Some(kv: ::Item) => {
1142 self.count += 1;
1143 Some(private::Pair::split(self:kv))
1144 }
1145 None => None,
1146 }
1147 }
1148}
1149
1150impl<'de, I, E> de::Deserializer<'de> for MapDeserializer<'de, I, E>
1151where
1152 I: Iterator,
1153 I::Item: private::Pair,
1154 First<I::Item>: IntoDeserializer<'de, E>,
1155 Second<I::Item>: IntoDeserializer<'de, E>,
1156 E: de::Error,
1157{
1158 type Error = E;
1159
1160 fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
1161 where
1162 V: de::Visitor<'de>,
1163 {
1164 let value = tri!(visitor.visit_map(&mut self));
1165 tri!(self.end());
1166 Ok(value)
1167 }
1168
1169 fn deserialize_seq<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
1170 where
1171 V: de::Visitor<'de>,
1172 {
1173 let value = tri!(visitor.visit_seq(&mut self));
1174 tri!(self.end());
1175 Ok(value)
1176 }
1177
1178 fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
1179 where
1180 V: de::Visitor<'de>,
1181 {
1182 let _ = len;
1183 self.deserialize_seq(visitor)
1184 }
1185
1186 forward_to_deserialize_any! {
1187 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
1188 bytes byte_buf option unit unit_struct newtype_struct tuple_struct map
1189 struct enum identifier ignored_any
1190 }
1191}
1192
1193impl<'de, I, E> de::MapAccess<'de> for MapDeserializer<'de, I, E>
1194where
1195 I: Iterator,
1196 I::Item: private::Pair,
1197 First<I::Item>: IntoDeserializer<'de, E>,
1198 Second<I::Item>: IntoDeserializer<'de, E>,
1199 E: de::Error,
1200{
1201 type Error = E;
1202
1203 fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1204 where
1205 T: de::DeserializeSeed<'de>,
1206 {
1207 match self.next_pair() {
1208 Some((key, value)) => {
1209 self.value = Some(value);
1210 seed.deserialize(key.into_deserializer()).map(Some)
1211 }
1212 None => Ok(None),
1213 }
1214 }
1215
1216 fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
1217 where
1218 T: de::DeserializeSeed<'de>,
1219 {
1220 let value = self.value.take();
1221 // Panic because this indicates a bug in the program rather than an
1222 // expected failure.
1223 let value = value.expect("MapAccess::next_value called before next_key");
1224 seed.deserialize(value.into_deserializer())
1225 }
1226
1227 fn next_entry_seed<TK, TV>(
1228 &mut self,
1229 kseed: TK,
1230 vseed: TV,
1231 ) -> Result<Option<(TK::Value, TV::Value)>, Self::Error>
1232 where
1233 TK: de::DeserializeSeed<'de>,
1234 TV: de::DeserializeSeed<'de>,
1235 {
1236 match self.next_pair() {
1237 Some((key, value)) => {
1238 let key = tri!(kseed.deserialize(key.into_deserializer()));
1239 let value = tri!(vseed.deserialize(value.into_deserializer()));
1240 Ok(Some((key, value)))
1241 }
1242 None => Ok(None),
1243 }
1244 }
1245
1246 fn size_hint(&self) -> Option<usize> {
1247 size_hint::from_bounds(&self.iter)
1248 }
1249}
1250
1251impl<'de, I, E> de::SeqAccess<'de> for MapDeserializer<'de, I, E>
1252where
1253 I: Iterator,
1254 I::Item: private::Pair,
1255 First<I::Item>: IntoDeserializer<'de, E>,
1256 Second<I::Item>: IntoDeserializer<'de, E>,
1257 E: de::Error,
1258{
1259 type Error = E;
1260
1261 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1262 where
1263 T: de::DeserializeSeed<'de>,
1264 {
1265 match self.next_pair() {
1266 Some((k: <::Item as Pair>::First, v: <::Item as Pair>::Second)) => {
1267 let de: PairDeserializer<<::Item as Pair>::First, …, …> = PairDeserializer(k, v, PhantomData);
1268 seed.deserialize(de).map(op:Some)
1269 }
1270 None => Ok(None),
1271 }
1272 }
1273
1274 fn size_hint(&self) -> Option<usize> {
1275 size_hint::from_bounds(&self.iter)
1276 }
1277}
1278
1279// Cannot #[derive(Clone)] because of the bound `Second<I::Item>: Clone`.
1280impl<'de, I, E> Clone for MapDeserializer<'de, I, E>
1281where
1282 I: Iterator + Clone,
1283 I::Item: private::Pair,
1284 Second<I::Item>: Clone,
1285{
1286 fn clone(&self) -> Self {
1287 MapDeserializer {
1288 iter: self.iter.clone(),
1289 value: self.value.clone(),
1290 count: self.count,
1291 lifetime: self.lifetime,
1292 error: self.error,
1293 }
1294 }
1295}
1296
1297impl<'de, I, E> Debug for MapDeserializer<'de, I, E>
1298where
1299 I: Iterator + Debug,
1300 I::Item: private::Pair,
1301 Second<I::Item>: Debug,
1302{
1303 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1304 formatter&mut DebugStruct<'_, '_>
1305 .debug_struct("MapDeserializer")
1306 .field("iter", &self.iter)
1307 .field("value", &self.value)
1308 .field(name:"count", &self.count)
1309 .finish()
1310 }
1311}
1312
1313// Used in the `impl SeqAccess for MapDeserializer` to visit the map as a
1314// sequence of pairs.
1315struct PairDeserializer<A, B, E>(A, B, PhantomData<E>);
1316
1317impl<'de, A, B, E> de::Deserializer<'de> for PairDeserializer<A, B, E>
1318where
1319 A: IntoDeserializer<'de, E>,
1320 B: IntoDeserializer<'de, E>,
1321 E: de::Error,
1322{
1323 type Error = E;
1324
1325 forward_to_deserialize_any! {
1326 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
1327 bytes byte_buf option unit unit_struct newtype_struct tuple_struct map
1328 struct enum identifier ignored_any
1329 }
1330
1331 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1332 where
1333 V: de::Visitor<'de>,
1334 {
1335 self.deserialize_seq(visitor)
1336 }
1337
1338 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1339 where
1340 V: de::Visitor<'de>,
1341 {
1342 let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData);
1343 let pair = tri!(visitor.visit_seq(&mut pair_visitor));
1344 if pair_visitor.1.is_none() {
1345 Ok(pair)
1346 } else {
1347 let remaining = pair_visitor.size_hint().unwrap();
1348 // First argument is the number of elements in the data, second
1349 // argument is the number of elements expected by the Deserialize.
1350 Err(de::Error::invalid_length(2, &ExpectedInSeq(2 - remaining)))
1351 }
1352 }
1353
1354 fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
1355 where
1356 V: de::Visitor<'de>,
1357 {
1358 if len == 2 {
1359 self.deserialize_seq(visitor)
1360 } else {
1361 // First argument is the number of elements in the data, second
1362 // argument is the number of elements expected by the Deserialize.
1363 Err(de::Error::invalid_length(2, &ExpectedInSeq(len)))
1364 }
1365 }
1366}
1367
1368struct PairVisitor<A, B, E>(Option<A>, Option<B>, PhantomData<E>);
1369
1370impl<'de, A, B, E> de::SeqAccess<'de> for PairVisitor<A, B, E>
1371where
1372 A: IntoDeserializer<'de, E>,
1373 B: IntoDeserializer<'de, E>,
1374 E: de::Error,
1375{
1376 type Error = E;
1377
1378 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1379 where
1380 T: de::DeserializeSeed<'de>,
1381 {
1382 if let Some(k) = self.0.take() {
1383 seed.deserialize(k.into_deserializer()).map(Some)
1384 } else if let Some(v) = self.1.take() {
1385 seed.deserialize(v.into_deserializer()).map(Some)
1386 } else {
1387 Ok(None)
1388 }
1389 }
1390
1391 fn size_hint(&self) -> Option<usize> {
1392 if self.0.is_some() {
1393 Some(2)
1394 } else if self.1.is_some() {
1395 Some(1)
1396 } else {
1397 Some(0)
1398 }
1399 }
1400}
1401
1402struct ExpectedInMap(usize);
1403
1404impl Expected for ExpectedInMap {
1405 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1406 if self.0 == 1 {
1407 write!(formatter, "1 element in map")
1408 } else {
1409 write!(formatter, "{} elements in map", self.0)
1410 }
1411 }
1412}
1413
1414////////////////////////////////////////////////////////////////////////////////
1415
1416#[cfg(any(feature = "std", feature = "alloc"))]
1417impl<'de, K, V, E> IntoDeserializer<'de, E> for BTreeMap<K, V>
1418where
1419 K: IntoDeserializer<'de, E> + Eq + Ord,
1420 V: IntoDeserializer<'de, E>,
1421 E: de::Error,
1422{
1423 type Deserializer = MapDeserializer<'de, <Self as IntoIterator>::IntoIter, E>;
1424
1425 fn into_deserializer(self) -> Self::Deserializer {
1426 MapDeserializer::new(self.into_iter())
1427 }
1428}
1429
1430#[cfg(feature = "std")]
1431impl<'de, K, V, S, E> IntoDeserializer<'de, E> for HashMap<K, V, S>
1432where
1433 K: IntoDeserializer<'de, E> + Eq + Hash,
1434 V: IntoDeserializer<'de, E>,
1435 S: BuildHasher,
1436 E: de::Error,
1437{
1438 type Deserializer = MapDeserializer<'de, <Self as IntoIterator>::IntoIter, E>;
1439
1440 fn into_deserializer(self) -> Self::Deserializer {
1441 MapDeserializer::new(self.into_iter())
1442 }
1443}
1444
1445////////////////////////////////////////////////////////////////////////////////
1446
1447/// A deserializer holding a `MapAccess`.
1448#[derive(Clone, Debug)]
1449pub struct MapAccessDeserializer<A> {
1450 map: A,
1451}
1452
1453impl<A> MapAccessDeserializer<A> {
1454 /// Construct a new `MapAccessDeserializer<A>`.
1455 pub fn new(map: A) -> Self {
1456 MapAccessDeserializer { map }
1457 }
1458}
1459
1460impl<'de, A> de::Deserializer<'de> for MapAccessDeserializer<A>
1461where
1462 A: de::MapAccess<'de>,
1463{
1464 type Error = A::Error;
1465
1466 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1467 where
1468 V: de::Visitor<'de>,
1469 {
1470 visitor.visit_map(self.map)
1471 }
1472
1473 fn deserialize_enum<V>(
1474 self,
1475 _name: &str,
1476 _variants: &'static [&'static str],
1477 visitor: V,
1478 ) -> Result<V::Value, Self::Error>
1479 where
1480 V: de::Visitor<'de>,
1481 {
1482 visitor.visit_enum(self)
1483 }
1484
1485 forward_to_deserialize_any! {
1486 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
1487 bytes byte_buf option unit unit_struct newtype_struct seq tuple
1488 tuple_struct map struct identifier ignored_any
1489 }
1490}
1491
1492impl<'de, A> de::EnumAccess<'de> for MapAccessDeserializer<A>
1493where
1494 A: de::MapAccess<'de>,
1495{
1496 type Error = A::Error;
1497 type Variant = private::MapAsEnum<A>;
1498
1499 fn variant_seed<T>(mut self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
1500 where
1501 T: de::DeserializeSeed<'de>,
1502 {
1503 match tri!(self.map.next_key_seed(seed)) {
1504 Some(key: ::Value) => Ok((key, private::map_as_enum(self.map))),
1505 None => Err(de::Error::invalid_type(unexp:de::Unexpected::Map, &"enum")),
1506 }
1507 }
1508}
1509
1510////////////////////////////////////////////////////////////////////////////////
1511
1512/// A deserializer holding an `EnumAccess`.
1513#[derive(Clone, Debug)]
1514pub struct EnumAccessDeserializer<A> {
1515 access: A,
1516}
1517
1518impl<A> EnumAccessDeserializer<A> {
1519 /// Construct a new `EnumAccessDeserializer<A>`.
1520 pub fn new(access: A) -> Self {
1521 EnumAccessDeserializer { access }
1522 }
1523}
1524
1525impl<'de, A> de::Deserializer<'de> for EnumAccessDeserializer<A>
1526where
1527 A: de::EnumAccess<'de>,
1528{
1529 type Error = A::Error;
1530
1531 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1532 where
1533 V: de::Visitor<'de>,
1534 {
1535 visitor.visit_enum(self.access)
1536 }
1537
1538 forward_to_deserialize_any! {
1539 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
1540 bytes byte_buf option unit unit_struct newtype_struct seq tuple
1541 tuple_struct map struct enum identifier ignored_any
1542 }
1543}
1544
1545////////////////////////////////////////////////////////////////////////////////
1546
1547mod private {
1548 use crate::lib::*;
1549
1550 use crate::de::{
1551 self, DeserializeSeed, Deserializer, MapAccess, Unexpected, VariantAccess, Visitor,
1552 };
1553
1554 pub struct UnitOnly<E> {
1555 marker: PhantomData<E>,
1556 }
1557
1558 pub fn unit_only<T, E>(t: T) -> (T, UnitOnly<E>) {
1559 (
1560 t,
1561 UnitOnly {
1562 marker: PhantomData,
1563 },
1564 )
1565 }
1566
1567 impl<'de, E> de::VariantAccess<'de> for UnitOnly<E>
1568 where
1569 E: de::Error,
1570 {
1571 type Error = E;
1572
1573 fn unit_variant(self) -> Result<(), Self::Error> {
1574 Ok(())
1575 }
1576
1577 fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
1578 where
1579 T: de::DeserializeSeed<'de>,
1580 {
1581 Err(de::Error::invalid_type(
1582 Unexpected::UnitVariant,
1583 &"newtype variant",
1584 ))
1585 }
1586
1587 fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
1588 where
1589 V: de::Visitor<'de>,
1590 {
1591 Err(de::Error::invalid_type(
1592 Unexpected::UnitVariant,
1593 &"tuple variant",
1594 ))
1595 }
1596
1597 fn struct_variant<V>(
1598 self,
1599 _fields: &'static [&'static str],
1600 _visitor: V,
1601 ) -> Result<V::Value, Self::Error>
1602 where
1603 V: de::Visitor<'de>,
1604 {
1605 Err(de::Error::invalid_type(
1606 Unexpected::UnitVariant,
1607 &"struct variant",
1608 ))
1609 }
1610 }
1611
1612 pub struct MapAsEnum<A> {
1613 map: A,
1614 }
1615
1616 pub fn map_as_enum<A>(map: A) -> MapAsEnum<A> {
1617 MapAsEnum { map }
1618 }
1619
1620 impl<'de, A> VariantAccess<'de> for MapAsEnum<A>
1621 where
1622 A: MapAccess<'de>,
1623 {
1624 type Error = A::Error;
1625
1626 fn unit_variant(mut self) -> Result<(), Self::Error> {
1627 self.map.next_value()
1628 }
1629
1630 fn newtype_variant_seed<T>(mut self, seed: T) -> Result<T::Value, Self::Error>
1631 where
1632 T: DeserializeSeed<'de>,
1633 {
1634 self.map.next_value_seed(seed)
1635 }
1636
1637 fn tuple_variant<V>(mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
1638 where
1639 V: Visitor<'de>,
1640 {
1641 self.map.next_value_seed(SeedTupleVariant { len, visitor })
1642 }
1643
1644 fn struct_variant<V>(
1645 mut self,
1646 _fields: &'static [&'static str],
1647 visitor: V,
1648 ) -> Result<V::Value, Self::Error>
1649 where
1650 V: Visitor<'de>,
1651 {
1652 self.map.next_value_seed(SeedStructVariant { visitor })
1653 }
1654 }
1655
1656 struct SeedTupleVariant<V> {
1657 len: usize,
1658 visitor: V,
1659 }
1660
1661 impl<'de, V> DeserializeSeed<'de> for SeedTupleVariant<V>
1662 where
1663 V: Visitor<'de>,
1664 {
1665 type Value = V::Value;
1666
1667 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1668 where
1669 D: Deserializer<'de>,
1670 {
1671 deserializer.deserialize_tuple(self.len, self.visitor)
1672 }
1673 }
1674
1675 struct SeedStructVariant<V> {
1676 visitor: V,
1677 }
1678
1679 impl<'de, V> DeserializeSeed<'de> for SeedStructVariant<V>
1680 where
1681 V: Visitor<'de>,
1682 {
1683 type Value = V::Value;
1684
1685 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1686 where
1687 D: Deserializer<'de>,
1688 {
1689 deserializer.deserialize_map(self.visitor)
1690 }
1691 }
1692
1693 /// Avoid having to restate the generic types on `MapDeserializer`. The
1694 /// `Iterator::Item` contains enough information to figure out K and V.
1695 pub trait Pair {
1696 type First;
1697 type Second;
1698 fn split(self) -> (Self::First, Self::Second);
1699 }
1700
1701 impl<A, B> Pair for (A, B) {
1702 type First = A;
1703 type Second = B;
1704 fn split(self) -> (A, B) {
1705 self
1706 }
1707 }
1708
1709 pub type First<T> = <T as Pair>::First;
1710 pub type Second<T> = <T as Pair>::Second;
1711}
1712