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