Coverage Report

Created: 2026-01-13 06:57

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