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