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