Coverage Report

Created: 2025-06-23 13:53

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