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