Skip to content
Myr

mod.rs

This file

Path

serde_core/src/de/mod.rs

2,392 lines · 81.9 KiB · Rust

Last changed by

Merge pull request #2992 from dtolnay/inplaceseedDavid Tolnaybefore adoption9d3410e

History of this file

Take it

1//! Generic data structure deserialization framework.2//!3//! The two most important traits in this module are [`Deserialize`] and4//! [`Deserializer`].5//!6//!  - **A type that implements `Deserialize` is a data structure** that can be7//!    deserialized from any data format supported by Serde, and conversely8//!  - **A type that implements `Deserializer` is a data format** that can9//!    deserialize any data structure supported by Serde.10//!11//! # The Deserialize trait12//!13//! Serde provides [`Deserialize`] implementations for many Rust primitive and14//! standard library types. The complete list is below. All of these can be15//! deserialized using Serde out of the box.16//!17//! Additionally, Serde provides a procedural macro called [`serde_derive`] to18//! automatically generate [`Deserialize`] implementations for structs and enums19//! in your program. See the [derive section of the manual] for how to use this.20//!21//! In rare cases it may be necessary to implement [`Deserialize`] manually for22//! some type in your program. See the [Implementing `Deserialize`] section of23//! the manual for more about this.24//!25//! Third-party crates may provide [`Deserialize`] implementations for types26//! that they expose. For example the [`linked-hash-map`] crate provides a27//! [`LinkedHashMap<K, V>`] type that is deserializable by Serde because the28//! crate provides an implementation of [`Deserialize`] for it.29//!30//! # The Deserializer trait31//!32//! [`Deserializer`] implementations are provided by third-party crates, for33//! example [`serde_json`], [`serde_yaml`] and [`postcard`].34//!35//! A partial list of well-maintained formats is given on the [Serde36//! website][data formats].37//!38//! # Implementations of Deserialize provided by Serde39//!40//! This is a slightly different set of types than what is supported for41//! serialization. Some types can be serialized by Serde but not deserialized.42//! One example is `OsStr`.43//!44//!  - **Primitive types**:45//!    - bool46//!    - i8, i16, i32, i64, i128, isize47//!    - u8, u16, u32, u64, u128, usize48//!    - f32, f6449//!    - char50//!  - **Compound types**:51//!    - \[T; 0\] through \[T; 32\]52//!    - tuples up to size 1653//!  - **Common standard library types**:54//!    - String55//!    - Option\<T\>56//!    - Result\<T, E\>57//!    - PhantomData\<T\>58//!  - **Wrapper types**:59//!    - Box\<T\>60//!    - Box\<\[T\]\>61//!    - Box\<str\>62//!    - Cow\<'a, T\>63//!    - Cell\<T\>64//!    - RefCell\<T\>65//!    - Mutex\<T\>66//!    - RwLock\<T\>67//!    - Rc\<T\>&emsp;*(if* features = \["rc"\] *is enabled)*68//!    - Arc\<T\>&emsp;*(if* features = \["rc"\] *is enabled)*69//!  - **Collection types**:70//!    - BTreeMap\<K, V\>71//!    - BTreeSet\<T\>72//!    - BinaryHeap\<T\>73//!    - HashMap\<K, V, H\>74//!    - HashSet\<T, H\>75//!    - LinkedList\<T\>76//!    - VecDeque\<T\>77//!    - Vec\<T\>78//!  - **Zero-copy types**:79//!    - &str80//!    - &\[u8\]81//!  - **FFI types**:82//!    - CString83//!    - Box\<CStr\>84//!    - OsString85//!  - **Miscellaneous standard library types**:86//!    - Duration87//!    - SystemTime88//!    - Path89//!    - PathBuf90//!    - Range\<T\>91//!    - RangeInclusive\<T\>92//!    - Bound\<T\>93//!    - num::NonZero*94//!    - `!` *(unstable)*95//!  - **Net types**:96//!    - IpAddr97//!    - Ipv4Addr98//!    - Ipv6Addr99//!    - SocketAddr100//!    - SocketAddrV4101//!    - SocketAddrV6102//!103//! [Implementing `Deserialize`]: https://serde.rs/impl-deserialize.html104//! [`Deserialize`]: crate::Deserialize105//! [`Deserializer`]: crate::Deserializer106//! [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html107//! [`postcard`]: https://github.com/jamesmunns/postcard108//! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map109//! [`serde_derive`]: https://crates.io/crates/serde_derive110//! [`serde_json`]: https://github.com/serde-rs/json111//! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml112//! [derive section of the manual]: https://serde.rs/derive.html113//! [data formats]: https://serde.rs/#data-formats114115use crate::lib::*;116117////////////////////////////////////////////////////////////////////////////////118119pub mod value;120121mod ignored_any;122mod impls;123124pub use self::ignored_any::IgnoredAny;125#[cfg(all(not(feature = "std"), no_core_error))]126#[doc(no_inline)]127pub use crate::std_error::Error as StdError;128#[cfg(not(any(feature = "std", no_core_error)))]129#[doc(no_inline)]130pub use core::error::Error as StdError;131#[cfg(feature = "std")]132#[doc(no_inline)]133pub use std::error::Error as StdError;134135////////////////////////////////////////////////////////////////////////////////136137macro_rules! declare_error_trait {138    (Error: Sized $(+ $($supertrait:ident)::+)*) => {139        /// The `Error` trait allows `Deserialize` implementations to create descriptive140        /// error messages belonging to the `Deserializer` against which they are141        /// currently running.142        ///143        /// Every `Deserializer` declares an `Error` type that encompasses both144        /// general-purpose deserialization errors as well as errors specific to the145        /// particular deserialization format. For example the `Error` type of146        /// `serde_json` can represent errors like an invalid JSON escape sequence or an147        /// unterminated string literal, in addition to the error cases that are part of148        /// this trait.149        ///150        /// Most deserializers should only need to provide the `Error::custom` method151        /// and inherit the default behavior for the other methods.152        ///153        /// # Example implementation154        ///155        /// The [example data format] presented on the website shows an error156        /// type appropriate for a basic JSON data format.157        ///158        /// [example data format]: https://serde.rs/data-format.html159        #[cfg_attr(160            not(no_diagnostic_namespace),161            diagnostic::on_unimplemented(162                message = "the trait bound `{Self}: serde::de::Error` is not satisfied",163            )164        )]165        pub trait Error: Sized $(+ $($supertrait)::+)* {166            /// Raised when there is general error when deserializing a type.167            ///168            /// The message should not be capitalized and should not end with a period.169            ///170            /// ```edition2021171            /// # use std::str::FromStr;172            /// #173            /// # struct IpAddr;174            /// #175            /// # impl FromStr for IpAddr {176            /// #     type Err = String;177            /// #178            /// #     fn from_str(_: &str) -> Result<Self, String> {179            /// #         unimplemented!()180            /// #     }181            /// # }182            /// #183            /// use serde::de::{self, Deserialize, Deserializer};184            ///185            /// impl<'de> Deserialize<'de> for IpAddr {186            ///     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>187            ///     where188            ///         D: Deserializer<'de>,189            ///     {190            ///         let s = String::deserialize(deserializer)?;191            ///         s.parse().map_err(de::Error::custom)192            ///     }193            /// }194            /// ```195            fn custom<T>(msg: T) -> Self196            where197                T: Display;198199            /// Raised when a `Deserialize` receives a type different from what it was200            /// expecting.201            ///202            /// The `unexp` argument provides information about what type was received.203            /// This is the type that was present in the input file or other source data204            /// of the Deserializer.205            ///206            /// The `exp` argument provides information about what type was being207            /// expected. This is the type that is written in the program.208            ///209            /// For example if we try to deserialize a String out of a JSON file210            /// containing an integer, the unexpected type is the integer and the211            /// expected type is the string.212            #[cold]213            fn invalid_type(unexp: Unexpected, exp: &dyn Expected) -> Self {214                Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp))215            }216217            /// Raised when a `Deserialize` receives a value of the right type but that218            /// is wrong for some other reason.219            ///220            /// The `unexp` argument provides information about what value was received.221            /// This is the value that was present in the input file or other source222            /// data of the Deserializer.223            ///224            /// The `exp` argument provides information about what value was being225            /// expected. This is the type that is written in the program.226            ///227            /// For example if we try to deserialize a String out of some binary data228            /// that is not valid UTF-8, the unexpected value is the bytes and the229            /// expected value is a string.230            #[cold]231            fn invalid_value(unexp: Unexpected, exp: &dyn Expected) -> Self {232                Error::custom(format_args!("invalid value: {}, expected {}", unexp, exp))233            }234235            /// Raised when deserializing a sequence or map and the input data contains236            /// too many or too few elements.237            ///238            /// The `len` argument is the number of elements encountered. The sequence239            /// or map may have expected more arguments or fewer arguments.240            ///241            /// The `exp` argument provides information about what data was being242            /// expected. For example `exp` might say that a tuple of size 6 was243            /// expected.244            #[cold]245            fn invalid_length(len: usize, exp: &dyn Expected) -> Self {246                Error::custom(format_args!("invalid length {}, expected {}", len, exp))247            }248249            /// Raised when a `Deserialize` enum type received a variant with an250            /// unrecognized name.251            #[cold]252            fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self {253                if expected.is_empty() {254                    Error::custom(format_args!(255                        "unknown variant `{}`, there are no variants",256                        variant257                    ))258                } else {259                    Error::custom(format_args!(260                        "unknown variant `{}`, expected {}",261                        variant,262                        OneOf { names: expected }263                    ))264                }265            }266267            /// Raised when a `Deserialize` struct type received a field with an268            /// unrecognized name.269            #[cold]270            fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {271                if expected.is_empty() {272                    Error::custom(format_args!(273                        "unknown field `{}`, there are no fields",274                        field275                    ))276                } else {277                    Error::custom(format_args!(278                        "unknown field `{}`, expected {}",279                        field,280                        OneOf { names: expected }281                    ))282                }283            }284285            /// Raised when a `Deserialize` struct type expected to receive a required286            /// field with a particular name but that field was not present in the287            /// input.288            #[cold]289            fn missing_field(field: &'static str) -> Self {290                Error::custom(format_args!("missing field `{}`", field))291            }292293            /// Raised when a `Deserialize` struct type received more than one of the294            /// same field.295            #[cold]296            fn duplicate_field(field: &'static str) -> Self {297                Error::custom(format_args!("duplicate field `{}`", field))298            }299        }300    }301}302303#[cfg(feature = "std")]304declare_error_trait!(Error: Sized + StdError);305306#[cfg(not(feature = "std"))]307declare_error_trait!(Error: Sized + Debug + Display);308309/// `Unexpected` represents an unexpected invocation of any one of the `Visitor`310/// trait methods.311///312/// This is used as an argument to the `invalid_type`, `invalid_value`, and313/// `invalid_length` methods of the `Error` trait to build error messages.314///315/// ```edition2021316/// # use std::fmt;317/// #318/// # use serde::de::{self, Unexpected, Visitor};319/// #320/// # struct Example;321/// #322/// # impl<'de> Visitor<'de> for Example {323/// #     type Value = ();324/// #325/// #     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {326/// #         write!(formatter, "definitely not a boolean")327/// #     }328/// #329/// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>330/// where331///     E: de::Error,332/// {333///     Err(de::Error::invalid_type(Unexpected::Bool(v), &self))334/// }335/// # }336/// ```337#[derive(Copy, Clone, PartialEq, Debug)]338pub enum Unexpected<'a> {339    /// The input contained a boolean value that was not expected.340    Bool(bool),341342    /// The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that343    /// was not expected.344    Unsigned(u64),345346    /// The input contained a signed integer `i8`, `i16`, `i32` or `i64` that347    /// was not expected.348    Signed(i64),349350    /// The input contained a floating point `f32` or `f64` that was not351    /// expected.352    Float(f64),353354    /// The input contained a `char` that was not expected.355    Char(char),356357    /// The input contained a `&str` or `String` that was not expected.358    Str(&'a str),359360    /// The input contained a `&[u8]` or `Vec<u8>` that was not expected.361    Bytes(&'a [u8]),362363    /// The input contained a unit `()` that was not expected.364    Unit,365366    /// The input contained an `Option<T>` that was not expected.367    Option,368369    /// The input contained a newtype struct that was not expected.370    NewtypeStruct,371372    /// The input contained a sequence that was not expected.373    Seq,374375    /// The input contained a map that was not expected.376    Map,377378    /// The input contained an enum that was not expected.379    Enum,380381    /// The input contained a unit variant that was not expected.382    UnitVariant,383384    /// The input contained a newtype variant that was not expected.385    NewtypeVariant,386387    /// The input contained a tuple variant that was not expected.388    TupleVariant,389390    /// The input contained a struct variant that was not expected.391    StructVariant,392393    /// A message stating what uncategorized thing the input contained that was394    /// not expected.395    ///396    /// The message should be a noun or noun phrase, not capitalized and without397    /// a period. An example message is "unoriginal superhero".398    Other(&'a str),399}400401impl<'a> fmt::Display for Unexpected<'a> {402    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {403        use self::Unexpected::*;404        match *self {405            Bool(b) => write!(formatter, "boolean `{}`", b),406            Unsigned(i) => write!(formatter, "integer `{}`", i),407            Signed(i) => write!(formatter, "integer `{}`", i),408            Float(f) => write!(formatter, "floating point `{}`", WithDecimalPoint(f)),409            Char(c) => write!(formatter, "character `{}`", c),410            Str(s) => write!(formatter, "string {:?}", s),411            Bytes(_) => formatter.write_str("byte array"),412            Unit => formatter.write_str("unit value"),413            Option => formatter.write_str("Option value"),414            NewtypeStruct => formatter.write_str("newtype struct"),415            Seq => formatter.write_str("sequence"),416            Map => formatter.write_str("map"),417            Enum => formatter.write_str("enum"),418            UnitVariant => formatter.write_str("unit variant"),419            NewtypeVariant => formatter.write_str("newtype variant"),420            TupleVariant => formatter.write_str("tuple variant"),421            StructVariant => formatter.write_str("struct variant"),422            Other(other) => formatter.write_str(other),423        }424    }425}426427/// `Expected` represents an explanation of what data a `Visitor` was expecting428/// to receive.429///430/// This is used as an argument to the `invalid_type`, `invalid_value`, and431/// `invalid_length` methods of the `Error` trait to build error messages. The432/// message should be a noun or noun phrase that completes the sentence "This433/// Visitor expects to receive ...", for example the message could be "an434/// integer between 0 and 64". The message should not be capitalized and should435/// not end with a period.436///437/// Within the context of a `Visitor` implementation, the `Visitor` itself438/// (`&self`) is an implementation of this trait.439///440/// ```edition2021441/// # use serde::de::{self, Unexpected, Visitor};442/// # use std::fmt;443/// #444/// # struct Example;445/// #446/// # impl<'de> Visitor<'de> for Example {447/// #     type Value = ();448/// #449/// #     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {450/// #         write!(formatter, "definitely not a boolean")451/// #     }452/// #453/// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>454/// where455///     E: de::Error,456/// {457///     Err(de::Error::invalid_type(Unexpected::Bool(v), &self))458/// }459/// # }460/// ```461///462/// Outside of a `Visitor`, `&"..."` can be used.463///464/// ```edition2021465/// # use serde::de::{self, Unexpected};466/// #467/// # fn example<E>() -> Result<(), E>468/// # where469/// #     E: de::Error,470/// # {471/// #     let v = true;472/// return Err(de::Error::invalid_type(473///     Unexpected::Bool(v),474///     &"a negative integer",475/// ));476/// # }477/// ```478#[cfg_attr(479    not(no_diagnostic_namespace),480    diagnostic::on_unimplemented(481        message = "the trait bound `{Self}: serde::de::Expected` is not satisfied",482    )483)]484pub trait Expected {485    /// Format an explanation of what data was being expected. Same signature as486    /// the `Display` and `Debug` traits.487    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result;488}489490impl<'de, T> Expected for T491where492    T: Visitor<'de>,493{494    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {495        self.expecting(formatter)496    }497}498499impl Expected for &str {500    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {501        formatter.write_str(self)502    }503}504505impl Display for dyn Expected + '_ {506    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {507        Expected::fmt(self, formatter)508    }509}510511////////////////////////////////////////////////////////////////////////////////512513/// A **data structure** that can be deserialized from any data format supported514/// by Serde.515///516/// Serde provides `Deserialize` implementations for many Rust primitive and517/// standard library types. The complete list is [here][crate::de]. All of these518/// can be deserialized using Serde out of the box.519///520/// Additionally, Serde provides a procedural macro called `serde_derive` to521/// automatically generate `Deserialize` implementations for structs and enums522/// in your program. See the [derive section of the manual][derive] for how to523/// use this.524///525/// In rare cases it may be necessary to implement `Deserialize` manually for526/// some type in your program. See the [Implementing527/// `Deserialize`][impl-deserialize] section of the manual for more about this.528///529/// Third-party crates may provide `Deserialize` implementations for types that530/// they expose. For example the `linked-hash-map` crate provides a531/// `LinkedHashMap<K, V>` type that is deserializable by Serde because the crate532/// provides an implementation of `Deserialize` for it.533///534/// [derive]: https://serde.rs/derive.html535/// [impl-deserialize]: https://serde.rs/impl-deserialize.html536///537/// # Lifetime538///539/// The `'de` lifetime of this trait is the lifetime of data that may be540/// borrowed by `Self` when deserialized. See the page [Understanding541/// deserializer lifetimes] for a more detailed explanation of these lifetimes.542///543/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html544#[cfg_attr(545    not(no_diagnostic_namespace),546    diagnostic::on_unimplemented(547        // Prevents `serde_core::de::Deserialize` appearing in the error message548        // in projects with no direct dependency on serde_core.549        message = "the trait bound `{Self}: serde::Deserialize<'de>` is not satisfied",550        note = "for local types consider adding `#[derive(serde::Deserialize)]` to your `{Self}` type",551        note = "for types from other crates check whether the crate offers a `serde` feature flag",552    )553)]554pub trait Deserialize<'de>: Sized {555    /// Deserialize this value from the given Serde deserializer.556    ///557    /// See the [Implementing `Deserialize`][impl-deserialize] section of the558    /// manual for more information about how to implement this method.559    ///560    /// [impl-deserialize]: https://serde.rs/impl-deserialize.html561    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>562    where563        D: Deserializer<'de>;564565    /// Deserializes a value into `self` from the given Deserializer.566    ///567    /// The purpose of this method is to allow the deserializer to reuse568    /// resources and avoid copies. As such, if this method returns an error,569    /// `self` will be in an indeterminate state where some parts of the struct570    /// have been overwritten. Although whatever state that is will be571    /// memory-safe.572    ///573    /// This is generally useful when repeatedly deserializing values that574    /// are processed one at a time, where the value of `self` doesn't matter575    /// when the next deserialization occurs.576    ///577    /// If you manually implement this, your recursive deserializations should578    /// use `deserialize_in_place`.579    ///580    /// This method is stable and an official public API, but hidden from the581    /// documentation because it is almost never what newbies are looking for.582    /// Showing it in rustdoc would cause it to be featured more prominently583    /// than it deserves.584    #[doc(hidden)]585    fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>586    where587        D: Deserializer<'de>,588    {589        // Default implementation just delegates to `deserialize` impl.590        *place = tri!(Deserialize::deserialize(deserializer));591        Ok(())592    }593}594595/// A data structure that can be deserialized without borrowing any data from596/// the deserializer.597///598/// This is primarily useful for trait bounds on functions. For example a599/// `from_str` function may be able to deserialize a data structure that borrows600/// from the input string, but a `from_reader` function may only deserialize601/// owned data.602///603/// ```edition2021604/// # use serde::de::{Deserialize, DeserializeOwned};605/// # use std::io::{Read, Result};606/// #607/// # trait Ignore {608/// fn from_str<'a, T>(s: &'a str) -> Result<T>609/// where610///     T: Deserialize<'a>;611///612/// fn from_reader<R, T>(rdr: R) -> Result<T>613/// where614///     R: Read,615///     T: DeserializeOwned;616/// # }617/// ```618///619/// # Lifetime620///621/// The relationship between `Deserialize` and `DeserializeOwned` in trait622/// bounds is explained in more detail on the page [Understanding deserializer623/// lifetimes].624///625/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html626#[cfg_attr(627    not(no_diagnostic_namespace),628    diagnostic::on_unimplemented(629        message = "the trait bound `{Self}: serde::de::DeserializeOwned` is not satisfied",630    )631)]632pub trait DeserializeOwned: for<'de> Deserialize<'de> {}633impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}634635/// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you636/// ever find yourself looking for a way to pass data into a `Deserialize` impl,637/// this trait is the way to do it.638///639/// As one example of stateful deserialization consider deserializing a JSON640/// array into an existing buffer. Using the `Deserialize` trait we could641/// deserialize a JSON array into a `Vec<T>` but it would be a freshly allocated642/// `Vec<T>`; there is no way for `Deserialize` to reuse a previously allocated643/// buffer. Using `DeserializeSeed` instead makes this possible as in the644/// example code below.645///646/// The canonical API for stateless deserialization looks like this:647///648/// ```edition2021649/// # use serde::Deserialize;650/// #651/// # enum Error {}652/// #653/// fn func<'de, T: Deserialize<'de>>() -> Result<T, Error>654/// # {655/// #     unimplemented!()656/// # }657/// ```658///659/// Adjusting an API like this to support stateful deserialization is a matter660/// of accepting a seed as input:661///662/// ```edition2021663/// # use serde::de::DeserializeSeed;664/// #665/// # enum Error {}666/// #667/// fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result<T::Value, Error>668/// # {669/// #     let _ = seed;670/// #     unimplemented!()671/// # }672/// ```673///674/// In practice the majority of deserialization is stateless. An API expecting a675/// seed can be appeased by passing `std::marker::PhantomData` as a seed in the676/// case of stateless deserialization.677///678/// # Lifetime679///680/// The `'de` lifetime of this trait is the lifetime of data that may be681/// borrowed by `Self::Value` when deserialized. See the page [Understanding682/// deserializer lifetimes] for a more detailed explanation of these lifetimes.683///684/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html685///686/// # Example687///688/// Suppose we have JSON that looks like `[[1, 2], [3, 4, 5], [6]]` and we need689/// to deserialize it into a flat representation like `vec![1, 2, 3, 4, 5, 6]`.690/// Allocating a brand new `Vec<T>` for each subarray would be slow. Instead we691/// would like to allocate a single `Vec<T>` and then deserialize each subarray692/// into it. This requires stateful deserialization using the `DeserializeSeed`693/// trait.694///695/// ```edition2021696/// use serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor};697/// use std::fmt;698/// use std::marker::PhantomData;699///700/// // A DeserializeSeed implementation that uses stateful deserialization to701/// // append array elements onto the end of an existing vector. The preexisting702/// // state ("seed") in this case is the Vec<T>. The `deserialize` method of703/// // `ExtendVec` will be traversing the inner arrays of the JSON input and704/// // appending each integer into the existing Vec.705/// struct ExtendVec<'a, T: 'a>(&'a mut Vec<T>);706///707/// impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T>708/// where709///     T: Deserialize<'de>,710/// {711///     // The return type of the `deserialize` method. This implementation712///     // appends onto an existing vector but does not create any new data713///     // structure, so the return type is ().714///     type Value = ();715///716///     fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>717///     where718///         D: Deserializer<'de>,719///     {720///         // Visitor implementation that will walk an inner array of the JSON721///         // input.722///         struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec<T>);723///724///         impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T>725///         where726///             T: Deserialize<'de>,727///         {728///             type Value = ();729///730///             fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {731///                 write!(formatter, "an array of integers")732///             }733///734///             fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error>735///             where736///                 A: SeqAccess<'de>,737///             {738///                 // Decrease the number of reallocations if there are many elements739///                 if let Some(size_hint) = seq.size_hint() {740///                     self.0.reserve(size_hint);741///                 }742///743///                 // Visit each element in the inner array and push it onto744///                 // the existing vector.745///                 while let Some(elem) = seq.next_element()? {746///                     self.0.push(elem);747///                 }748///                 Ok(())749///             }750///         }751///752///         deserializer.deserialize_seq(ExtendVecVisitor(self.0))753///     }754/// }755///756/// // Visitor implementation that will walk the outer array of the JSON input.757/// struct FlattenedVecVisitor<T>(PhantomData<T>);758///759/// impl<'de, T> Visitor<'de> for FlattenedVecVisitor<T>760/// where761///     T: Deserialize<'de>,762/// {763///     // This Visitor constructs a single Vec<T> to hold the flattened764///     // contents of the inner arrays.765///     type Value = Vec<T>;766///767///     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {768///         write!(formatter, "an array of arrays")769///     }770///771///     fn visit_seq<A>(self, mut seq: A) -> Result<Vec<T>, A::Error>772///     where773///         A: SeqAccess<'de>,774///     {775///         // Create a single Vec to hold the flattened contents.776///         let mut vec = Vec::new();777///778///         // Each iteration through this loop is one inner array.779///         while let Some(()) = seq.next_element_seed(ExtendVec(&mut vec))? {780///             // Nothing to do; inner array has been appended into `vec`.781///         }782///783///         // Return the finished vec.784///         Ok(vec)785///     }786/// }787///788/// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error>789/// # where790/// #     D: Deserializer<'de>,791/// # {792/// let visitor = FlattenedVecVisitor(PhantomData);793/// let flattened: Vec<u64> = deserializer.deserialize_seq(visitor)?;794/// #     Ok(())795/// # }796/// ```797#[cfg_attr(798    not(no_diagnostic_namespace),799    diagnostic::on_unimplemented(800        message = "the trait bound `{Self}: serde::de::DeserializeSeed<'de>` is not satisfied",801    )802)]803pub trait DeserializeSeed<'de>: Sized {804    /// The type produced by using this seed.805    type Value;806807    /// Equivalent to the more common `Deserialize::deserialize` method, except808    /// with some initial piece of data (the seed) passed in.809    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>810    where811        D: Deserializer<'de>;812}813814impl<'de, T> DeserializeSeed<'de> for PhantomData<T>815where816    T: Deserialize<'de>,817{818    type Value = T;819820    #[inline]821    fn deserialize<D>(self, deserializer: D) -> Result<T, D::Error>822    where823        D: Deserializer<'de>,824    {825        T::deserialize(deserializer)826    }827}828829////////////////////////////////////////////////////////////////////////////////830831/// A **data format** that can deserialize any data structure supported by832/// Serde.833///834/// The role of this trait is to define the deserialization half of the [Serde835/// data model], which is a way to categorize every Rust data type into one of836/// 29 possible types. Each method of the `Deserializer` trait corresponds to one837/// of the types of the data model.838///839/// Implementations of `Deserialize` map themselves into this data model by840/// passing to the `Deserializer` a `Visitor` implementation that can receive841/// these various types.842///843/// The types that make up the Serde data model are:844///845///  - **14 primitive types**846///    - bool847///    - i8, i16, i32, i64, i128848///    - u8, u16, u32, u64, u128849///    - f32, f64850///    - char851///  - **string**852///    - UTF-8 bytes with a length and no null terminator.853///    - When serializing, all strings are handled equally. When deserializing,854///      there are three flavors of strings: transient, owned, and borrowed.855///  - **byte array** - \[u8\]856///    - Similar to strings, during deserialization byte arrays can be857///      transient, owned, or borrowed.858///  - **option**859///    - Either none or some value.860///  - **unit**861///    - The type of `()` in Rust. It represents an anonymous value containing862///      no data.863///  - **unit_struct**864///    - For example `struct Unit` or `PhantomData<T>`. It represents a named865///      value containing no data.866///  - **unit_variant**867///    - For example the `E::A` and `E::B` in `enum E { A, B }`.868///  - **newtype_struct**869///    - For example `struct Millimeters(u8)`.870///  - **newtype_variant**871///    - For example the `E::N` in `enum E { N(u8) }`.872///  - **seq**873///    - A variably sized heterogeneous sequence of values, for example `Vec<T>`874///      or `HashSet<T>`. When serializing, the length may or may not be known875///      before iterating through all the data. When deserializing, the length876///      is determined by looking at the serialized data.877///  - **tuple**878///    - A statically sized heterogeneous sequence of values for which the879///      length will be known at deserialization time without looking at the880///      serialized data, for example `(u8,)` or `(String, u64, Vec<T>)` or881///      `[u64; 10]`.882///  - **tuple_struct**883///    - A named tuple, for example `struct Rgb(u8, u8, u8)`.884///  - **tuple_variant**885///    - For example the `E::T` in `enum E { T(u8, u8) }`.886///  - **map**887///    - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.888///  - **struct**889///    - A heterogeneous key-value pairing in which the keys are strings and890///      will be known at deserialization time without looking at the serialized891///      data, for example `struct S { r: u8, g: u8, b: u8 }`.892///  - **struct_variant**893///    - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`.894///895/// The `Deserializer` trait supports two entry point styles which enables896/// different kinds of deserialization.897///898/// 1. The `deserialize_any` method. Self-describing data formats like JSON are899///    able to look at the serialized data and tell what it represents. For900///    example the JSON deserializer may see an opening curly brace (`{`) and901///    know that it is seeing a map. If the data format supports902///    `Deserializer::deserialize_any`, it will drive the Visitor using whatever903///    type it sees in the input. JSON uses this approach when deserializing904///    `serde_json::Value` which is an enum that can represent any JSON905///    document. Without knowing what is in a JSON document, we can deserialize906///    it to `serde_json::Value` by going through907///    `Deserializer::deserialize_any`.908///909/// 2. The various `deserialize_*` methods. Non-self-describing formats like910///    Postcard need to be told what is in the input in order to deserialize it.911///    The `deserialize_*` methods are hints to the deserializer for how to912///    interpret the next piece of input. Non-self-describing formats are not913///    able to deserialize something like `serde_json::Value` which relies on914///    `Deserializer::deserialize_any`.915///916/// When implementing `Deserialize`, you should avoid relying on917/// `Deserializer::deserialize_any` unless you need to be told by the918/// Deserializer what type is in the input. Know that relying on919/// `Deserializer::deserialize_any` means your data type will be able to920/// deserialize from self-describing formats only, ruling out Postcard and many921/// others.922///923/// [Serde data model]: https://serde.rs/data-model.html924///925/// # Lifetime926///927/// The `'de` lifetime of this trait is the lifetime of data that may be928/// borrowed from the input when deserializing. See the page [Understanding929/// deserializer lifetimes] for a more detailed explanation of these lifetimes.930///931/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html932///933/// # Example implementation934///935/// The [example data format] presented on the website contains example code for936/// a basic JSON `Deserializer`.937///938/// [example data format]: https://serde.rs/data-format.html939#[cfg_attr(940    not(no_diagnostic_namespace),941    diagnostic::on_unimplemented(942        message = "the trait bound `{Self}: serde::de::Deserializer<'de>` is not satisfied",943    )944)]945pub trait Deserializer<'de>: Sized {946    /// The error type that can be returned if some error occurs during947    /// deserialization.948    type Error: Error;949950    /// Require the `Deserializer` to figure out how to drive the visitor based951    /// on what data type is in the input.952    ///953    /// When implementing `Deserialize`, you should avoid relying on954    /// `Deserializer::deserialize_any` unless you need to be told by the955    /// Deserializer what type is in the input. Know that relying on956    /// `Deserializer::deserialize_any` means your data type will be able to957    /// deserialize from self-describing formats only, ruling out Postcard and958    /// many others.959    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>960    where961        V: Visitor<'de>;962963    /// Hint that the `Deserialize` type is expecting a `bool` value.964    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>965    where966        V: Visitor<'de>;967968    /// Hint that the `Deserialize` type is expecting an `i8` value.969    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>970    where971        V: Visitor<'de>;972973    /// Hint that the `Deserialize` type is expecting an `i16` value.974    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>975    where976        V: Visitor<'de>;977978    /// Hint that the `Deserialize` type is expecting an `i32` value.979    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>980    where981        V: Visitor<'de>;982983    /// Hint that the `Deserialize` type is expecting an `i64` value.984    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>985    where986        V: Visitor<'de>;987988    /// Hint that the `Deserialize` type is expecting an `i128` value.989    ///990    /// The default behavior unconditionally returns an error.991    fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value, Self::Error>992    where993        V: Visitor<'de>,994    {995        let _ = visitor;996        Err(Error::custom("i128 is not supported"))997    }998999    /// Hint that the `Deserialize` type is expecting a `u8` value.1000    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>1001    where1002        V: Visitor<'de>;10031004    /// Hint that the `Deserialize` type is expecting a `u16` value.1005    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>1006    where1007        V: Visitor<'de>;10081009    /// Hint that the `Deserialize` type is expecting a `u32` value.1010    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>1011    where1012        V: Visitor<'de>;10131014    /// Hint that the `Deserialize` type is expecting a `u64` value.1015    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>1016    where1017        V: Visitor<'de>;10181019    /// Hint that the `Deserialize` type is expecting an `u128` value.1020    ///1021    /// The default behavior unconditionally returns an error.1022    fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value, Self::Error>1023    where1024        V: Visitor<'de>,1025    {1026        let _ = visitor;1027        Err(Error::custom("u128 is not supported"))1028    }10291030    /// Hint that the `Deserialize` type is expecting a `f32` value.1031    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>1032    where1033        V: Visitor<'de>;10341035    /// Hint that the `Deserialize` type is expecting a `f64` value.1036    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>1037    where1038        V: Visitor<'de>;10391040    /// Hint that the `Deserialize` type is expecting a `char` value.1041    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>1042    where1043        V: Visitor<'de>;10441045    /// Hint that the `Deserialize` type is expecting a string value and does1046    /// not benefit from taking ownership of buffered data owned by the1047    /// `Deserializer`.1048    ///1049    /// If the `Visitor` would benefit from taking ownership of `String` data,1050    /// indicate this to the `Deserializer` by using `deserialize_string`1051    /// instead.1052    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>1053    where1054        V: Visitor<'de>;10551056    /// Hint that the `Deserialize` type is expecting a string value and would1057    /// benefit from taking ownership of buffered data owned by the1058    /// `Deserializer`.1059    ///1060    /// If the `Visitor` would not benefit from taking ownership of `String`1061    /// data, indicate that to the `Deserializer` by using `deserialize_str`1062    /// instead.1063    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>1064    where1065        V: Visitor<'de>;10661067    /// Hint that the `Deserialize` type is expecting a byte array and does not1068    /// benefit from taking ownership of buffered data owned by the1069    /// `Deserializer`.1070    ///1071    /// If the `Visitor` would benefit from taking ownership of `Vec<u8>` data,1072    /// indicate this to the `Deserializer` by using `deserialize_byte_buf`1073    /// instead.1074    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>1075    where1076        V: Visitor<'de>;10771078    /// Hint that the `Deserialize` type is expecting a byte array and would1079    /// benefit from taking ownership of buffered data owned by the1080    /// `Deserializer`.1081    ///1082    /// If the `Visitor` would not benefit from taking ownership of `Vec<u8>`1083    /// data, indicate that to the `Deserializer` by using `deserialize_bytes`1084    /// instead.1085    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>1086    where1087        V: Visitor<'de>;10881089    /// Hint that the `Deserialize` type is expecting an optional value.1090    ///1091    /// This allows deserializers that encode an optional value as a nullable1092    /// value to convert the null value into `None` and a regular value into1093    /// `Some(value)`.1094    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>1095    where1096        V: Visitor<'de>;10971098    /// Hint that the `Deserialize` type is expecting a unit value.1099    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>1100    where1101        V: Visitor<'de>;11021103    /// Hint that the `Deserialize` type is expecting a unit struct with a1104    /// particular name.1105    fn deserialize_unit_struct<V>(1106        self,1107        name: &'static str,1108        visitor: V,1109    ) -> Result<V::Value, Self::Error>1110    where1111        V: Visitor<'de>;11121113    /// Hint that the `Deserialize` type is expecting a newtype struct with a1114    /// particular name.1115    fn deserialize_newtype_struct<V>(1116        self,1117        name: &'static str,1118        visitor: V,1119    ) -> Result<V::Value, Self::Error>1120    where1121        V: Visitor<'de>;11221123    /// Hint that the `Deserialize` type is expecting a sequence of values.1124    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>1125    where1126        V: Visitor<'de>;11271128    /// Hint that the `Deserialize` type is expecting a sequence of values and1129    /// knows how many values there are without looking at the serialized data.1130    fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>1131    where1132        V: Visitor<'de>;11331134    /// Hint that the `Deserialize` type is expecting a tuple struct with a1135    /// particular name and number of fields.1136    fn deserialize_tuple_struct<V>(1137        self,1138        name: &'static str,1139        len: usize,1140        visitor: V,1141    ) -> Result<V::Value, Self::Error>1142    where1143        V: Visitor<'de>;11441145    /// Hint that the `Deserialize` type is expecting a map of key-value pairs.1146    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>1147    where1148        V: Visitor<'de>;11491150    /// Hint that the `Deserialize` type is expecting a struct with a particular1151    /// name and fields.1152    fn deserialize_struct<V>(1153        self,1154        name: &'static str,1155        fields: &'static [&'static str],1156        visitor: V,1157    ) -> Result<V::Value, Self::Error>1158    where1159        V: Visitor<'de>;11601161    /// Hint that the `Deserialize` type is expecting an enum value with a1162    /// particular name and possible variants.1163    fn deserialize_enum<V>(1164        self,1165        name: &'static str,1166        variants: &'static [&'static str],1167        visitor: V,1168    ) -> Result<V::Value, Self::Error>1169    where1170        V: Visitor<'de>;11711172    /// Hint that the `Deserialize` type is expecting the name of a struct1173    /// field or the discriminant of an enum variant.1174    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>1175    where1176        V: Visitor<'de>;11771178    /// Hint that the `Deserialize` type needs to deserialize a value whose type1179    /// doesn't matter because it is ignored.1180    ///1181    /// Deserializers for non-self-describing formats may not support this mode.1182    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>1183    where1184        V: Visitor<'de>;11851186    /// Determine whether `Deserialize` implementations should expect to1187    /// deserialize their human-readable form.1188    ///1189    /// Some types have a human-readable form that may be somewhat expensive to1190    /// construct, as well as a binary form that is compact and efficient.1191    /// Generally text-based formats like JSON and YAML will prefer to use the1192    /// human-readable one and binary formats like Postcard will prefer the1193    /// compact one.1194    ///1195    /// ```edition20211196    /// # use std::ops::Add;1197    /// # use std::str::FromStr;1198    /// #1199    /// # struct Timestamp;1200    /// #1201    /// # impl Timestamp {1202    /// #     const EPOCH: Timestamp = Timestamp;1203    /// # }1204    /// #1205    /// # impl FromStr for Timestamp {1206    /// #     type Err = String;1207    /// #     fn from_str(_: &str) -> Result<Self, Self::Err> {1208    /// #         unimplemented!()1209    /// #     }1210    /// # }1211    /// #1212    /// # struct Duration;1213    /// #1214    /// # impl Duration {1215    /// #     fn seconds(_: u64) -> Self { unimplemented!() }1216    /// # }1217    /// #1218    /// # impl Add<Duration> for Timestamp {1219    /// #     type Output = Timestamp;1220    /// #     fn add(self, _: Duration) -> Self::Output {1221    /// #         unimplemented!()1222    /// #     }1223    /// # }1224    /// #1225    /// use serde::de::{self, Deserialize, Deserializer};1226    ///1227    /// impl<'de> Deserialize<'de> for Timestamp {1228    ///     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1229    ///     where1230    ///         D: Deserializer<'de>,1231    ///     {1232    ///         if deserializer.is_human_readable() {1233    ///             // Deserialize from a human-readable string like "2015-05-15T17:01:00Z".1234    ///             let s = String::deserialize(deserializer)?;1235    ///             Timestamp::from_str(&s).map_err(de::Error::custom)1236    ///         } else {1237    ///             // Deserialize from a compact binary representation, seconds since1238    ///             // the Unix epoch.1239    ///             let n = u64::deserialize(deserializer)?;1240    ///             Ok(Timestamp::EPOCH + Duration::seconds(n))1241    ///         }1242    ///     }1243    /// }1244    /// ```1245    ///1246    /// The default implementation of this method returns `true`. Data formats1247    /// may override this to `false` to request a compact form for types that1248    /// support one. Note that modifying this method to change a format from1249    /// human-readable to compact or vice versa should be regarded as a breaking1250    /// change, as a value serialized in human-readable mode is not required to1251    /// deserialize from the same data in compact mode.1252    #[inline]1253    fn is_human_readable(&self) -> bool {1254        true1255    }12561257    // Not public API.1258    #[cfg(all(not(no_serde_derive), any(feature = "std", feature = "alloc")))]1259    #[doc(hidden)]1260    fn __deserialize_content_v1<V>(self, visitor: V) -> Result<V::Value, Self::Error>1261    where1262        V: Visitor<'de, Value = crate::private::Content<'de>>,1263    {1264        self.deserialize_any(visitor)1265    }1266}12671268////////////////////////////////////////////////////////////////////////////////12691270/// This trait represents a visitor that walks through a deserializer.1271///1272/// # Lifetime1273///1274/// The `'de` lifetime of this trait is the requirement for lifetime of data1275/// that may be borrowed by `Self::Value`. See the page [Understanding1276/// deserializer lifetimes] for a more detailed explanation of these lifetimes.1277///1278/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html1279///1280/// # Example1281///1282/// ```edition20211283/// # use serde::de::{self, Unexpected, Visitor};1284/// # use std::fmt;1285/// #1286/// /// A visitor that deserializes a long string - a string containing at least1287/// /// some minimum number of bytes.1288/// struct LongString {1289///     min: usize,1290/// }1291///1292/// impl<'de> Visitor<'de> for LongString {1293///     type Value = String;1294///1295///     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1296///         write!(formatter, "a string containing at least {} bytes", self.min)1297///     }1298///1299///     fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>1300///     where1301///         E: de::Error,1302///     {1303///         if s.len() >= self.min {1304///             Ok(s.to_owned())1305///         } else {1306///             Err(de::Error::invalid_value(Unexpected::Str(s), &self))1307///         }1308///     }1309/// }1310/// ```1311#[cfg_attr(1312    not(no_diagnostic_namespace),1313    diagnostic::on_unimplemented(1314        message = "the trait bound `{Self}: serde::de::Visitor<'de>` is not satisfied",1315    )1316)]1317pub trait Visitor<'de>: Sized {1318    /// The value produced by this visitor.1319    type Value;13201321    /// Format a message stating what data this Visitor expects to receive.1322    ///1323    /// This is used in error messages. The message should complete the sentence1324    /// "This Visitor expects to receive ...", for example the message could be1325    /// "an integer between 0 and 64". The message should not be capitalized and1326    /// should not end with a period.1327    ///1328    /// ```edition20211329    /// # use std::fmt;1330    /// #1331    /// # struct S {1332    /// #     max: usize,1333    /// # }1334    /// #1335    /// # impl<'de> serde::de::Visitor<'de> for S {1336    /// #     type Value = ();1337    /// #1338    /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1339    ///     write!(formatter, "an integer between 0 and {}", self.max)1340    /// }1341    /// # }1342    /// ```1343    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result;13441345    /// The input contains a boolean.1346    ///1347    /// The default implementation fails with a type error.1348    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>1349    where1350        E: Error,1351    {1352        Err(Error::invalid_type(Unexpected::Bool(v), &self))1353    }13541355    /// The input contains an `i8`.1356    ///1357    /// The default implementation forwards to [`visit_i64`].1358    ///1359    /// [`visit_i64`]: #method.visit_i641360    fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>1361    where1362        E: Error,1363    {1364        self.visit_i64(v as i64)1365    }13661367    /// The input contains an `i16`.1368    ///1369    /// The default implementation forwards to [`visit_i64`].1370    ///1371    /// [`visit_i64`]: #method.visit_i641372    fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>1373    where1374        E: Error,1375    {1376        self.visit_i64(v as i64)1377    }13781379    /// The input contains an `i32`.1380    ///1381    /// The default implementation forwards to [`visit_i64`].1382    ///1383    /// [`visit_i64`]: #method.visit_i641384    fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>1385    where1386        E: Error,1387    {1388        self.visit_i64(v as i64)1389    }13901391    /// The input contains an `i64`.1392    ///1393    /// The default implementation fails with a type error.1394    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>1395    where1396        E: Error,1397    {1398        Err(Error::invalid_type(Unexpected::Signed(v), &self))1399    }14001401    /// The input contains a `i128`.1402    ///1403    /// The default implementation fails with a type error.1404    fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>1405    where1406        E: Error,1407    {1408        let mut buf = [0u8; 58];1409        let mut writer = crate::format::Buf::new(&mut buf);1410        fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as i128", v)).unwrap();1411        Err(Error::invalid_type(1412            Unexpected::Other(writer.as_str()),1413            &self,1414        ))1415    }14161417    /// The input contains a `u8`.1418    ///1419    /// The default implementation forwards to [`visit_u64`].1420    ///1421    /// [`visit_u64`]: #method.visit_u641422    fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>1423    where1424        E: Error,1425    {1426        self.visit_u64(v as u64)1427    }14281429    /// The input contains a `u16`.1430    ///1431    /// The default implementation forwards to [`visit_u64`].1432    ///1433    /// [`visit_u64`]: #method.visit_u641434    fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>1435    where1436        E: Error,1437    {1438        self.visit_u64(v as u64)1439    }14401441    /// The input contains a `u32`.1442    ///1443    /// The default implementation forwards to [`visit_u64`].1444    ///1445    /// [`visit_u64`]: #method.visit_u641446    fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>1447    where1448        E: Error,1449    {1450        self.visit_u64(v as u64)1451    }14521453    /// The input contains a `u64`.1454    ///1455    /// The default implementation fails with a type error.1456    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>1457    where1458        E: Error,1459    {1460        Err(Error::invalid_type(Unexpected::Unsigned(v), &self))1461    }14621463    /// The input contains a `u128`.1464    ///1465    /// The default implementation fails with a type error.1466    fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>1467    where1468        E: Error,1469    {1470        let mut buf = [0u8; 57];1471        let mut writer = crate::format::Buf::new(&mut buf);1472        fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as u128", v)).unwrap();1473        Err(Error::invalid_type(1474            Unexpected::Other(writer.as_str()),1475            &self,1476        ))1477    }14781479    /// The input contains an `f32`.1480    ///1481    /// The default implementation forwards to [`visit_f64`].1482    ///1483    /// [`visit_f64`]: #method.visit_f641484    fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>1485    where1486        E: Error,1487    {1488        self.visit_f64(v as f64)1489    }14901491    /// The input contains an `f64`.1492    ///1493    /// The default implementation fails with a type error.1494    fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>1495    where1496        E: Error,1497    {1498        Err(Error::invalid_type(Unexpected::Float(v), &self))1499    }15001501    /// The input contains a `char`.1502    ///1503    /// The default implementation forwards to [`visit_str`] as a one-character1504    /// string.1505    ///1506    /// [`visit_str`]: #method.visit_str1507    #[inline]1508    fn visit_char<E>(self, v: char) -> Result<Self::Value, E>1509    where1510        E: Error,1511    {1512        self.visit_str(v.encode_utf8(&mut [0u8; 4]))1513    }15141515    /// The input contains a string. The lifetime of the string is ephemeral and1516    /// it may be destroyed after this method returns.1517    ///1518    /// This method allows the `Deserializer` to avoid a copy by retaining1519    /// ownership of any buffered data. `Deserialize` implementations that do1520    /// not benefit from taking ownership of `String` data should indicate that1521    /// to the deserializer by using `Deserializer::deserialize_str` rather than1522    /// `Deserializer::deserialize_string`.1523    ///1524    /// It is never correct to implement `visit_string` without implementing1525    /// `visit_str`. Implement neither, both, or just `visit_str`.1526    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>1527    where1528        E: Error,1529    {1530        Err(Error::invalid_type(Unexpected::Str(v), &self))1531    }15321533    /// The input contains a string that lives at least as long as the1534    /// `Deserializer`.1535    ///1536    /// This enables zero-copy deserialization of strings in some formats. For1537    /// example JSON input containing the JSON string `"borrowed"` can be1538    /// deserialized with zero copying into a `&'a str` as long as the input1539    /// data outlives `'a`.1540    ///1541    /// The default implementation forwards to `visit_str`.1542    #[inline]1543    fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>1544    where1545        E: Error,1546    {1547        self.visit_str(v)1548    }15491550    /// The input contains a string and ownership of the string is being given1551    /// to the `Visitor`.1552    ///1553    /// This method allows the `Visitor` to avoid a copy by taking ownership of1554    /// a string created by the `Deserializer`. `Deserialize` implementations1555    /// that benefit from taking ownership of `String` data should indicate that1556    /// to the deserializer by using `Deserializer::deserialize_string` rather1557    /// than `Deserializer::deserialize_str`, although not every deserializer1558    /// will honor such a request.1559    ///1560    /// It is never correct to implement `visit_string` without implementing1561    /// `visit_str`. Implement neither, both, or just `visit_str`.1562    ///1563    /// The default implementation forwards to `visit_str` and then drops the1564    /// `String`.1565    #[inline]1566    #[cfg(any(feature = "std", feature = "alloc"))]1567    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]1568    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>1569    where1570        E: Error,1571    {1572        self.visit_str(&v)1573    }15741575    /// The input contains a byte array. The lifetime of the byte array is1576    /// ephemeral and it may be destroyed after this method returns.1577    ///1578    /// This method allows the `Deserializer` to avoid a copy by retaining1579    /// ownership of any buffered data. `Deserialize` implementations that do1580    /// not benefit from taking ownership of `Vec<u8>` data should indicate that1581    /// to the deserializer by using `Deserializer::deserialize_bytes` rather1582    /// than `Deserializer::deserialize_byte_buf`.1583    ///1584    /// It is never correct to implement `visit_byte_buf` without implementing1585    /// `visit_bytes`. Implement neither, both, or just `visit_bytes`.1586    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>1587    where1588        E: Error,1589    {1590        Err(Error::invalid_type(Unexpected::Bytes(v), &self))1591    }15921593    /// The input contains a byte array that lives at least as long as the1594    /// `Deserializer`.1595    ///1596    /// This enables zero-copy deserialization of bytes in some formats. For1597    /// example Postcard data containing bytes can be deserialized with zero1598    /// copying into a `&'a [u8]` as long as the input data outlives `'a`.1599    ///1600    /// The default implementation forwards to `visit_bytes`.1601    #[inline]1602    fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>1603    where1604        E: Error,1605    {1606        self.visit_bytes(v)1607    }16081609    /// The input contains a byte array and ownership of the byte array is being1610    /// given to the `Visitor`.1611    ///1612    /// This method allows the `Visitor` to avoid a copy by taking ownership of1613    /// a byte buffer created by the `Deserializer`. `Deserialize`1614    /// implementations that benefit from taking ownership of `Vec<u8>` data1615    /// should indicate that to the deserializer by using1616    /// `Deserializer::deserialize_byte_buf` rather than1617    /// `Deserializer::deserialize_bytes`, although not every deserializer will1618    /// honor such a request.1619    ///1620    /// It is never correct to implement `visit_byte_buf` without implementing1621    /// `visit_bytes`. Implement neither, both, or just `visit_bytes`.1622    ///1623    /// The default implementation forwards to `visit_bytes` and then drops the1624    /// `Vec<u8>`.1625    #[cfg(any(feature = "std", feature = "alloc"))]1626    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]1627    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>1628    where1629        E: Error,1630    {1631        self.visit_bytes(&v)1632    }16331634    /// The input contains an optional that is absent.1635    ///1636    /// The default implementation fails with a type error.1637    fn visit_none<E>(self) -> Result<Self::Value, E>1638    where1639        E: Error,1640    {1641        Err(Error::invalid_type(Unexpected::Option, &self))1642    }16431644    /// The input contains an optional that is present.1645    ///1646    /// The default implementation fails with a type error.1647    fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>1648    where1649        D: Deserializer<'de>,1650    {1651        let _ = deserializer;1652        Err(Error::invalid_type(Unexpected::Option, &self))1653    }16541655    /// The input contains a unit `()`.1656    ///1657    /// The default implementation fails with a type error.1658    fn visit_unit<E>(self) -> Result<Self::Value, E>1659    where1660        E: Error,1661    {1662        Err(Error::invalid_type(Unexpected::Unit, &self))1663    }16641665    /// The input contains a newtype struct.1666    ///1667    /// The content of the newtype struct may be read from the given1668    /// `Deserializer`.1669    ///1670    /// The default implementation fails with a type error.1671    fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>1672    where1673        D: Deserializer<'de>,1674    {1675        let _ = deserializer;1676        Err(Error::invalid_type(Unexpected::NewtypeStruct, &self))1677    }16781679    /// The input contains a sequence of elements.1680    ///1681    /// The default implementation fails with a type error.1682    fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>1683    where1684        A: SeqAccess<'de>,1685    {1686        let _ = seq;1687        Err(Error::invalid_type(Unexpected::Seq, &self))1688    }16891690    /// The input contains a key-value map.1691    ///1692    /// The default implementation fails with a type error.1693    fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>1694    where1695        A: MapAccess<'de>,1696    {1697        let _ = map;1698        Err(Error::invalid_type(Unexpected::Map, &self))1699    }17001701    /// The input contains an enum.1702    ///1703    /// The default implementation fails with a type error.1704    fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>1705    where1706        A: EnumAccess<'de>,1707    {1708        let _ = data;1709        Err(Error::invalid_type(Unexpected::Enum, &self))1710    }17111712    // Used when deserializing a flattened Option field. Not public API.1713    #[doc(hidden)]1714    fn __private_visit_untagged_option<D>(self, _: D) -> Result<Self::Value, ()>1715    where1716        D: Deserializer<'de>,1717    {1718        Err(())1719    }1720}17211722////////////////////////////////////////////////////////////////////////////////17231724/// Provides a `Visitor` access to each element of a sequence in the input.1725///1726/// This is a trait that a `Deserializer` passes to a `Visitor` implementation,1727/// which deserializes each item in a sequence.1728///1729/// # Lifetime1730///1731/// The `'de` lifetime of this trait is the lifetime of data that may be1732/// borrowed by deserialized sequence elements. See the page [Understanding1733/// deserializer lifetimes] for a more detailed explanation of these lifetimes.1734///1735/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html1736///1737/// # Example implementation1738///1739/// The [example data format] presented on the website demonstrates an1740/// implementation of `SeqAccess` for a basic JSON data format.1741///1742/// [example data format]: https://serde.rs/data-format.html1743#[cfg_attr(1744    not(no_diagnostic_namespace),1745    diagnostic::on_unimplemented(1746        message = "the trait bound `{Self}: serde::de::SeqAccess<'de>` is not satisfied",1747    )1748)]1749pub trait SeqAccess<'de> {1750    /// The error type that can be returned if some error occurs during1751    /// deserialization.1752    type Error: Error;17531754    /// This returns `Ok(Some(value))` for the next value in the sequence, or1755    /// `Ok(None)` if there are no more remaining items.1756    ///1757    /// `Deserialize` implementations should typically use1758    /// `SeqAccess::next_element` instead.1759    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>1760    where1761        T: DeserializeSeed<'de>;17621763    /// This returns `Ok(Some(value))` for the next value in the sequence, or1764    /// `Ok(None)` if there are no more remaining items.1765    ///1766    /// This method exists as a convenience for `Deserialize` implementations.1767    /// `SeqAccess` implementations should not override the default behavior.1768    #[inline]1769    fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error>1770    where1771        T: Deserialize<'de>,1772    {1773        self.next_element_seed(PhantomData)1774    }17751776    /// Returns the number of elements remaining in the sequence, if known.1777    #[inline]1778    fn size_hint(&self) -> Option<usize> {1779        None1780    }1781}17821783impl<'de, A> SeqAccess<'de> for &mut A1784where1785    A: ?Sized + SeqAccess<'de>,1786{1787    type Error = A::Error;17881789    #[inline]1790    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>1791    where1792        T: DeserializeSeed<'de>,1793    {1794        (**self).next_element_seed(seed)1795    }17961797    #[inline]1798    fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error>1799    where1800        T: Deserialize<'de>,1801    {1802        (**self).next_element()1803    }18041805    #[inline]1806    fn size_hint(&self) -> Option<usize> {1807        (**self).size_hint()1808    }1809}18101811////////////////////////////////////////////////////////////////////////////////18121813/// Provides a `Visitor` access to each entry of a map in the input.1814///1815/// This is a trait that a `Deserializer` passes to a `Visitor` implementation.1816///1817/// # Lifetime1818///1819/// The `'de` lifetime of this trait is the lifetime of data that may be1820/// borrowed by deserialized map entries. See the page [Understanding1821/// deserializer lifetimes] for a more detailed explanation of these lifetimes.1822///1823/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html1824///1825/// # Example implementation1826///1827/// The [example data format] presented on the website demonstrates an1828/// implementation of `MapAccess` for a basic JSON data format.1829///1830/// [example data format]: https://serde.rs/data-format.html1831#[cfg_attr(1832    not(no_diagnostic_namespace),1833    diagnostic::on_unimplemented(1834        message = "the trait bound `{Self}: serde::de::MapAccess<'de>` is not satisfied",1835    )1836)]1837pub trait MapAccess<'de> {1838    /// The error type that can be returned if some error occurs during1839    /// deserialization.1840    type Error: Error;18411842    /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`1843    /// if there are no more remaining entries.1844    ///1845    /// `Deserialize` implementations should typically use1846    /// `MapAccess::next_key` or `MapAccess::next_entry` instead.1847    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>1848    where1849        K: DeserializeSeed<'de>;18501851    /// This returns a `Ok(value)` for the next value in the map.1852    ///1853    /// `Deserialize` implementations should typically use1854    /// `MapAccess::next_value` instead.1855    ///1856    /// # Panics1857    ///1858    /// Calling `next_value_seed` before `next_key_seed` is incorrect and is1859    /// allowed to panic or return bogus results.1860    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>1861    where1862        V: DeserializeSeed<'de>;18631864    /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in1865    /// the map, or `Ok(None)` if there are no more remaining items.1866    ///1867    /// `MapAccess` implementations should override the default behavior if a1868    /// more efficient implementation is possible.1869    ///1870    /// `Deserialize` implementations should typically use1871    /// `MapAccess::next_entry` instead.1872    #[inline]1873    fn next_entry_seed<K, V>(1874        &mut self,1875        kseed: K,1876        vseed: V,1877    ) -> Result<Option<(K::Value, V::Value)>, Self::Error>1878    where1879        K: DeserializeSeed<'de>,1880        V: DeserializeSeed<'de>,1881    {1882        match tri!(self.next_key_seed(kseed)) {1883            Some(key) => {1884                let value = tri!(self.next_value_seed(vseed));1885                Ok(Some((key, value)))1886            }1887            None => Ok(None),1888        }1889    }18901891    /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`1892    /// if there are no more remaining entries.1893    ///1894    /// This method exists as a convenience for `Deserialize` implementations.1895    /// `MapAccess` implementations should not override the default behavior.1896    #[inline]1897    fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error>1898    where1899        K: Deserialize<'de>,1900    {1901        self.next_key_seed(PhantomData)1902    }19031904    /// This returns a `Ok(value)` for the next value in the map.1905    ///1906    /// This method exists as a convenience for `Deserialize` implementations.1907    /// `MapAccess` implementations should not override the default behavior.1908    ///1909    /// # Panics1910    ///1911    /// Calling `next_value` before `next_key` is incorrect and is allowed to1912    /// panic or return bogus results.1913    #[inline]1914    fn next_value<V>(&mut self) -> Result<V, Self::Error>1915    where1916        V: Deserialize<'de>,1917    {1918        self.next_value_seed(PhantomData)1919    }19201921    /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in1922    /// the map, or `Ok(None)` if there are no more remaining items.1923    ///1924    /// This method exists as a convenience for `Deserialize` implementations.1925    /// `MapAccess` implementations should not override the default behavior.1926    #[inline]1927    fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>1928    where1929        K: Deserialize<'de>,1930        V: Deserialize<'de>,1931    {1932        self.next_entry_seed(PhantomData, PhantomData)1933    }19341935    /// Returns the number of entries remaining in the map, if known.1936    #[inline]1937    fn size_hint(&self) -> Option<usize> {1938        None1939    }1940}19411942impl<'de, A> MapAccess<'de> for &mut A1943where1944    A: ?Sized + MapAccess<'de>,1945{1946    type Error = A::Error;19471948    #[inline]1949    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>1950    where1951        K: DeserializeSeed<'de>,1952    {1953        (**self).next_key_seed(seed)1954    }19551956    #[inline]1957    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>1958    where1959        V: DeserializeSeed<'de>,1960    {1961        (**self).next_value_seed(seed)1962    }19631964    #[inline]1965    fn next_entry_seed<K, V>(1966        &mut self,1967        kseed: K,1968        vseed: V,1969    ) -> Result<Option<(K::Value, V::Value)>, Self::Error>1970    where1971        K: DeserializeSeed<'de>,1972        V: DeserializeSeed<'de>,1973    {1974        (**self).next_entry_seed(kseed, vseed)1975    }19761977    #[inline]1978    fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>1979    where1980        K: Deserialize<'de>,1981        V: Deserialize<'de>,1982    {1983        (**self).next_entry()1984    }19851986    #[inline]1987    fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error>1988    where1989        K: Deserialize<'de>,1990    {1991        (**self).next_key()1992    }19931994    #[inline]1995    fn next_value<V>(&mut self) -> Result<V, Self::Error>1996    where1997        V: Deserialize<'de>,1998    {1999        (**self).next_value()2000    }

The first 2,000 of 2,392 lines.