1 // Copyright 2017 Serde Developers
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
9 //! Generic data structure deserialization framework.
11 //! The two most important traits in this module are [`Deserialize`] and
14 //! - **A type that implements `Deserialize` is a data structure** that can be
15 //! deserialized from any data format supported by Serde, and conversely
16 //! - **A type that implements `Deserializer` is a data format** that can
17 //! deserialize any data structure supported by Serde.
19 //! # The Deserialize trait
21 //! Serde provides [`Deserialize`] implementations for many Rust primitive and
22 //! standard library types. The complete list is below. All of these can be
23 //! deserialized using Serde out of the box.
25 //! Additionally, Serde provides a procedural macro called [`serde_derive`] to
26 //! automatically generate [`Deserialize`] implementations for structs and enums
27 //! in your program. See the [codegen section of the manual] for how to use
30 //! In rare cases it may be necessary to implement [`Deserialize`] manually for
31 //! some type in your program. See the [Implementing `Deserialize`] section of
32 //! the manual for more about this.
34 //! Third-party crates may provide [`Deserialize`] implementations for types
35 //! that they expose. For example the [`linked-hash-map`] crate provides a
36 //! [`LinkedHashMap<K, V>`] type that is deserializable by Serde because the
37 //! crate provides an implementation of [`Deserialize`] for it.
39 //! # The Deserializer trait
41 //! [`Deserializer`] implementations are provided by third-party crates, for
42 //! example [`serde_json`], [`serde_yaml`] and [`bincode`].
44 //! A partial list of well-maintained formats is given on the [Serde
45 //! website][data formats].
47 //! # Implementations of Deserialize provided by Serde
49 //! This is a slightly different set of types than what is supported for
50 //! serialization. Some types can be serialized by Serde but not deserialized.
51 //! One example is `OsStr`.
53 //! - **Primitive types**:
55 //! - i8, i16, i32, i64, isize
56 //! - u8, u16, u32, u64, usize
59 //! - **Compound types**:
60 //! - [T; 0] through [T; 32]
61 //! - tuples up to size 16
62 //! - **Common standard library types**:
66 //! - PhantomData\<T\>
67 //! - **Wrapper types**:
78 //! - **Collection types**:
79 //! - BTreeMap\<K, V\>
82 //! - HashMap\<K, V, H\>
87 //! - EnumSet\<T\> (unstable)
88 //! - **Zero-copy types**:
95 //! - **Miscellaneous standard library types**:
101 //! - NonZero\<T\> (unstable)
110 //! [Implementing `Deserialize`]: https://serde.rs/impl-deserialize.html
111 //! [`Deserialize`]: ../trait.Deserialize.html
112 //! [`Deserializer`]: ../trait.Deserializer.html
113 //! [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html
114 //! [`bincode`]: https://github.com/TyOverby/bincode
115 //! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map
116 //! [`serde_derive`]: https://crates.io/crates/serde_derive
117 //! [`serde_json`]: https://github.com/serde-rs/json
118 //! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml
119 //! [codegen section of the manual]: https://serde.rs/codegen.html
120 //! [data formats]: https://serde.rs/#data-formats
124 ////////////////////////////////////////////////////////////////////////////////
133 pub use self::ignored_any
::IgnoredAny
;
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.
152 pub trait Error
: Sized $
(+ $
($supertrait
)::+)* {
153 /// Raised when there is general error when deserializing a type.
155 /// The message should not be capitalized and should not end with a period.
158 /// # use std::str::FromStr;
162 /// # impl FromStr for IpAddr {
163 /// # type Err = String;
165 /// # fn from_str(_: &str) -> Result<Self, String> {
166 /// # unimplemented!()
170 /// use serde::de::{self, Deserialize, Deserializer};
172 /// impl<'de> Deserialize<'de> for IpAddr {
173 /// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
174 /// where D: Deserializer<'de>
176 /// let s = try!(String::deserialize(deserializer));
177 /// s.parse().map_err(de::Error::custom)
181 fn custom
<T
>(msg
: T
) -> Self
185 /// Raised when a `Deserialize` receives a type different from what it was
188 /// The `unexp` argument provides information about what type was received.
189 /// This is the type that was present in the input file or other source data
190 /// of the Deserializer.
192 /// The `exp` argument provides information about what type was being
193 /// expected. This is the type that is written in the program.
195 /// For example if we try to deserialize a String out of a JSON file
196 /// containing an integer, the unexpected type is the integer and the
197 /// expected type is the string.
198 fn invalid_type(unexp
: Unexpected
, exp
: &Expected
) -> Self {
199 Error
::custom(format_args
!("invalid type: {}, expected {}", unexp
, exp
))
202 /// Raised when a `Deserialize` receives a value of the right type but that
203 /// is wrong for some other reason.
205 /// The `unexp` argument provides information about what value was received.
206 /// This is the value that was present in the input file or other source
207 /// data of the Deserializer.
209 /// The `exp` argument provides information about what value was being
210 /// expected. This is the type that is written in the program.
212 /// For example if we try to deserialize a String out of some binary data
213 /// that is not valid UTF-8, the unexpected value is the bytes and the
214 /// expected value is a string.
215 fn invalid_value(unexp
: Unexpected
, exp
: &Expected
) -> Self {
216 Error
::custom(format_args
!("invalid value: {}, expected {}", unexp
, exp
))
219 /// Raised when deserializing a sequence or map and the input data contains
220 /// too many or too few elements.
222 /// The `len` argument is the number of elements encountered. The sequence
223 /// or map may have expected more arguments or fewer arguments.
225 /// The `exp` argument provides information about what data was being
226 /// expected. For example `exp` might say that a tuple of size 6 was
228 fn invalid_length(len
: usize, exp
: &Expected
) -> Self {
229 Error
::custom(format_args
!("invalid length {}, expected {}", len
, exp
))
232 /// Raised when a `Deserialize` enum type received a variant with an
233 /// unrecognized name.
234 fn unknown_variant(variant
: &str, expected
: &'
static [&'
static str]) -> Self {
235 if expected
.is_empty() {
236 Error
::custom(format_args
!("unknown variant `{}`, there are no variants",
239 Error
::custom(format_args
!("unknown variant `{}`, expected {}",
241 OneOf { names: expected }
))
245 /// Raised when a `Deserialize` struct type received a field with an
246 /// unrecognized name.
247 fn unknown_field(field
: &str, expected
: &'
static [&'
static str]) -> Self {
248 if expected
.is_empty() {
249 Error
::custom(format_args
!("unknown field `{}`, there are no fields",
252 Error
::custom(format_args
!("unknown field `{}`, expected {}",
254 OneOf { names: expected }
))
258 /// Raised when a `Deserialize` struct type expected to receive a required
259 /// field with a particular name but that field was not present in the
261 fn missing_field(field
: &'
static str) -> Self {
262 Error
::custom(format_args
!("missing field `{}`", field
))
265 /// Raised when a `Deserialize` struct type received more than one of the
267 fn duplicate_field(field
: &'
static str) -> Self {
268 Error
::custom(format_args
!("duplicate field `{}`", field
))
274 #[cfg(feature = "std")]
275 declare_error_trait
!(Error
: Sized
+ error
::Error
);
277 #[cfg(not(feature = "std"))]
278 declare_error_trait
!(Error
: Sized
+ Debug
+ Display
);
280 /// `Unexpected` represents an unexpected invocation of any one of the `Visitor`
283 /// This is used as an argument to the `invalid_type`, `invalid_value`, and
284 /// `invalid_length` methods of the `Error` trait to build error messages.
289 /// # use serde::de::{self, Unexpected, Visitor};
291 /// # struct Example;
293 /// # impl<'de> Visitor<'de> for Example {
294 /// # type Value = ();
296 /// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
297 /// # write!(formatter, "definitely not a boolean")
300 /// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
301 /// where E: de::Error
303 /// Err(de::Error::invalid_type(Unexpected::Bool(v), &self))
307 #[derive(Copy, Clone, PartialEq, Debug)]
308 pub enum Unexpected
<'a
> {
309 /// The input contained a boolean value that was not expected.
312 /// The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that
313 /// was not expected.
316 /// The input contained a signed integer `i8`, `i16`, `i32` or `i64` that
317 /// was not expected.
320 /// The input contained a floating point `f32` or `f64` that was not
324 /// The input contained a `char` that was not expected.
327 /// The input contained a `&str` or `String` that was not expected.
330 /// The input contained a `&[u8]` or `Vec<u8>` that was not expected.
333 /// The input contained a unit `()` that was not expected.
336 /// The input contained an `Option<T>` that was not expected.
339 /// The input contained a newtype struct that was not expected.
342 /// The input contained a sequence that was not expected.
345 /// The input contained a map that was not expected.
348 /// The input contained an enum that was not expected.
351 /// The input contained a unit variant that was not expected.
354 /// The input contained a newtype variant that was not expected.
357 /// The input contained a tuple variant that was not expected.
360 /// The input contained a struct variant that was not expected.
363 /// A message stating what uncategorized thing the input contained that was
366 /// The message should be a noun or noun phrase, not capitalized and without
367 /// a period. An example message is "unoriginal superhero".
371 impl<'a
> fmt
::Display
for Unexpected
<'a
> {
372 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> Result
<(), fmt
::Error
> {
373 use self::Unexpected
::*;
375 Bool(b
) => write
!(formatter
, "boolean `{}`", b
),
376 Unsigned(i
) => write
!(formatter
, "integer `{}`", i
),
377 Signed(i
) => write
!(formatter
, "integer `{}`", i
),
378 Float(f
) => write
!(formatter
, "floating point `{}`", f
),
379 Char(c
) => write
!(formatter
, "character `{}`", c
),
380 Str(s
) => write
!(formatter
, "string {:?}", s
),
381 Bytes(_
) => write
!(formatter
, "byte array"),
382 Unit
=> write
!(formatter
, "unit value"),
383 Option
=> write
!(formatter
, "Option value"),
384 NewtypeStruct
=> write
!(formatter
, "newtype struct"),
385 Seq
=> write
!(formatter
, "sequence"),
386 Map
=> write
!(formatter
, "map"),
387 Enum
=> write
!(formatter
, "enum"),
388 UnitVariant
=> write
!(formatter
, "unit variant"),
389 NewtypeVariant
=> write
!(formatter
, "newtype variant"),
390 TupleVariant
=> write
!(formatter
, "tuple variant"),
391 StructVariant
=> write
!(formatter
, "struct variant"),
392 Other(other
) => formatter
.write_str(other
),
397 /// `Expected` represents an explanation of what data a `Visitor` was expecting
400 /// This is used as an argument to the `invalid_type`, `invalid_value`, and
401 /// `invalid_length` methods of the `Error` trait to build error messages. The
402 /// message should be a noun or noun phrase that completes the sentence "This
403 /// Visitor expects to receive ...", for example the message could be "an
404 /// integer between 0 and 64". The message should not be capitalized and should
405 /// not end with a period.
407 /// Within the context of a `Visitor` implementation, the `Visitor` itself
408 /// (`&self`) is an implementation of this trait.
413 /// # use serde::de::{self, Unexpected, Visitor};
415 /// # struct Example;
417 /// # impl<'de> Visitor<'de> for Example {
418 /// # type Value = ();
420 /// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
421 /// # write!(formatter, "definitely not a boolean")
424 /// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
425 /// where E: de::Error
427 /// Err(de::Error::invalid_type(Unexpected::Bool(v), &self))
432 /// Outside of a `Visitor`, `&"..."` can be used.
435 /// # use serde::de::{self, Unexpected};
437 /// # fn example<E>() -> Result<(), E>
438 /// # where E: de::Error
441 /// return Err(de::Error::invalid_type(Unexpected::Bool(v), &"a negative integer"));
445 /// Format an explanation of what data was being expected. Same signature as
446 /// the `Display` and `Debug` traits.
447 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
;
450 impl<'de
, T
> Expected
for T
454 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
455 self.expecting(formatter
)
459 impl<'a
> Expected
for &'a
str {
460 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
461 formatter
.write_str(self)
465 impl<'a
> Display
for Expected
+ 'a
{
466 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
467 Expected
::fmt(self, formatter
)
471 ////////////////////////////////////////////////////////////////////////////////
473 /// A **data structure** that can be deserialized from any data format supported
476 /// Serde provides `Deserialize` implementations for many Rust primitive and
477 /// standard library types. The complete list is [here][de]. All of these can
478 /// be deserialized using Serde out of the box.
480 /// Additionally, Serde provides a procedural macro called `serde_derive` to
481 /// automatically generate `Deserialize` implementations for structs and enums
482 /// in your program. See the [codegen section of the manual][codegen] for how to
485 /// In rare cases it may be necessary to implement `Deserialize` manually for
486 /// some type in your program. See the [Implementing
487 /// `Deserialize`][impl-deserialize] section of the manual for more about this.
489 /// Third-party crates may provide `Deserialize` implementations for types that
490 /// they expose. For example the `linked-hash-map` crate provides a
491 /// `LinkedHashMap<K, V>` type that is deserializable by Serde because the crate
492 /// provides an implementation of `Deserialize` for it.
494 /// [de]: https://docs.serde.rs/serde/de/index.html
495 /// [codegen]: https://serde.rs/codegen.html
496 /// [impl-deserialize]: https://serde.rs/impl-deserialize.html
497 pub trait Deserialize
<'de
>: Sized
{
498 /// Deserialize this value from the given Serde deserializer.
500 /// See the [Implementing `Deserialize`][impl-deserialize] section of the
501 /// manual for more information about how to implement this method.
503 /// [impl-deserialize]: https://serde.rs/impl-deserialize.html
504 fn deserialize
<D
>(deserializer
: D
) -> Result
<Self, D
::Error
>
506 D
: Deserializer
<'de
>;
509 /// A data structure that can be deserialized without borrowing any data from
510 /// the deserializer.
512 /// This is primarily useful for trait bounds on functions. For example a
513 /// `from_str` function may be able to deserialize a data structure that borrows
514 /// from the input string, but a `from_reader` function may only deserialize
518 /// # use serde::de::{Deserialize, DeserializeOwned};
519 /// # use std::io::{Read, Result};
522 /// fn from_str<'a, T>(s: &'a str) -> Result<T>
523 /// where T: Deserialize<'a>;
525 /// fn from_reader<R, T>(rdr: R) -> Result<T>
527 /// T: DeserializeOwned;
530 pub trait DeserializeOwned
: for<'de
> Deserialize
<'de
> {}
531 impl<T
> DeserializeOwned
for T
533 T
: for<'de
> Deserialize
<'de
>,
537 /// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you
538 /// ever find yourself looking for a way to pass data into a `Deserialize` impl,
539 /// this trait is the way to do it.
541 /// As one example of stateful deserialization consider deserializing a JSON
542 /// array into an existing buffer. Using the `Deserialize` trait we could
543 /// deserialize a JSON array into a `Vec<T>` but it would be a freshly allocated
544 /// `Vec<T>`; there is no way for `Deserialize` to reuse a previously allocated
545 /// buffer. Using `DeserializeSeed` instead makes this possible as in the
546 /// example code below.
548 /// The canonical API for stateless deserialization looks like this:
551 /// # use serde::Deserialize;
555 /// fn func<'de, T: Deserialize<'de>>() -> Result<T, Error>
557 /// # unimplemented!()
561 /// Adjusting an API like this to support stateful deserialization is a matter
562 /// of accepting a seed as input:
565 /// # use serde::de::DeserializeSeed;
569 /// fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result<T::Value, Error>
572 /// # unimplemented!()
576 /// In practice the majority of deserialization is stateless. An API expecting a
577 /// seed can be appeased by passing `std::marker::PhantomData` as a seed in the
578 /// case of stateless deserialization.
582 /// Suppose we have JSON that looks like `[[1, 2], [3, 4, 5], [6]]` and we need
583 /// to deserialize it into a flat representation like `vec![1, 2, 3, 4, 5, 6]`.
584 /// Allocating a brand new `Vec<T>` for each subarray would be slow. Instead we
585 /// would like to allocate a single `Vec<T>` and then deserialize each subarray
586 /// into it. This requires stateful deserialization using the `DeserializeSeed`
591 /// use std::marker::PhantomData;
593 /// use serde::de::{Deserialize, DeserializeSeed, Deserializer, Visitor, SeqAccess};
595 /// // A DeserializeSeed implementation that uses stateful deserialization to
596 /// // append array elements onto the end of an existing vector. The preexisting
597 /// // state ("seed") in this case is the Vec<T>. The `deserialize` method of
598 /// // `ExtendVec` will be traversing the inner arrays of the JSON input and
599 /// // appending each integer into the existing Vec.
600 /// struct ExtendVec<'a, T: 'a>(&'a mut Vec<T>);
602 /// impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T>
603 /// where T: Deserialize<'de>
605 /// // The return type of the `deserialize` method. This implementation
606 /// // appends onto an existing vector but does not create any new data
607 /// // structure, so the return type is ().
610 /// fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
611 /// where D: Deserializer<'de>
613 /// // Visitor implementation that will walk an inner array of the JSON
615 /// struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec<T>);
617 /// impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T>
618 /// where T: Deserialize<'de>
622 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
623 /// write!(formatter, "an array of integers")
626 /// fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error>
627 /// where A: SeqAccess<'de>
629 /// // Visit each element in the inner array and push it onto
630 /// // the existing vector.
631 /// while let Some(elem) = seq.next_element()? {
632 /// self.0.push(elem);
638 /// deserializer.deserialize_seq(ExtendVecVisitor(self.0))
642 /// // Visitor implementation that will walk the outer array of the JSON input.
643 /// struct FlattenedVecVisitor<T>(PhantomData<T>);
645 /// impl<'de, T> Visitor<'de> for FlattenedVecVisitor<T>
646 /// where T: Deserialize<'de>
648 /// // This Visitor constructs a single Vec<T> to hold the flattened
649 /// // contents of the inner arrays.
650 /// type Value = Vec<T>;
652 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
653 /// write!(formatter, "an array of arrays")
656 /// fn visit_seq<A>(self, mut seq: A) -> Result<Vec<T>, A::Error>
657 /// where A: SeqAccess<'de>
659 /// // Create a single Vec to hold the flattened contents.
660 /// let mut vec = Vec::new();
662 /// // Each iteration through this loop is one inner array.
663 /// while let Some(()) = seq.next_element_seed(ExtendVec(&mut vec))? {
664 /// // Nothing to do; inner array has been appended into `vec`.
667 /// // Return the finished vec.
672 /// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error>
673 /// # where D: Deserializer<'de>
675 /// let visitor = FlattenedVecVisitor(PhantomData);
676 /// let flattened: Vec<u64> = deserializer.deserialize_seq(visitor)?;
680 pub trait DeserializeSeed
<'de
>: Sized
{
681 /// The type produced by using this seed.
684 /// Equivalent to the more common `Deserialize::deserialize` method, except
685 /// with some initial piece of data (the seed) passed in.
686 fn deserialize
<D
>(self, deserializer
: D
) -> Result
<Self::Value
, D
::Error
>
688 D
: Deserializer
<'de
>;
691 impl<'de
, T
> DeserializeSeed
<'de
> for PhantomData
<T
>
698 fn deserialize
<D
>(self, deserializer
: D
) -> Result
<T
, D
::Error
>
700 D
: Deserializer
<'de
>,
702 T
::deserialize(deserializer
)
706 ////////////////////////////////////////////////////////////////////////////////
708 /// A **data format** that can deserialize any data structure supported by
711 /// The role of this trait is to define the deserialization half of the Serde
712 /// data model, which is a way to categorize every Rust data type into one of 27
713 /// possible types. Each method of the `Serializer` trait corresponds to one of
714 /// the types of the data model.
716 /// Implementations of `Deserialize` map themselves into this data model by
717 /// passing to the `Deserializer` a `Visitor` implementation that can receive
718 /// these various types.
720 /// The types that make up the Serde data model are:
722 /// - **12 primitive types**
724 /// - i8, i16, i32, i64
725 /// - u8, u16, u32, u64
729 /// - UTF-8 bytes with a length and no null terminator.
730 /// - When serializing, all strings are handled equally. When deserializing,
731 /// there are three flavors of strings: transient, owned, and borrowed.
732 /// - **byte array** - [u8]
733 /// - Similar to strings, during deserialization byte arrays can be transient,
734 /// owned, or borrowed.
736 /// - Either none or some value.
738 /// - The type of `()` in Rust. It represents an anonymous value containing no
740 /// - **unit_struct**
741 /// - For example `struct Unit` or `PhantomData<T>`. It represents a named value
742 /// containing no data.
743 /// - **unit_variant**
744 /// - For example the `E::A` and `E::B` in `enum E { A, B }`.
745 /// - **newtype_struct**
746 /// - For example `struct Millimeters(u8)`.
747 /// - **newtype_variant**
748 /// - For example the `E::N` in `enum E { N(u8) }`.
750 /// - A variably sized heterogeneous sequence of values, for example `Vec<T>` or
751 /// `HashSet<T>`. When serializing, the length may or may not be known before
752 /// iterating through all the data. When deserializing, the length is determined
753 /// by looking at the serialized data.
755 /// - A statically sized heterogeneous sequence of values for which the length
756 /// will be known at deserialization time without looking at the serialized
757 /// data, for example `(u8,)` or `(String, u64, Vec<T>)` or `[u64; 10]`.
758 /// - **tuple_struct**
759 /// - A named tuple, for example `struct Rgb(u8, u8, u8)`.
760 /// - **tuple_variant**
761 /// - For example the `E::T` in `enum E { T(u8, u8) }`.
763 /// - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.
765 /// - A heterogeneous key-value pairing in which the keys are strings and will be
766 /// known at deserialization time without looking at the serialized data, for
767 /// example `struct S { r: u8, g: u8, b: u8 }`.
768 /// - **struct_variant**
769 /// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`.
771 /// The `Deserializer` trait supports two entry point styles which enables
772 /// different kinds of deserialization.
774 /// 1. The `deserialize` method. Self-describing data formats like JSON are able
775 /// to look at the serialized data and tell what it represents. For example
776 /// the JSON deserializer may see an opening curly brace (`{`) and know that
777 /// it is seeing a map. If the data format supports
778 /// `Deserializer::deserialize_any`, it will drive the Visitor using whatever
779 /// type it sees in the input. JSON uses this approach when deserializing
780 /// `serde_json::Value` which is an enum that can represent any JSON
781 /// document. Without knowing what is in a JSON document, we can deserialize
782 /// it to `serde_json::Value` by going through `Deserializer::deserialize_any`.
784 /// 2. The various `deserialize_*` methods. Non-self-describing formats like
785 /// Bincode need to be told what is in the input in order to deserialize it.
786 /// The `deserialize_*` methods are hints to the deserializer for how to
787 /// interpret the next piece of input. Non-self-describing formats are not
788 /// able to deserialize something like `serde_json::Value` which relies on
789 /// `Deserializer::deserialize_any`.
791 /// When implementing `Deserialize`, you should avoid relying on
792 /// `Deserializer::deserialize_any` unless you need to be told by the Deserializer
793 /// what type is in the input. Know that relying on `Deserializer::deserialize_any`
794 /// means your data type will be able to deserialize from self-describing
795 /// formats only, ruling out Bincode and many others.
796 pub trait Deserializer
<'de
>: Sized
{
797 /// The error type that can be returned if some error occurs during
801 /// Require the `Deserializer` to figure out how to drive the visitor based
802 /// on what data type is in the input.
804 /// When implementing `Deserialize`, you should avoid relying on
805 /// `Deserializer::deserialize_any` unless you need to be told by the
806 /// Deserializer what type is in the input. Know that relying on
807 /// `Deserializer::deserialize_any` means your data type will be able to
808 /// deserialize from self-describing formats only, ruling out Bincode and
810 fn deserialize_any
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
814 /// Hint that the `Deserialize` type is expecting a `bool` value.
815 fn deserialize_bool
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
819 /// Hint that the `Deserialize` type is expecting an `i8` value.
820 fn deserialize_i8
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
824 /// Hint that the `Deserialize` type is expecting an `i16` value.
825 fn deserialize_i16
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
829 /// Hint that the `Deserialize` type is expecting an `i32` value.
830 fn deserialize_i32
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
834 /// Hint that the `Deserialize` type is expecting an `i64` value.
835 fn deserialize_i64
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
839 /// Hint that the `Deserialize` type is expecting a `u8` value.
840 fn deserialize_u8
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
844 /// Hint that the `Deserialize` type is expecting a `u16` value.
845 fn deserialize_u16
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
849 /// Hint that the `Deserialize` type is expecting a `u32` value.
850 fn deserialize_u32
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
854 /// Hint that the `Deserialize` type is expecting a `u64` value.
855 fn deserialize_u64
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
859 /// Hint that the `Deserialize` type is expecting a `f32` value.
860 fn deserialize_f32
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
864 /// Hint that the `Deserialize` type is expecting a `f64` value.
865 fn deserialize_f64
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
869 /// Hint that the `Deserialize` type is expecting a `char` value.
870 fn deserialize_char
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
874 /// Hint that the `Deserialize` type is expecting a string value and does
875 /// not benefit from taking ownership of buffered data owned by the
878 /// If the `Visitor` would benefit from taking ownership of `String` data,
879 /// indiciate this to the `Deserializer` by using `deserialize_string`
881 fn deserialize_str
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
885 /// Hint that the `Deserialize` type is expecting a string value and would
886 /// benefit from taking ownership of buffered data owned by the
889 /// If the `Visitor` would not benefit from taking ownership of `String`
890 /// data, indicate that to the `Deserializer` by using `deserialize_str`
892 fn deserialize_string
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
896 /// Hint that the `Deserialize` type is expecting a byte array and does not
897 /// benefit from taking ownership of buffered data owned by the
900 /// If the `Visitor` would benefit from taking ownership of `Vec<u8>` data,
901 /// indicate this to the `Deserializer` by using `deserialize_byte_buf`
903 fn deserialize_bytes
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
907 /// Hint that the `Deserialize` type is expecting a byte array and would
908 /// benefit from taking ownership of buffered data owned by the
911 /// If the `Visitor` would not benefit from taking ownership of `Vec<u8>`
912 /// data, indicate that to the `Deserializer` by using `deserialize_bytes`
914 fn deserialize_byte_buf
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
918 /// Hint that the `Deserialize` type is expecting an optional value.
920 /// This allows deserializers that encode an optional value as a nullable
921 /// value to convert the null value into `None` and a regular value into
923 fn deserialize_option
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
927 /// Hint that the `Deserialize` type is expecting a unit value.
928 fn deserialize_unit
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
932 /// Hint that the `Deserialize` type is expecting a unit struct with a
934 fn deserialize_unit_struct
<V
>(
938 ) -> Result
<V
::Value
, Self::Error
>
942 /// Hint that the `Deserialize` type is expecting a newtype struct with a
944 fn deserialize_newtype_struct
<V
>(
948 ) -> Result
<V
::Value
, Self::Error
>
952 /// Hint that the `Deserialize` type is expecting a sequence of values.
953 fn deserialize_seq
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
957 /// Hint that the `Deserialize` type is expecting a sequence of values and
958 /// knows how many values there are without looking at the serialized data.
959 fn deserialize_tuple
<V
>(self, len
: usize, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
963 /// Hint that the `Deserialize` type is expecting a tuple struct with a
964 /// particular name and number of fields.
965 fn deserialize_tuple_struct
<V
>(
970 ) -> Result
<V
::Value
, Self::Error
>
974 /// Hint that the `Deserialize` type is expecting a map of key-value pairs.
975 fn deserialize_map
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
979 /// Hint that the `Deserialize` type is expecting a struct with a particular
981 fn deserialize_struct
<V
>(
984 fields
: &'
static [&'
static str],
986 ) -> Result
<V
::Value
, Self::Error
>
990 /// Hint that the `Deserialize` type is expecting an enum value with a
991 /// particular name and possible variants.
992 fn deserialize_enum
<V
>(
995 variants
: &'
static [&'
static str],
997 ) -> Result
<V
::Value
, Self::Error
>
1001 /// Hint that the `Deserialize` type is expecting the name of a struct
1002 /// field or the discriminant of an enum variant.
1003 fn deserialize_identifier
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1007 /// Hint that the `Deserialize` type needs to deserialize a value whose type
1008 /// doesn't matter because it is ignored.
1010 /// Deserializers for non-self-describing formats may not support this mode.
1011 fn deserialize_ignored_any
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1016 ////////////////////////////////////////////////////////////////////////////////
1018 /// This trait represents a visitor that walks through a deserializer.
1023 /// # use serde::de::{self, Unexpected, Visitor};
1025 /// /// A visitor that deserializes a long string - a string containing at least
1026 /// /// some minimum number of bytes.
1027 /// struct LongString {
1031 /// impl<'de> Visitor<'de> for LongString {
1032 /// type Value = String;
1034 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1035 /// write!(formatter, "a string containing at least {} bytes", self.min)
1038 /// fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
1039 /// where E: de::Error
1041 /// if s.len() >= self.min {
1042 /// Ok(s.to_owned())
1044 /// Err(de::Error::invalid_value(Unexpected::Str(s), &self))
1049 pub trait Visitor
<'de
>: Sized
{
1050 /// The value produced by this visitor.
1053 /// Format a message stating what data this Visitor expects to receive.
1055 /// This is used in error messages. The message should complete the sentence
1056 /// "This Visitor expects to receive ...", for example the message could be
1057 /// "an integer between 0 and 64". The message should not be capitalized and
1058 /// should not end with a period.
1067 /// # impl<'de> serde::de::Visitor<'de> for S {
1068 /// # type Value = ();
1070 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1071 /// write!(formatter, "an integer between 0 and {}", self.max)
1075 fn expecting(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
;
1077 /// The input contains a boolean.
1079 /// The default implementation fails with a type error.
1080 fn visit_bool
<E
>(self, v
: bool
) -> Result
<Self::Value
, E
>
1084 Err(Error
::invalid_type(Unexpected
::Bool(v
), &self))
1087 /// The input contains an `i8`.
1089 /// The default implementation forwards to [`visit_i64`].
1091 /// [`visit_i64`]: #method.visit_i64
1092 fn visit_i8
<E
>(self, v
: i8) -> Result
<Self::Value
, E
>
1096 self.visit_i64(v
as i64)
1099 /// The input contains an `i16`.
1101 /// The default implementation forwards to [`visit_i64`].
1103 /// [`visit_i64`]: #method.visit_i64
1104 fn visit_i16
<E
>(self, v
: i16) -> Result
<Self::Value
, E
>
1108 self.visit_i64(v
as i64)
1111 /// The input contains an `i32`.
1113 /// The default implementation forwards to [`visit_i64`].
1115 /// [`visit_i64`]: #method.visit_i64
1116 fn visit_i32
<E
>(self, v
: i32) -> Result
<Self::Value
, E
>
1120 self.visit_i64(v
as i64)
1123 /// The input contains an `i64`.
1125 /// The default implementation fails with a type error.
1126 fn visit_i64
<E
>(self, v
: i64) -> Result
<Self::Value
, E
>
1130 Err(Error
::invalid_type(Unexpected
::Signed(v
), &self))
1133 /// The input contains a `u8`.
1135 /// The default implementation forwards to [`visit_u64`].
1137 /// [`visit_u64`]: #method.visit_u64
1138 fn visit_u8
<E
>(self, v
: u8) -> Result
<Self::Value
, E
>
1142 self.visit_u64(v
as u64)
1145 /// The input contains a `u16`.
1147 /// The default implementation forwards to [`visit_u64`].
1149 /// [`visit_u64`]: #method.visit_u64
1150 fn visit_u16
<E
>(self, v
: u16) -> Result
<Self::Value
, E
>
1154 self.visit_u64(v
as u64)
1157 /// The input contains a `u32`.
1159 /// The default implementation forwards to [`visit_u64`].
1161 /// [`visit_u64`]: #method.visit_u64
1162 fn visit_u32
<E
>(self, v
: u32) -> Result
<Self::Value
, E
>
1166 self.visit_u64(v
as u64)
1169 /// The input contains a `u64`.
1171 /// The default implementation fails with a type error.
1172 fn visit_u64
<E
>(self, v
: u64) -> Result
<Self::Value
, E
>
1176 Err(Error
::invalid_type(Unexpected
::Unsigned(v
), &self))
1179 /// The input contains an `f32`.
1181 /// The default implementation forwards to [`visit_f64`].
1183 /// [`visit_f64`]: #method.visit_f64
1184 fn visit_f32
<E
>(self, v
: f32) -> Result
<Self::Value
, E
>
1188 self.visit_f64(v
as f64)
1191 /// The input contains an `f64`.
1193 /// The default implementation fails with a type error.
1194 fn visit_f64
<E
>(self, v
: f64) -> Result
<Self::Value
, E
>
1198 Err(Error
::invalid_type(Unexpected
::Float(v
), &self))
1201 /// The input contains a `char`.
1203 /// The default implementation forwards to [`visit_str`] as a one-character
1206 /// [`visit_str`]: #method.visit_str
1208 fn visit_char
<E
>(self, v
: char) -> Result
<Self::Value
, E
>
1212 self.visit_str(utf8
::encode(v
).as_str())
1215 /// The input contains a string. The lifetime of the string is ephemeral and
1216 /// it may be destroyed after this method returns.
1218 /// This method allows the `Deserializer` to avoid a copy by retaining
1219 /// ownership of any buffered data. `Deserialize` implementations that do
1220 /// not benefit from taking ownership of `String` data should indicate that
1221 /// to the deserializer by using `Deserializer::deserialize_str` rather than
1222 /// `Deserializer::deserialize_string`.
1224 /// It is never correct to implement `visit_string` without implementing
1225 /// `visit_str`. Implement neither, both, or just `visit_str`.
1226 fn visit_str
<E
>(self, v
: &str) -> Result
<Self::Value
, E
>
1230 Err(Error
::invalid_type(Unexpected
::Str(v
), &self))
1233 /// The input contains a string that lives at least as long as the
1236 /// This enables zero-copy deserialization of strings in some formats. For
1237 /// example JSON input containing the JSON string `"borrowed"` can be
1238 /// deserialized with zero copying into a `&'a str` as long as the input
1239 /// data outlives `'a`.
1241 /// The default implementation forwards to `visit_str`.
1243 fn visit_borrowed_str
<E
>(self, v
: &'de
str) -> Result
<Self::Value
, E
>
1250 /// The input contains a string and ownership of the string is being given
1251 /// to the `Visitor`.
1253 /// This method allows the `Visitor` to avoid a copy by taking ownership of
1254 /// a string created by the `Deserializer`. `Deserialize` implementations
1255 /// that benefit from taking ownership of `String` data should indicate that
1256 /// to the deserializer by using `Deserializer::deserialize_string` rather
1257 /// than `Deserializer::deserialize_str`, although not every deserializer
1258 /// will honor such a request.
1260 /// It is never correct to implement `visit_string` without implementing
1261 /// `visit_str`. Implement neither, both, or just `visit_str`.
1263 /// The default implementation forwards to `visit_str` and then drops the
1266 #[cfg(any(feature = "std", feature = "alloc"))]
1267 fn visit_string
<E
>(self, v
: String
) -> Result
<Self::Value
, E
>
1274 /// The input contains a byte array. The lifetime of the byte array is
1275 /// ephemeral and it may be destroyed after this method returns.
1277 /// This method allows the `Deserializer` to avoid a copy by retaining
1278 /// ownership of any buffered data. `Deserialize` implementations that do
1279 /// not benefit from taking ownership of `Vec<u8>` data should indicate that
1280 /// to the deserializer by using `Deserializer::deserialize_bytes` rather
1281 /// than `Deserializer::deserialize_byte_buf`.
1283 /// It is never correct to implement `visit_byte_buf` without implementing
1284 /// `visit_bytes`. Implement neither, both, or just `visit_bytes`.
1285 fn visit_bytes
<E
>(self, v
: &[u8]) -> Result
<Self::Value
, E
>
1290 Err(Error
::invalid_type(Unexpected
::Bytes(v
), &self))
1293 /// The input contains a byte array that lives at least as long as the
1296 /// This enables zero-copy deserialization of bytes in some formats. For
1297 /// example Bincode data containing bytes can be deserialized with zero
1298 /// copying into a `&'a [u8]` as long as the input data outlives `'a`.
1300 /// The default implementation forwards to `visit_bytes`.
1302 fn visit_borrowed_bytes
<E
>(self, v
: &'de
[u8]) -> Result
<Self::Value
, E
>
1309 /// The input contains a byte array and ownership of the byte array is being
1310 /// given to the `Visitor`.
1312 /// This method allows the `Visitor` to avoid a copy by taking ownership of
1313 /// a byte buffer created by the `Deserializer`. `Deserialize`
1314 /// implementations that benefit from taking ownership of `Vec<u8>` data
1315 /// should indicate that to the deserializer by using
1316 /// `Deserializer::deserialize_byte_buf` rather than
1317 /// `Deserializer::deserialize_bytes`, although not every deserializer will
1318 /// honor such a request.
1320 /// It is never correct to implement `visit_byte_buf` without implementing
1321 /// `visit_bytes`. Implement neither, both, or just `visit_bytes`.
1323 /// The default implementation forwards to `visit_bytes` and then drops the
1325 #[cfg(any(feature = "std", feature = "alloc"))]
1326 fn visit_byte_buf
<E
>(self, v
: Vec
<u8>) -> Result
<Self::Value
, E
>
1330 self.visit_bytes(&v
)
1333 /// The input contains an optional that is absent.
1335 /// The default implementation fails with a type error.
1336 fn visit_none
<E
>(self) -> Result
<Self::Value
, E
>
1340 Err(Error
::invalid_type(Unexpected
::Option
, &self))
1343 /// The input contains an optional that is present.
1345 /// The default implementation fails with a type error.
1346 fn visit_some
<D
>(self, deserializer
: D
) -> Result
<Self::Value
, D
::Error
>
1348 D
: Deserializer
<'de
>,
1350 let _
= deserializer
;
1351 Err(Error
::invalid_type(Unexpected
::Option
, &self))
1354 /// The input contains a unit `()`.
1356 /// The default implementation fails with a type error.
1357 fn visit_unit
<E
>(self) -> Result
<Self::Value
, E
>
1361 Err(Error
::invalid_type(Unexpected
::Unit
, &self))
1364 /// The input contains a newtype struct.
1366 /// The content of the newtype struct may be read from the given
1369 /// The default implementation fails with a type error.
1370 fn visit_newtype_struct
<D
>(self, deserializer
: D
) -> Result
<Self::Value
, D
::Error
>
1372 D
: Deserializer
<'de
>,
1374 let _
= deserializer
;
1375 Err(Error
::invalid_type(Unexpected
::NewtypeStruct
, &self))
1378 /// The input contains a sequence of elements.
1380 /// The default implementation fails with a type error.
1381 fn visit_seq
<A
>(self, seq
: A
) -> Result
<Self::Value
, A
::Error
>
1386 Err(Error
::invalid_type(Unexpected
::Seq
, &self))
1389 /// The input contains a key-value map.
1391 /// The default implementation fails with a type error.
1392 fn visit_map
<A
>(self, map
: A
) -> Result
<Self::Value
, A
::Error
>
1397 Err(Error
::invalid_type(Unexpected
::Map
, &self))
1400 /// The input contains an enum.
1402 /// The default implementation fails with a type error.
1403 fn visit_enum
<A
>(self, data
: A
) -> Result
<Self::Value
, A
::Error
>
1408 Err(Error
::invalid_type(Unexpected
::Enum
, &self))
1412 ////////////////////////////////////////////////////////////////////////////////
1414 /// Provides a `Visitor` access to each element of a sequence in the input.
1416 /// This is a trait that a `Deserializer` passes to a `Visitor` implementation,
1417 /// which deserializes each item in a sequence.
1418 pub trait SeqAccess
<'de
> {
1419 /// The error type that can be returned if some error occurs during
1420 /// deserialization.
1423 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1424 /// `Ok(None)` if there are no more remaining items.
1426 /// `Deserialize` implementations should typically use
1427 /// `SeqAccess::next_element` instead.
1428 fn next_element_seed
<T
>(&mut self, seed
: T
) -> Result
<Option
<T
::Value
>, Self::Error
>
1430 T
: DeserializeSeed
<'de
>;
1432 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1433 /// `Ok(None)` if there are no more remaining items.
1435 /// This method exists as a convenience for `Deserialize` implementations.
1436 /// `SeqAccess` implementations should not override the default behavior.
1438 fn next_element
<T
>(&mut self) -> Result
<Option
<T
>, Self::Error
>
1440 T
: Deserialize
<'de
>,
1442 self.next_element_seed(PhantomData
)
1445 /// Returns the number of elements remaining in the sequence, if known.
1447 fn size_hint(&self) -> Option
<usize> {
1452 impl<'de
, 'a
, A
> SeqAccess
<'de
> for &'a
mut A
1456 type Error
= A
::Error
;
1459 fn next_element_seed
<T
>(&mut self, seed
: T
) -> Result
<Option
<T
::Value
>, Self::Error
>
1461 T
: DeserializeSeed
<'de
>,
1463 (**self).next_element_seed(seed
)
1467 fn next_element
<T
>(&mut self) -> Result
<Option
<T
>, Self::Error
>
1469 T
: Deserialize
<'de
>,
1471 (**self).next_element()
1475 fn size_hint(&self) -> Option
<usize> {
1476 (**self).size_hint()
1480 ////////////////////////////////////////////////////////////////////////////////
1482 /// Provides a `Visitor` access to each entry of a map in the input.
1484 /// This is a trait that a `Deserializer` passes to a `Visitor` implementation.
1485 pub trait MapAccess
<'de
> {
1486 /// The error type that can be returned if some error occurs during
1487 /// deserialization.
1490 /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
1491 /// if there are no more remaining entries.
1493 /// `Deserialize` implementations should typically use
1494 /// `MapAccess::next_key` or `MapAccess::next_entry` instead.
1495 fn next_key_seed
<K
>(&mut self, seed
: K
) -> Result
<Option
<K
::Value
>, Self::Error
>
1497 K
: DeserializeSeed
<'de
>;
1499 /// This returns a `Ok(value)` for the next value in the map.
1501 /// `Deserialize` implementations should typically use
1502 /// `MapAccess::next_value` instead.
1506 /// Calling `next_value_seed` before `next_key_seed` is incorrect and is
1507 /// allowed to panic or return bogus results.
1508 fn next_value_seed
<V
>(&mut self, seed
: V
) -> Result
<V
::Value
, Self::Error
>
1510 V
: DeserializeSeed
<'de
>;
1512 /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in
1513 /// the map, or `Ok(None)` if there are no more remaining items.
1515 /// `MapAccess` implementations should override the default behavior if a
1516 /// more efficient implementation is possible.
1518 /// `Deserialize` implementations should typically use
1519 /// `MapAccess::next_entry` instead.
1521 fn next_entry_seed
<K
, V
>(
1525 ) -> Result
<Option
<(K
::Value
, V
::Value
)>, Self::Error
>
1527 K
: DeserializeSeed
<'de
>,
1528 V
: DeserializeSeed
<'de
>,
1530 match try
!(self.next_key_seed(kseed
)) {
1532 let value
= try
!(self.next_value_seed(vseed
));
1533 Ok(Some((key
, value
)))
1539 /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
1540 /// if there are no more remaining entries.
1542 /// This method exists as a convenience for `Deserialize` implementations.
1543 /// `MapAccess` implementations should not override the default behavior.
1545 fn next_key
<K
>(&mut self) -> Result
<Option
<K
>, Self::Error
>
1547 K
: Deserialize
<'de
>,
1549 self.next_key_seed(PhantomData
)
1552 /// This returns a `Ok(value)` for the next value in the map.
1554 /// This method exists as a convenience for `Deserialize` implementations.
1555 /// `MapAccess` implementations should not override the default behavior.
1559 /// Calling `next_value` before `next_key` is incorrect and is allowed to
1560 /// panic or return bogus results.
1562 fn next_value
<V
>(&mut self) -> Result
<V
, Self::Error
>
1564 V
: Deserialize
<'de
>,
1566 self.next_value_seed(PhantomData
)
1569 /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in
1570 /// the map, or `Ok(None)` if there are no more remaining items.
1572 /// This method exists as a convenience for `Deserialize` implementations.
1573 /// `MapAccess` implementations should not override the default behavior.
1575 fn next_entry
<K
, V
>(&mut self) -> Result
<Option
<(K
, V
)>, Self::Error
>
1577 K
: Deserialize
<'de
>,
1578 V
: Deserialize
<'de
>,
1580 self.next_entry_seed(PhantomData
, PhantomData
)
1583 /// Returns the number of entries remaining in the map, if known.
1585 fn size_hint(&self) -> Option
<usize> {
1590 impl<'de
, 'a
, A
> MapAccess
<'de
> for &'a
mut A
1594 type Error
= A
::Error
;
1597 fn next_key_seed
<K
>(&mut self, seed
: K
) -> Result
<Option
<K
::Value
>, Self::Error
>
1599 K
: DeserializeSeed
<'de
>,
1601 (**self).next_key_seed(seed
)
1605 fn next_value_seed
<V
>(&mut self, seed
: V
) -> Result
<V
::Value
, Self::Error
>
1607 V
: DeserializeSeed
<'de
>,
1609 (**self).next_value_seed(seed
)
1613 fn next_entry_seed
<K
, V
>(
1617 ) -> Result
<Option
<(K
::Value
, V
::Value
)>, Self::Error
>
1619 K
: DeserializeSeed
<'de
>,
1620 V
: DeserializeSeed
<'de
>,
1622 (**self).next_entry_seed(kseed
, vseed
)
1626 fn next_entry
<K
, V
>(&mut self) -> Result
<Option
<(K
, V
)>, Self::Error
>
1628 K
: Deserialize
<'de
>,
1629 V
: Deserialize
<'de
>,
1631 (**self).next_entry()
1635 fn next_key
<K
>(&mut self) -> Result
<Option
<K
>, Self::Error
>
1637 K
: Deserialize
<'de
>,
1643 fn next_value
<V
>(&mut self) -> Result
<V
, Self::Error
>
1645 V
: Deserialize
<'de
>,
1647 (**self).next_value()
1651 fn size_hint(&self) -> Option
<usize> {
1652 (**self).size_hint()
1656 ////////////////////////////////////////////////////////////////////////////////
1658 /// Provides a `Visitor` access to the data of an enum in the input.
1660 /// `EnumAccess` is created by the `Deserializer` and passed to the
1661 /// `Visitor` in order to identify which variant of an enum to deserialize.
1662 pub trait EnumAccess
<'de
>: Sized
{
1663 /// The error type that can be returned if some error occurs during
1664 /// deserialization.
1666 /// The `Visitor` that will be used to deserialize the content of the enum
1668 type Variant
: VariantAccess
<'de
, Error
= Self::Error
>;
1670 /// `variant` is called to identify which variant to deserialize.
1672 /// `Deserialize` implementations should typically use `EnumAccess::variant`
1674 fn variant_seed
<V
>(self, seed
: V
) -> Result
<(V
::Value
, Self::Variant
), Self::Error
>
1676 V
: DeserializeSeed
<'de
>;
1678 /// `variant` is called to identify which variant to deserialize.
1680 /// This method exists as a convenience for `Deserialize` implementations.
1681 /// `EnumAccess` implementations should not override the default behavior.
1683 fn variant
<V
>(self) -> Result
<(V
, Self::Variant
), Self::Error
>
1685 V
: Deserialize
<'de
>,
1687 self.variant_seed(PhantomData
)
1691 /// `VariantAccess` is a visitor that is created by the `Deserializer` and
1692 /// passed to the `Deserialize` to deserialize the content of a particular enum
1694 pub trait VariantAccess
<'de
>: Sized
{
1695 /// The error type that can be returned if some error occurs during
1696 /// deserialization. Must match the error type of our `EnumAccess`.
1699 /// Called when deserializing a variant with no values.
1701 /// If the data contains a different type of variant, the following
1702 /// `invalid_type` error should be constructed:
1705 /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
1709 /// # impl<'de> VariantAccess<'de> for X {
1710 /// # type Error = value::Error;
1712 /// fn unit_variant(self) -> Result<(), Self::Error> {
1713 /// // What the data actually contained; suppose it is a tuple variant.
1714 /// let unexp = Unexpected::TupleVariant;
1715 /// Err(de::Error::invalid_type(unexp, &"unit variant"))
1718 /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
1719 /// # where T: DeserializeSeed<'de>
1720 /// # { unimplemented!() }
1722 /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
1723 /// # where V: Visitor<'de>
1724 /// # { unimplemented!() }
1726 /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
1727 /// # where V: Visitor<'de>
1728 /// # { unimplemented!() }
1731 fn unit_variant(self) -> Result
<(), Self::Error
>;
1733 /// Called when deserializing a variant with a single value.
1735 /// `Deserialize` implementations should typically use
1736 /// `VariantAccess::newtype_variant` instead.
1738 /// If the data contains a different type of variant, the following
1739 /// `invalid_type` error should be constructed:
1742 /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
1746 /// # impl<'de> VariantAccess<'de> for X {
1747 /// # type Error = value::Error;
1749 /// # fn unit_variant(self) -> Result<(), Self::Error> {
1750 /// # unimplemented!()
1753 /// fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
1754 /// where T: DeserializeSeed<'de>
1756 /// // What the data actually contained; suppose it is a unit variant.
1757 /// let unexp = Unexpected::UnitVariant;
1758 /// Err(de::Error::invalid_type(unexp, &"newtype variant"))
1761 /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
1762 /// # where V: Visitor<'de>
1763 /// # { unimplemented!() }
1765 /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
1766 /// # where V: Visitor<'de>
1767 /// # { unimplemented!() }
1770 fn newtype_variant_seed
<T
>(self, seed
: T
) -> Result
<T
::Value
, Self::Error
>
1772 T
: DeserializeSeed
<'de
>;
1774 /// Called when deserializing a variant with a single value.
1776 /// This method exists as a convenience for `Deserialize` implementations.
1777 /// `VariantAccess` implementations should not override the default
1780 fn newtype_variant
<T
>(self) -> Result
<T
, Self::Error
>
1782 T
: Deserialize
<'de
>,
1784 self.newtype_variant_seed(PhantomData
)
1787 /// Called when deserializing a tuple-like variant.
1789 /// The `len` is the number of fields expected in the tuple variant.
1791 /// If the data contains a different type of variant, the following
1792 /// `invalid_type` error should be constructed:
1795 /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
1799 /// # impl<'de> VariantAccess<'de> for X {
1800 /// # type Error = value::Error;
1802 /// # fn unit_variant(self) -> Result<(), Self::Error> {
1803 /// # unimplemented!()
1806 /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
1807 /// # where T: DeserializeSeed<'de>
1808 /// # { unimplemented!() }
1810 /// fn tuple_variant<V>(self,
1812 /// _visitor: V) -> Result<V::Value, Self::Error>
1813 /// where V: Visitor<'de>
1815 /// // What the data actually contained; suppose it is a unit variant.
1816 /// let unexp = Unexpected::UnitVariant;
1817 /// Err(de::Error::invalid_type(unexp, &"tuple variant"))
1820 /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
1821 /// # where V: Visitor<'de>
1822 /// # { unimplemented!() }
1825 fn tuple_variant
<V
>(self, len
: usize, visitor
: V
) -> Result
<V
::Value
, Self::Error
>
1829 /// Called when deserializing a struct-like variant.
1831 /// The `fields` are the names of the fields of the struct variant.
1833 /// If the data contains a different type of variant, the following
1834 /// `invalid_type` error should be constructed:
1837 /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
1841 /// # impl<'de> VariantAccess<'de> for X {
1842 /// # type Error = value::Error;
1844 /// # fn unit_variant(self) -> Result<(), Self::Error> {
1845 /// # unimplemented!()
1848 /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
1849 /// # where T: DeserializeSeed<'de>
1850 /// # { unimplemented!() }
1852 /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
1853 /// # where V: Visitor<'de>
1854 /// # { unimplemented!() }
1856 /// fn struct_variant<V>(self,
1857 /// _fields: &'static [&'static str],
1858 /// _visitor: V) -> Result<V::Value, Self::Error>
1859 /// where V: Visitor<'de>
1861 /// // What the data actually contained; suppose it is a unit variant.
1862 /// let unexp = Unexpected::UnitVariant;
1863 /// Err(de::Error::invalid_type(unexp, &"struct variant"))
1867 fn struct_variant
<V
>(
1869 fields
: &'
static [&'
static str],
1871 ) -> Result
<V
::Value
, Self::Error
>
1876 ////////////////////////////////////////////////////////////////////////////////
1878 /// Converts an existing value into a `Deserializer` from which other values can
1879 /// be deserialized.
1883 /// extern crate serde_derive;
1885 /// extern crate serde;
1887 /// use std::str::FromStr;
1888 /// use serde::de::{value, Deserialize, IntoDeserializer};
1890 /// #[derive(Deserialize)]
1896 /// impl FromStr for Setting {
1897 /// type Err = value::Error;
1899 /// fn from_str(s: &str) -> Result<Self, Self::Err> {
1900 /// Self::deserialize(s.into_deserializer())
1906 pub trait IntoDeserializer
<'de
, E
: Error
= value
::Error
> {
1907 /// The type of the deserializer being converted into.
1908 type Deserializer
: Deserializer
<'de
, Error
= E
>;
1910 /// Convert this value into a deserializer.
1911 fn into_deserializer(self) -> Self::Deserializer
;
1914 ////////////////////////////////////////////////////////////////////////////////
1916 /// Used in error messages.
1919 /// - expected `a` or `b`
1920 /// - expected one of `a`, `b`, `c`
1922 /// The slice of names must not be empty.
1924 names
: &'
static [&'
static str],
1927 impl Display
for OneOf
{
1928 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
1929 match self.names
.len() {
1930 0 => panic
!(), // special case elsewhere
1931 1 => write
!(formatter
, "`{}`", self.names
[0]),
1932 2 => write
!(formatter
, "`{}` or `{}`", self.names
[0], self.names
[1]),
1934 try
!(write
!(formatter
, "one of "));
1935 for (i
, alt
) in self.names
.iter().enumerate() {
1937 try
!(write
!(formatter
, ", "));
1939 try
!(write
!(formatter
, "`{}`", alt
));