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