1 //! Generic data structure deserialization framework.
3 //! The two most important traits in this module are [`Deserialize`] and
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.
11 //! # The Deserialize trait
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.
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.
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.
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.
30 //! # The Deserializer trait
32 //! [`Deserializer`] implementations are provided by third-party crates, for
33 //! example [`serde_json`], [`serde_yaml`] and [`bincode`].
35 //! A partial list of well-maintained formats is given on the [Serde
36 //! website][data formats].
38 //! # Implementations of Deserialize provided by Serde
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`.
44 //! - **Primitive types**:
46 //! - i8, i16, i32, i64, i128, isize
47 //! - u8, u16, u32, u64, u128, usize
50 //! - **Compound types**:
51 //! - \[T; 0\] through \[T; 32\]
52 //! - tuples up to size 16
53 //! - **Common standard library types**:
57 //! - PhantomData\<T\>
58 //! - **Wrapper types**:
67 //! - Rc\<T\> *(if* features = ["rc"] *is enabled)*
68 //! - Arc\<T\> *(if* features = ["rc"] *is enabled)*
69 //! - **Collection types**:
70 //! - BTreeMap\<K, V\>
73 //! - HashMap\<K, V, H\>
78 //! - **Zero-copy types**:
85 //! - **Miscellaneous standard library types**:
91 //! - RangeInclusive\<T\>
94 //! - `!` *(unstable)*
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
117 ////////////////////////////////////////////////////////////////////////////////
125 pub use self::ignored_any
::IgnoredAny
;
127 #[cfg(feature = "std")]
129 pub use std
::error
::Error
as StdError
;
130 #[cfg(not(feature = "std"))]
132 pub use std_error
::Error
as StdError
;
134 ////////////////////////////////////////////////////////////////////////////////
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.
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
149 /// Most deserializers should only need to provide the `Error::custom` method
150 /// and inherit the default behavior for the other methods.
152 /// # Example implementation
154 /// The [example data format] presented on the website shows an error
155 /// type appropriate for a basic JSON data format.
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.
161 /// The message should not be capitalized and should not end with a period.
164 /// # use std::str::FromStr;
168 /// # impl FromStr for IpAddr {
169 /// # type Err = String;
171 /// # fn from_str(_: &str) -> Result<Self, String> {
172 /// # unimplemented!()
176 /// use serde::de::{self, Deserialize, Deserializer};
178 /// impl<'de> Deserialize<'de> for IpAddr {
179 /// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
181 /// D: Deserializer<'de>,
183 /// let s = String::deserialize(deserializer)?;
184 /// s.parse().map_err(de::Error::custom)
188 fn custom
<T
>(msg
: T
) -> Self
192 /// Raised when a `Deserialize` receives a type different from what it was
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.
199 /// The `exp` argument provides information about what type was being
200 /// expected. This is the type that is written in the program.
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.
206 fn invalid_type(unexp
: Unexpected
, exp
: &Expected
) -> Self {
207 Error
::custom(format_args
!("invalid type: {}, expected {}", unexp
, exp
))
210 /// Raised when a `Deserialize` receives a value of the right type but that
211 /// is wrong for some other reason.
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.
217 /// The `exp` argument provides information about what value was being
218 /// expected. This is the type that is written in the program.
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.
224 fn invalid_value(unexp
: Unexpected
, exp
: &Expected
) -> Self {
225 Error
::custom(format_args
!("invalid value: {}, expected {}", unexp
, exp
))
228 /// Raised when deserializing a sequence or map and the input data contains
229 /// too many or too few elements.
231 /// The `len` argument is the number of elements encountered. The sequence
232 /// or map may have expected more arguments or fewer arguments.
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
238 fn invalid_length(len
: usize, exp
: &Expected
) -> Self {
239 Error
::custom(format_args
!("invalid length {}, expected {}", len
, exp
))
242 /// Raised when a `Deserialize` enum type received a variant with an
243 /// unrecognized name.
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",
252 Error
::custom(format_args
!(
253 "unknown variant `{}`, expected {}",
255 OneOf { names: expected }
260 /// Raised when a `Deserialize` struct type received a field with an
261 /// unrecognized name.
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",
270 Error
::custom(format_args
!(
271 "unknown field `{}`, expected {}",
273 OneOf { names: expected }
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
282 fn missing_field(field
: &'
static str) -> Self {
283 Error
::custom(format_args
!("missing field `{}`", field
))
286 /// Raised when a `Deserialize` struct type received more than one of the
289 fn duplicate_field(field
: &'
static str) -> Self {
290 Error
::custom(format_args
!("duplicate field `{}`", field
))
296 #[cfg(feature = "std")]
297 declare_error_trait
!(Error
: Sized
+ StdError
);
299 #[cfg(not(feature = "std"))]
300 declare_error_trait
!(Error
: Sized
+ Debug
+ Display
);
302 /// `Unexpected` represents an unexpected invocation of any one of the `Visitor`
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.
311 /// # use serde::de::{self, Unexpected, Visitor};
313 /// # struct Example;
315 /// # impl<'de> Visitor<'de> for Example {
316 /// # type Value = ();
318 /// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
319 /// # write!(formatter, "definitely not a boolean")
322 /// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
326 /// Err(de::Error::invalid_type(Unexpected::Bool(v), &self))
330 #[derive(Copy, Clone, PartialEq, Debug)]
331 pub enum Unexpected
<'a
> {
332 /// The input contained a boolean value that was not expected.
335 /// The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that
336 /// was not expected.
339 /// The input contained a signed integer `i8`, `i16`, `i32` or `i64` that
340 /// was not expected.
343 /// The input contained a floating point `f32` or `f64` that was not
347 /// The input contained a `char` that was not expected.
350 /// The input contained a `&str` or `String` that was not expected.
353 /// The input contained a `&[u8]` or `Vec<u8>` that was not expected.
356 /// The input contained a unit `()` that was not expected.
359 /// The input contained an `Option<T>` that was not expected.
362 /// The input contained a newtype struct that was not expected.
365 /// The input contained a sequence that was not expected.
368 /// The input contained a map that was not expected.
371 /// The input contained an enum that was not expected.
374 /// The input contained a unit variant that was not expected.
377 /// The input contained a newtype variant that was not expected.
380 /// The input contained a tuple variant that was not expected.
383 /// The input contained a struct variant that was not expected.
386 /// A message stating what uncategorized thing the input contained that was
389 /// The message should be a noun or noun phrase, not capitalized and without
390 /// a period. An example message is "unoriginal superhero".
394 impl<'a
> fmt
::Display
for Unexpected
<'a
> {
395 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
396 use self::Unexpected
::*;
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
),
420 /// `Expected` represents an explanation of what data a `Visitor` was expecting
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.
430 /// Within the context of a `Visitor` implementation, the `Visitor` itself
431 /// (`&self`) is an implementation of this trait.
436 /// # use serde::de::{self, Unexpected, Visitor};
438 /// # struct Example;
440 /// # impl<'de> Visitor<'de> for Example {
441 /// # type Value = ();
443 /// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
444 /// # write!(formatter, "definitely not a boolean")
447 /// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
451 /// Err(de::Error::invalid_type(Unexpected::Bool(v), &self))
456 /// Outside of a `Visitor`, `&"..."` can be used.
459 /// # use serde::de::{self, Unexpected};
461 /// # fn example<E>() -> Result<(), E>
466 /// return Err(de::Error::invalid_type(Unexpected::Bool(v), &"a negative integer"));
470 /// Format an explanation of what data was being expected. Same signature as
471 /// the `Display` and `Debug` traits.
472 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
;
475 impl<'de
, T
> Expected
for T
479 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
480 self.expecting(formatter
)
484 impl<'a
> Expected
for &'a
str {
485 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
486 formatter
.write_str(self)
490 impl<'a
> Display
for Expected
+ 'a
{
491 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
492 Expected
::fmt(self, formatter
)
496 ////////////////////////////////////////////////////////////////////////////////
498 /// A **data structure** that can be deserialized from any data format supported
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.
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
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.
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.
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
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.
529 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
530 pub trait Deserialize
<'de
>: Sized
{
531 /// Deserialize this value from the given Serde deserializer.
533 /// See the [Implementing `Deserialize`][impl-deserialize] section of the
534 /// manual for more information about how to implement this method.
536 /// [impl-deserialize]: https://serde.rs/impl-deserialize.html
537 fn deserialize
<D
>(deserializer
: D
) -> Result
<Self, D
::Error
>
539 D
: Deserializer
<'de
>;
541 /// Deserializes a value into `self` from the given Deserializer.
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
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.
553 /// If you manually implement this, your recursive deserializations should
554 /// use `deserialize_in_place`.
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.
561 fn deserialize_in_place
<D
>(deserializer
: D
, place
: &mut Self) -> Result
<(), D
::Error
>
563 D
: Deserializer
<'de
>,
565 // Default implementation just delegates to `deserialize` impl.
566 *place
= Deserialize
::deserialize(deserializer
)?
;
571 /// A data structure that can be deserialized without borrowing any data from
572 /// the deserializer.
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
580 /// # use serde::de::{Deserialize, DeserializeOwned};
581 /// # use std::io::{Read, Result};
584 /// fn from_str<'a, T>(s: &'a str) -> Result<T>
586 /// T: Deserialize<'a>;
588 /// fn from_reader<R, T>(rdr: R) -> Result<T>
591 /// T: DeserializeOwned;
597 /// The relationship between `Deserialize` and `DeserializeOwned` in trait
598 /// bounds is explained in more detail on the page [Understanding deserializer
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
> {}
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.
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.
616 /// The canonical API for stateless deserialization looks like this:
619 /// # use serde::Deserialize;
623 /// fn func<'de, T: Deserialize<'de>>() -> Result<T, Error>
625 /// # unimplemented!()
629 /// Adjusting an API like this to support stateful deserialization is a matter
630 /// of accepting a seed as input:
633 /// # use serde::de::DeserializeSeed;
637 /// fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result<T::Value, Error>
640 /// # unimplemented!()
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.
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.
654 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
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`
667 /// use std::marker::PhantomData;
669 /// use serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor};
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>);
678 /// impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T>
680 /// T: Deserialize<'de>,
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 ().
687 /// fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
689 /// D: Deserializer<'de>,
691 /// // Visitor implementation that will walk an inner array of the JSON
693 /// struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec<T>);
695 /// impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T>
697 /// T: Deserialize<'de>,
701 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
702 /// write!(formatter, "an array of integers")
705 /// fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error>
707 /// A: SeqAccess<'de>,
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);
718 /// deserializer.deserialize_seq(ExtendVecVisitor(self.0))
722 /// // Visitor implementation that will walk the outer array of the JSON input.
723 /// struct FlattenedVecVisitor<T>(PhantomData<T>);
725 /// impl<'de, T> Visitor<'de> for FlattenedVecVisitor<T>
727 /// T: Deserialize<'de>,
729 /// // This Visitor constructs a single Vec<T> to hold the flattened
730 /// // contents of the inner arrays.
731 /// type Value = Vec<T>;
733 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
734 /// write!(formatter, "an array of arrays")
737 /// fn visit_seq<A>(self, mut seq: A) -> Result<Vec<T>, A::Error>
739 /// A: SeqAccess<'de>,
741 /// // Create a single Vec to hold the flattened contents.
742 /// let mut vec = Vec::new();
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`.
749 /// // Return the finished vec.
754 /// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error>
756 /// # D: Deserializer<'de>,
758 /// let visitor = FlattenedVecVisitor(PhantomData);
759 /// let flattened: Vec<u64> = deserializer.deserialize_seq(visitor)?;
763 pub trait DeserializeSeed
<'de
>: Sized
{
764 /// The type produced by using this seed.
767 /// Equivalent to the more common `Deserialize::deserialize` method, except
768 /// with some initial piece of data (the seed) passed in.
769 fn deserialize
<D
>(self, deserializer
: D
) -> Result
<Self::Value
, D
::Error
>
771 D
: Deserializer
<'de
>;
774 impl<'de
, T
> DeserializeSeed
<'de
> for PhantomData
<T
>
781 fn deserialize
<D
>(self, deserializer
: D
) -> Result
<T
, D
::Error
>
783 D
: Deserializer
<'de
>,
785 T
::deserialize(deserializer
)
789 ////////////////////////////////////////////////////////////////////////////////
791 /// A **data format** that can deserialize any data structure supported by
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.
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.
803 /// The types that make up the Serde data model are:
805 /// - **14 primitive types**
807 /// - i8, i16, i32, i64, i128
808 /// - u8, u16, u32, u64, u128
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.
819 /// - Either none or some value.
821 /// - The type of `()` in Rust. It represents an anonymous value containing
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) }`.
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.
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
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) }`.
847 /// - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.
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 } }`.
855 /// The `Deserializer` trait supports two entry point styles which enables
856 /// different kinds of deserialization.
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`.
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`.
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
883 /// [Serde data model]: https://serde.rs/data-model.html
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.
891 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
893 /// # Example implementation
895 /// The [example data format] presented on the website contains example code for
896 /// a basic JSON `Deserializer`.
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
904 /// Require the `Deserializer` to figure out how to drive the visitor based
905 /// on what data type is in the input.
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
913 fn deserialize_any
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
917 /// Hint that the `Deserialize` type is expecting a `bool` value.
918 fn deserialize_bool
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
922 /// Hint that the `Deserialize` type is expecting an `i8` value.
923 fn deserialize_i8
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
927 /// Hint that the `Deserialize` type is expecting an `i16` value.
928 fn deserialize_i16
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
932 /// Hint that the `Deserialize` type is expecting an `i32` value.
933 fn deserialize_i32
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
937 /// Hint that the `Deserialize` type is expecting an `i64` value.
938 fn deserialize_i64
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
942 serde_if_integer128
! {
943 /// Hint that the `Deserialize` type is expecting an `i128` value.
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
>
952 Err(Error
::custom("i128 is not supported"))
956 /// Hint that the `Deserialize` type is expecting a `u8` value.
957 fn deserialize_u8
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
961 /// Hint that the `Deserialize` type is expecting a `u16` value.
962 fn deserialize_u16
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
966 /// Hint that the `Deserialize` type is expecting a `u32` value.
967 fn deserialize_u32
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
971 /// Hint that the `Deserialize` type is expecting a `u64` value.
972 fn deserialize_u64
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
976 serde_if_integer128
! {
977 /// Hint that the `Deserialize` type is expecting an `u128` value.
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
>
986 Err(Error
::custom("u128 is not supported"))
990 /// Hint that the `Deserialize` type is expecting a `f32` value.
991 fn deserialize_f32
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
995 /// Hint that the `Deserialize` type is expecting a `f64` value.
996 fn deserialize_f64
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1000 /// Hint that the `Deserialize` type is expecting a `char` value.
1001 fn deserialize_char
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
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
1009 /// If the `Visitor` would benefit from taking ownership of `String` data,
1010 /// indicate this to the `Deserializer` by using `deserialize_string`
1012 fn deserialize_str
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1016 /// Hint that the `Deserialize` type is expecting a string value and would
1017 /// benefit from taking ownership of buffered data owned by the
1020 /// If the `Visitor` would not benefit from taking ownership of `String`
1021 /// data, indicate that to the `Deserializer` by using `deserialize_str`
1023 fn deserialize_string
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
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
1031 /// If the `Visitor` would benefit from taking ownership of `Vec<u8>` data,
1032 /// indicate this to the `Deserializer` by using `deserialize_byte_buf`
1034 fn deserialize_bytes
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1038 /// Hint that the `Deserialize` type is expecting a byte array and would
1039 /// benefit from taking ownership of buffered data owned by the
1042 /// If the `Visitor` would not benefit from taking ownership of `Vec<u8>`
1043 /// data, indicate that to the `Deserializer` by using `deserialize_bytes`
1045 fn deserialize_byte_buf
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1049 /// Hint that the `Deserialize` type is expecting an optional value.
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
1054 fn deserialize_option
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1058 /// Hint that the `Deserialize` type is expecting a unit value.
1059 fn deserialize_unit
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1063 /// Hint that the `Deserialize` type is expecting a unit struct with a
1064 /// particular name.
1065 fn deserialize_unit_struct
<V
>(
1069 ) -> Result
<V
::Value
, Self::Error
>
1073 /// Hint that the `Deserialize` type is expecting a newtype struct with a
1074 /// particular name.
1075 fn deserialize_newtype_struct
<V
>(
1079 ) -> Result
<V
::Value
, Self::Error
>
1083 /// Hint that the `Deserialize` type is expecting a sequence of values.
1084 fn deserialize_seq
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
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.
1090 fn deserialize_tuple
<V
>(self, len
: usize, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1094 /// Hint that the `Deserialize` type is expecting a tuple struct with a
1095 /// particular name and number of fields.
1096 fn deserialize_tuple_struct
<V
>(
1101 ) -> Result
<V
::Value
, Self::Error
>
1105 /// Hint that the `Deserialize` type is expecting a map of key-value pairs.
1106 fn deserialize_map
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1110 /// Hint that the `Deserialize` type is expecting a struct with a particular
1111 /// name and fields.
1112 fn deserialize_struct
<V
>(
1115 fields
: &'
static [&'
static str],
1117 ) -> Result
<V
::Value
, Self::Error
>
1121 /// Hint that the `Deserialize` type is expecting an enum value with a
1122 /// particular name and possible variants.
1123 fn deserialize_enum
<V
>(
1126 variants
: &'
static [&'
static str],
1128 ) -> Result
<V
::Value
, Self::Error
>
1132 /// Hint that the `Deserialize` type is expecting the name of a struct
1133 /// field or the discriminant of an enum variant.
1134 fn deserialize_identifier
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1138 /// Hint that the `Deserialize` type needs to deserialize a value whose type
1139 /// doesn't matter because it is ignored.
1141 /// Deserializers for non-self-describing formats may not support this mode.
1142 fn deserialize_ignored_any
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1146 /// Determine whether `Deserialize` implementations should expect to
1147 /// deserialize their human-readable form.
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
1156 /// # use std::ops::Add;
1157 /// # use std::str::FromStr;
1159 /// # struct Timestamp;
1161 /// # impl Timestamp {
1162 /// # const EPOCH: Timestamp = Timestamp;
1165 /// # impl FromStr for Timestamp {
1166 /// # type Err = String;
1167 /// # fn from_str(_: &str) -> Result<Self, Self::Err> {
1168 /// # unimplemented!()
1172 /// # struct Duration;
1174 /// # impl Duration {
1175 /// # fn seconds(_: u64) -> Self { unimplemented!() }
1178 /// # impl Add<Duration> for Timestamp {
1179 /// # type Output = Timestamp;
1180 /// # fn add(self, _: Duration) -> Self::Output {
1181 /// # unimplemented!()
1185 /// use serde::de::{self, Deserialize, Deserializer};
1187 /// impl<'de> Deserialize<'de> for Timestamp {
1188 /// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1190 /// D: Deserializer<'de>,
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)
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))
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.
1213 fn is_human_readable(&self) -> bool
{
1218 ////////////////////////////////////////////////////////////////////////////////
1220 /// This trait represents a visitor that walks through a deserializer.
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.
1228 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1235 /// # use serde::de::{self, Unexpected, Visitor};
1237 /// /// A visitor that deserializes a long string - a string containing at least
1238 /// /// some minimum number of bytes.
1239 /// struct LongString {
1243 /// impl<'de> Visitor<'de> for LongString {
1244 /// type Value = String;
1246 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1247 /// write!(formatter, "a string containing at least {} bytes", self.min)
1250 /// fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
1254 /// if s.len() >= self.min {
1255 /// Ok(s.to_owned())
1257 /// Err(de::Error::invalid_value(Unexpected::Str(s), &self))
1262 pub trait Visitor
<'de
>: Sized
{
1263 /// The value produced by this visitor.
1266 /// Format a message stating what data this Visitor expects to receive.
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.
1280 /// # impl<'de> serde::de::Visitor<'de> for S {
1281 /// # type Value = ();
1283 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1284 /// write!(formatter, "an integer between 0 and {}", self.max)
1288 fn expecting(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
;
1290 /// The input contains a boolean.
1292 /// The default implementation fails with a type error.
1293 fn visit_bool
<E
>(self, v
: bool
) -> Result
<Self::Value
, E
>
1297 Err(Error
::invalid_type(Unexpected
::Bool(v
), &self))
1300 /// The input contains an `i8`.
1302 /// The default implementation forwards to [`visit_i64`].
1304 /// [`visit_i64`]: #method.visit_i64
1305 fn visit_i8
<E
>(self, v
: i8) -> Result
<Self::Value
, E
>
1309 self.visit_i64(v
as i64)
1312 /// The input contains an `i16`.
1314 /// The default implementation forwards to [`visit_i64`].
1316 /// [`visit_i64`]: #method.visit_i64
1317 fn visit_i16
<E
>(self, v
: i16) -> Result
<Self::Value
, E
>
1321 self.visit_i64(v
as i64)
1324 /// The input contains an `i32`.
1326 /// The default implementation forwards to [`visit_i64`].
1328 /// [`visit_i64`]: #method.visit_i64
1329 fn visit_i32
<E
>(self, v
: i32) -> Result
<Self::Value
, E
>
1333 self.visit_i64(v
as i64)
1336 /// The input contains an `i64`.
1338 /// The default implementation fails with a type error.
1339 fn visit_i64
<E
>(self, v
: i64) -> Result
<Self::Value
, E
>
1343 Err(Error
::invalid_type(Unexpected
::Signed(v
), &self))
1346 serde_if_integer128
! {
1347 /// The input contains a `i128`.
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
>
1356 Err(Error
::invalid_type(Unexpected
::Other("i128"), &self))
1360 /// The input contains a `u8`.
1362 /// The default implementation forwards to [`visit_u64`].
1364 /// [`visit_u64`]: #method.visit_u64
1365 fn visit_u8
<E
>(self, v
: u8) -> Result
<Self::Value
, E
>
1369 self.visit_u64(v
as u64)
1372 /// The input contains a `u16`.
1374 /// The default implementation forwards to [`visit_u64`].
1376 /// [`visit_u64`]: #method.visit_u64
1377 fn visit_u16
<E
>(self, v
: u16) -> Result
<Self::Value
, E
>
1381 self.visit_u64(v
as u64)
1384 /// The input contains a `u32`.
1386 /// The default implementation forwards to [`visit_u64`].
1388 /// [`visit_u64`]: #method.visit_u64
1389 fn visit_u32
<E
>(self, v
: u32) -> Result
<Self::Value
, E
>
1393 self.visit_u64(v
as u64)
1396 /// The input contains a `u64`.
1398 /// The default implementation fails with a type error.
1399 fn visit_u64
<E
>(self, v
: u64) -> Result
<Self::Value
, E
>
1403 Err(Error
::invalid_type(Unexpected
::Unsigned(v
), &self))
1406 serde_if_integer128
! {
1407 /// The input contains a `u128`.
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
>
1416 Err(Error
::invalid_type(Unexpected
::Other("u128"), &self))
1420 /// The input contains an `f32`.
1422 /// The default implementation forwards to [`visit_f64`].
1424 /// [`visit_f64`]: #method.visit_f64
1425 fn visit_f32
<E
>(self, v
: f32) -> Result
<Self::Value
, E
>
1429 self.visit_f64(v
as f64)
1432 /// The input contains an `f64`.
1434 /// The default implementation fails with a type error.
1435 fn visit_f64
<E
>(self, v
: f64) -> Result
<Self::Value
, E
>
1439 Err(Error
::invalid_type(Unexpected
::Float(v
), &self))
1442 /// The input contains a `char`.
1444 /// The default implementation forwards to [`visit_str`] as a one-character
1447 /// [`visit_str`]: #method.visit_str
1449 fn visit_char
<E
>(self, v
: char) -> Result
<Self::Value
, E
>
1453 self.visit_str(utf8
::encode(v
).as_str())
1456 /// The input contains a string. The lifetime of the string is ephemeral and
1457 /// it may be destroyed after this method returns.
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`.
1465 /// It is never correct to implement `visit_string` without implementing
1466 /// `visit_str`. Implement neither, both, or just `visit_str`.
1467 fn visit_str
<E
>(self, v
: &str) -> Result
<Self::Value
, E
>
1471 Err(Error
::invalid_type(Unexpected
::Str(v
), &self))
1474 /// The input contains a string that lives at least as long as the
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`.
1482 /// The default implementation forwards to `visit_str`.
1484 fn visit_borrowed_str
<E
>(self, v
: &'de
str) -> Result
<Self::Value
, E
>
1491 /// The input contains a string and ownership of the string is being given
1492 /// to the `Visitor`.
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.
1501 /// It is never correct to implement `visit_string` without implementing
1502 /// `visit_str`. Implement neither, both, or just `visit_str`.
1504 /// The default implementation forwards to `visit_str` and then drops the
1507 #[cfg(any(feature = "std", feature = "alloc"))]
1508 fn visit_string
<E
>(self, v
: String
) -> Result
<Self::Value
, E
>
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.
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`.
1524 /// It is never correct to implement `visit_byte_buf` without implementing
1525 /// `visit_bytes`. Implement neither, both, or just `visit_bytes`.
1526 fn visit_bytes
<E
>(self, v
: &[u8]) -> Result
<Self::Value
, E
>
1531 Err(Error
::invalid_type(Unexpected
::Bytes(v
), &self))
1534 /// The input contains a byte array that lives at least as long as the
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`.
1541 /// The default implementation forwards to `visit_bytes`.
1543 fn visit_borrowed_bytes
<E
>(self, v
: &'de
[u8]) -> Result
<Self::Value
, E
>
1550 /// The input contains a byte array and ownership of the byte array is being
1551 /// given to the `Visitor`.
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.
1561 /// It is never correct to implement `visit_byte_buf` without implementing
1562 /// `visit_bytes`. Implement neither, both, or just `visit_bytes`.
1564 /// The default implementation forwards to `visit_bytes` and then drops the
1566 #[cfg(any(feature = "std", feature = "alloc"))]
1567 fn visit_byte_buf
<E
>(self, v
: Vec
<u8>) -> Result
<Self::Value
, E
>
1571 self.visit_bytes(&v
)
1574 /// The input contains an optional that is absent.
1576 /// The default implementation fails with a type error.
1577 fn visit_none
<E
>(self) -> Result
<Self::Value
, E
>
1581 Err(Error
::invalid_type(Unexpected
::Option
, &self))
1584 /// The input contains an optional that is present.
1586 /// The default implementation fails with a type error.
1587 fn visit_some
<D
>(self, deserializer
: D
) -> Result
<Self::Value
, D
::Error
>
1589 D
: Deserializer
<'de
>,
1591 let _
= deserializer
;
1592 Err(Error
::invalid_type(Unexpected
::Option
, &self))
1595 /// The input contains a unit `()`.
1597 /// The default implementation fails with a type error.
1598 fn visit_unit
<E
>(self) -> Result
<Self::Value
, E
>
1602 Err(Error
::invalid_type(Unexpected
::Unit
, &self))
1605 /// The input contains a newtype struct.
1607 /// The content of the newtype struct may be read from the given
1610 /// The default implementation fails with a type error.
1611 fn visit_newtype_struct
<D
>(self, deserializer
: D
) -> Result
<Self::Value
, D
::Error
>
1613 D
: Deserializer
<'de
>,
1615 let _
= deserializer
;
1616 Err(Error
::invalid_type(Unexpected
::NewtypeStruct
, &self))
1619 /// The input contains a sequence of elements.
1621 /// The default implementation fails with a type error.
1622 fn visit_seq
<A
>(self, seq
: A
) -> Result
<Self::Value
, A
::Error
>
1627 Err(Error
::invalid_type(Unexpected
::Seq
, &self))
1630 /// The input contains a key-value map.
1632 /// The default implementation fails with a type error.
1633 fn visit_map
<A
>(self, map
: A
) -> Result
<Self::Value
, A
::Error
>
1638 Err(Error
::invalid_type(Unexpected
::Map
, &self))
1641 /// The input contains an enum.
1643 /// The default implementation fails with a type error.
1644 fn visit_enum
<A
>(self, data
: A
) -> Result
<Self::Value
, A
::Error
>
1649 Err(Error
::invalid_type(Unexpected
::Enum
, &self))
1652 // Used when deserializing a flattened Option field. Not public API.
1654 fn __private_visit_untagged_option
<D
>(self, _
: D
) -> Result
<Self::Value
, ()>
1656 D
: Deserializer
<'de
>,
1662 ////////////////////////////////////////////////////////////////////////////////
1664 /// Provides a `Visitor` access to each element of a sequence in the input.
1666 /// This is a trait that a `Deserializer` passes to a `Visitor` implementation,
1667 /// which deserializes each item in a sequence.
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.
1675 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1677 /// # Example implementation
1679 /// The [example data format] presented on the website demonstrates an
1680 /// implementation of `SeqAccess` for a basic JSON data format.
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.
1688 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1689 /// `Ok(None)` if there are no more remaining items.
1691 /// `Deserialize` implementations should typically use
1692 /// `SeqAccess::next_element` instead.
1693 fn next_element_seed
<T
>(&mut self, seed
: T
) -> Result
<Option
<T
::Value
>, Self::Error
>
1695 T
: DeserializeSeed
<'de
>;
1697 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1698 /// `Ok(None)` if there are no more remaining items.
1700 /// This method exists as a convenience for `Deserialize` implementations.
1701 /// `SeqAccess` implementations should not override the default behavior.
1703 fn next_element
<T
>(&mut self) -> Result
<Option
<T
>, Self::Error
>
1705 T
: Deserialize
<'de
>,
1707 self.next_element_seed(PhantomData
)
1710 /// Returns the number of elements remaining in the sequence, if known.
1712 fn size_hint(&self) -> Option
<usize> {
1717 impl<'de
, 'a
, A
> SeqAccess
<'de
> for &'a
mut A
1721 type Error
= A
::Error
;
1724 fn next_element_seed
<T
>(&mut self, seed
: T
) -> Result
<Option
<T
::Value
>, Self::Error
>
1726 T
: DeserializeSeed
<'de
>,
1728 (**self).next_element_seed(seed
)
1732 fn next_element
<T
>(&mut self) -> Result
<Option
<T
>, Self::Error
>
1734 T
: Deserialize
<'de
>,
1736 (**self).next_element()
1740 fn size_hint(&self) -> Option
<usize> {
1741 (**self).size_hint()
1745 ////////////////////////////////////////////////////////////////////////////////
1747 /// Provides a `Visitor` access to each entry of a map in the input.
1749 /// This is a trait that a `Deserializer` passes to a `Visitor` implementation.
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.
1757 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1759 /// # Example implementation
1761 /// The [example data format] presented on the website demonstrates an
1762 /// implementation of `MapAccess` for a basic JSON data format.
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.
1770 /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
1771 /// if there are no more remaining entries.
1773 /// `Deserialize` implementations should typically use
1774 /// `MapAccess::next_key` or `MapAccess::next_entry` instead.
1775 fn next_key_seed
<K
>(&mut self, seed
: K
) -> Result
<Option
<K
::Value
>, Self::Error
>
1777 K
: DeserializeSeed
<'de
>;
1779 /// This returns a `Ok(value)` for the next value in the map.
1781 /// `Deserialize` implementations should typically use
1782 /// `MapAccess::next_value` instead.
1786 /// Calling `next_value_seed` before `next_key_seed` is incorrect and is
1787 /// allowed to panic or return bogus results.
1788 fn next_value_seed
<V
>(&mut self, seed
: V
) -> Result
<V
::Value
, Self::Error
>
1790 V
: DeserializeSeed
<'de
>;
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.
1795 /// `MapAccess` implementations should override the default behavior if a
1796 /// more efficient implementation is possible.
1798 /// `Deserialize` implementations should typically use
1799 /// `MapAccess::next_entry` instead.
1801 fn next_entry_seed
<K
, V
>(
1805 ) -> Result
<Option
<(K
::Value
, V
::Value
)>, Self::Error
>
1807 K
: DeserializeSeed
<'de
>,
1808 V
: DeserializeSeed
<'de
>,
1810 match try
!(self.next_key_seed(kseed
)) {
1812 let value
= try
!(self.next_value_seed(vseed
));
1813 Ok(Some((key
, value
)))
1819 /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
1820 /// if there are no more remaining entries.
1822 /// This method exists as a convenience for `Deserialize` implementations.
1823 /// `MapAccess` implementations should not override the default behavior.
1825 fn next_key
<K
>(&mut self) -> Result
<Option
<K
>, Self::Error
>
1827 K
: Deserialize
<'de
>,
1829 self.next_key_seed(PhantomData
)
1832 /// This returns a `Ok(value)` for the next value in the map.
1834 /// This method exists as a convenience for `Deserialize` implementations.
1835 /// `MapAccess` implementations should not override the default behavior.
1839 /// Calling `next_value` before `next_key` is incorrect and is allowed to
1840 /// panic or return bogus results.
1842 fn next_value
<V
>(&mut self) -> Result
<V
, Self::Error
>
1844 V
: Deserialize
<'de
>,
1846 self.next_value_seed(PhantomData
)
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.
1852 /// This method exists as a convenience for `Deserialize` implementations.
1853 /// `MapAccess` implementations should not override the default behavior.
1855 fn next_entry
<K
, V
>(&mut self) -> Result
<Option
<(K
, V
)>, Self::Error
>
1857 K
: Deserialize
<'de
>,
1858 V
: Deserialize
<'de
>,
1860 self.next_entry_seed(PhantomData
, PhantomData
)
1863 /// Returns the number of entries remaining in the map, if known.
1865 fn size_hint(&self) -> Option
<usize> {
1870 impl<'de
, 'a
, A
> MapAccess
<'de
> for &'a
mut A
1874 type Error
= A
::Error
;
1877 fn next_key_seed
<K
>(&mut self, seed
: K
) -> Result
<Option
<K
::Value
>, Self::Error
>
1879 K
: DeserializeSeed
<'de
>,
1881 (**self).next_key_seed(seed
)
1885 fn next_value_seed
<V
>(&mut self, seed
: V
) -> Result
<V
::Value
, Self::Error
>
1887 V
: DeserializeSeed
<'de
>,
1889 (**self).next_value_seed(seed
)
1893 fn next_entry_seed
<K
, V
>(
1897 ) -> Result
<Option
<(K
::Value
, V
::Value
)>, Self::Error
>
1899 K
: DeserializeSeed
<'de
>,
1900 V
: DeserializeSeed
<'de
>,
1902 (**self).next_entry_seed(kseed
, vseed
)
1906 fn next_entry
<K
, V
>(&mut self) -> Result
<Option
<(K
, V
)>, Self::Error
>
1908 K
: Deserialize
<'de
>,
1909 V
: Deserialize
<'de
>,
1911 (**self).next_entry()
1915 fn next_key
<K
>(&mut self) -> Result
<Option
<K
>, Self::Error
>
1917 K
: Deserialize
<'de
>,
1923 fn next_value
<V
>(&mut self) -> Result
<V
, Self::Error
>
1925 V
: Deserialize
<'de
>,
1927 (**self).next_value()
1931 fn size_hint(&self) -> Option
<usize> {
1932 (**self).size_hint()
1936 ////////////////////////////////////////////////////////////////////////////////
1938 /// Provides a `Visitor` access to the data of an enum in the input.
1940 /// `EnumAccess` is created by the `Deserializer` and passed to the
1941 /// `Visitor` in order to identify which variant of an enum to deserialize.
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.
1949 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1951 /// # Example implementation
1953 /// The [example data format] presented on the website demonstrates an
1954 /// implementation of `EnumAccess` for a basic JSON data format.
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.
1961 /// The `Visitor` that will be used to deserialize the content of the enum
1963 type Variant
: VariantAccess
<'de
, Error
= Self::Error
>;
1965 /// `variant` is called to identify which variant to deserialize.
1967 /// `Deserialize` implementations should typically use `EnumAccess::variant`
1969 fn variant_seed
<V
>(self, seed
: V
) -> Result
<(V
::Value
, Self::Variant
), Self::Error
>
1971 V
: DeserializeSeed
<'de
>;
1973 /// `variant` is called to identify which variant to deserialize.
1975 /// This method exists as a convenience for `Deserialize` implementations.
1976 /// `EnumAccess` implementations should not override the default behavior.
1978 fn variant
<V
>(self) -> Result
<(V
, Self::Variant
), Self::Error
>
1980 V
: Deserialize
<'de
>,
1982 self.variant_seed(PhantomData
)
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
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.
1996 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1998 /// # Example implementation
2000 /// The [example data format] presented on the website demonstrates an
2001 /// implementation of `VariantAccess` for a basic JSON data format.
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`.
2009 /// Called when deserializing a variant with no values.
2011 /// If the data contains a different type of variant, the following
2012 /// `invalid_type` error should be constructed:
2015 /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
2019 /// # impl<'de> VariantAccess<'de> for X {
2020 /// # type Error = value::Error;
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"))
2028 /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
2030 /// # T: DeserializeSeed<'de>,
2031 /// # { unimplemented!() }
2033 /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
2035 /// # V: Visitor<'de>,
2036 /// # { unimplemented!() }
2038 /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
2040 /// # V: Visitor<'de>,
2041 /// # { unimplemented!() }
2044 fn unit_variant(self) -> Result
<(), Self::Error
>;
2046 /// Called when deserializing a variant with a single value.
2048 /// `Deserialize` implementations should typically use
2049 /// `VariantAccess::newtype_variant` instead.
2051 /// If the data contains a different type of variant, the following
2052 /// `invalid_type` error should be constructed:
2055 /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
2059 /// # impl<'de> VariantAccess<'de> for X {
2060 /// # type Error = value::Error;
2062 /// # fn unit_variant(self) -> Result<(), Self::Error> {
2063 /// # unimplemented!()
2066 /// fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
2068 /// T: DeserializeSeed<'de>,
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"))
2075 /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
2077 /// # V: Visitor<'de>,
2078 /// # { unimplemented!() }
2080 /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
2082 /// # V: Visitor<'de>,
2083 /// # { unimplemented!() }
2086 fn newtype_variant_seed
<T
>(self, seed
: T
) -> Result
<T
::Value
, Self::Error
>
2088 T
: DeserializeSeed
<'de
>;
2090 /// Called when deserializing a variant with a single value.
2092 /// This method exists as a convenience for `Deserialize` implementations.
2093 /// `VariantAccess` implementations should not override the default
2096 fn newtype_variant
<T
>(self) -> Result
<T
, Self::Error
>
2098 T
: Deserialize
<'de
>,
2100 self.newtype_variant_seed(PhantomData
)
2103 /// Called when deserializing a tuple-like variant.
2105 /// The `len` is the number of fields expected in the tuple variant.
2107 /// If the data contains a different type of variant, the following
2108 /// `invalid_type` error should be constructed:
2111 /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
2115 /// # impl<'de> VariantAccess<'de> for X {
2116 /// # type Error = value::Error;
2118 /// # fn unit_variant(self) -> Result<(), Self::Error> {
2119 /// # unimplemented!()
2122 /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
2124 /// # T: DeserializeSeed<'de>,
2125 /// # { unimplemented!() }
2127 /// fn tuple_variant<V>(
2131 /// ) -> Result<V::Value, Self::Error>
2133 /// V: Visitor<'de>,
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"))
2140 /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
2142 /// # V: Visitor<'de>,
2143 /// # { unimplemented!() }
2146 fn tuple_variant
<V
>(self, len
: usize, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
2150 /// Called when deserializing a struct-like variant.
2152 /// The `fields` are the names of the fields of the struct variant.
2154 /// If the data contains a different type of variant, the following
2155 /// `invalid_type` error should be constructed:
2158 /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
2162 /// # impl<'de> VariantAccess<'de> for X {
2163 /// # type Error = value::Error;
2165 /// # fn unit_variant(self) -> Result<(), Self::Error> {
2166 /// # unimplemented!()
2169 /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
2171 /// # T: DeserializeSeed<'de>,
2172 /// # { unimplemented!() }
2174 /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
2176 /// # V: Visitor<'de>,
2177 /// # { unimplemented!() }
2179 /// fn struct_variant<V>(
2181 /// _fields: &'static [&'static str],
2183 /// ) -> Result<V::Value, Self::Error>
2185 /// V: Visitor<'de>,
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"))
2193 fn struct_variant
<V
>(
2195 fields
: &'
static [&'
static str],
2197 ) -> Result
<V
::Value
, Self::Error
>
2202 ////////////////////////////////////////////////////////////////////////////////
2204 /// Converts an existing value into a `Deserializer` from which other values can
2205 /// be deserialized.
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.
2213 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
2218 /// use std::str::FromStr;
2219 /// use serde::Deserialize;
2220 /// use serde::de::{value, IntoDeserializer};
2222 /// #[derive(Deserialize)]
2228 /// impl FromStr for Setting {
2229 /// type Err = value::Error;
2231 /// fn from_str(s: &str) -> Result<Self, Self::Err> {
2232 /// Self::deserialize(s.into_deserializer())
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
>;
2240 /// Convert this value into a deserializer.
2241 fn into_deserializer(self) -> Self::Deserializer
;
2244 ////////////////////////////////////////////////////////////////////////////////
2246 /// Used in error messages.
2249 /// - expected `a` or `b`
2250 /// - expected one of `a`, `b`, `c`
2252 /// The slice of names must not be empty.
2254 names
: &'
static [&'
static str],
2257 impl Display
for OneOf
{
2258 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]),
2264 try
!(write
!(formatter
, "one of "));
2265 for (i
, alt
) in self.names
.iter().enumerate() {
2267 try
!(write
!(formatter
, ", "));
2269 try
!(write
!(formatter
, "`{}`", alt
));