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 ////////////////////////////////////////////////////////////////////////////////
126 pub use self::ignored_any
::IgnoredAny
;
128 #[cfg(feature = "std")]
130 pub use std
::error
::Error
as StdError
;
131 #[cfg(not(feature = "std"))]
133 pub use std_error
::Error
as StdError
;
135 ////////////////////////////////////////////////////////////////////////////////
137 macro_rules
! declare_error_trait
{
138 (Error
: Sized $
(+ $
($supertrait
:ident
)::+)*) => {
139 /// The `Error` trait allows `Deserialize` implementations to create descriptive
140 /// error messages belonging to the `Deserializer` against which they are
141 /// currently running.
143 /// Every `Deserializer` declares an `Error` type that encompasses both
144 /// general-purpose deserialization errors as well as errors specific to the
145 /// particular deserialization format. For example the `Error` type of
146 /// `serde_json` can represent errors like an invalid JSON escape sequence or an
147 /// unterminated string literal, in addition to the error cases that are part of
150 /// Most deserializers should only need to provide the `Error::custom` method
151 /// and inherit the default behavior for the other methods.
153 /// # Example implementation
155 /// The [example data format] presented on the website shows an error
156 /// type appropriate for a basic JSON data format.
158 /// [example data format]: https://serde.rs/data-format.html
159 pub trait Error
: Sized $
(+ $
($supertrait
)::+)* {
160 /// Raised when there is general error when deserializing a type.
162 /// The message should not be capitalized and should not end with a period.
165 /// # use std::str::FromStr;
169 /// # impl FromStr for IpAddr {
170 /// # type Err = String;
172 /// # fn from_str(_: &str) -> Result<Self, String> {
173 /// # unimplemented!()
177 /// use serde::de::{self, Deserialize, Deserializer};
179 /// impl<'de> Deserialize<'de> for IpAddr {
180 /// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
182 /// D: Deserializer<'de>,
184 /// let s = String::deserialize(deserializer)?;
185 /// s.parse().map_err(de::Error::custom)
189 fn custom
<T
>(msg
: T
) -> Self
193 /// Raised when a `Deserialize` receives a type different from what it was
196 /// The `unexp` argument provides information about what type was received.
197 /// This is the type that was present in the input file or other source data
198 /// of the Deserializer.
200 /// The `exp` argument provides information about what type was being
201 /// expected. This is the type that is written in the program.
203 /// For example if we try to deserialize a String out of a JSON file
204 /// containing an integer, the unexpected type is the integer and the
205 /// expected type is the string.
207 fn invalid_type(unexp
: Unexpected
, exp
: &Expected
) -> Self {
208 Error
::custom(format_args
!("invalid type: {}, expected {}", unexp
, exp
))
211 /// Raised when a `Deserialize` receives a value of the right type but that
212 /// is wrong for some other reason.
214 /// The `unexp` argument provides information about what value was received.
215 /// This is the value that was present in the input file or other source
216 /// data of the Deserializer.
218 /// The `exp` argument provides information about what value was being
219 /// expected. This is the type that is written in the program.
221 /// For example if we try to deserialize a String out of some binary data
222 /// that is not valid UTF-8, the unexpected value is the bytes and the
223 /// expected value is a string.
225 fn invalid_value(unexp
: Unexpected
, exp
: &Expected
) -> Self {
226 Error
::custom(format_args
!("invalid value: {}, expected {}", unexp
, exp
))
229 /// Raised when deserializing a sequence or map and the input data contains
230 /// too many or too few elements.
232 /// The `len` argument is the number of elements encountered. The sequence
233 /// or map may have expected more arguments or fewer arguments.
235 /// The `exp` argument provides information about what data was being
236 /// expected. For example `exp` might say that a tuple of size 6 was
239 fn invalid_length(len
: usize, exp
: &Expected
) -> Self {
240 Error
::custom(format_args
!("invalid length {}, expected {}", len
, exp
))
243 /// Raised when a `Deserialize` enum type received a variant with an
244 /// unrecognized name.
246 fn unknown_variant(variant
: &str, expected
: &'
static [&'
static str]) -> Self {
247 if expected
.is_empty() {
248 Error
::custom(format_args
!(
249 "unknown variant `{}`, there are no variants",
253 Error
::custom(format_args
!(
254 "unknown variant `{}`, expected {}",
256 OneOf { names: expected }
261 /// Raised when a `Deserialize` struct type received a field with an
262 /// unrecognized name.
264 fn unknown_field(field
: &str, expected
: &'
static [&'
static str]) -> Self {
265 if expected
.is_empty() {
266 Error
::custom(format_args
!(
267 "unknown field `{}`, there are no fields",
271 Error
::custom(format_args
!(
272 "unknown field `{}`, expected {}",
274 OneOf { names: expected }
279 /// Raised when a `Deserialize` struct type expected to receive a required
280 /// field with a particular name but that field was not present in the
283 fn missing_field(field
: &'
static str) -> Self {
284 Error
::custom(format_args
!("missing field `{}`", field
))
287 /// Raised when a `Deserialize` struct type received more than one of the
290 fn duplicate_field(field
: &'
static str) -> Self {
291 Error
::custom(format_args
!("duplicate field `{}`", field
))
297 #[cfg(feature = "std")]
298 declare_error_trait
!(Error
: Sized
+ StdError
);
300 #[cfg(not(feature = "std"))]
301 declare_error_trait
!(Error
: Sized
+ Debug
+ Display
);
303 /// `Unexpected` represents an unexpected invocation of any one of the `Visitor`
306 /// This is used as an argument to the `invalid_type`, `invalid_value`, and
307 /// `invalid_length` methods of the `Error` trait to build error messages.
312 /// # use serde::de::{self, Unexpected, Visitor};
314 /// # struct Example;
316 /// # impl<'de> Visitor<'de> for Example {
317 /// # type Value = ();
319 /// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
320 /// # write!(formatter, "definitely not a boolean")
323 /// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
327 /// Err(de::Error::invalid_type(Unexpected::Bool(v), &self))
331 #[derive(Copy, Clone, PartialEq, Debug)]
332 pub enum Unexpected
<'a
> {
333 /// The input contained a boolean value that was not expected.
336 /// The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that
337 /// was not expected.
340 /// The input contained a signed integer `i8`, `i16`, `i32` or `i64` that
341 /// was not expected.
344 /// The input contained a floating point `f32` or `f64` that was not
348 /// The input contained a `char` that was not expected.
351 /// The input contained a `&str` or `String` that was not expected.
354 /// The input contained a `&[u8]` or `Vec<u8>` that was not expected.
357 /// The input contained a unit `()` that was not expected.
360 /// The input contained an `Option<T>` that was not expected.
363 /// The input contained a newtype struct that was not expected.
366 /// The input contained a sequence that was not expected.
369 /// The input contained a map that was not expected.
372 /// The input contained an enum that was not expected.
375 /// The input contained a unit variant that was not expected.
378 /// The input contained a newtype variant that was not expected.
381 /// The input contained a tuple variant that was not expected.
384 /// The input contained a struct variant that was not expected.
387 /// A message stating what uncategorized thing the input contained that was
390 /// The message should be a noun or noun phrase, not capitalized and without
391 /// a period. An example message is "unoriginal superhero".
395 impl<'a
> fmt
::Display
for Unexpected
<'a
> {
396 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> Result
<(), fmt
::Error
> {
397 use self::Unexpected
::*;
399 Bool(b
) => write
!(formatter
, "boolean `{}`", b
),
400 Unsigned(i
) => write
!(formatter
, "integer `{}`", i
),
401 Signed(i
) => write
!(formatter
, "integer `{}`", i
),
402 Float(f
) => write
!(formatter
, "floating point `{}`", f
),
403 Char(c
) => write
!(formatter
, "character `{}`", c
),
404 Str(s
) => write
!(formatter
, "string {:?}", s
),
405 Bytes(_
) => write
!(formatter
, "byte array"),
406 Unit
=> write
!(formatter
, "unit value"),
407 Option
=> write
!(formatter
, "Option value"),
408 NewtypeStruct
=> write
!(formatter
, "newtype struct"),
409 Seq
=> write
!(formatter
, "sequence"),
410 Map
=> write
!(formatter
, "map"),
411 Enum
=> write
!(formatter
, "enum"),
412 UnitVariant
=> write
!(formatter
, "unit variant"),
413 NewtypeVariant
=> write
!(formatter
, "newtype variant"),
414 TupleVariant
=> write
!(formatter
, "tuple variant"),
415 StructVariant
=> write
!(formatter
, "struct variant"),
416 Other(other
) => formatter
.write_str(other
),
421 /// `Expected` represents an explanation of what data a `Visitor` was expecting
424 /// This is used as an argument to the `invalid_type`, `invalid_value`, and
425 /// `invalid_length` methods of the `Error` trait to build error messages. The
426 /// message should be a noun or noun phrase that completes the sentence "This
427 /// Visitor expects to receive ...", for example the message could be "an
428 /// integer between 0 and 64". The message should not be capitalized and should
429 /// not end with a period.
431 /// Within the context of a `Visitor` implementation, the `Visitor` itself
432 /// (`&self`) is an implementation of this trait.
437 /// # use serde::de::{self, Unexpected, Visitor};
439 /// # struct Example;
441 /// # impl<'de> Visitor<'de> for Example {
442 /// # type Value = ();
444 /// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
445 /// # write!(formatter, "definitely not a boolean")
448 /// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
452 /// Err(de::Error::invalid_type(Unexpected::Bool(v), &self))
457 /// Outside of a `Visitor`, `&"..."` can be used.
460 /// # use serde::de::{self, Unexpected};
462 /// # fn example<E>() -> Result<(), E>
467 /// return Err(de::Error::invalid_type(Unexpected::Bool(v), &"a negative integer"));
471 /// Format an explanation of what data was being expected. Same signature as
472 /// the `Display` and `Debug` traits.
473 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
;
476 impl<'de
, T
> Expected
for T
480 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
481 self.expecting(formatter
)
485 impl<'a
> Expected
for &'a
str {
486 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
487 formatter
.write_str(self)
491 impl<'a
> Display
for Expected
+ 'a
{
492 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
493 Expected
::fmt(self, formatter
)
497 ////////////////////////////////////////////////////////////////////////////////
499 /// A **data structure** that can be deserialized from any data format supported
502 /// Serde provides `Deserialize` implementations for many Rust primitive and
503 /// standard library types. The complete list is [here][de]. All of these can
504 /// be deserialized using Serde out of the box.
506 /// Additionally, Serde provides a procedural macro called `serde_derive` to
507 /// automatically generate `Deserialize` implementations for structs and enums
508 /// in your program. See the [derive section of the manual][derive] for how to
511 /// In rare cases it may be necessary to implement `Deserialize` manually for
512 /// some type in your program. See the [Implementing
513 /// `Deserialize`][impl-deserialize] section of the manual for more about this.
515 /// Third-party crates may provide `Deserialize` implementations for types that
516 /// they expose. For example the `linked-hash-map` crate provides a
517 /// `LinkedHashMap<K, V>` type that is deserializable by Serde because the crate
518 /// provides an implementation of `Deserialize` for it.
520 /// [de]: https://docs.serde.rs/serde/de/index.html
521 /// [derive]: https://serde.rs/derive.html
522 /// [impl-deserialize]: https://serde.rs/impl-deserialize.html
526 /// The `'de` lifetime of this trait is the lifetime of data that may be
527 /// borrowed by `Self` when deserialized. See the page [Understanding
528 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
530 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
531 pub trait Deserialize
<'de
>: Sized
{
532 /// Deserialize this value from the given Serde deserializer.
534 /// See the [Implementing `Deserialize`][impl-deserialize] section of the
535 /// manual for more information about how to implement this method.
537 /// [impl-deserialize]: https://serde.rs/impl-deserialize.html
538 fn deserialize
<D
>(deserializer
: D
) -> Result
<Self, D
::Error
>
540 D
: Deserializer
<'de
>;
542 /// Deserializes a value into `self` from the given Deserializer.
544 /// The purpose of this method is to allow the deserializer to reuse
545 /// resources and avoid copies. As such, if this method returns an error,
546 /// `self` will be in an indeterminate state where some parts of the struct
547 /// have been overwritten. Although whatever state that is will be
550 /// This is generally useful when repeatedly deserializing values that
551 /// are processed one at a time, where the value of `self` doesn't matter
552 /// when the next deserialization occurs.
554 /// If you manually implement this, your recursive deserializations should
555 /// use `deserialize_in_place`.
557 /// This method is stable and an official public API, but hidden from the
558 /// documentation because it is almost never what newbies are looking for.
559 /// Showing it in rustdoc would cause it to be featured more prominently
560 /// than it deserves.
562 fn deserialize_in_place
<D
>(deserializer
: D
, place
: &mut Self) -> Result
<(), D
::Error
>
564 D
: Deserializer
<'de
>,
566 // Default implementation just delegates to `deserialize` impl.
567 *place
= Deserialize
::deserialize(deserializer
)?
;
572 /// A data structure that can be deserialized without borrowing any data from
573 /// the deserializer.
575 /// This is primarily useful for trait bounds on functions. For example a
576 /// `from_str` function may be able to deserialize a data structure that borrows
577 /// from the input string, but a `from_reader` function may only deserialize
581 /// # use serde::de::{Deserialize, DeserializeOwned};
582 /// # use std::io::{Read, Result};
585 /// fn from_str<'a, T>(s: &'a str) -> Result<T>
587 /// T: Deserialize<'a>;
589 /// fn from_reader<R, T>(rdr: R) -> Result<T>
592 /// T: DeserializeOwned;
598 /// The relationship between `Deserialize` and `DeserializeOwned` in trait
599 /// bounds is explained in more detail on the page [Understanding deserializer
602 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
603 pub trait DeserializeOwned
: for<'de
> Deserialize
<'de
> {}
604 impl<T
> DeserializeOwned
for T
where T
: for<'de
> Deserialize
<'de
> {}
606 /// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you
607 /// ever find yourself looking for a way to pass data into a `Deserialize` impl,
608 /// this trait is the way to do it.
610 /// As one example of stateful deserialization consider deserializing a JSON
611 /// array into an existing buffer. Using the `Deserialize` trait we could
612 /// deserialize a JSON array into a `Vec<T>` but it would be a freshly allocated
613 /// `Vec<T>`; there is no way for `Deserialize` to reuse a previously allocated
614 /// buffer. Using `DeserializeSeed` instead makes this possible as in the
615 /// example code below.
617 /// The canonical API for stateless deserialization looks like this:
620 /// # use serde::Deserialize;
624 /// fn func<'de, T: Deserialize<'de>>() -> Result<T, Error>
626 /// # unimplemented!()
630 /// Adjusting an API like this to support stateful deserialization is a matter
631 /// of accepting a seed as input:
634 /// # use serde::de::DeserializeSeed;
638 /// fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result<T::Value, Error>
641 /// # unimplemented!()
645 /// In practice the majority of deserialization is stateless. An API expecting a
646 /// seed can be appeased by passing `std::marker::PhantomData` as a seed in the
647 /// case of stateless deserialization.
651 /// The `'de` lifetime of this trait is the lifetime of data that may be
652 /// borrowed by `Self::Value` when deserialized. See the page [Understanding
653 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
655 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
659 /// Suppose we have JSON that looks like `[[1, 2], [3, 4, 5], [6]]` and we need
660 /// to deserialize it into a flat representation like `vec![1, 2, 3, 4, 5, 6]`.
661 /// Allocating a brand new `Vec<T>` for each subarray would be slow. Instead we
662 /// would like to allocate a single `Vec<T>` and then deserialize each subarray
663 /// into it. This requires stateful deserialization using the `DeserializeSeed`
668 /// use std::marker::PhantomData;
670 /// use serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor};
672 /// // A DeserializeSeed implementation that uses stateful deserialization to
673 /// // append array elements onto the end of an existing vector. The preexisting
674 /// // state ("seed") in this case is the Vec<T>. The `deserialize` method of
675 /// // `ExtendVec` will be traversing the inner arrays of the JSON input and
676 /// // appending each integer into the existing Vec.
677 /// struct ExtendVec<'a, T: 'a>(&'a mut Vec<T>);
679 /// impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T>
681 /// T: Deserialize<'de>,
683 /// // The return type of the `deserialize` method. This implementation
684 /// // appends onto an existing vector but does not create any new data
685 /// // structure, so the return type is ().
688 /// fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
690 /// D: Deserializer<'de>,
692 /// // Visitor implementation that will walk an inner array of the JSON
694 /// struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec<T>);
696 /// impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T>
698 /// T: Deserialize<'de>,
702 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
703 /// write!(formatter, "an array of integers")
706 /// fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error>
708 /// A: SeqAccess<'de>,
710 /// // Visit each element in the inner array and push it onto
711 /// // the existing vector.
712 /// while let Some(elem) = seq.next_element()? {
713 /// self.0.push(elem);
719 /// deserializer.deserialize_seq(ExtendVecVisitor(self.0))
723 /// // Visitor implementation that will walk the outer array of the JSON input.
724 /// struct FlattenedVecVisitor<T>(PhantomData<T>);
726 /// impl<'de, T> Visitor<'de> for FlattenedVecVisitor<T>
728 /// T: Deserialize<'de>,
730 /// // This Visitor constructs a single Vec<T> to hold the flattened
731 /// // contents of the inner arrays.
732 /// type Value = Vec<T>;
734 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
735 /// write!(formatter, "an array of arrays")
738 /// fn visit_seq<A>(self, mut seq: A) -> Result<Vec<T>, A::Error>
740 /// A: SeqAccess<'de>,
742 /// // Create a single Vec to hold the flattened contents.
743 /// let mut vec = Vec::new();
745 /// // Each iteration through this loop is one inner array.
746 /// while let Some(()) = seq.next_element_seed(ExtendVec(&mut vec))? {
747 /// // Nothing to do; inner array has been appended into `vec`.
750 /// // Return the finished vec.
755 /// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error>
757 /// # D: Deserializer<'de>,
759 /// let visitor = FlattenedVecVisitor(PhantomData);
760 /// let flattened: Vec<u64> = deserializer.deserialize_seq(visitor)?;
764 pub trait DeserializeSeed
<'de
>: Sized
{
765 /// The type produced by using this seed.
768 /// Equivalent to the more common `Deserialize::deserialize` method, except
769 /// with some initial piece of data (the seed) passed in.
770 fn deserialize
<D
>(self, deserializer
: D
) -> Result
<Self::Value
, D
::Error
>
772 D
: Deserializer
<'de
>;
775 impl<'de
, T
> DeserializeSeed
<'de
> for PhantomData
<T
>
782 fn deserialize
<D
>(self, deserializer
: D
) -> Result
<T
, D
::Error
>
784 D
: Deserializer
<'de
>,
786 T
::deserialize(deserializer
)
790 ////////////////////////////////////////////////////////////////////////////////
792 /// A **data format** that can deserialize any data structure supported by
795 /// The role of this trait is to define the deserialization half of the [Serde
796 /// data model], which is a way to categorize every Rust data type into one of
797 /// 29 possible types. Each method of the `Deserializer` trait corresponds to one
798 /// of the types of the data model.
800 /// Implementations of `Deserialize` map themselves into this data model by
801 /// passing to the `Deserializer` a `Visitor` implementation that can receive
802 /// these various types.
804 /// The types that make up the Serde data model are:
806 /// - **14 primitive types**
808 /// - i8, i16, i32, i64, i128
809 /// - u8, u16, u32, u64, u128
813 /// - UTF-8 bytes with a length and no null terminator.
814 /// - When serializing, all strings are handled equally. When deserializing,
815 /// there are three flavors of strings: transient, owned, and borrowed.
816 /// - **byte array** - \[u8\]
817 /// - Similar to strings, during deserialization byte arrays can be
818 /// transient, owned, or borrowed.
820 /// - Either none or some value.
822 /// - The type of `()` in Rust. It represents an anonymous value containing
824 /// - **unit_struct**
825 /// - For example `struct Unit` or `PhantomData<T>`. It represents a named
826 /// value containing no data.
827 /// - **unit_variant**
828 /// - For example the `E::A` and `E::B` in `enum E { A, B }`.
829 /// - **newtype_struct**
830 /// - For example `struct Millimeters(u8)`.
831 /// - **newtype_variant**
832 /// - For example the `E::N` in `enum E { N(u8) }`.
834 /// - A variably sized heterogeneous sequence of values, for example `Vec<T>`
835 /// or `HashSet<T>`. When serializing, the length may or may not be known
836 /// before iterating through all the data. When deserializing, the length
837 /// is determined by looking at the serialized data.
839 /// - A statically sized heterogeneous sequence of values for which the
840 /// length will be known at deserialization time without looking at the
841 /// serialized data, for example `(u8,)` or `(String, u64, Vec<T>)` or
843 /// - **tuple_struct**
844 /// - A named tuple, for example `struct Rgb(u8, u8, u8)`.
845 /// - **tuple_variant**
846 /// - For example the `E::T` in `enum E { T(u8, u8) }`.
848 /// - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.
850 /// - A heterogeneous key-value pairing in which the keys are strings and
851 /// will be known at deserialization time without looking at the serialized
852 /// data, for example `struct S { r: u8, g: u8, b: u8 }`.
853 /// - **struct_variant**
854 /// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`.
856 /// The `Deserializer` trait supports two entry point styles which enables
857 /// different kinds of deserialization.
859 /// 1. The `deserialize` method. Self-describing data formats like JSON are able
860 /// to look at the serialized data and tell what it represents. For example
861 /// the JSON deserializer may see an opening curly brace (`{`) and know that
862 /// it is seeing a map. If the data format supports
863 /// `Deserializer::deserialize_any`, it will drive the Visitor using whatever
864 /// type it sees in the input. JSON uses this approach when deserializing
865 /// `serde_json::Value` which is an enum that can represent any JSON
866 /// document. Without knowing what is in a JSON document, we can deserialize
867 /// it to `serde_json::Value` by going through
868 /// `Deserializer::deserialize_any`.
870 /// 2. The various `deserialize_*` methods. Non-self-describing formats like
871 /// Bincode need to be told what is in the input in order to deserialize it.
872 /// The `deserialize_*` methods are hints to the deserializer for how to
873 /// interpret the next piece of input. Non-self-describing formats are not
874 /// able to deserialize something like `serde_json::Value` which relies on
875 /// `Deserializer::deserialize_any`.
877 /// When implementing `Deserialize`, you should avoid relying on
878 /// `Deserializer::deserialize_any` unless you need to be told by the
879 /// Deserializer what type is in the input. Know that relying on
880 /// `Deserializer::deserialize_any` means your data type will be able to
881 /// deserialize from self-describing formats only, ruling out Bincode and many
884 /// [Serde data model]: https://serde.rs/data-model.html
888 /// The `'de` lifetime of this trait is the lifetime of data that may be
889 /// borrowed from the input when deserializing. See the page [Understanding
890 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
892 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
894 /// # Example implementation
896 /// The [example data format] presented on the website contains example code for
897 /// a basic JSON `Deserializer`.
899 /// [example data format]: https://serde.rs/data-format.html
900 pub trait Deserializer
<'de
>: Sized
{
901 /// The error type that can be returned if some error occurs during
905 /// Require the `Deserializer` to figure out how to drive the visitor based
906 /// on what data type is in the input.
908 /// When implementing `Deserialize`, you should avoid relying on
909 /// `Deserializer::deserialize_any` unless you need to be told by the
910 /// Deserializer what type is in the input. Know that relying on
911 /// `Deserializer::deserialize_any` means your data type will be able to
912 /// deserialize from self-describing formats only, ruling out Bincode and
914 fn deserialize_any
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
918 /// Hint that the `Deserialize` type is expecting a `bool` value.
919 fn deserialize_bool
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
923 /// Hint that the `Deserialize` type is expecting an `i8` value.
924 fn deserialize_i8
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
928 /// Hint that the `Deserialize` type is expecting an `i16` value.
929 fn deserialize_i16
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
933 /// Hint that the `Deserialize` type is expecting an `i32` value.
934 fn deserialize_i32
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
938 /// Hint that the `Deserialize` type is expecting an `i64` value.
939 fn deserialize_i64
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
943 serde_if_integer128
! {
944 /// Hint that the `Deserialize` type is expecting an `i128` value.
946 /// This method is available only on Rust compiler versions >=1.26. The
947 /// default behavior unconditionally returns an error.
948 fn deserialize_i128
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
953 Err(Error
::custom("i128 is not supported"))
957 /// Hint that the `Deserialize` type is expecting a `u8` value.
958 fn deserialize_u8
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
962 /// Hint that the `Deserialize` type is expecting a `u16` value.
963 fn deserialize_u16
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
967 /// Hint that the `Deserialize` type is expecting a `u32` value.
968 fn deserialize_u32
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
972 /// Hint that the `Deserialize` type is expecting a `u64` value.
973 fn deserialize_u64
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
977 serde_if_integer128
! {
978 /// Hint that the `Deserialize` type is expecting an `u128` value.
980 /// This method is available only on Rust compiler versions >=1.26. The
981 /// default behavior unconditionally returns an error.
982 fn deserialize_u128
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
987 Err(Error
::custom("u128 is not supported"))
991 /// Hint that the `Deserialize` type is expecting a `f32` value.
992 fn deserialize_f32
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
996 /// Hint that the `Deserialize` type is expecting a `f64` value.
997 fn deserialize_f64
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1001 /// Hint that the `Deserialize` type is expecting a `char` value.
1002 fn deserialize_char
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1006 /// Hint that the `Deserialize` type is expecting a string value and does
1007 /// not benefit from taking ownership of buffered data owned by the
1010 /// If the `Visitor` would benefit from taking ownership of `String` data,
1011 /// indiciate this to the `Deserializer` by using `deserialize_string`
1013 fn deserialize_str
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1017 /// Hint that the `Deserialize` type is expecting a string value and would
1018 /// benefit from taking ownership of buffered data owned by the
1021 /// If the `Visitor` would not benefit from taking ownership of `String`
1022 /// data, indicate that to the `Deserializer` by using `deserialize_str`
1024 fn deserialize_string
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1028 /// Hint that the `Deserialize` type is expecting a byte array and does not
1029 /// benefit from taking ownership of buffered data owned by the
1032 /// If the `Visitor` would benefit from taking ownership of `Vec<u8>` data,
1033 /// indicate this to the `Deserializer` by using `deserialize_byte_buf`
1035 fn deserialize_bytes
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1039 /// Hint that the `Deserialize` type is expecting a byte array and would
1040 /// benefit from taking ownership of buffered data owned by the
1043 /// If the `Visitor` would not benefit from taking ownership of `Vec<u8>`
1044 /// data, indicate that to the `Deserializer` by using `deserialize_bytes`
1046 fn deserialize_byte_buf
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1050 /// Hint that the `Deserialize` type is expecting an optional value.
1052 /// This allows deserializers that encode an optional value as a nullable
1053 /// value to convert the null value into `None` and a regular value into
1055 fn deserialize_option
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1059 /// Hint that the `Deserialize` type is expecting a unit value.
1060 fn deserialize_unit
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1064 /// Hint that the `Deserialize` type is expecting a unit struct with a
1065 /// particular name.
1066 fn deserialize_unit_struct
<V
>(
1070 ) -> Result
<V
::Value
, Self::Error
>
1074 /// Hint that the `Deserialize` type is expecting a newtype struct with a
1075 /// particular name.
1076 fn deserialize_newtype_struct
<V
>(
1080 ) -> Result
<V
::Value
, Self::Error
>
1084 /// Hint that the `Deserialize` type is expecting a sequence of values.
1085 fn deserialize_seq
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1089 /// Hint that the `Deserialize` type is expecting a sequence of values and
1090 /// knows how many values there are without looking at the serialized data.
1091 fn deserialize_tuple
<V
>(self, len
: usize, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1095 /// Hint that the `Deserialize` type is expecting a tuple struct with a
1096 /// particular name and number of fields.
1097 fn deserialize_tuple_struct
<V
>(
1102 ) -> Result
<V
::Value
, Self::Error
>
1106 /// Hint that the `Deserialize` type is expecting a map of key-value pairs.
1107 fn deserialize_map
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1111 /// Hint that the `Deserialize` type is expecting a struct with a particular
1112 /// name and fields.
1113 fn deserialize_struct
<V
>(
1116 fields
: &'
static [&'
static str],
1118 ) -> Result
<V
::Value
, Self::Error
>
1122 /// Hint that the `Deserialize` type is expecting an enum value with a
1123 /// particular name and possible variants.
1124 fn deserialize_enum
<V
>(
1127 variants
: &'
static [&'
static str],
1129 ) -> Result
<V
::Value
, Self::Error
>
1133 /// Hint that the `Deserialize` type is expecting the name of a struct
1134 /// field or the discriminant of an enum variant.
1135 fn deserialize_identifier
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1139 /// Hint that the `Deserialize` type needs to deserialize a value whose type
1140 /// doesn't matter because it is ignored.
1142 /// Deserializers for non-self-describing formats may not support this mode.
1143 fn deserialize_ignored_any
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1147 /// Determine whether `Deserialize` implementations should expect to
1148 /// deserialize their human-readable form.
1150 /// Some types have a human-readable form that may be somewhat expensive to
1151 /// construct, as well as a binary form that is compact and efficient.
1152 /// Generally text-based formats like JSON and YAML will prefer to use the
1153 /// human-readable one and binary formats like Bincode will prefer the
1157 /// # use std::ops::Add;
1158 /// # use std::str::FromStr;
1160 /// # struct Timestamp;
1162 /// # impl Timestamp {
1163 /// # const EPOCH: Timestamp = Timestamp;
1166 /// # impl FromStr for Timestamp {
1167 /// # type Err = String;
1168 /// # fn from_str(_: &str) -> Result<Self, Self::Err> {
1169 /// # unimplemented!()
1173 /// # struct Duration;
1175 /// # impl Duration {
1176 /// # fn seconds(_: u64) -> Self { unimplemented!() }
1179 /// # impl Add<Duration> for Timestamp {
1180 /// # type Output = Timestamp;
1181 /// # fn add(self, _: Duration) -> Self::Output {
1182 /// # unimplemented!()
1186 /// use serde::de::{self, Deserialize, Deserializer};
1188 /// impl<'de> Deserialize<'de> for Timestamp {
1189 /// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1191 /// D: Deserializer<'de>,
1193 /// if deserializer.is_human_readable() {
1194 /// // Deserialize from a human-readable string like "2015-05-15T17:01:00Z".
1195 /// let s = String::deserialize(deserializer)?;
1196 /// Timestamp::from_str(&s).map_err(de::Error::custom)
1198 /// // Deserialize from a compact binary representation, seconds since
1199 /// // the Unix epoch.
1200 /// let n = u64::deserialize(deserializer)?;
1201 /// Ok(Timestamp::EPOCH + Duration::seconds(n))
1207 /// The default implementation of this method returns `true`. Data formats
1208 /// may override this to `false` to request a compact form for types that
1209 /// support one. Note that modifying this method to change a format from
1210 /// human-readable to compact or vice versa should be regarded as a breaking
1211 /// change, as a value serialized in human-readable mode is not required to
1212 /// deserialize from the same data in compact mode.
1214 fn is_human_readable(&self) -> bool
{
1219 ////////////////////////////////////////////////////////////////////////////////
1221 /// This trait represents a visitor that walks through a deserializer.
1225 /// The `'de` lifetime of this trait is the requirement for lifetime of data
1226 /// that may be borrowed by `Self::Value`. See the page [Understanding
1227 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1229 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1236 /// # use serde::de::{self, Unexpected, Visitor};
1238 /// /// A visitor that deserializes a long string - a string containing at least
1239 /// /// some minimum number of bytes.
1240 /// struct LongString {
1244 /// impl<'de> Visitor<'de> for LongString {
1245 /// type Value = String;
1247 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1248 /// write!(formatter, "a string containing at least {} bytes", self.min)
1251 /// fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
1255 /// if s.len() >= self.min {
1256 /// Ok(s.to_owned())
1258 /// Err(de::Error::invalid_value(Unexpected::Str(s), &self))
1263 pub trait Visitor
<'de
>: Sized
{
1264 /// The value produced by this visitor.
1267 /// Format a message stating what data this Visitor expects to receive.
1269 /// This is used in error messages. The message should complete the sentence
1270 /// "This Visitor expects to receive ...", for example the message could be
1271 /// "an integer between 0 and 64". The message should not be capitalized and
1272 /// should not end with a period.
1281 /// # impl<'de> serde::de::Visitor<'de> for S {
1282 /// # type Value = ();
1284 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1285 /// write!(formatter, "an integer between 0 and {}", self.max)
1289 fn expecting(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
;
1291 /// The input contains a boolean.
1293 /// The default implementation fails with a type error.
1294 fn visit_bool
<E
>(self, v
: bool
) -> Result
<Self::Value
, E
>
1298 Err(Error
::invalid_type(Unexpected
::Bool(v
), &self))
1301 /// The input contains an `i8`.
1303 /// The default implementation forwards to [`visit_i64`].
1305 /// [`visit_i64`]: #method.visit_i64
1306 fn visit_i8
<E
>(self, v
: i8) -> Result
<Self::Value
, E
>
1310 self.visit_i64(v
as i64)
1313 /// The input contains an `i16`.
1315 /// The default implementation forwards to [`visit_i64`].
1317 /// [`visit_i64`]: #method.visit_i64
1318 fn visit_i16
<E
>(self, v
: i16) -> Result
<Self::Value
, E
>
1322 self.visit_i64(v
as i64)
1325 /// The input contains an `i32`.
1327 /// The default implementation forwards to [`visit_i64`].
1329 /// [`visit_i64`]: #method.visit_i64
1330 fn visit_i32
<E
>(self, v
: i32) -> Result
<Self::Value
, E
>
1334 self.visit_i64(v
as i64)
1337 /// The input contains an `i64`.
1339 /// The default implementation fails with a type error.
1340 fn visit_i64
<E
>(self, v
: i64) -> Result
<Self::Value
, E
>
1344 Err(Error
::invalid_type(Unexpected
::Signed(v
), &self))
1347 serde_if_integer128
! {
1348 /// The input contains a `i128`.
1350 /// This method is available only on Rust compiler versions >=1.26. The
1351 /// default implementation fails with a type error.
1352 fn visit_i128
<E
>(self, v
: i128
) -> Result
<Self::Value
, E
>
1357 Err(Error
::invalid_type(Unexpected
::Other("i128"), &self))
1361 /// The input contains a `u8`.
1363 /// The default implementation forwards to [`visit_u64`].
1365 /// [`visit_u64`]: #method.visit_u64
1366 fn visit_u8
<E
>(self, v
: u8) -> Result
<Self::Value
, E
>
1370 self.visit_u64(v
as u64)
1373 /// The input contains a `u16`.
1375 /// The default implementation forwards to [`visit_u64`].
1377 /// [`visit_u64`]: #method.visit_u64
1378 fn visit_u16
<E
>(self, v
: u16) -> Result
<Self::Value
, E
>
1382 self.visit_u64(v
as u64)
1385 /// The input contains a `u32`.
1387 /// The default implementation forwards to [`visit_u64`].
1389 /// [`visit_u64`]: #method.visit_u64
1390 fn visit_u32
<E
>(self, v
: u32) -> Result
<Self::Value
, E
>
1394 self.visit_u64(v
as u64)
1397 /// The input contains a `u64`.
1399 /// The default implementation fails with a type error.
1400 fn visit_u64
<E
>(self, v
: u64) -> Result
<Self::Value
, E
>
1404 Err(Error
::invalid_type(Unexpected
::Unsigned(v
), &self))
1407 serde_if_integer128
! {
1408 /// The input contains a `u128`.
1410 /// This method is available only on Rust compiler versions >=1.26. The
1411 /// default implementation fails with a type error.
1412 fn visit_u128
<E
>(self, v
: u128
) -> Result
<Self::Value
, E
>
1417 Err(Error
::invalid_type(Unexpected
::Other("u128"), &self))
1421 /// The input contains an `f32`.
1423 /// The default implementation forwards to [`visit_f64`].
1425 /// [`visit_f64`]: #method.visit_f64
1426 fn visit_f32
<E
>(self, v
: f32) -> Result
<Self::Value
, E
>
1430 self.visit_f64(v
as f64)
1433 /// The input contains an `f64`.
1435 /// The default implementation fails with a type error.
1436 fn visit_f64
<E
>(self, v
: f64) -> Result
<Self::Value
, E
>
1440 Err(Error
::invalid_type(Unexpected
::Float(v
), &self))
1443 /// The input contains a `char`.
1445 /// The default implementation forwards to [`visit_str`] as a one-character
1448 /// [`visit_str`]: #method.visit_str
1450 fn visit_char
<E
>(self, v
: char) -> Result
<Self::Value
, E
>
1454 self.visit_str(utf8
::encode(v
).as_str())
1457 /// The input contains a string. The lifetime of the string is ephemeral and
1458 /// it may be destroyed after this method returns.
1460 /// This method allows the `Deserializer` to avoid a copy by retaining
1461 /// ownership of any buffered data. `Deserialize` implementations that do
1462 /// not benefit from taking ownership of `String` data should indicate that
1463 /// to the deserializer by using `Deserializer::deserialize_str` rather than
1464 /// `Deserializer::deserialize_string`.
1466 /// It is never correct to implement `visit_string` without implementing
1467 /// `visit_str`. Implement neither, both, or just `visit_str`.
1468 fn visit_str
<E
>(self, v
: &str) -> Result
<Self::Value
, E
>
1472 Err(Error
::invalid_type(Unexpected
::Str(v
), &self))
1475 /// The input contains a string that lives at least as long as the
1478 /// This enables zero-copy deserialization of strings in some formats. For
1479 /// example JSON input containing the JSON string `"borrowed"` can be
1480 /// deserialized with zero copying into a `&'a str` as long as the input
1481 /// data outlives `'a`.
1483 /// The default implementation forwards to `visit_str`.
1485 fn visit_borrowed_str
<E
>(self, v
: &'de
str) -> Result
<Self::Value
, E
>
1492 /// The input contains a string and ownership of the string is being given
1493 /// to the `Visitor`.
1495 /// This method allows the `Visitor` to avoid a copy by taking ownership of
1496 /// a string created by the `Deserializer`. `Deserialize` implementations
1497 /// that benefit from taking ownership of `String` data should indicate that
1498 /// to the deserializer by using `Deserializer::deserialize_string` rather
1499 /// than `Deserializer::deserialize_str`, although not every deserializer
1500 /// will honor such a request.
1502 /// It is never correct to implement `visit_string` without implementing
1503 /// `visit_str`. Implement neither, both, or just `visit_str`.
1505 /// The default implementation forwards to `visit_str` and then drops the
1508 #[cfg(any(feature = "std", feature = "alloc"))]
1509 fn visit_string
<E
>(self, v
: String
) -> Result
<Self::Value
, E
>
1516 /// The input contains a byte array. The lifetime of the byte array is
1517 /// ephemeral and it may be destroyed after this method returns.
1519 /// This method allows the `Deserializer` to avoid a copy by retaining
1520 /// ownership of any buffered data. `Deserialize` implementations that do
1521 /// not benefit from taking ownership of `Vec<u8>` data should indicate that
1522 /// to the deserializer by using `Deserializer::deserialize_bytes` rather
1523 /// than `Deserializer::deserialize_byte_buf`.
1525 /// It is never correct to implement `visit_byte_buf` without implementing
1526 /// `visit_bytes`. Implement neither, both, or just `visit_bytes`.
1527 fn visit_bytes
<E
>(self, v
: &[u8]) -> Result
<Self::Value
, E
>
1532 Err(Error
::invalid_type(Unexpected
::Bytes(v
), &self))
1535 /// The input contains a byte array that lives at least as long as the
1538 /// This enables zero-copy deserialization of bytes in some formats. For
1539 /// example Bincode data containing bytes can be deserialized with zero
1540 /// copying into a `&'a [u8]` as long as the input data outlives `'a`.
1542 /// The default implementation forwards to `visit_bytes`.
1544 fn visit_borrowed_bytes
<E
>(self, v
: &'de
[u8]) -> Result
<Self::Value
, E
>
1551 /// The input contains a byte array and ownership of the byte array is being
1552 /// given to the `Visitor`.
1554 /// This method allows the `Visitor` to avoid a copy by taking ownership of
1555 /// a byte buffer created by the `Deserializer`. `Deserialize`
1556 /// implementations that benefit from taking ownership of `Vec<u8>` data
1557 /// should indicate that to the deserializer by using
1558 /// `Deserializer::deserialize_byte_buf` rather than
1559 /// `Deserializer::deserialize_bytes`, although not every deserializer will
1560 /// honor such a request.
1562 /// It is never correct to implement `visit_byte_buf` without implementing
1563 /// `visit_bytes`. Implement neither, both, or just `visit_bytes`.
1565 /// The default implementation forwards to `visit_bytes` and then drops the
1567 #[cfg(any(feature = "std", feature = "alloc"))]
1568 fn visit_byte_buf
<E
>(self, v
: Vec
<u8>) -> Result
<Self::Value
, E
>
1572 self.visit_bytes(&v
)
1575 /// The input contains an optional that is absent.
1577 /// The default implementation fails with a type error.
1578 fn visit_none
<E
>(self) -> Result
<Self::Value
, E
>
1582 Err(Error
::invalid_type(Unexpected
::Option
, &self))
1585 /// The input contains an optional that is present.
1587 /// The default implementation fails with a type error.
1588 fn visit_some
<D
>(self, deserializer
: D
) -> Result
<Self::Value
, D
::Error
>
1590 D
: Deserializer
<'de
>,
1592 let _
= deserializer
;
1593 Err(Error
::invalid_type(Unexpected
::Option
, &self))
1596 /// The input contains a unit `()`.
1598 /// The default implementation fails with a type error.
1599 fn visit_unit
<E
>(self) -> Result
<Self::Value
, E
>
1603 Err(Error
::invalid_type(Unexpected
::Unit
, &self))
1606 /// The input contains a newtype struct.
1608 /// The content of the newtype struct may be read from the given
1611 /// The default implementation fails with a type error.
1612 fn visit_newtype_struct
<D
>(self, deserializer
: D
) -> Result
<Self::Value
, D
::Error
>
1614 D
: Deserializer
<'de
>,
1616 let _
= deserializer
;
1617 Err(Error
::invalid_type(Unexpected
::NewtypeStruct
, &self))
1620 /// The input contains a sequence of elements.
1622 /// The default implementation fails with a type error.
1623 fn visit_seq
<A
>(self, seq
: A
) -> Result
<Self::Value
, A
::Error
>
1628 Err(Error
::invalid_type(Unexpected
::Seq
, &self))
1631 /// The input contains a key-value map.
1633 /// The default implementation fails with a type error.
1634 fn visit_map
<A
>(self, map
: A
) -> Result
<Self::Value
, A
::Error
>
1639 Err(Error
::invalid_type(Unexpected
::Map
, &self))
1642 /// The input contains an enum.
1644 /// The default implementation fails with a type error.
1645 fn visit_enum
<A
>(self, data
: A
) -> Result
<Self::Value
, A
::Error
>
1650 Err(Error
::invalid_type(Unexpected
::Enum
, &self))
1653 // Used when deserializing a flattened Option field. Not public API.
1655 fn __private_visit_untagged_option
<D
>(self, _
: D
) -> Result
<Self::Value
, ()>
1657 D
: Deserializer
<'de
>,
1663 ////////////////////////////////////////////////////////////////////////////////
1665 /// Provides a `Visitor` access to each element of a sequence in the input.
1667 /// This is a trait that a `Deserializer` passes to a `Visitor` implementation,
1668 /// which deserializes each item in a sequence.
1672 /// The `'de` lifetime of this trait is the lifetime of data that may be
1673 /// borrowed by deserialized sequence elements. See the page [Understanding
1674 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1676 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1678 /// # Example implementation
1680 /// The [example data format] presented on the website demonstrates an
1681 /// implementation of `SeqAccess` for a basic JSON data format.
1683 /// [example data format]: https://serde.rs/data-format.html
1684 pub trait SeqAccess
<'de
> {
1685 /// The error type that can be returned if some error occurs during
1686 /// deserialization.
1689 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1690 /// `Ok(None)` if there are no more remaining items.
1692 /// `Deserialize` implementations should typically use
1693 /// `SeqAccess::next_element` instead.
1694 fn next_element_seed
<T
>(&mut self, seed
: T
) -> Result
<Option
<T
::Value
>, Self::Error
>
1696 T
: DeserializeSeed
<'de
>;
1698 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1699 /// `Ok(None)` if there are no more remaining items.
1701 /// This method exists as a convenience for `Deserialize` implementations.
1702 /// `SeqAccess` implementations should not override the default behavior.
1704 fn next_element
<T
>(&mut self) -> Result
<Option
<T
>, Self::Error
>
1706 T
: Deserialize
<'de
>,
1708 self.next_element_seed(PhantomData
)
1711 /// Returns the number of elements remaining in the sequence, if known.
1713 fn size_hint(&self) -> Option
<usize> {
1718 impl<'de
, 'a
, A
> SeqAccess
<'de
> for &'a
mut A
1722 type Error
= A
::Error
;
1725 fn next_element_seed
<T
>(&mut self, seed
: T
) -> Result
<Option
<T
::Value
>, Self::Error
>
1727 T
: DeserializeSeed
<'de
>,
1729 (**self).next_element_seed(seed
)
1733 fn next_element
<T
>(&mut self) -> Result
<Option
<T
>, Self::Error
>
1735 T
: Deserialize
<'de
>,
1737 (**self).next_element()
1741 fn size_hint(&self) -> Option
<usize> {
1742 (**self).size_hint()
1746 ////////////////////////////////////////////////////////////////////////////////
1748 /// Provides a `Visitor` access to each entry of a map in the input.
1750 /// This is a trait that a `Deserializer` passes to a `Visitor` implementation.
1754 /// The `'de` lifetime of this trait is the lifetime of data that may be
1755 /// borrowed by deserialized map entries. See the page [Understanding
1756 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1758 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1760 /// # Example implementation
1762 /// The [example data format] presented on the website demonstrates an
1763 /// implementation of `MapAccess` for a basic JSON data format.
1765 /// [example data format]: https://serde.rs/data-format.html
1766 pub trait MapAccess
<'de
> {
1767 /// The error type that can be returned if some error occurs during
1768 /// deserialization.
1771 /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
1772 /// if there are no more remaining entries.
1774 /// `Deserialize` implementations should typically use
1775 /// `MapAccess::next_key` or `MapAccess::next_entry` instead.
1776 fn next_key_seed
<K
>(&mut self, seed
: K
) -> Result
<Option
<K
::Value
>, Self::Error
>
1778 K
: DeserializeSeed
<'de
>;
1780 /// This returns a `Ok(value)` for the next value in the map.
1782 /// `Deserialize` implementations should typically use
1783 /// `MapAccess::next_value` instead.
1787 /// Calling `next_value_seed` before `next_key_seed` is incorrect and is
1788 /// allowed to panic or return bogus results.
1789 fn next_value_seed
<V
>(&mut self, seed
: V
) -> Result
<V
::Value
, Self::Error
>
1791 V
: DeserializeSeed
<'de
>;
1793 /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in
1794 /// the map, or `Ok(None)` if there are no more remaining items.
1796 /// `MapAccess` implementations should override the default behavior if a
1797 /// more efficient implementation is possible.
1799 /// `Deserialize` implementations should typically use
1800 /// `MapAccess::next_entry` instead.
1802 fn next_entry_seed
<K
, V
>(
1806 ) -> Result
<Option
<(K
::Value
, V
::Value
)>, Self::Error
>
1808 K
: DeserializeSeed
<'de
>,
1809 V
: DeserializeSeed
<'de
>,
1811 match try
!(self.next_key_seed(kseed
)) {
1813 let value
= try
!(self.next_value_seed(vseed
));
1814 Ok(Some((key
, value
)))
1820 /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
1821 /// if there are no more remaining entries.
1823 /// This method exists as a convenience for `Deserialize` implementations.
1824 /// `MapAccess` implementations should not override the default behavior.
1826 fn next_key
<K
>(&mut self) -> Result
<Option
<K
>, Self::Error
>
1828 K
: Deserialize
<'de
>,
1830 self.next_key_seed(PhantomData
)
1833 /// This returns a `Ok(value)` for the next value in the map.
1835 /// This method exists as a convenience for `Deserialize` implementations.
1836 /// `MapAccess` implementations should not override the default behavior.
1840 /// Calling `next_value` before `next_key` is incorrect and is allowed to
1841 /// panic or return bogus results.
1843 fn next_value
<V
>(&mut self) -> Result
<V
, Self::Error
>
1845 V
: Deserialize
<'de
>,
1847 self.next_value_seed(PhantomData
)
1850 /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in
1851 /// the map, or `Ok(None)` if there are no more remaining items.
1853 /// This method exists as a convenience for `Deserialize` implementations.
1854 /// `MapAccess` implementations should not override the default behavior.
1856 fn next_entry
<K
, V
>(&mut self) -> Result
<Option
<(K
, V
)>, Self::Error
>
1858 K
: Deserialize
<'de
>,
1859 V
: Deserialize
<'de
>,
1861 self.next_entry_seed(PhantomData
, PhantomData
)
1864 /// Returns the number of entries remaining in the map, if known.
1866 fn size_hint(&self) -> Option
<usize> {
1871 impl<'de
, 'a
, A
> MapAccess
<'de
> for &'a
mut A
1875 type Error
= A
::Error
;
1878 fn next_key_seed
<K
>(&mut self, seed
: K
) -> Result
<Option
<K
::Value
>, Self::Error
>
1880 K
: DeserializeSeed
<'de
>,
1882 (**self).next_key_seed(seed
)
1886 fn next_value_seed
<V
>(&mut self, seed
: V
) -> Result
<V
::Value
, Self::Error
>
1888 V
: DeserializeSeed
<'de
>,
1890 (**self).next_value_seed(seed
)
1894 fn next_entry_seed
<K
, V
>(
1898 ) -> Result
<Option
<(K
::Value
, V
::Value
)>, Self::Error
>
1900 K
: DeserializeSeed
<'de
>,
1901 V
: DeserializeSeed
<'de
>,
1903 (**self).next_entry_seed(kseed
, vseed
)
1907 fn next_entry
<K
, V
>(&mut self) -> Result
<Option
<(K
, V
)>, Self::Error
>
1909 K
: Deserialize
<'de
>,
1910 V
: Deserialize
<'de
>,
1912 (**self).next_entry()
1916 fn next_key
<K
>(&mut self) -> Result
<Option
<K
>, Self::Error
>
1918 K
: Deserialize
<'de
>,
1924 fn next_value
<V
>(&mut self) -> Result
<V
, Self::Error
>
1926 V
: Deserialize
<'de
>,
1928 (**self).next_value()
1932 fn size_hint(&self) -> Option
<usize> {
1933 (**self).size_hint()
1937 ////////////////////////////////////////////////////////////////////////////////
1939 /// Provides a `Visitor` access to the data of an enum in the input.
1941 /// `EnumAccess` is created by the `Deserializer` and passed to the
1942 /// `Visitor` in order to identify which variant of an enum to deserialize.
1946 /// The `'de` lifetime of this trait is the lifetime of data that may be
1947 /// borrowed by the deserialized enum variant. See the page [Understanding
1948 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1950 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1952 /// # Example implementation
1954 /// The [example data format] presented on the website demonstrates an
1955 /// implementation of `EnumAccess` for a basic JSON data format.
1957 /// [example data format]: https://serde.rs/data-format.html
1958 pub trait EnumAccess
<'de
>: Sized
{
1959 /// The error type that can be returned if some error occurs during
1960 /// deserialization.
1962 /// The `Visitor` that will be used to deserialize the content of the enum
1964 type Variant
: VariantAccess
<'de
, Error
= Self::Error
>;
1966 /// `variant` is called to identify which variant to deserialize.
1968 /// `Deserialize` implementations should typically use `EnumAccess::variant`
1970 fn variant_seed
<V
>(self, seed
: V
) -> Result
<(V
::Value
, Self::Variant
), Self::Error
>
1972 V
: DeserializeSeed
<'de
>;
1974 /// `variant` is called to identify which variant to deserialize.
1976 /// This method exists as a convenience for `Deserialize` implementations.
1977 /// `EnumAccess` implementations should not override the default behavior.
1979 fn variant
<V
>(self) -> Result
<(V
, Self::Variant
), Self::Error
>
1981 V
: Deserialize
<'de
>,
1983 self.variant_seed(PhantomData
)
1987 /// `VariantAccess` is a visitor that is created by the `Deserializer` and
1988 /// passed to the `Deserialize` to deserialize the content of a particular enum
1993 /// The `'de` lifetime of this trait is the lifetime of data that may be
1994 /// borrowed by the deserialized enum variant. See the page [Understanding
1995 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1997 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1999 /// # Example implementation
2001 /// The [example data format] presented on the website demonstrates an
2002 /// implementation of `VariantAccess` for a basic JSON data format.
2004 /// [example data format]: https://serde.rs/data-format.html
2005 pub trait VariantAccess
<'de
>: Sized
{
2006 /// The error type that can be returned if some error occurs during
2007 /// deserialization. Must match the error type of our `EnumAccess`.
2010 /// Called when deserializing a variant with no values.
2012 /// If the data contains a different type of variant, the following
2013 /// `invalid_type` error should be constructed:
2016 /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
2020 /// # impl<'de> VariantAccess<'de> for X {
2021 /// # type Error = value::Error;
2023 /// fn unit_variant(self) -> Result<(), Self::Error> {
2024 /// // What the data actually contained; suppose it is a tuple variant.
2025 /// let unexp = Unexpected::TupleVariant;
2026 /// Err(de::Error::invalid_type(unexp, &"unit variant"))
2029 /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
2031 /// # T: DeserializeSeed<'de>,
2032 /// # { unimplemented!() }
2034 /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
2036 /// # V: Visitor<'de>,
2037 /// # { unimplemented!() }
2039 /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
2041 /// # V: Visitor<'de>,
2042 /// # { unimplemented!() }
2045 fn unit_variant(self) -> Result
<(), Self::Error
>;
2047 /// Called when deserializing a variant with a single value.
2049 /// `Deserialize` implementations should typically use
2050 /// `VariantAccess::newtype_variant` instead.
2052 /// If the data contains a different type of variant, the following
2053 /// `invalid_type` error should be constructed:
2056 /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
2060 /// # impl<'de> VariantAccess<'de> for X {
2061 /// # type Error = value::Error;
2063 /// # fn unit_variant(self) -> Result<(), Self::Error> {
2064 /// # unimplemented!()
2067 /// fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
2069 /// T: DeserializeSeed<'de>,
2071 /// // What the data actually contained; suppose it is a unit variant.
2072 /// let unexp = Unexpected::UnitVariant;
2073 /// Err(de::Error::invalid_type(unexp, &"newtype variant"))
2076 /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
2078 /// # V: Visitor<'de>,
2079 /// # { unimplemented!() }
2081 /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
2083 /// # V: Visitor<'de>,
2084 /// # { unimplemented!() }
2087 fn newtype_variant_seed
<T
>(self, seed
: T
) -> Result
<T
::Value
, Self::Error
>
2089 T
: DeserializeSeed
<'de
>;
2091 /// Called when deserializing a variant with a single value.
2093 /// This method exists as a convenience for `Deserialize` implementations.
2094 /// `VariantAccess` implementations should not override the default
2097 fn newtype_variant
<T
>(self) -> Result
<T
, Self::Error
>
2099 T
: Deserialize
<'de
>,
2101 self.newtype_variant_seed(PhantomData
)
2104 /// Called when deserializing a tuple-like variant.
2106 /// The `len` is the number of fields expected in the tuple variant.
2108 /// If the data contains a different type of variant, the following
2109 /// `invalid_type` error should be constructed:
2112 /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
2116 /// # impl<'de> VariantAccess<'de> for X {
2117 /// # type Error = value::Error;
2119 /// # fn unit_variant(self) -> Result<(), Self::Error> {
2120 /// # unimplemented!()
2123 /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
2125 /// # T: DeserializeSeed<'de>,
2126 /// # { unimplemented!() }
2128 /// fn tuple_variant<V>(
2132 /// ) -> Result<V::Value, Self::Error>
2134 /// V: Visitor<'de>,
2136 /// // What the data actually contained; suppose it is a unit variant.
2137 /// let unexp = Unexpected::UnitVariant;
2138 /// Err(de::Error::invalid_type(unexp, &"tuple variant"))
2141 /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
2143 /// # V: Visitor<'de>,
2144 /// # { unimplemented!() }
2147 fn tuple_variant
<V
>(self, len
: usize, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
2151 /// Called when deserializing a struct-like variant.
2153 /// The `fields` are the names of the fields of the struct variant.
2155 /// If the data contains a different type of variant, the following
2156 /// `invalid_type` error should be constructed:
2159 /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
2163 /// # impl<'de> VariantAccess<'de> for X {
2164 /// # type Error = value::Error;
2166 /// # fn unit_variant(self) -> Result<(), Self::Error> {
2167 /// # unimplemented!()
2170 /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
2172 /// # T: DeserializeSeed<'de>,
2173 /// # { unimplemented!() }
2175 /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
2177 /// # V: Visitor<'de>,
2178 /// # { unimplemented!() }
2180 /// fn struct_variant<V>(
2182 /// _fields: &'static [&'static str],
2184 /// ) -> Result<V::Value, Self::Error>
2186 /// V: Visitor<'de>,
2188 /// // What the data actually contained; suppose it is a unit variant.
2189 /// let unexp = Unexpected::UnitVariant;
2190 /// Err(de::Error::invalid_type(unexp, &"struct variant"))
2194 fn struct_variant
<V
>(
2196 fields
: &'
static [&'
static str],
2198 ) -> Result
<V
::Value
, Self::Error
>
2203 ////////////////////////////////////////////////////////////////////////////////
2205 /// Converts an existing value into a `Deserializer` from which other values can
2206 /// be deserialized.
2210 /// The `'de` lifetime of this trait is the lifetime of data that may be
2211 /// borrowed from the resulting `Deserializer`. See the page [Understanding
2212 /// deserializer lifetimes] for a more detailed explanation of these lifetimes.
2214 /// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
2219 /// use std::str::FromStr;
2220 /// use serde::Deserialize;
2221 /// use serde::de::{value, IntoDeserializer};
2223 /// #[derive(Deserialize)]
2229 /// impl FromStr for Setting {
2230 /// type Err = value::Error;
2232 /// fn from_str(s: &str) -> Result<Self, Self::Err> {
2233 /// Self::deserialize(s.into_deserializer())
2237 pub trait IntoDeserializer
<'de
, E
: Error
= value
::Error
> {
2238 /// The type of the deserializer being converted into.
2239 type Deserializer
: Deserializer
<'de
, Error
= E
>;
2241 /// Convert this value into a deserializer.
2242 fn into_deserializer(self) -> Self::Deserializer
;
2245 ////////////////////////////////////////////////////////////////////////////////
2247 /// Used in error messages.
2250 /// - expected `a` or `b`
2251 /// - expected one of `a`, `b`, `c`
2253 /// The slice of names must not be empty.
2255 names
: &'
static [&'
static str],
2258 impl Display
for OneOf
{
2259 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
2260 match self.names
.len() {
2261 0 => panic
!(), // special case elsewhere
2262 1 => write
!(formatter
, "`{}`", self.names
[0]),
2263 2 => write
!(formatter
, "`{}` or `{}`", self.names
[0], self.names
[1]),
2265 try
!(write
!(formatter
, "one of "));
2266 for (i
, alt
) in self.names
.iter().enumerate() {
2268 try
!(write
!(formatter
, ", "));
2270 try
!(write
!(formatter
, "`{}`", alt
));