1 //! Generic data structure deserialization framework.
2 //!
3 //! The two most important traits in this module are [`Deserialize`] and
4 //! [`Deserializer`].
5 //!
6 //!  - **A type that implements `Deserialize` is a data structure** that can be
7 //!    deserialized from any data format supported by Serde, and conversely
8 //!  - **A type that implements `Deserializer` is a data format** that can
9 //!    deserialize any data structure supported by Serde.
10 //!
11 //! # The Deserialize trait
12 //!
13 //! Serde provides [`Deserialize`] implementations for many Rust primitive and
14 //! standard library types. The complete list is below. All of these can be
15 //! deserialized using Serde out of the box.
16 //!
17 //! Additionally, Serde provides a procedural macro called [`serde_derive`] to
18 //! automatically generate [`Deserialize`] implementations for structs and enums
19 //! in your program. See the [derive section of the manual] for how to use this.
20 //!
21 //! In rare cases it may be necessary to implement [`Deserialize`] manually for
22 //! some type in your program. See the [Implementing `Deserialize`] section of
23 //! the manual for more about this.
24 //!
25 //! Third-party crates may provide [`Deserialize`] implementations for types
26 //! that they expose. For example the [`linked-hash-map`] crate provides a
27 //! [`LinkedHashMap<K, V>`] type that is deserializable by Serde because the
28 //! crate provides an implementation of [`Deserialize`] for it.
29 //!
30 //! # The Deserializer trait
31 //!
32 //! [`Deserializer`] implementations are provided by third-party crates, for
33 //! example [`serde_json`], [`serde_yaml`] and [`bincode`].
34 //!
35 //! A partial list of well-maintained formats is given on the [Serde
36 //! website][data formats].
37 //!
38 //! # Implementations of Deserialize provided by Serde
39 //!
40 //! This is a slightly different set of types than what is supported for
41 //! serialization. Some types can be serialized by Serde but not deserialized.
42 //! One example is `OsStr`.
43 //!
44 //!  - **Primitive types**:
45 //!    - bool
46 //!    - i8, i16, i32, i64, i128, isize
47 //!    - u8, u16, u32, u64, u128, usize
48 //!    - f32, f64
49 //!    - char
50 //!  - **Compound types**:
51 //!    - \[T; 0\] through \[T; 32\]
52 //!    - tuples up to size 16
53 //!  - **Common standard library types**:
54 //!    - String
55 //!    - Option\<T\>
56 //!    - Result\<T, E\>
57 //!    - PhantomData\<T\>
58 //!  - **Wrapper types**:
59 //!    - Box\<T\>
60 //!    - Box\<\[T\]\>
61 //!    - Box\<str\>
62 //!    - Cow\<'a, T\>
63 //!    - Cell\<T\>
64 //!    - RefCell\<T\>
65 //!    - Mutex\<T\>
66 //!    - RwLock\<T\>
67 //!    - Rc\<T\>&emsp;*(if* features = ["rc"] *is enabled)*
68 //!    - Arc\<T\>&emsp;*(if* features = ["rc"] *is enabled)*
69 //!  - **Collection types**:
70 //!    - BTreeMap\<K, V\>
71 //!    - BTreeSet\<T\>
72 //!    - BinaryHeap\<T\>
73 //!    - HashMap\<K, V, H\>
74 //!    - HashSet\<T, H\>
75 //!    - LinkedList\<T\>
76 //!    - VecDeque\<T\>
77 //!    - Vec\<T\>
78 //!  - **Zero-copy types**:
79 //!    - &str
80 //!    - &\[u8\]
81 //!  - **FFI types**:
82 //!    - CString
83 //!    - Box\<CStr\>
84 //!    - OsString
85 //!  - **Miscellaneous standard library types**:
86 //!    - Duration
87 //!    - SystemTime
88 //!    - Path
89 //!    - PathBuf
90 //!    - Range\<T\>
91 //!    - RangeInclusive\<T\>
92 //!    - Bound\<T\>
93 //!    - num::NonZero*
94 //!    - `!` *(unstable)*
95 //!  - **Net types**:
96 //!    - IpAddr
97 //!    - Ipv4Addr
98 //!    - Ipv6Addr
99 //!    - SocketAddr
100 //!    - SocketAddrV4
101 //!    - SocketAddrV6
102 //!
103 //! [Implementing `Deserialize`]: https://serde.rs/impl-deserialize.html
104 //! [`Deserialize`]: ../trait.Deserialize.html
105 //! [`Deserializer`]: ../trait.Deserializer.html
106 //! [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html
107 //! [`bincode`]: https://github.com/servo/bincode
108 //! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map
109 //! [`serde_derive`]: https://crates.io/crates/serde_derive
110 //! [`serde_json`]: https://github.com/serde-rs/json
111 //! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml
112 //! [derive section of the manual]: https://serde.rs/derive.html
113 //! [data formats]: https://serde.rs/#data-formats
114 
115 use lib::*;
116 
117 ////////////////////////////////////////////////////////////////////////////////
118 
119 pub mod value;
120 
121 mod ignored_any;
122 mod impls;
123 mod utf8;
124 
125 pub use self::ignored_any::IgnoredAny;
126 
127 #[cfg(feature = "std")]
128 #[doc(no_inline)]
129 pub use std::error::Error as StdError;
130 #[cfg(not(feature = "std"))]
131 #[doc(no_inline)]
132 pub use std_error::Error as StdError;
133 
134 ////////////////////////////////////////////////////////////////////////////////
135 
136 macro_rules! declare_error_trait {
137     (Error: Sized $(+ $($supertrait:ident)::+)*) => {
138         /// The `Error` trait allows `Deserialize` implementations to create descriptive
139         /// error messages belonging to the `Deserializer` against which they are
140         /// currently running.
141         ///
142         /// Every `Deserializer` declares an `Error` type that encompasses both
143         /// general-purpose deserialization errors as well as errors specific to the
144         /// particular deserialization format. For example the `Error` type of
145         /// `serde_json` can represent errors like an invalid JSON escape sequence or an
146         /// unterminated string literal, in addition to the error cases that are part of
147         /// this trait.
148         ///
149         /// Most deserializers should only need to provide the `Error::custom` method
150         /// and inherit the default behavior for the other methods.
151         ///
152         /// # Example implementation
153         ///
154         /// The [example data format] presented on the website shows an error
155         /// type appropriate for a basic JSON data format.
156         ///
157         /// [example data format]: https://serde.rs/data-format.html
158         pub trait Error: Sized $(+ $($supertrait)::+)* {
159             /// Raised when there is general error when deserializing a type.
160             ///
161             /// The message should not be capitalized and should not end with a period.
162             ///
163             /// ```edition2018
164             /// # use std::str::FromStr;
165             /// #
166             /// # struct IpAddr;
167             /// #
168             /// # impl FromStr for IpAddr {
169             /// #     type Err = String;
170             /// #
171             /// #     fn from_str(_: &str) -> Result<Self, String> {
172             /// #         unimplemented!()
173             /// #     }
174             /// # }
175             /// #
176             /// use serde::de::{self, Deserialize, Deserializer};
177             ///
178             /// impl<'de> Deserialize<'de> for IpAddr {
179             ///     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
180             ///     where
181             ///         D: Deserializer<'de>,
182             ///     {
183             ///         let s = String::deserialize(deserializer)?;
184             ///         s.parse().map_err(de::Error::custom)
185             ///     }
186             /// }
187             /// ```
188             fn custom<T>(msg: T) -> Self
189             where
190                 T: Display;
191 
192             /// Raised when a `Deserialize` receives a type different from what it was
193             /// expecting.
194             ///
195             /// The `unexp` argument provides information about what type was received.
196             /// This is the type that was present in the input file or other source data
197             /// of the Deserializer.
198             ///
199             /// The `exp` argument provides information about what type was being
200             /// expected. This is the type that is written in the program.
201             ///
202             /// For example if we try to deserialize a String out of a JSON file
203             /// containing an integer, the unexpected type is the integer and the
204             /// expected type is the string.
205             #[cold]
206             fn invalid_type(unexp: Unexpected, exp: &Expected) -> Self {
207                 Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp))
208             }
209 
210             /// Raised when a `Deserialize` receives a value of the right type but that
211             /// is wrong for some other reason.
212             ///
213             /// The `unexp` argument provides information about what value was received.
214             /// This is the value that was present in the input file or other source
215             /// data of the Deserializer.
216             ///
217             /// The `exp` argument provides information about what value was being
218             /// expected. This is the type that is written in the program.
219             ///
220             /// For example if we try to deserialize a String out of some binary data
221             /// that is not valid UTF-8, the unexpected value is the bytes and the
222             /// expected value is a string.
223             #[cold]
224             fn invalid_value(unexp: Unexpected, exp: &Expected) -> Self {
225                 Error::custom(format_args!("invalid value: {}, expected {}", unexp, exp))
226             }
227 
228             /// Raised when deserializing a sequence or map and the input data contains
229             /// too many or too few elements.
230             ///
231             /// The `len` argument is the number of elements encountered. The sequence
232             /// or map may have expected more arguments or fewer arguments.
233             ///
234             /// The `exp` argument provides information about what data was being
235             /// expected. For example `exp` might say that a tuple of size 6 was
236             /// expected.
237             #[cold]
238             fn invalid_length(len: usize, exp: &Expected) -> Self {
239                 Error::custom(format_args!("invalid length {}, expected {}", len, exp))
240             }
241 
242             /// Raised when a `Deserialize` enum type received a variant with an
243             /// unrecognized name.
244             #[cold]
245             fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self {
246                 if expected.is_empty() {
247                     Error::custom(format_args!(
248                         "unknown variant `{}`, there are no variants",
249                         variant
250                     ))
251                 } else {
252                     Error::custom(format_args!(
253                         "unknown variant `{}`, expected {}",
254                         variant,
255                         OneOf { names: expected }
256                     ))
257                 }
258             }
259 
260             /// Raised when a `Deserialize` struct type received a field with an
261             /// unrecognized name.
262             #[cold]
263             fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
264                 if expected.is_empty() {
265                     Error::custom(format_args!(
266                         "unknown field `{}`, there are no fields",
267                         field
268                     ))
269                 } else {
270                     Error::custom(format_args!(
271                         "unknown field `{}`, expected {}",
272                         field,
273                         OneOf { names: expected }
274                     ))
275                 }
276             }
277 
278             /// Raised when a `Deserialize` struct type expected to receive a required
279             /// field with a particular name but that field was not present in the
280             /// input.
281             #[cold]
282             fn missing_field(field: &'static str) -> Self {
283                 Error::custom(format_args!("missing field `{}`", field))
284             }
285 
286             /// Raised when a `Deserialize` struct type received more than one of the
287             /// same field.
288             #[cold]
289             fn duplicate_field(field: &'static str) -> Self {
290                 Error::custom(format_args!("duplicate field `{}`", field))
291             }
292         }
293     }
294 }
295 
296 #[cfg(feature = "std")]
297 declare_error_trait!(Error: Sized + StdError);
298 
299 #[cfg(not(feature = "std"))]
300 declare_error_trait!(Error: Sized + Debug + Display);
301 
302 /// `Unexpected` represents an unexpected invocation of any one of the `Visitor`
303 /// trait methods.
304 ///
305 /// This is used as an argument to the `invalid_type`, `invalid_value`, and
306 /// `invalid_length` methods of the `Error` trait to build error messages.
307 ///
308 /// ```edition2018
309 /// # use std::fmt;
310 /// #
311 /// # use serde::de::{self, Unexpected, Visitor};
312 /// #
313 /// # struct Example;
314 /// #
315 /// # impl<'de> Visitor<'de> for Example {
316 /// #     type Value = ();
317 /// #
318 /// #     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
319 /// #         write!(formatter, "definitely not a boolean")
320 /// #     }
321 /// #
322 /// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
323 /// where
324 ///     E: de::Error,
325 /// {
326 ///     Err(de::Error::invalid_type(Unexpected::Bool(v), &self))
327 /// }
328 /// # }
329 /// ```
330 #[derive(Copy, Clone, PartialEq, Debug)]
331 pub enum Unexpected<'a> {
332     /// The input contained a boolean value that was not expected.
333     Bool(bool),
334 
335     /// The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that
336     /// was not expected.
337     Unsigned(u64),
338 
339     /// The input contained a signed integer `i8`, `i16`, `i32` or `i64` that
340     /// was not expected.
341     Signed(i64),
342 
343     /// The input contained a floating point `f32` or `f64` that was not
344     /// expected.
345     Float(f64),
346 
347     /// The input contained a `char` that was not expected.
348     Char(char),
349 
350     /// The input contained a `&str` or `String` that was not expected.
351     Str(&'a str),
352 
353     /// The input contained a `&[u8]` or `Vec<u8>` that was not expected.
354     Bytes(&'a [u8]),
355 
356     /// The input contained a unit `()` that was not expected.
357     Unit,
358 
359     /// The input contained an `Option<T>` that was not expected.
360     Option,
361 
362     /// The input contained a newtype struct that was not expected.
363     NewtypeStruct,
364 
365     /// The input contained a sequence that was not expected.
366     Seq,
367 
368     /// The input contained a map that was not expected.
369     Map,
370 
371     /// The input contained an enum that was not expected.
372     Enum,
373 
374     /// The input contained a unit variant that was not expected.
375     UnitVariant,
376 
377     /// The input contained a newtype variant that was not expected.
378     NewtypeVariant,
379 
380     /// The input contained a tuple variant that was not expected.
381     TupleVariant,
382 
383     /// The input contained a struct variant that was not expected.
384     StructVariant,
385 
386     /// A message stating what uncategorized thing the input contained that was
387     /// not expected.
388     ///
389     /// The message should be a noun or noun phrase, not capitalized and without
390     /// a period. An example message is "unoriginal superhero".
391     Other(&'a str),
392 }
393 
394 impl<'a> fmt::Display for Unexpected<'a> {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result395     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
396         use self::Unexpected::*;
397         match *self {
398             Bool(b) => write!(formatter, "boolean `{}`", b),
399             Unsigned(i) => write!(formatter, "integer `{}`", i),
400             Signed(i) => write!(formatter, "integer `{}`", i),
401             Float(f) => write!(formatter, "floating point `{}`", f),
402             Char(c) => write!(formatter, "character `{}`", c),
403             Str(s) => write!(formatter, "string {:?}", s),
404             Bytes(_) => write!(formatter, "byte array"),
405             Unit => write!(formatter, "unit value"),
406             Option => write!(formatter, "Option value"),
407             NewtypeStruct => write!(formatter, "newtype struct"),
408             Seq => write!(formatter, "sequence"),
409             Map => write!(formatter, "map"),
410             Enum => write!(formatter, "enum"),
411             UnitVariant => write!(formatter, "unit variant"),
412             NewtypeVariant => write!(formatter, "newtype variant"),
413             TupleVariant => write!(formatter, "tuple variant"),
414             StructVariant => write!(formatter, "struct variant"),
415             Other(other) => formatter.write_str(other),
416         }
417     }
418 }
419 
420 /// `Expected` represents an explanation of what data a `Visitor` was expecting
421 /// to receive.
422 ///
423 /// This is used as an argument to the `invalid_type`, `invalid_value`, and
424 /// `invalid_length` methods of the `Error` trait to build error messages. The
425 /// message should be a noun or noun phrase that completes the sentence "This
426 /// Visitor expects to receive ...", for example the message could be "an
427 /// integer between 0 and 64". The message should not be capitalized and should
428 /// not end with a period.
429 ///
430 /// Within the context of a `Visitor` implementation, the `Visitor` itself
431 /// (`&self`) is an implementation of this trait.
432 ///
433 /// ```edition2018
434 /// # use std::fmt;
435 /// #
436 /// # use serde::de::{self, Unexpected, Visitor};
437 /// #
438 /// # struct Example;
439 /// #
440 /// # impl<'de> Visitor<'de> for Example {
441 /// #     type Value = ();
442 /// #
443 /// #     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
444 /// #         write!(formatter, "definitely not a boolean")
445 /// #     }
446 /// #
447 /// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
448 /// where
449 ///     E: de::Error,
450 /// {
451 ///     Err(de::Error::invalid_type(Unexpected::Bool(v), &self))
452 /// }
453 /// # }
454 /// ```
455 ///
456 /// Outside of a `Visitor`, `&"..."` can be used.
457 ///
458 /// ```edition2018
459 /// # use serde::de::{self, Unexpected};
460 /// #
461 /// # fn example<E>() -> Result<(), E>
462 /// # where
463 /// #     E: de::Error,
464 /// # {
465 /// #     let v = true;
466 /// return Err(de::Error::invalid_type(Unexpected::Bool(v), &"a negative integer"));
467 /// # }
468 /// ```
469 pub trait Expected {
470     /// Format an explanation of what data was being expected. Same signature as
471     /// the `Display` and `Debug` traits.
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result472     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result;
473 }
474 
475 impl<'de, T> Expected for T
476 where
477     T: Visitor<'de>,
478 {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result479     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
480         self.expecting(formatter)
481     }
482 }
483 
484 impl<'a> Expected for &'a str {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result485     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
486         formatter.write_str(self)
487     }
488 }
489 
490 impl<'a> Display for Expected + 'a {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result491     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
492         Expected::fmt(self, formatter)
493     }
494 }
495 
496 ////////////////////////////////////////////////////////////////////////////////
497 
498 /// A **data structure** that can be deserialized from any data format supported
499 /// by Serde.
500 ///
501 /// Serde provides `Deserialize` implementations for many Rust primitive and
502 /// standard library types. The complete list is [here][de]. All of these can
503 /// be deserialized using Serde out of the box.
504 ///
505 /// Additionally, Serde provides a procedural macro called `serde_derive` to
506 /// automatically generate `Deserialize` implementations for structs and enums
507 /// in your program. See the [derive section of the manual][derive] for how to
508 /// use this.
509 ///
510 /// In rare cases it may be necessary to implement `Deserialize` manually for
511 /// some type in your program. See the [Implementing
512 /// `Deserialize`][impl-deserialize] section of the manual for more about this.
513 ///
514 /// Third-party crates may provide `Deserialize` implementations for types that
515 /// they expose. For example the `linked-hash-map` crate provides a
516 /// `LinkedHashMap<K, V>` type that is deserializable by Serde because the crate
517 /// provides an implementation of `Deserialize` for it.
518 ///
519 /// [de]: https://docs.serde.rs/serde/de/index.html
520 /// [derive]: https://serde.rs/derive.html
521 /// [impl-deserialize]: https://serde.rs/impl-deserialize.html
522 ///
523 /// # Lifetime
524 ///
525 /// The `'de` lifetime of this trait is the lifetime of data that may be
526 /// borrowed by `Self` when deserialized. See the page [Understanding
527 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
528 ///
529 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
530 pub trait Deserialize<'de>: Sized {
531     /// Deserialize this value from the given Serde deserializer.
532     ///
533     /// See the [Implementing `Deserialize`][impl-deserialize] section of the
534     /// manual for more information about how to implement this method.
535     ///
536     /// [impl-deserialize]: https://serde.rs/impl-deserialize.html
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>537     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
538     where
539         D: Deserializer<'de>;
540 
541     /// Deserializes a value into `self` from the given Deserializer.
542     ///
543     /// The purpose of this method is to allow the deserializer to reuse
544     /// resources and avoid copies. As such, if this method returns an error,
545     /// `self` will be in an indeterminate state where some parts of the struct
546     /// have been overwritten. Although whatever state that is will be
547     /// memory-safe.
548     ///
549     /// This is generally useful when repeatedly deserializing values that
550     /// are processed one at a time, where the value of `self` doesn't matter
551     /// when the next deserialization occurs.
552     ///
553     /// If you manually implement this, your recursive deserializations should
554     /// use `deserialize_in_place`.
555     ///
556     /// This method is stable and an official public API, but hidden from the
557     /// documentation because it is almost never what newbies are looking for.
558     /// Showing it in rustdoc would cause it to be featured more prominently
559     /// than it deserves.
560     #[doc(hidden)]
deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> where D: Deserializer<'de>,561     fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
562     where
563         D: Deserializer<'de>,
564     {
565         // Default implementation just delegates to `deserialize` impl.
566         *place = Deserialize::deserialize(deserializer)?;
567         Ok(())
568     }
569 }
570 
571 /// A data structure that can be deserialized without borrowing any data from
572 /// the deserializer.
573 ///
574 /// This is primarily useful for trait bounds on functions. For example a
575 /// `from_str` function may be able to deserialize a data structure that borrows
576 /// from the input string, but a `from_reader` function may only deserialize
577 /// owned data.
578 ///
579 /// ```edition2018
580 /// # use serde::de::{Deserialize, DeserializeOwned};
581 /// # use std::io::{Read, Result};
582 /// #
583 /// # trait Ignore {
584 /// fn from_str<'a, T>(s: &'a str) -> Result<T>
585 /// where
586 ///     T: Deserialize<'a>;
587 ///
588 /// fn from_reader<R, T>(rdr: R) -> Result<T>
589 /// where
590 ///     R: Read,
591 ///     T: DeserializeOwned;
592 /// # }
593 /// ```
594 ///
595 /// # Lifetime
596 ///
597 /// The relationship between `Deserialize` and `DeserializeOwned` in trait
598 /// bounds is explained in more detail on the page [Understanding deserializer
599 /// lifetimes].
600 ///
601 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
602 pub trait DeserializeOwned: for<'de> Deserialize<'de> {}
603 impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
604 
605 /// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you
606 /// ever find yourself looking for a way to pass data into a `Deserialize` impl,
607 /// this trait is the way to do it.
608 ///
609 /// As one example of stateful deserialization consider deserializing a JSON
610 /// array into an existing buffer. Using the `Deserialize` trait we could
611 /// deserialize a JSON array into a `Vec<T>` but it would be a freshly allocated
612 /// `Vec<T>`; there is no way for `Deserialize` to reuse a previously allocated
613 /// buffer. Using `DeserializeSeed` instead makes this possible as in the
614 /// example code below.
615 ///
616 /// The canonical API for stateless deserialization looks like this:
617 ///
618 /// ```edition2018
619 /// # use serde::Deserialize;
620 /// #
621 /// # enum Error {}
622 /// #
623 /// fn func<'de, T: Deserialize<'de>>() -> Result<T, Error>
624 /// # {
625 /// #     unimplemented!()
626 /// # }
627 /// ```
628 ///
629 /// Adjusting an API like this to support stateful deserialization is a matter
630 /// of accepting a seed as input:
631 ///
632 /// ```edition2018
633 /// # use serde::de::DeserializeSeed;
634 /// #
635 /// # enum Error {}
636 /// #
637 /// fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result<T::Value, Error>
638 /// # {
639 /// #     let _ = seed;
640 /// #     unimplemented!()
641 /// # }
642 /// ```
643 ///
644 /// In practice the majority of deserialization is stateless. An API expecting a
645 /// seed can be appeased by passing `std::marker::PhantomData` as a seed in the
646 /// case of stateless deserialization.
647 ///
648 /// # Lifetime
649 ///
650 /// The `'de` lifetime of this trait is the lifetime of data that may be
651 /// borrowed by `Self::Value` when deserialized. See the page [Understanding
652 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
653 ///
654 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
655 ///
656 /// # Example
657 ///
658 /// Suppose we have JSON that looks like `[[1, 2], [3, 4, 5], [6]]` and we need
659 /// to deserialize it into a flat representation like `vec![1, 2, 3, 4, 5, 6]`.
660 /// Allocating a brand new `Vec<T>` for each subarray would be slow. Instead we
661 /// would like to allocate a single `Vec<T>` and then deserialize each subarray
662 /// into it. This requires stateful deserialization using the `DeserializeSeed`
663 /// trait.
664 ///
665 /// ```edition2018
666 /// use std::fmt;
667 /// use std::marker::PhantomData;
668 ///
669 /// use serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor};
670 ///
671 /// // A DeserializeSeed implementation that uses stateful deserialization to
672 /// // append array elements onto the end of an existing vector. The preexisting
673 /// // state ("seed") in this case is the Vec<T>. The `deserialize` method of
674 /// // `ExtendVec` will be traversing the inner arrays of the JSON input and
675 /// // appending each integer into the existing Vec.
676 /// struct ExtendVec<'a, T: 'a>(&'a mut Vec<T>);
677 ///
678 /// impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T>
679 /// where
680 ///     T: Deserialize<'de>,
681 /// {
682 ///     // The return type of the `deserialize` method. This implementation
683 ///     // appends onto an existing vector but does not create any new data
684 ///     // structure, so the return type is ().
685 ///     type Value = ();
686 ///
687 ///     fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
688 ///     where
689 ///         D: Deserializer<'de>,
690 ///     {
691 ///         // Visitor implementation that will walk an inner array of the JSON
692 ///         // input.
693 ///         struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec<T>);
694 ///
695 ///         impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T>
696 ///         where
697 ///             T: Deserialize<'de>,
698 ///         {
699 ///             type Value = ();
700 ///
701 ///             fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
702 ///                 write!(formatter, "an array of integers")
703 ///             }
704 ///
705 ///             fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error>
706 ///             where
707 ///                 A: SeqAccess<'de>,
708 ///             {
709 ///                 // Visit each element in the inner array and push it onto
710 ///                 // the existing vector.
711 ///                 while let Some(elem) = seq.next_element()? {
712 ///                     self.0.push(elem);
713 ///                 }
714 ///                 Ok(())
715 ///             }
716 ///         }
717 ///
718 ///         deserializer.deserialize_seq(ExtendVecVisitor(self.0))
719 ///     }
720 /// }
721 ///
722 /// // Visitor implementation that will walk the outer array of the JSON input.
723 /// struct FlattenedVecVisitor<T>(PhantomData<T>);
724 ///
725 /// impl<'de, T> Visitor<'de> for FlattenedVecVisitor<T>
726 /// where
727 ///     T: Deserialize<'de>,
728 /// {
729 ///     // This Visitor constructs a single Vec<T> to hold the flattened
730 ///     // contents of the inner arrays.
731 ///     type Value = Vec<T>;
732 ///
733 ///     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
734 ///         write!(formatter, "an array of arrays")
735 ///     }
736 ///
737 ///     fn visit_seq<A>(self, mut seq: A) -> Result<Vec<T>, A::Error>
738 ///     where
739 ///         A: SeqAccess<'de>,
740 ///     {
741 ///         // Create a single Vec to hold the flattened contents.
742 ///         let mut vec = Vec::new();
743 ///
744 ///         // Each iteration through this loop is one inner array.
745 ///         while let Some(()) = seq.next_element_seed(ExtendVec(&mut vec))? {
746 ///             // Nothing to do; inner array has been appended into `vec`.
747 ///         }
748 ///
749 ///         // Return the finished vec.
750 ///         Ok(vec)
751 ///     }
752 /// }
753 ///
754 /// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error>
755 /// # where
756 /// #     D: Deserializer<'de>,
757 /// # {
758 /// let visitor = FlattenedVecVisitor(PhantomData);
759 /// let flattened: Vec<u64> = deserializer.deserialize_seq(visitor)?;
760 /// #     Ok(())
761 /// # }
762 /// ```
763 pub trait DeserializeSeed<'de>: Sized {
764     /// The type produced by using this seed.
765     type Value;
766 
767     /// Equivalent to the more common `Deserialize::deserialize` method, except
768     /// with some initial piece of data (the seed) passed in.
deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>769     fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
770     where
771         D: Deserializer<'de>;
772 }
773 
774 impl<'de, T> DeserializeSeed<'de> for PhantomData<T>
775 where
776     T: Deserialize<'de>,
777 {
778     type Value = T;
779 
780     #[inline]
deserialize<D>(self, deserializer: D) -> Result<T, D::Error> where D: Deserializer<'de>,781     fn deserialize<D>(self, deserializer: D) -> Result<T, D::Error>
782     where
783         D: Deserializer<'de>,
784     {
785         T::deserialize(deserializer)
786     }
787 }
788 
789 ////////////////////////////////////////////////////////////////////////////////
790 
791 /// A **data format** that can deserialize any data structure supported by
792 /// Serde.
793 ///
794 /// The role of this trait is to define the deserialization half of the [Serde
795 /// data model], which is a way to categorize every Rust data type into one of
796 /// 29 possible types. Each method of the `Deserializer` trait corresponds to one
797 /// of the types of the data model.
798 ///
799 /// Implementations of `Deserialize` map themselves into this data model by
800 /// passing to the `Deserializer` a `Visitor` implementation that can receive
801 /// these various types.
802 ///
803 /// The types that make up the Serde data model are:
804 ///
805 ///  - **14 primitive types**
806 ///    - bool
807 ///    - i8, i16, i32, i64, i128
808 ///    - u8, u16, u32, u64, u128
809 ///    - f32, f64
810 ///    - char
811 ///  - **string**
812 ///    - UTF-8 bytes with a length and no null terminator.
813 ///    - When serializing, all strings are handled equally. When deserializing,
814 ///      there are three flavors of strings: transient, owned, and borrowed.
815 ///  - **byte array** - \[u8\]
816 ///    - Similar to strings, during deserialization byte arrays can be
817 ///      transient, owned, or borrowed.
818 ///  - **option**
819 ///    - Either none or some value.
820 ///  - **unit**
821 ///    - The type of `()` in Rust. It represents an anonymous value containing
822 ///      no data.
823 ///  - **unit_struct**
824 ///    - For example `struct Unit` or `PhantomData<T>`. It represents a named
825 ///      value containing no data.
826 ///  - **unit_variant**
827 ///    - For example the `E::A` and `E::B` in `enum E { A, B }`.
828 ///  - **newtype_struct**
829 ///    - For example `struct Millimeters(u8)`.
830 ///  - **newtype_variant**
831 ///    - For example the `E::N` in `enum E { N(u8) }`.
832 ///  - **seq**
833 ///    - A variably sized heterogeneous sequence of values, for example `Vec<T>`
834 ///      or `HashSet<T>`. When serializing, the length may or may not be known
835 ///      before iterating through all the data. When deserializing, the length
836 ///      is determined by looking at the serialized data.
837 ///  - **tuple**
838 ///    - A statically sized heterogeneous sequence of values for which the
839 ///      length will be known at deserialization time without looking at the
840 ///      serialized data, for example `(u8,)` or `(String, u64, Vec<T>)` or
841 ///      `[u64; 10]`.
842 ///  - **tuple_struct**
843 ///    - A named tuple, for example `struct Rgb(u8, u8, u8)`.
844 ///  - **tuple_variant**
845 ///    - For example the `E::T` in `enum E { T(u8, u8) }`.
846 ///  - **map**
847 ///    - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.
848 ///  - **struct**
849 ///    - A heterogeneous key-value pairing in which the keys are strings and
850 ///      will be known at deserialization time without looking at the serialized
851 ///      data, for example `struct S { r: u8, g: u8, b: u8 }`.
852 ///  - **struct_variant**
853 ///    - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`.
854 ///
855 /// The `Deserializer` trait supports two entry point styles which enables
856 /// different kinds of deserialization.
857 ///
858 /// 1. The `deserialize` method. Self-describing data formats like JSON are able
859 ///    to look at the serialized data and tell what it represents. For example
860 ///    the JSON deserializer may see an opening curly brace (`{`) and know that
861 ///    it is seeing a map. If the data format supports
862 ///    `Deserializer::deserialize_any`, it will drive the Visitor using whatever
863 ///    type it sees in the input. JSON uses this approach when deserializing
864 ///    `serde_json::Value` which is an enum that can represent any JSON
865 ///    document. Without knowing what is in a JSON document, we can deserialize
866 ///    it to `serde_json::Value` by going through
867 ///    `Deserializer::deserialize_any`.
868 ///
869 /// 2. The various `deserialize_*` methods. Non-self-describing formats like
870 ///    Bincode need to be told what is in the input in order to deserialize it.
871 ///    The `deserialize_*` methods are hints to the deserializer for how to
872 ///    interpret the next piece of input. Non-self-describing formats are not
873 ///    able to deserialize something like `serde_json::Value` which relies on
874 ///    `Deserializer::deserialize_any`.
875 ///
876 /// When implementing `Deserialize`, you should avoid relying on
877 /// `Deserializer::deserialize_any` unless you need to be told by the
878 /// Deserializer what type is in the input. Know that relying on
879 /// `Deserializer::deserialize_any` means your data type will be able to
880 /// deserialize from self-describing formats only, ruling out Bincode and many
881 /// others.
882 ///
883 /// [Serde data model]: https://serde.rs/data-model.html
884 ///
885 /// # Lifetime
886 ///
887 /// The `'de` lifetime of this trait is the lifetime of data that may be
888 /// borrowed from the input when deserializing. See the page [Understanding
889 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
890 ///
891 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
892 ///
893 /// # Example implementation
894 ///
895 /// The [example data format] presented on the website contains example code for
896 /// a basic JSON `Deserializer`.
897 ///
898 /// [example data format]: https://serde.rs/data-format.html
899 pub trait Deserializer<'de>: Sized {
900     /// The error type that can be returned if some error occurs during
901     /// deserialization.
902     type Error: Error;
903 
904     /// Require the `Deserializer` to figure out how to drive the visitor based
905     /// on what data type is in the input.
906     ///
907     /// When implementing `Deserialize`, you should avoid relying on
908     /// `Deserializer::deserialize_any` unless you need to be told by the
909     /// Deserializer what type is in the input. Know that relying on
910     /// `Deserializer::deserialize_any` means your data type will be able to
911     /// deserialize from self-describing formats only, ruling out Bincode and
912     /// many others.
deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>913     fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
914     where
915         V: Visitor<'de>;
916 
917     /// Hint that the `Deserialize` type is expecting a `bool` value.
deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>918     fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
919     where
920         V: Visitor<'de>;
921 
922     /// Hint that the `Deserialize` type is expecting an `i8` value.
deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>923     fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
924     where
925         V: Visitor<'de>;
926 
927     /// Hint that the `Deserialize` type is expecting an `i16` value.
deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>928     fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
929     where
930         V: Visitor<'de>;
931 
932     /// Hint that the `Deserialize` type is expecting an `i32` value.
deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>933     fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
934     where
935         V: Visitor<'de>;
936 
937     /// Hint that the `Deserialize` type is expecting an `i64` value.
deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>938     fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
939     where
940         V: Visitor<'de>;
941 
942     serde_if_integer128! {
943         /// Hint that the `Deserialize` type is expecting an `i128` value.
944         ///
945         /// This method is available only on Rust compiler versions >=1.26. The
946         /// default behavior unconditionally returns an error.
947         fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value, Self::Error>
948         where
949             V: Visitor<'de>
950         {
951             let _ = visitor;
952             Err(Error::custom("i128 is not supported"))
953         }
954     }
955 
956     /// Hint that the `Deserialize` type is expecting a `u8` value.
deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>957     fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
958     where
959         V: Visitor<'de>;
960 
961     /// Hint that the `Deserialize` type is expecting a `u16` value.
deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>962     fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
963     where
964         V: Visitor<'de>;
965 
966     /// Hint that the `Deserialize` type is expecting a `u32` value.
deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>967     fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
968     where
969         V: Visitor<'de>;
970 
971     /// Hint that the `Deserialize` type is expecting a `u64` value.
deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>972     fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
973     where
974         V: Visitor<'de>;
975 
976     serde_if_integer128! {
977         /// Hint that the `Deserialize` type is expecting an `u128` value.
978         ///
979         /// This method is available only on Rust compiler versions >=1.26. The
980         /// default behavior unconditionally returns an error.
981         fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value, Self::Error>
982         where
983             V: Visitor<'de>
984         {
985             let _ = visitor;
986             Err(Error::custom("u128 is not supported"))
987         }
988     }
989 
990     /// Hint that the `Deserialize` type is expecting a `f32` value.
deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>991     fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
992     where
993         V: Visitor<'de>;
994 
995     /// Hint that the `Deserialize` type is expecting a `f64` value.
deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>996     fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
997     where
998         V: Visitor<'de>;
999 
1000     /// Hint that the `Deserialize` type is expecting a `char` value.
deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>1001     fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1002     where
1003         V: Visitor<'de>;
1004 
1005     /// Hint that the `Deserialize` type is expecting a string value and does
1006     /// not benefit from taking ownership of buffered data owned by the
1007     /// `Deserializer`.
1008     ///
1009     /// If the `Visitor` would benefit from taking ownership of `String` data,
1010     /// indicate this to the `Deserializer` by using `deserialize_string`
1011     /// instead.
deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>1012     fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1013     where
1014         V: Visitor<'de>;
1015 
1016     /// Hint that the `Deserialize` type is expecting a string value and would
1017     /// benefit from taking ownership of buffered data owned by the
1018     /// `Deserializer`.
1019     ///
1020     /// If the `Visitor` would not benefit from taking ownership of `String`
1021     /// data, indicate that to the `Deserializer` by using `deserialize_str`
1022     /// instead.
deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>1023     fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1024     where
1025         V: Visitor<'de>;
1026 
1027     /// Hint that the `Deserialize` type is expecting a byte array and does not
1028     /// benefit from taking ownership of buffered data owned by the
1029     /// `Deserializer`.
1030     ///
1031     /// If the `Visitor` would benefit from taking ownership of `Vec<u8>` data,
1032     /// indicate this to the `Deserializer` by using `deserialize_byte_buf`
1033     /// instead.
deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>1034     fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1035     where
1036         V: Visitor<'de>;
1037 
1038     /// Hint that the `Deserialize` type is expecting a byte array and would
1039     /// benefit from taking ownership of buffered data owned by the
1040     /// `Deserializer`.
1041     ///
1042     /// If the `Visitor` would not benefit from taking ownership of `Vec<u8>`
1043     /// data, indicate that to the `Deserializer` by using `deserialize_bytes`
1044     /// instead.
deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>1045     fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1046     where
1047         V: Visitor<'de>;
1048 
1049     /// Hint that the `Deserialize` type is expecting an optional value.
1050     ///
1051     /// This allows deserializers that encode an optional value as a nullable
1052     /// value to convert the null value into `None` and a regular value into
1053     /// `Some(value)`.
deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>1054     fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1055     where
1056         V: Visitor<'de>;
1057 
1058     /// Hint that the `Deserialize` type is expecting a unit value.
deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>1059     fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1060     where
1061         V: Visitor<'de>;
1062 
1063     /// Hint that the `Deserialize` type is expecting a unit struct with a
1064     /// particular name.
deserialize_unit_struct<V>( self, name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>1065     fn deserialize_unit_struct<V>(
1066         self,
1067         name: &'static str,
1068         visitor: V,
1069     ) -> Result<V::Value, Self::Error>
1070     where
1071         V: Visitor<'de>;
1072 
1073     /// Hint that the `Deserialize` type is expecting a newtype struct with a
1074     /// particular name.
deserialize_newtype_struct<V>( self, name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>1075     fn deserialize_newtype_struct<V>(
1076         self,
1077         name: &'static str,
1078         visitor: V,
1079     ) -> Result<V::Value, Self::Error>
1080     where
1081         V: Visitor<'de>;
1082 
1083     /// Hint that the `Deserialize` type is expecting a sequence of values.
deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>1084     fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1085     where
1086         V: Visitor<'de>;
1087 
1088     /// Hint that the `Deserialize` type is expecting a sequence of values and
1089     /// knows how many values there are without looking at the serialized data.
deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>1090     fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
1091     where
1092         V: Visitor<'de>;
1093 
1094     /// Hint that the `Deserialize` type is expecting a tuple struct with a
1095     /// particular name and number of fields.
deserialize_tuple_struct<V>( self, name: &'static str, len: usize, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>1096     fn deserialize_tuple_struct<V>(
1097         self,
1098         name: &'static str,
1099         len: usize,
1100         visitor: V,
1101     ) -> Result<V::Value, Self::Error>
1102     where
1103         V: Visitor<'de>;
1104 
1105     /// Hint that the `Deserialize` type is expecting a map of key-value pairs.
deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>1106     fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1107     where
1108         V: Visitor<'de>;
1109 
1110     /// Hint that the `Deserialize` type is expecting a struct with a particular
1111     /// name and fields.
deserialize_struct<V>( self, name: &'static str, fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>1112     fn deserialize_struct<V>(
1113         self,
1114         name: &'static str,
1115         fields: &'static [&'static str],
1116         visitor: V,
1117     ) -> Result<V::Value, Self::Error>
1118     where
1119         V: Visitor<'de>;
1120 
1121     /// Hint that the `Deserialize` type is expecting an enum value with a
1122     /// particular name and possible variants.
deserialize_enum<V>( self, name: &'static str, variants: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>1123     fn deserialize_enum<V>(
1124         self,
1125         name: &'static str,
1126         variants: &'static [&'static str],
1127         visitor: V,
1128     ) -> Result<V::Value, Self::Error>
1129     where
1130         V: Visitor<'de>;
1131 
1132     /// Hint that the `Deserialize` type is expecting the name of a struct
1133     /// field or the discriminant of an enum variant.
deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>1134     fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1135     where
1136         V: Visitor<'de>;
1137 
1138     /// Hint that the `Deserialize` type needs to deserialize a value whose type
1139     /// doesn't matter because it is ignored.
1140     ///
1141     /// Deserializers for non-self-describing formats may not support this mode.
deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>1142     fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1143     where
1144         V: Visitor<'de>;
1145 
1146     /// Determine whether `Deserialize` implementations should expect to
1147     /// deserialize their human-readable form.
1148     ///
1149     /// Some types have a human-readable form that may be somewhat expensive to
1150     /// construct, as well as a binary form that is compact and efficient.
1151     /// Generally text-based formats like JSON and YAML will prefer to use the
1152     /// human-readable one and binary formats like Bincode will prefer the
1153     /// compact one.
1154     ///
1155     /// ```edition2018
1156     /// # use std::ops::Add;
1157     /// # use std::str::FromStr;
1158     /// #
1159     /// # struct Timestamp;
1160     /// #
1161     /// # impl Timestamp {
1162     /// #     const EPOCH: Timestamp = Timestamp;
1163     /// # }
1164     /// #
1165     /// # impl FromStr for Timestamp {
1166     /// #     type Err = String;
1167     /// #     fn from_str(_: &str) -> Result<Self, Self::Err> {
1168     /// #         unimplemented!()
1169     /// #     }
1170     /// # }
1171     /// #
1172     /// # struct Duration;
1173     /// #
1174     /// # impl Duration {
1175     /// #     fn seconds(_: u64) -> Self { unimplemented!() }
1176     /// # }
1177     /// #
1178     /// # impl Add<Duration> for Timestamp {
1179     /// #     type Output = Timestamp;
1180     /// #     fn add(self, _: Duration) -> Self::Output {
1181     /// #         unimplemented!()
1182     /// #     }
1183     /// # }
1184     /// #
1185     /// use serde::de::{self, Deserialize, Deserializer};
1186     ///
1187     /// impl<'de> Deserialize<'de> for Timestamp {
1188     ///     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1189     ///     where
1190     ///         D: Deserializer<'de>,
1191     ///     {
1192     ///         if deserializer.is_human_readable() {
1193     ///             // Deserialize from a human-readable string like "2015-05-15T17:01:00Z".
1194     ///             let s = String::deserialize(deserializer)?;
1195     ///             Timestamp::from_str(&s).map_err(de::Error::custom)
1196     ///         } else {
1197     ///             // Deserialize from a compact binary representation, seconds since
1198     ///             // the Unix epoch.
1199     ///             let n = u64::deserialize(deserializer)?;
1200     ///             Ok(Timestamp::EPOCH + Duration::seconds(n))
1201     ///         }
1202     ///     }
1203     /// }
1204     /// ```
1205     ///
1206     /// The default implementation of this method returns `true`. Data formats
1207     /// may override this to `false` to request a compact form for types that
1208     /// support one. Note that modifying this method to change a format from
1209     /// human-readable to compact or vice versa should be regarded as a breaking
1210     /// change, as a value serialized in human-readable mode is not required to
1211     /// deserialize from the same data in compact mode.
1212     #[inline]
is_human_readable(&self) -> bool1213     fn is_human_readable(&self) -> bool {
1214         true
1215     }
1216 }
1217 
1218 ////////////////////////////////////////////////////////////////////////////////
1219 
1220 /// This trait represents a visitor that walks through a deserializer.
1221 ///
1222 /// # Lifetime
1223 ///
1224 /// The `'de` lifetime of this trait is the requirement for lifetime of data
1225 /// that may be borrowed by `Self::Value`. See the page [Understanding
1226 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1227 ///
1228 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1229 ///
1230 /// # Example
1231 ///
1232 /// ```edition2018
1233 /// # use std::fmt;
1234 /// #
1235 /// # use serde::de::{self, Unexpected, Visitor};
1236 /// #
1237 /// /// A visitor that deserializes a long string - a string containing at least
1238 /// /// some minimum number of bytes.
1239 /// struct LongString {
1240 ///     min: usize,
1241 /// }
1242 ///
1243 /// impl<'de> Visitor<'de> for LongString {
1244 ///     type Value = String;
1245 ///
1246 ///     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1247 ///         write!(formatter, "a string containing at least {} bytes", self.min)
1248 ///     }
1249 ///
1250 ///     fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
1251 ///     where
1252 ///         E: de::Error,
1253 ///     {
1254 ///         if s.len() >= self.min {
1255 ///             Ok(s.to_owned())
1256 ///         } else {
1257 ///             Err(de::Error::invalid_value(Unexpected::Str(s), &self))
1258 ///         }
1259 ///     }
1260 /// }
1261 /// ```
1262 pub trait Visitor<'de>: Sized {
1263     /// The value produced by this visitor.
1264     type Value;
1265 
1266     /// Format a message stating what data this Visitor expects to receive.
1267     ///
1268     /// This is used in error messages. The message should complete the sentence
1269     /// "This Visitor expects to receive ...", for example the message could be
1270     /// "an integer between 0 and 64". The message should not be capitalized and
1271     /// should not end with a period.
1272     ///
1273     /// ```edition2018
1274     /// # use std::fmt;
1275     /// #
1276     /// # struct S {
1277     /// #     max: usize,
1278     /// # }
1279     /// #
1280     /// # impl<'de> serde::de::Visitor<'de> for S {
1281     /// #     type Value = ();
1282     /// #
1283     /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1284     ///     write!(formatter, "an integer between 0 and {}", self.max)
1285     /// }
1286     /// # }
1287     /// ```
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result1288     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result;
1289 
1290     /// The input contains a boolean.
1291     ///
1292     /// The default implementation fails with a type error.
visit_bool<E>(self, v: bool) -> Result<Self::Value, E> where E: Error,1293     fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1294     where
1295         E: Error,
1296     {
1297         Err(Error::invalid_type(Unexpected::Bool(v), &self))
1298     }
1299 
1300     /// The input contains an `i8`.
1301     ///
1302     /// The default implementation forwards to [`visit_i64`].
1303     ///
1304     /// [`visit_i64`]: #method.visit_i64
visit_i8<E>(self, v: i8) -> Result<Self::Value, E> where E: Error,1305     fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
1306     where
1307         E: Error,
1308     {
1309         self.visit_i64(v as i64)
1310     }
1311 
1312     /// The input contains an `i16`.
1313     ///
1314     /// The default implementation forwards to [`visit_i64`].
1315     ///
1316     /// [`visit_i64`]: #method.visit_i64
visit_i16<E>(self, v: i16) -> Result<Self::Value, E> where E: Error,1317     fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
1318     where
1319         E: Error,
1320     {
1321         self.visit_i64(v as i64)
1322     }
1323 
1324     /// The input contains an `i32`.
1325     ///
1326     /// The default implementation forwards to [`visit_i64`].
1327     ///
1328     /// [`visit_i64`]: #method.visit_i64
visit_i32<E>(self, v: i32) -> Result<Self::Value, E> where E: Error,1329     fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
1330     where
1331         E: Error,
1332     {
1333         self.visit_i64(v as i64)
1334     }
1335 
1336     /// The input contains an `i64`.
1337     ///
1338     /// The default implementation fails with a type error.
visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: Error,1339     fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
1340     where
1341         E: Error,
1342     {
1343         Err(Error::invalid_type(Unexpected::Signed(v), &self))
1344     }
1345 
1346     serde_if_integer128! {
1347         /// The input contains a `i128`.
1348         ///
1349         /// This method is available only on Rust compiler versions >=1.26. The
1350         /// default implementation fails with a type error.
1351         fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
1352         where
1353             E: Error,
1354         {
1355             let _ = v;
1356             Err(Error::invalid_type(Unexpected::Other("i128"), &self))
1357         }
1358     }
1359 
1360     /// The input contains a `u8`.
1361     ///
1362     /// The default implementation forwards to [`visit_u64`].
1363     ///
1364     /// [`visit_u64`]: #method.visit_u64
visit_u8<E>(self, v: u8) -> Result<Self::Value, E> where E: Error,1365     fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
1366     where
1367         E: Error,
1368     {
1369         self.visit_u64(v as u64)
1370     }
1371 
1372     /// The input contains a `u16`.
1373     ///
1374     /// The default implementation forwards to [`visit_u64`].
1375     ///
1376     /// [`visit_u64`]: #method.visit_u64
visit_u16<E>(self, v: u16) -> Result<Self::Value, E> where E: Error,1377     fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
1378     where
1379         E: Error,
1380     {
1381         self.visit_u64(v as u64)
1382     }
1383 
1384     /// The input contains a `u32`.
1385     ///
1386     /// The default implementation forwards to [`visit_u64`].
1387     ///
1388     /// [`visit_u64`]: #method.visit_u64
visit_u32<E>(self, v: u32) -> Result<Self::Value, E> where E: Error,1389     fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
1390     where
1391         E: Error,
1392     {
1393         self.visit_u64(v as u64)
1394     }
1395 
1396     /// The input contains a `u64`.
1397     ///
1398     /// The default implementation fails with a type error.
visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: Error,1399     fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
1400     where
1401         E: Error,
1402     {
1403         Err(Error::invalid_type(Unexpected::Unsigned(v), &self))
1404     }
1405 
1406     serde_if_integer128! {
1407         /// The input contains a `u128`.
1408         ///
1409         /// This method is available only on Rust compiler versions >=1.26. The
1410         /// default implementation fails with a type error.
1411         fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
1412         where
1413             E: Error,
1414         {
1415             let _ = v;
1416             Err(Error::invalid_type(Unexpected::Other("u128"), &self))
1417         }
1418     }
1419 
1420     /// The input contains an `f32`.
1421     ///
1422     /// The default implementation forwards to [`visit_f64`].
1423     ///
1424     /// [`visit_f64`]: #method.visit_f64
visit_f32<E>(self, v: f32) -> Result<Self::Value, E> where E: Error,1425     fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
1426     where
1427         E: Error,
1428     {
1429         self.visit_f64(v as f64)
1430     }
1431 
1432     /// The input contains an `f64`.
1433     ///
1434     /// The default implementation fails with a type error.
visit_f64<E>(self, v: f64) -> Result<Self::Value, E> where E: Error,1435     fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
1436     where
1437         E: Error,
1438     {
1439         Err(Error::invalid_type(Unexpected::Float(v), &self))
1440     }
1441 
1442     /// The input contains a `char`.
1443     ///
1444     /// The default implementation forwards to [`visit_str`] as a one-character
1445     /// string.
1446     ///
1447     /// [`visit_str`]: #method.visit_str
1448     #[inline]
visit_char<E>(self, v: char) -> Result<Self::Value, E> where E: Error,1449     fn visit_char<E>(self, v: char) -> Result<Self::Value, E>
1450     where
1451         E: Error,
1452     {
1453         self.visit_str(utf8::encode(v).as_str())
1454     }
1455 
1456     /// The input contains a string. The lifetime of the string is ephemeral and
1457     /// it may be destroyed after this method returns.
1458     ///
1459     /// This method allows the `Deserializer` to avoid a copy by retaining
1460     /// ownership of any buffered data. `Deserialize` implementations that do
1461     /// not benefit from taking ownership of `String` data should indicate that
1462     /// to the deserializer by using `Deserializer::deserialize_str` rather than
1463     /// `Deserializer::deserialize_string`.
1464     ///
1465     /// It is never correct to implement `visit_string` without implementing
1466     /// `visit_str`. Implement neither, both, or just `visit_str`.
visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: Error,1467     fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1468     where
1469         E: Error,
1470     {
1471         Err(Error::invalid_type(Unexpected::Str(v), &self))
1472     }
1473 
1474     /// The input contains a string that lives at least as long as the
1475     /// `Deserializer`.
1476     ///
1477     /// This enables zero-copy deserialization of strings in some formats. For
1478     /// example JSON input containing the JSON string `"borrowed"` can be
1479     /// deserialized with zero copying into a `&'a str` as long as the input
1480     /// data outlives `'a`.
1481     ///
1482     /// The default implementation forwards to `visit_str`.
1483     #[inline]
visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E> where E: Error,1484     fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
1485     where
1486         E: Error,
1487     {
1488         self.visit_str(v)
1489     }
1490 
1491     /// The input contains a string and ownership of the string is being given
1492     /// to the `Visitor`.
1493     ///
1494     /// This method allows the `Visitor` to avoid a copy by taking ownership of
1495     /// a string created by the `Deserializer`. `Deserialize` implementations
1496     /// that benefit from taking ownership of `String` data should indicate that
1497     /// to the deserializer by using `Deserializer::deserialize_string` rather
1498     /// than `Deserializer::deserialize_str`, although not every deserializer
1499     /// will honor such a request.
1500     ///
1501     /// It is never correct to implement `visit_string` without implementing
1502     /// `visit_str`. Implement neither, both, or just `visit_str`.
1503     ///
1504     /// The default implementation forwards to `visit_str` and then drops the
1505     /// `String`.
1506     #[inline]
1507     #[cfg(any(feature = "std", feature = "alloc"))]
visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: Error,1508     fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1509     where
1510         E: Error,
1511     {
1512         self.visit_str(&v)
1513     }
1514 
1515     /// The input contains a byte array. The lifetime of the byte array is
1516     /// ephemeral and it may be destroyed after this method returns.
1517     ///
1518     /// This method allows the `Deserializer` to avoid a copy by retaining
1519     /// ownership of any buffered data. `Deserialize` implementations that do
1520     /// not benefit from taking ownership of `Vec<u8>` data should indicate that
1521     /// to the deserializer by using `Deserializer::deserialize_bytes` rather
1522     /// than `Deserializer::deserialize_byte_buf`.
1523     ///
1524     /// It is never correct to implement `visit_byte_buf` without implementing
1525     /// `visit_bytes`. Implement neither, both, or just `visit_bytes`.
visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> where E: Error,1526     fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1527     where
1528         E: Error,
1529     {
1530         let _ = v;
1531         Err(Error::invalid_type(Unexpected::Bytes(v), &self))
1532     }
1533 
1534     /// The input contains a byte array that lives at least as long as the
1535     /// `Deserializer`.
1536     ///
1537     /// This enables zero-copy deserialization of bytes in some formats. For
1538     /// example Bincode data containing bytes can be deserialized with zero
1539     /// copying into a `&'a [u8]` as long as the input data outlives `'a`.
1540     ///
1541     /// The default implementation forwards to `visit_bytes`.
1542     #[inline]
visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E> where E: Error,1543     fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
1544     where
1545         E: Error,
1546     {
1547         self.visit_bytes(v)
1548     }
1549 
1550     /// The input contains a byte array and ownership of the byte array is being
1551     /// given to the `Visitor`.
1552     ///
1553     /// This method allows the `Visitor` to avoid a copy by taking ownership of
1554     /// a byte buffer created by the `Deserializer`. `Deserialize`
1555     /// implementations that benefit from taking ownership of `Vec<u8>` data
1556     /// should indicate that to the deserializer by using
1557     /// `Deserializer::deserialize_byte_buf` rather than
1558     /// `Deserializer::deserialize_bytes`, although not every deserializer will
1559     /// honor such a request.
1560     ///
1561     /// It is never correct to implement `visit_byte_buf` without implementing
1562     /// `visit_bytes`. Implement neither, both, or just `visit_bytes`.
1563     ///
1564     /// The default implementation forwards to `visit_bytes` and then drops the
1565     /// `Vec<u8>`.
1566     #[cfg(any(feature = "std", feature = "alloc"))]
visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> where E: Error,1567     fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1568     where
1569         E: Error,
1570     {
1571         self.visit_bytes(&v)
1572     }
1573 
1574     /// The input contains an optional that is absent.
1575     ///
1576     /// The default implementation fails with a type error.
visit_none<E>(self) -> Result<Self::Value, E> where E: Error,1577     fn visit_none<E>(self) -> Result<Self::Value, E>
1578     where
1579         E: Error,
1580     {
1581         Err(Error::invalid_type(Unexpected::Option, &self))
1582     }
1583 
1584     /// The input contains an optional that is present.
1585     ///
1586     /// The default implementation fails with a type error.
visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>,1587     fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1588     where
1589         D: Deserializer<'de>,
1590     {
1591         let _ = deserializer;
1592         Err(Error::invalid_type(Unexpected::Option, &self))
1593     }
1594 
1595     /// The input contains a unit `()`.
1596     ///
1597     /// The default implementation fails with a type error.
visit_unit<E>(self) -> Result<Self::Value, E> where E: Error,1598     fn visit_unit<E>(self) -> Result<Self::Value, E>
1599     where
1600         E: Error,
1601     {
1602         Err(Error::invalid_type(Unexpected::Unit, &self))
1603     }
1604 
1605     /// The input contains a newtype struct.
1606     ///
1607     /// The content of the newtype struct may be read from the given
1608     /// `Deserializer`.
1609     ///
1610     /// The default implementation fails with a type error.
visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>,1611     fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1612     where
1613         D: Deserializer<'de>,
1614     {
1615         let _ = deserializer;
1616         Err(Error::invalid_type(Unexpected::NewtypeStruct, &self))
1617     }
1618 
1619     /// The input contains a sequence of elements.
1620     ///
1621     /// The default implementation fails with a type error.
visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>,1622     fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1623     where
1624         A: SeqAccess<'de>,
1625     {
1626         let _ = seq;
1627         Err(Error::invalid_type(Unexpected::Seq, &self))
1628     }
1629 
1630     /// The input contains a key-value map.
1631     ///
1632     /// The default implementation fails with a type error.
visit_map<A>(self, map: A) -> Result<Self::Value, A::Error> where A: MapAccess<'de>,1633     fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
1634     where
1635         A: MapAccess<'de>,
1636     {
1637         let _ = map;
1638         Err(Error::invalid_type(Unexpected::Map, &self))
1639     }
1640 
1641     /// The input contains an enum.
1642     ///
1643     /// The default implementation fails with a type error.
visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error> where A: EnumAccess<'de>,1644     fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
1645     where
1646         A: EnumAccess<'de>,
1647     {
1648         let _ = data;
1649         Err(Error::invalid_type(Unexpected::Enum, &self))
1650     }
1651 
1652     // Used when deserializing a flattened Option field. Not public API.
1653     #[doc(hidden)]
__private_visit_untagged_option<D>(self, _: D) -> Result<Self::Value, ()> where D: Deserializer<'de>,1654     fn __private_visit_untagged_option<D>(self, _: D) -> Result<Self::Value, ()>
1655     where
1656         D: Deserializer<'de>,
1657     {
1658         Err(())
1659     }
1660 }
1661 
1662 ////////////////////////////////////////////////////////////////////////////////
1663 
1664 /// Provides a `Visitor` access to each element of a sequence in the input.
1665 ///
1666 /// This is a trait that a `Deserializer` passes to a `Visitor` implementation,
1667 /// which deserializes each item in a sequence.
1668 ///
1669 /// # Lifetime
1670 ///
1671 /// The `'de` lifetime of this trait is the lifetime of data that may be
1672 /// borrowed by deserialized sequence elements. See the page [Understanding
1673 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1674 ///
1675 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1676 ///
1677 /// # Example implementation
1678 ///
1679 /// The [example data format] presented on the website demonstrates an
1680 /// implementation of `SeqAccess` for a basic JSON data format.
1681 ///
1682 /// [example data format]: https://serde.rs/data-format.html
1683 pub trait SeqAccess<'de> {
1684     /// The error type that can be returned if some error occurs during
1685     /// deserialization.
1686     type Error: Error;
1687 
1688     /// This returns `Ok(Some(value))` for the next value in the sequence, or
1689     /// `Ok(None)` if there are no more remaining items.
1690     ///
1691     /// `Deserialize` implementations should typically use
1692     /// `SeqAccess::next_element` instead.
next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> where T: DeserializeSeed<'de>1693     fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1694     where
1695         T: DeserializeSeed<'de>;
1696 
1697     /// This returns `Ok(Some(value))` for the next value in the sequence, or
1698     /// `Ok(None)` if there are no more remaining items.
1699     ///
1700     /// This method exists as a convenience for `Deserialize` implementations.
1701     /// `SeqAccess` implementations should not override the default behavior.
1702     #[inline]
next_element<T>(&mut self) -> Result<Option<T>, Self::Error> where T: Deserialize<'de>,1703     fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error>
1704     where
1705         T: Deserialize<'de>,
1706     {
1707         self.next_element_seed(PhantomData)
1708     }
1709 
1710     /// Returns the number of elements remaining in the sequence, if known.
1711     #[inline]
size_hint(&self) -> Option<usize>1712     fn size_hint(&self) -> Option<usize> {
1713         None
1714     }
1715 }
1716 
1717 impl<'de, 'a, A: ?Sized> SeqAccess<'de> for &'a mut A
1718 where
1719     A: SeqAccess<'de>,
1720 {
1721     type Error = A::Error;
1722 
1723     #[inline]
next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> where T: DeserializeSeed<'de>,1724     fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1725     where
1726         T: DeserializeSeed<'de>,
1727     {
1728         (**self).next_element_seed(seed)
1729     }
1730 
1731     #[inline]
next_element<T>(&mut self) -> Result<Option<T>, Self::Error> where T: Deserialize<'de>,1732     fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error>
1733     where
1734         T: Deserialize<'de>,
1735     {
1736         (**self).next_element()
1737     }
1738 
1739     #[inline]
size_hint(&self) -> Option<usize>1740     fn size_hint(&self) -> Option<usize> {
1741         (**self).size_hint()
1742     }
1743 }
1744 
1745 ////////////////////////////////////////////////////////////////////////////////
1746 
1747 /// Provides a `Visitor` access to each entry of a map in the input.
1748 ///
1749 /// This is a trait that a `Deserializer` passes to a `Visitor` implementation.
1750 ///
1751 /// # Lifetime
1752 ///
1753 /// The `'de` lifetime of this trait is the lifetime of data that may be
1754 /// borrowed by deserialized map entries. See the page [Understanding
1755 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1756 ///
1757 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1758 ///
1759 /// # Example implementation
1760 ///
1761 /// The [example data format] presented on the website demonstrates an
1762 /// implementation of `MapAccess` for a basic JSON data format.
1763 ///
1764 /// [example data format]: https://serde.rs/data-format.html
1765 pub trait MapAccess<'de> {
1766     /// The error type that can be returned if some error occurs during
1767     /// deserialization.
1768     type Error: Error;
1769 
1770     /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
1771     /// if there are no more remaining entries.
1772     ///
1773     /// `Deserialize` implementations should typically use
1774     /// `MapAccess::next_key` or `MapAccess::next_entry` instead.
next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> where K: DeserializeSeed<'de>1775     fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
1776     where
1777         K: DeserializeSeed<'de>;
1778 
1779     /// This returns a `Ok(value)` for the next value in the map.
1780     ///
1781     /// `Deserialize` implementations should typically use
1782     /// `MapAccess::next_value` instead.
1783     ///
1784     /// # Panics
1785     ///
1786     /// Calling `next_value_seed` before `next_key_seed` is incorrect and is
1787     /// allowed to panic or return bogus results.
next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> where V: DeserializeSeed<'de>1788     fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
1789     where
1790         V: DeserializeSeed<'de>;
1791 
1792     /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in
1793     /// the map, or `Ok(None)` if there are no more remaining items.
1794     ///
1795     /// `MapAccess` implementations should override the default behavior if a
1796     /// more efficient implementation is possible.
1797     ///
1798     /// `Deserialize` implementations should typically use
1799     /// `MapAccess::next_entry` instead.
1800     #[inline]
next_entry_seed<K, V>( &mut self, kseed: K, vseed: V, ) -> Result<Option<(K::Value, V::Value)>, Self::Error> where K: DeserializeSeed<'de>, V: DeserializeSeed<'de>,1801     fn next_entry_seed<K, V>(
1802         &mut self,
1803         kseed: K,
1804         vseed: V,
1805     ) -> Result<Option<(K::Value, V::Value)>, Self::Error>
1806     where
1807         K: DeserializeSeed<'de>,
1808         V: DeserializeSeed<'de>,
1809     {
1810         match try!(self.next_key_seed(kseed)) {
1811             Some(key) => {
1812                 let value = try!(self.next_value_seed(vseed));
1813                 Ok(Some((key, value)))
1814             }
1815             None => Ok(None),
1816         }
1817     }
1818 
1819     /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
1820     /// if there are no more remaining entries.
1821     ///
1822     /// This method exists as a convenience for `Deserialize` implementations.
1823     /// `MapAccess` implementations should not override the default behavior.
1824     #[inline]
next_key<K>(&mut self) -> Result<Option<K>, Self::Error> where K: Deserialize<'de>,1825     fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error>
1826     where
1827         K: Deserialize<'de>,
1828     {
1829         self.next_key_seed(PhantomData)
1830     }
1831 
1832     /// This returns a `Ok(value)` for the next value in the map.
1833     ///
1834     /// This method exists as a convenience for `Deserialize` implementations.
1835     /// `MapAccess` implementations should not override the default behavior.
1836     ///
1837     /// # Panics
1838     ///
1839     /// Calling `next_value` before `next_key` is incorrect and is allowed to
1840     /// panic or return bogus results.
1841     #[inline]
next_value<V>(&mut self) -> Result<V, Self::Error> where V: Deserialize<'de>,1842     fn next_value<V>(&mut self) -> Result<V, Self::Error>
1843     where
1844         V: Deserialize<'de>,
1845     {
1846         self.next_value_seed(PhantomData)
1847     }
1848 
1849     /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in
1850     /// the map, or `Ok(None)` if there are no more remaining items.
1851     ///
1852     /// This method exists as a convenience for `Deserialize` implementations.
1853     /// `MapAccess` implementations should not override the default behavior.
1854     #[inline]
next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error> where K: Deserialize<'de>, V: Deserialize<'de>,1855     fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
1856     where
1857         K: Deserialize<'de>,
1858         V: Deserialize<'de>,
1859     {
1860         self.next_entry_seed(PhantomData, PhantomData)
1861     }
1862 
1863     /// Returns the number of entries remaining in the map, if known.
1864     #[inline]
size_hint(&self) -> Option<usize>1865     fn size_hint(&self) -> Option<usize> {
1866         None
1867     }
1868 }
1869 
1870 impl<'de, 'a, A: ?Sized> MapAccess<'de> for &'a mut A
1871 where
1872     A: MapAccess<'de>,
1873 {
1874     type Error = A::Error;
1875 
1876     #[inline]
next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> where K: DeserializeSeed<'de>,1877     fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
1878     where
1879         K: DeserializeSeed<'de>,
1880     {
1881         (**self).next_key_seed(seed)
1882     }
1883 
1884     #[inline]
next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> where V: DeserializeSeed<'de>,1885     fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
1886     where
1887         V: DeserializeSeed<'de>,
1888     {
1889         (**self).next_value_seed(seed)
1890     }
1891 
1892     #[inline]
next_entry_seed<K, V>( &mut self, kseed: K, vseed: V, ) -> Result<Option<(K::Value, V::Value)>, Self::Error> where K: DeserializeSeed<'de>, V: DeserializeSeed<'de>,1893     fn next_entry_seed<K, V>(
1894         &mut self,
1895         kseed: K,
1896         vseed: V,
1897     ) -> Result<Option<(K::Value, V::Value)>, Self::Error>
1898     where
1899         K: DeserializeSeed<'de>,
1900         V: DeserializeSeed<'de>,
1901     {
1902         (**self).next_entry_seed(kseed, vseed)
1903     }
1904 
1905     #[inline]
next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error> where K: Deserialize<'de>, V: Deserialize<'de>,1906     fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
1907     where
1908         K: Deserialize<'de>,
1909         V: Deserialize<'de>,
1910     {
1911         (**self).next_entry()
1912     }
1913 
1914     #[inline]
next_key<K>(&mut self) -> Result<Option<K>, Self::Error> where K: Deserialize<'de>,1915     fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error>
1916     where
1917         K: Deserialize<'de>,
1918     {
1919         (**self).next_key()
1920     }
1921 
1922     #[inline]
next_value<V>(&mut self) -> Result<V, Self::Error> where V: Deserialize<'de>,1923     fn next_value<V>(&mut self) -> Result<V, Self::Error>
1924     where
1925         V: Deserialize<'de>,
1926     {
1927         (**self).next_value()
1928     }
1929 
1930     #[inline]
size_hint(&self) -> Option<usize>1931     fn size_hint(&self) -> Option<usize> {
1932         (**self).size_hint()
1933     }
1934 }
1935 
1936 ////////////////////////////////////////////////////////////////////////////////
1937 
1938 /// Provides a `Visitor` access to the data of an enum in the input.
1939 ///
1940 /// `EnumAccess` is created by the `Deserializer` and passed to the
1941 /// `Visitor` in order to identify which variant of an enum to deserialize.
1942 ///
1943 /// # Lifetime
1944 ///
1945 /// The `'de` lifetime of this trait is the lifetime of data that may be
1946 /// borrowed by the deserialized enum variant. See the page [Understanding
1947 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1948 ///
1949 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1950 ///
1951 /// # Example implementation
1952 ///
1953 /// The [example data format] presented on the website demonstrates an
1954 /// implementation of `EnumAccess` for a basic JSON data format.
1955 ///
1956 /// [example data format]: https://serde.rs/data-format.html
1957 pub trait EnumAccess<'de>: Sized {
1958     /// The error type that can be returned if some error occurs during
1959     /// deserialization.
1960     type Error: Error;
1961     /// The `Visitor` that will be used to deserialize the content of the enum
1962     /// variant.
1963     type Variant: VariantAccess<'de, Error = Self::Error>;
1964 
1965     /// `variant` is called to identify which variant to deserialize.
1966     ///
1967     /// `Deserialize` implementations should typically use `EnumAccess::variant`
1968     /// instead.
variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> where V: DeserializeSeed<'de>1969     fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
1970     where
1971         V: DeserializeSeed<'de>;
1972 
1973     /// `variant` is called to identify which variant to deserialize.
1974     ///
1975     /// This method exists as a convenience for `Deserialize` implementations.
1976     /// `EnumAccess` implementations should not override the default behavior.
1977     #[inline]
variant<V>(self) -> Result<(V, Self::Variant), Self::Error> where V: Deserialize<'de>,1978     fn variant<V>(self) -> Result<(V, Self::Variant), Self::Error>
1979     where
1980         V: Deserialize<'de>,
1981     {
1982         self.variant_seed(PhantomData)
1983     }
1984 }
1985 
1986 /// `VariantAccess` is a visitor that is created by the `Deserializer` and
1987 /// passed to the `Deserialize` to deserialize the content of a particular enum
1988 /// variant.
1989 ///
1990 /// # Lifetime
1991 ///
1992 /// The `'de` lifetime of this trait is the lifetime of data that may be
1993 /// borrowed by the deserialized enum variant. See the page [Understanding
1994 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1995 ///
1996 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1997 ///
1998 /// # Example implementation
1999 ///
2000 /// The [example data format] presented on the website demonstrates an
2001 /// implementation of `VariantAccess` for a basic JSON data format.
2002 ///
2003 /// [example data format]: https://serde.rs/data-format.html
2004 pub trait VariantAccess<'de>: Sized {
2005     /// The error type that can be returned if some error occurs during
2006     /// deserialization. Must match the error type of our `EnumAccess`.
2007     type Error: Error;
2008 
2009     /// Called when deserializing a variant with no values.
2010     ///
2011     /// If the data contains a different type of variant, the following
2012     /// `invalid_type` error should be constructed:
2013     ///
2014     /// ```edition2018
2015     /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
2016     /// #
2017     /// # struct X;
2018     /// #
2019     /// # impl<'de> VariantAccess<'de> for X {
2020     /// #     type Error = value::Error;
2021     /// #
2022     /// fn unit_variant(self) -> Result<(), Self::Error> {
2023     ///     // What the data actually contained; suppose it is a tuple variant.
2024     ///     let unexp = Unexpected::TupleVariant;
2025     ///     Err(de::Error::invalid_type(unexp, &"unit variant"))
2026     /// }
2027     /// #
2028     /// #     fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
2029     /// #     where
2030     /// #         T: DeserializeSeed<'de>,
2031     /// #     { unimplemented!() }
2032     /// #
2033     /// #     fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
2034     /// #     where
2035     /// #         V: Visitor<'de>,
2036     /// #     { unimplemented!() }
2037     /// #
2038     /// #     fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
2039     /// #     where
2040     /// #         V: Visitor<'de>,
2041     /// #     { unimplemented!() }
2042     /// # }
2043     /// ```
unit_variant(self) -> Result<(), Self::Error>2044     fn unit_variant(self) -> Result<(), Self::Error>;
2045 
2046     /// Called when deserializing a variant with a single value.
2047     ///
2048     /// `Deserialize` implementations should typically use
2049     /// `VariantAccess::newtype_variant` instead.
2050     ///
2051     /// If the data contains a different type of variant, the following
2052     /// `invalid_type` error should be constructed:
2053     ///
2054     /// ```edition2018
2055     /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
2056     /// #
2057     /// # struct X;
2058     /// #
2059     /// # impl<'de> VariantAccess<'de> for X {
2060     /// #     type Error = value::Error;
2061     /// #
2062     /// #     fn unit_variant(self) -> Result<(), Self::Error> {
2063     /// #         unimplemented!()
2064     /// #     }
2065     /// #
2066     /// fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
2067     /// where
2068     ///     T: DeserializeSeed<'de>,
2069     /// {
2070     ///     // What the data actually contained; suppose it is a unit variant.
2071     ///     let unexp = Unexpected::UnitVariant;
2072     ///     Err(de::Error::invalid_type(unexp, &"newtype variant"))
2073     /// }
2074     /// #
2075     /// #     fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
2076     /// #     where
2077     /// #         V: Visitor<'de>,
2078     /// #     { unimplemented!() }
2079     /// #
2080     /// #     fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
2081     /// #     where
2082     /// #         V: Visitor<'de>,
2083     /// #     { unimplemented!() }
2084     /// # }
2085     /// ```
newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error> where T: DeserializeSeed<'de>2086     fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
2087     where
2088         T: DeserializeSeed<'de>;
2089 
2090     /// Called when deserializing a variant with a single value.
2091     ///
2092     /// This method exists as a convenience for `Deserialize` implementations.
2093     /// `VariantAccess` implementations should not override the default
2094     /// behavior.
2095     #[inline]
newtype_variant<T>(self) -> Result<T, Self::Error> where T: Deserialize<'de>,2096     fn newtype_variant<T>(self) -> Result<T, Self::Error>
2097     where
2098         T: Deserialize<'de>,
2099     {
2100         self.newtype_variant_seed(PhantomData)
2101     }
2102 
2103     /// Called when deserializing a tuple-like variant.
2104     ///
2105     /// The `len` is the number of fields expected in the tuple variant.
2106     ///
2107     /// If the data contains a different type of variant, the following
2108     /// `invalid_type` error should be constructed:
2109     ///
2110     /// ```edition2018
2111     /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
2112     /// #
2113     /// # struct X;
2114     /// #
2115     /// # impl<'de> VariantAccess<'de> for X {
2116     /// #     type Error = value::Error;
2117     /// #
2118     /// #     fn unit_variant(self) -> Result<(), Self::Error> {
2119     /// #         unimplemented!()
2120     /// #     }
2121     /// #
2122     /// #     fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
2123     /// #     where
2124     /// #         T: DeserializeSeed<'de>,
2125     /// #     { unimplemented!() }
2126     /// #
2127     /// fn tuple_variant<V>(
2128     ///     self,
2129     ///     _len: usize,
2130     ///     _visitor: V,
2131     /// ) -> Result<V::Value, Self::Error>
2132     /// where
2133     ///     V: Visitor<'de>,
2134     /// {
2135     ///     // What the data actually contained; suppose it is a unit variant.
2136     ///     let unexp = Unexpected::UnitVariant;
2137     ///     Err(de::Error::invalid_type(unexp, &"tuple variant"))
2138     /// }
2139     /// #
2140     /// #     fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
2141     /// #     where
2142     /// #         V: Visitor<'de>,
2143     /// #     { unimplemented!() }
2144     /// # }
2145     /// ```
tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>2146     fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
2147     where
2148         V: Visitor<'de>;
2149 
2150     /// Called when deserializing a struct-like variant.
2151     ///
2152     /// The `fields` are the names of the fields of the struct variant.
2153     ///
2154     /// If the data contains a different type of variant, the following
2155     /// `invalid_type` error should be constructed:
2156     ///
2157     /// ```edition2018
2158     /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
2159     /// #
2160     /// # struct X;
2161     /// #
2162     /// # impl<'de> VariantAccess<'de> for X {
2163     /// #     type Error = value::Error;
2164     /// #
2165     /// #     fn unit_variant(self) -> Result<(), Self::Error> {
2166     /// #         unimplemented!()
2167     /// #     }
2168     /// #
2169     /// #     fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
2170     /// #     where
2171     /// #         T: DeserializeSeed<'de>,
2172     /// #     { unimplemented!() }
2173     /// #
2174     /// #     fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
2175     /// #     where
2176     /// #         V: Visitor<'de>,
2177     /// #     { unimplemented!() }
2178     /// #
2179     /// fn struct_variant<V>(
2180     ///     self,
2181     ///     _fields: &'static [&'static str],
2182     ///     _visitor: V,
2183     /// ) -> Result<V::Value, Self::Error>
2184     /// where
2185     ///     V: Visitor<'de>,
2186     /// {
2187     ///     // What the data actually contained; suppose it is a unit variant.
2188     ///     let unexp = Unexpected::UnitVariant;
2189     ///     Err(de::Error::invalid_type(unexp, &"struct variant"))
2190     /// }
2191     /// # }
2192     /// ```
struct_variant<V>( self, fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>2193     fn struct_variant<V>(
2194         self,
2195         fields: &'static [&'static str],
2196         visitor: V,
2197     ) -> Result<V::Value, Self::Error>
2198     where
2199         V: Visitor<'de>;
2200 }
2201 
2202 ////////////////////////////////////////////////////////////////////////////////
2203 
2204 /// Converts an existing value into a `Deserializer` from which other values can
2205 /// be deserialized.
2206 ///
2207 /// # Lifetime
2208 ///
2209 /// The `'de` lifetime of this trait is the lifetime of data that may be
2210 /// borrowed from the resulting `Deserializer`. See the page [Understanding
2211 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
2212 ///
2213 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
2214 ///
2215 /// # Example
2216 ///
2217 /// ```edition2018
2218 /// use std::str::FromStr;
2219 /// use serde::Deserialize;
2220 /// use serde::de::{value, IntoDeserializer};
2221 ///
2222 /// #[derive(Deserialize)]
2223 /// enum Setting {
2224 ///     On,
2225 ///     Off,
2226 /// }
2227 ///
2228 /// impl FromStr for Setting {
2229 ///     type Err = value::Error;
2230 ///
2231 ///     fn from_str(s: &str) -> Result<Self, Self::Err> {
2232 ///         Self::deserialize(s.into_deserializer())
2233 ///     }
2234 /// }
2235 /// ```
2236 pub trait IntoDeserializer<'de, E: Error = value::Error> {
2237     /// The type of the deserializer being converted into.
2238     type Deserializer: Deserializer<'de, Error = E>;
2239 
2240     /// Convert this value into a deserializer.
into_deserializer(self) -> Self::Deserializer2241     fn into_deserializer(self) -> Self::Deserializer;
2242 }
2243 
2244 ////////////////////////////////////////////////////////////////////////////////
2245 
2246 /// Used in error messages.
2247 ///
2248 /// - expected `a`
2249 /// - expected `a` or `b`
2250 /// - expected one of `a`, `b`, `c`
2251 ///
2252 /// The slice of names must not be empty.
2253 struct OneOf {
2254     names: &'static [&'static str],
2255 }
2256 
2257 impl Display for OneOf {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result2258     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2259         match self.names.len() {
2260             0 => panic!(), // special case elsewhere
2261             1 => write!(formatter, "`{}`", self.names[0]),
2262             2 => write!(formatter, "`{}` or `{}`", self.names[0], self.names[1]),
2263             _ => {
2264                 try!(write!(formatter, "one of "));
2265                 for (i, alt) in self.names.iter().enumerate() {
2266                     if i > 0 {
2267                         try!(write!(formatter, ", "));
2268                     }
2269                     try!(write!(formatter, "`{}`", alt));
2270                 }
2271                 Ok(())
2272             }
2273         }
2274     }
2275 }
2276