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