serde_core/de/
mod.rs

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