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