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