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