1 use lib::*;
2
3 use de::{
4 Deserialize, Deserializer, EnumAccess, Error, SeqAccess, Unexpected, VariantAccess, Visitor,
5 };
6
7 #[cfg(any(feature = "std", feature = "alloc", not(no_core_duration)))]
8 use de::MapAccess;
9
10 use seed::InPlaceSeed;
11
12 #[cfg(any(feature = "std", feature = "alloc"))]
13 use __private::size_hint;
14
15 ////////////////////////////////////////////////////////////////////////////////
16
17 struct UnitVisitor;
18
19 impl<'de> Visitor<'de> for UnitVisitor {
20 type Value = ();
21
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result22 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
23 formatter.write_str("unit")
24 }
25
visit_unit<E>(self) -> Result<Self::Value, E> where E: Error,26 fn visit_unit<E>(self) -> Result<Self::Value, E>
27 where
28 E: Error,
29 {
30 Ok(())
31 }
32 }
33
34 impl<'de> Deserialize<'de> for () {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,35 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
36 where
37 D: Deserializer<'de>,
38 {
39 deserializer.deserialize_unit(UnitVisitor)
40 }
41 }
42
43 #[cfg(feature = "unstable")]
44 impl<'de> Deserialize<'de> for ! {
deserialize<D>(_deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,45 fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
46 where
47 D: Deserializer<'de>,
48 {
49 Err(Error::custom("cannot deserialize `!`"))
50 }
51 }
52
53 ////////////////////////////////////////////////////////////////////////////////
54
55 struct BoolVisitor;
56
57 impl<'de> Visitor<'de> for BoolVisitor {
58 type Value = bool;
59
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result60 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
61 formatter.write_str("a boolean")
62 }
63
visit_bool<E>(self, v: bool) -> Result<Self::Value, E> where E: Error,64 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
65 where
66 E: Error,
67 {
68 Ok(v)
69 }
70 }
71
72 impl<'de> Deserialize<'de> for bool {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,73 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
74 where
75 D: Deserializer<'de>,
76 {
77 deserializer.deserialize_bool(BoolVisitor)
78 }
79 }
80
81 ////////////////////////////////////////////////////////////////////////////////
82
83 macro_rules! impl_deserialize_num {
84 ($primitive:ident, $nonzero:ident $(cfg($($cfg:tt)*))*, $deserialize:ident $($method:ident!($($val:ident : $visit:ident)*);)*) => {
85 impl_deserialize_num!($primitive, $deserialize $($method!($($val : $visit)*);)*);
86
87 #[cfg(all(not(no_num_nonzero), $($($cfg)*)*))]
88 impl<'de> Deserialize<'de> for num::$nonzero {
89 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
90 where
91 D: Deserializer<'de>,
92 {
93 struct NonZeroVisitor;
94
95 impl<'de> Visitor<'de> for NonZeroVisitor {
96 type Value = num::$nonzero;
97
98 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
99 formatter.write_str(concat!("a nonzero ", stringify!($primitive)))
100 }
101
102 $($($method!(nonzero $primitive $val : $visit);)*)*
103 }
104
105 deserializer.$deserialize(NonZeroVisitor)
106 }
107 }
108 };
109
110 ($primitive:ident, $deserialize:ident $($method:ident!($($val:ident : $visit:ident)*);)*) => {
111 impl<'de> Deserialize<'de> for $primitive {
112 #[inline]
113 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
114 where
115 D: Deserializer<'de>,
116 {
117 struct PrimitiveVisitor;
118
119 impl<'de> Visitor<'de> for PrimitiveVisitor {
120 type Value = $primitive;
121
122 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
123 formatter.write_str(stringify!($primitive))
124 }
125
126 $($($method!($val : $visit);)*)*
127 }
128
129 deserializer.$deserialize(PrimitiveVisitor)
130 }
131 }
132 };
133 }
134
135 macro_rules! num_self {
136 ($ty:ident : $visit:ident) => {
137 #[inline]
138 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
139 where
140 E: Error,
141 {
142 Ok(v)
143 }
144 };
145
146 (nonzero $primitive:ident $ty:ident : $visit:ident) => {
147 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
148 where
149 E: Error,
150 {
151 if let Some(nonzero) = Self::Value::new(v) {
152 Ok(nonzero)
153 } else {
154 Err(Error::invalid_value(Unexpected::Unsigned(0), &self))
155 }
156 }
157 };
158 }
159
160 macro_rules! num_as_self {
161 ($ty:ident : $visit:ident) => {
162 #[inline]
163 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
164 where
165 E: Error,
166 {
167 Ok(v as Self::Value)
168 }
169 };
170
171 (nonzero $primitive:ident $ty:ident : $visit:ident) => {
172 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
173 where
174 E: Error,
175 {
176 if let Some(nonzero) = Self::Value::new(v as $primitive) {
177 Ok(nonzero)
178 } else {
179 Err(Error::invalid_value(Unexpected::Unsigned(0), &self))
180 }
181 }
182 };
183 }
184
185 macro_rules! int_to_int {
186 ($ty:ident : $visit:ident) => {
187 #[inline]
188 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
189 where
190 E: Error,
191 {
192 if Self::Value::min_value() as i64 <= v as i64
193 && v as i64 <= Self::Value::max_value() as i64
194 {
195 Ok(v as Self::Value)
196 } else {
197 Err(Error::invalid_value(Unexpected::Signed(v as i64), &self))
198 }
199 }
200 };
201
202 (nonzero $primitive:ident $ty:ident : $visit:ident) => {
203 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
204 where
205 E: Error,
206 {
207 if $primitive::min_value() as i64 <= v as i64
208 && v as i64 <= $primitive::max_value() as i64
209 {
210 if let Some(nonzero) = Self::Value::new(v as $primitive) {
211 return Ok(nonzero);
212 }
213 }
214 Err(Error::invalid_value(Unexpected::Signed(v as i64), &self))
215 }
216 };
217 }
218
219 macro_rules! int_to_uint {
220 ($ty:ident : $visit:ident) => {
221 #[inline]
222 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
223 where
224 E: Error,
225 {
226 if 0 <= v && v as u64 <= Self::Value::max_value() as u64 {
227 Ok(v as Self::Value)
228 } else {
229 Err(Error::invalid_value(Unexpected::Signed(v as i64), &self))
230 }
231 }
232 };
233
234 (nonzero $primitive:ident $ty:ident : $visit:ident) => {
235 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
236 where
237 E: Error,
238 {
239 if 0 < v && v as u64 <= $primitive::max_value() as u64 {
240 if let Some(nonzero) = Self::Value::new(v as $primitive) {
241 return Ok(nonzero);
242 }
243 }
244 Err(Error::invalid_value(Unexpected::Signed(v as i64), &self))
245 }
246 };
247 }
248
249 macro_rules! uint_to_self {
250 ($ty:ident : $visit:ident) => {
251 #[inline]
252 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
253 where
254 E: Error,
255 {
256 if v as u64 <= Self::Value::max_value() as u64 {
257 Ok(v as Self::Value)
258 } else {
259 Err(Error::invalid_value(Unexpected::Unsigned(v as u64), &self))
260 }
261 }
262 };
263
264 (nonzero $primitive:ident $ty:ident : $visit:ident) => {
265 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
266 where
267 E: Error,
268 {
269 if v as u64 <= $primitive::max_value() as u64 {
270 if let Some(nonzero) = Self::Value::new(v as $primitive) {
271 return Ok(nonzero);
272 }
273 }
274 Err(Error::invalid_value(Unexpected::Unsigned(v as u64), &self))
275 }
276 };
277 }
278
279 impl_deserialize_num! {
280 i8, NonZeroI8 cfg(not(no_num_nonzero_signed)), deserialize_i8
281 num_self!(i8:visit_i8);
282 int_to_int!(i16:visit_i16 i32:visit_i32 i64:visit_i64);
283 uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
284 }
285
286 impl_deserialize_num! {
287 i16, NonZeroI16 cfg(not(no_num_nonzero_signed)), deserialize_i16
288 num_self!(i16:visit_i16);
289 num_as_self!(i8:visit_i8);
290 int_to_int!(i32:visit_i32 i64:visit_i64);
291 uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
292 }
293
294 impl_deserialize_num! {
295 i32, NonZeroI32 cfg(not(no_num_nonzero_signed)), deserialize_i32
296 num_self!(i32:visit_i32);
297 num_as_self!(i8:visit_i8 i16:visit_i16);
298 int_to_int!(i64:visit_i64);
299 uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
300 }
301
302 impl_deserialize_num! {
303 i64, NonZeroI64 cfg(not(no_num_nonzero_signed)), deserialize_i64
304 num_self!(i64:visit_i64);
305 num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32);
306 uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
307 }
308
309 impl_deserialize_num! {
310 isize, NonZeroIsize cfg(not(no_num_nonzero_signed)), deserialize_i64
311 num_as_self!(i8:visit_i8 i16:visit_i16);
312 int_to_int!(i32:visit_i32 i64:visit_i64);
313 uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
314 }
315
316 impl_deserialize_num! {
317 u8, NonZeroU8, deserialize_u8
318 num_self!(u8:visit_u8);
319 int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
320 uint_to_self!(u16:visit_u16 u32:visit_u32 u64:visit_u64);
321 }
322
323 impl_deserialize_num! {
324 u16, NonZeroU16, deserialize_u16
325 num_self!(u16:visit_u16);
326 num_as_self!(u8:visit_u8);
327 int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
328 uint_to_self!(u32:visit_u32 u64:visit_u64);
329 }
330
331 impl_deserialize_num! {
332 u32, NonZeroU32, deserialize_u32
333 num_self!(u32:visit_u32);
334 num_as_self!(u8:visit_u8 u16:visit_u16);
335 int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
336 uint_to_self!(u64:visit_u64);
337 }
338
339 impl_deserialize_num! {
340 u64, NonZeroU64, deserialize_u64
341 num_self!(u64:visit_u64);
342 num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32);
343 int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
344 }
345
346 impl_deserialize_num! {
347 usize, NonZeroUsize, deserialize_u64
348 num_as_self!(u8:visit_u8 u16:visit_u16);
349 int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
350 uint_to_self!(u32:visit_u32 u64:visit_u64);
351 }
352
353 impl_deserialize_num! {
354 f32, deserialize_f32
355 num_self!(f32:visit_f32);
356 num_as_self!(f64:visit_f64);
357 num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
358 num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
359 }
360
361 impl_deserialize_num! {
362 f64, deserialize_f64
363 num_self!(f64:visit_f64);
364 num_as_self!(f32:visit_f32);
365 num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
366 num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
367 }
368
369 serde_if_integer128! {
370 macro_rules! num_128 {
371 ($ty:ident : $visit:ident) => {
372 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
373 where
374 E: Error,
375 {
376 if v as i128 >= Self::Value::min_value() as i128
377 && v as u128 <= Self::Value::max_value() as u128
378 {
379 Ok(v as Self::Value)
380 } else {
381 Err(Error::invalid_value(
382 Unexpected::Other(stringify!($ty)),
383 &self,
384 ))
385 }
386 }
387 };
388
389 (nonzero $primitive:ident $ty:ident : $visit:ident) => {
390 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
391 where
392 E: Error,
393 {
394 if v as i128 >= $primitive::min_value() as i128
395 && v as u128 <= $primitive::max_value() as u128
396 {
397 if let Some(nonzero) = Self::Value::new(v as $primitive) {
398 Ok(nonzero)
399 } else {
400 Err(Error::invalid_value(Unexpected::Unsigned(0), &self))
401 }
402 } else {
403 Err(Error::invalid_value(
404 Unexpected::Other(stringify!($ty)),
405 &self,
406 ))
407 }
408 }
409 };
410 }
411
412 impl_deserialize_num! {
413 i128, NonZeroI128 cfg(not(no_num_nonzero_signed)), deserialize_i128
414 num_self!(i128:visit_i128);
415 num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
416 num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
417 num_128!(u128:visit_u128);
418 }
419
420 impl_deserialize_num! {
421 u128, NonZeroU128, deserialize_u128
422 num_self!(u128:visit_u128);
423 num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
424 int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);
425 num_128!(i128:visit_i128);
426 }
427 }
428
429 ////////////////////////////////////////////////////////////////////////////////
430
431 struct CharVisitor;
432
433 impl<'de> Visitor<'de> for CharVisitor {
434 type Value = char;
435
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result436 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
437 formatter.write_str("a character")
438 }
439
440 #[inline]
visit_char<E>(self, v: char) -> Result<Self::Value, E> where E: Error,441 fn visit_char<E>(self, v: char) -> Result<Self::Value, E>
442 where
443 E: Error,
444 {
445 Ok(v)
446 }
447
448 #[inline]
visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: Error,449 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
450 where
451 E: Error,
452 {
453 let mut iter = v.chars();
454 match (iter.next(), iter.next()) {
455 (Some(c), None) => Ok(c),
456 _ => Err(Error::invalid_value(Unexpected::Str(v), &self)),
457 }
458 }
459 }
460
461 impl<'de> Deserialize<'de> for char {
462 #[inline]
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,463 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
464 where
465 D: Deserializer<'de>,
466 {
467 deserializer.deserialize_char(CharVisitor)
468 }
469 }
470
471 ////////////////////////////////////////////////////////////////////////////////
472
473 #[cfg(any(feature = "std", feature = "alloc"))]
474 struct StringVisitor;
475 #[cfg(any(feature = "std", feature = "alloc"))]
476 struct StringInPlaceVisitor<'a>(&'a mut String);
477
478 #[cfg(any(feature = "std", feature = "alloc"))]
479 impl<'de> Visitor<'de> for StringVisitor {
480 type Value = String;
481
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result482 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
483 formatter.write_str("a string")
484 }
485
visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: Error,486 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
487 where
488 E: Error,
489 {
490 Ok(v.to_owned())
491 }
492
visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: Error,493 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
494 where
495 E: Error,
496 {
497 Ok(v)
498 }
499
visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> where E: Error,500 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
501 where
502 E: Error,
503 {
504 match str::from_utf8(v) {
505 Ok(s) => Ok(s.to_owned()),
506 Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
507 }
508 }
509
visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> where E: Error,510 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
511 where
512 E: Error,
513 {
514 match String::from_utf8(v) {
515 Ok(s) => Ok(s),
516 Err(e) => Err(Error::invalid_value(
517 Unexpected::Bytes(&e.into_bytes()),
518 &self,
519 )),
520 }
521 }
522 }
523
524 #[cfg(any(feature = "std", feature = "alloc"))]
525 impl<'a, 'de> Visitor<'de> for StringInPlaceVisitor<'a> {
526 type Value = ();
527
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result528 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
529 formatter.write_str("a string")
530 }
531
visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: Error,532 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
533 where
534 E: Error,
535 {
536 self.0.clear();
537 self.0.push_str(v);
538 Ok(())
539 }
540
visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: Error,541 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
542 where
543 E: Error,
544 {
545 *self.0 = v;
546 Ok(())
547 }
548
visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> where E: Error,549 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
550 where
551 E: Error,
552 {
553 match str::from_utf8(v) {
554 Ok(s) => {
555 self.0.clear();
556 self.0.push_str(s);
557 Ok(())
558 }
559 Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
560 }
561 }
562
visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> where E: Error,563 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
564 where
565 E: Error,
566 {
567 match String::from_utf8(v) {
568 Ok(s) => {
569 *self.0 = s;
570 Ok(())
571 }
572 Err(e) => Err(Error::invalid_value(
573 Unexpected::Bytes(&e.into_bytes()),
574 &self,
575 )),
576 }
577 }
578 }
579
580 #[cfg(any(feature = "std", feature = "alloc"))]
581 impl<'de> Deserialize<'de> for String {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,582 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
583 where
584 D: Deserializer<'de>,
585 {
586 deserializer.deserialize_string(StringVisitor)
587 }
588
deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> where D: Deserializer<'de>,589 fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
590 where
591 D: Deserializer<'de>,
592 {
593 deserializer.deserialize_string(StringInPlaceVisitor(place))
594 }
595 }
596
597 ////////////////////////////////////////////////////////////////////////////////
598
599 struct StrVisitor;
600
601 impl<'a> Visitor<'a> for StrVisitor {
602 type Value = &'a str;
603
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result604 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
605 formatter.write_str("a borrowed string")
606 }
607
visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> where E: Error,608 fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
609 where
610 E: Error,
611 {
612 Ok(v) // so easy
613 }
614
visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> where E: Error,615 fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
616 where
617 E: Error,
618 {
619 str::from_utf8(v).map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
620 }
621 }
622
623 impl<'de: 'a, 'a> Deserialize<'de> for &'a str {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,624 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
625 where
626 D: Deserializer<'de>,
627 {
628 deserializer.deserialize_str(StrVisitor)
629 }
630 }
631
632 ////////////////////////////////////////////////////////////////////////////////
633
634 struct BytesVisitor;
635
636 impl<'a> Visitor<'a> for BytesVisitor {
637 type Value = &'a [u8];
638
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result639 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
640 formatter.write_str("a borrowed byte array")
641 }
642
visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> where E: Error,643 fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
644 where
645 E: Error,
646 {
647 Ok(v)
648 }
649
visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> where E: Error,650 fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
651 where
652 E: Error,
653 {
654 Ok(v.as_bytes())
655 }
656 }
657
658 impl<'de: 'a, 'a> Deserialize<'de> for &'a [u8] {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,659 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
660 where
661 D: Deserializer<'de>,
662 {
663 deserializer.deserialize_bytes(BytesVisitor)
664 }
665 }
666
667 ////////////////////////////////////////////////////////////////////////////////
668
669 #[cfg(feature = "std")]
670 struct CStringVisitor;
671
672 #[cfg(feature = "std")]
673 impl<'de> Visitor<'de> for CStringVisitor {
674 type Value = CString;
675
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result676 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
677 formatter.write_str("byte array")
678 }
679
visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>,680 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
681 where
682 A: SeqAccess<'de>,
683 {
684 let len = size_hint::cautious(seq.size_hint());
685 let mut values = Vec::with_capacity(len);
686
687 while let Some(value) = try!(seq.next_element()) {
688 values.push(value);
689 }
690
691 CString::new(values).map_err(Error::custom)
692 }
693
visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> where E: Error,694 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
695 where
696 E: Error,
697 {
698 CString::new(v).map_err(Error::custom)
699 }
700
visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> where E: Error,701 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
702 where
703 E: Error,
704 {
705 CString::new(v).map_err(Error::custom)
706 }
707
visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: Error,708 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
709 where
710 E: Error,
711 {
712 CString::new(v).map_err(Error::custom)
713 }
714
visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: Error,715 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
716 where
717 E: Error,
718 {
719 CString::new(v).map_err(Error::custom)
720 }
721 }
722
723 #[cfg(feature = "std")]
724 impl<'de> Deserialize<'de> for CString {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,725 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
726 where
727 D: Deserializer<'de>,
728 {
729 deserializer.deserialize_byte_buf(CStringVisitor)
730 }
731 }
732
733 macro_rules! forwarded_impl {
734 (
735 $(#[doc = $doc:tt])*
736 ($($id:ident),*), $ty:ty, $func:expr
737 ) => {
738 $(#[doc = $doc])*
739 impl<'de $(, $id : Deserialize<'de>,)*> Deserialize<'de> for $ty {
740 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
741 where
742 D: Deserializer<'de>,
743 {
744 Deserialize::deserialize(deserializer).map($func)
745 }
746 }
747 }
748 }
749
750 #[cfg(all(feature = "std", not(no_de_boxed_c_str)))]
751 forwarded_impl!((), Box<CStr>, CString::into_boxed_c_str);
752
753 #[cfg(not(no_core_reverse))]
754 forwarded_impl!((T), Reverse<T>, Reverse);
755
756 ////////////////////////////////////////////////////////////////////////////////
757
758 struct OptionVisitor<T> {
759 marker: PhantomData<T>,
760 }
761
762 impl<'de, T> Visitor<'de> for OptionVisitor<T>
763 where
764 T: Deserialize<'de>,
765 {
766 type Value = Option<T>;
767
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result768 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
769 formatter.write_str("option")
770 }
771
772 #[inline]
visit_unit<E>(self) -> Result<Self::Value, E> where E: Error,773 fn visit_unit<E>(self) -> Result<Self::Value, E>
774 where
775 E: Error,
776 {
777 Ok(None)
778 }
779
780 #[inline]
visit_none<E>(self) -> Result<Self::Value, E> where E: Error,781 fn visit_none<E>(self) -> Result<Self::Value, E>
782 where
783 E: Error,
784 {
785 Ok(None)
786 }
787
788 #[inline]
visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>,789 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
790 where
791 D: Deserializer<'de>,
792 {
793 T::deserialize(deserializer).map(Some)
794 }
795
__private_visit_untagged_option<D>(self, deserializer: D) -> Result<Self::Value, ()> where D: Deserializer<'de>,796 fn __private_visit_untagged_option<D>(self, deserializer: D) -> Result<Self::Value, ()>
797 where
798 D: Deserializer<'de>,
799 {
800 Ok(T::deserialize(deserializer).ok())
801 }
802 }
803
804 impl<'de, T> Deserialize<'de> for Option<T>
805 where
806 T: Deserialize<'de>,
807 {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,808 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
809 where
810 D: Deserializer<'de>,
811 {
812 deserializer.deserialize_option(OptionVisitor {
813 marker: PhantomData,
814 })
815 }
816
817 // The Some variant's repr is opaque, so we can't play cute tricks with its
818 // tag to have deserialize_in_place build the content in place unconditionally.
819 //
820 // FIXME: investigate whether branching on the old value being Some to
821 // deserialize_in_place the value is profitable (probably data-dependent?)
822 }
823
824 ////////////////////////////////////////////////////////////////////////////////
825
826 struct PhantomDataVisitor<T: ?Sized> {
827 marker: PhantomData<T>,
828 }
829
830 impl<'de, T: ?Sized> Visitor<'de> for PhantomDataVisitor<T> {
831 type Value = PhantomData<T>;
832
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result833 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
834 formatter.write_str("unit")
835 }
836
837 #[inline]
visit_unit<E>(self) -> Result<Self::Value, E> where E: Error,838 fn visit_unit<E>(self) -> Result<Self::Value, E>
839 where
840 E: Error,
841 {
842 Ok(PhantomData)
843 }
844 }
845
846 impl<'de, T: ?Sized> Deserialize<'de> for PhantomData<T> {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,847 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
848 where
849 D: Deserializer<'de>,
850 {
851 let visitor = PhantomDataVisitor {
852 marker: PhantomData,
853 };
854 deserializer.deserialize_unit_struct("PhantomData", visitor)
855 }
856 }
857
858 ////////////////////////////////////////////////////////////////////////////////
859
860 #[cfg(any(feature = "std", feature = "alloc"))]
861 macro_rules! seq_impl {
862 (
863 $ty:ident <T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)*>,
864 $access:ident,
865 $clear:expr,
866 $with_capacity:expr,
867 $reserve:expr,
868 $insert:expr
869 ) => {
870 impl<'de, T $(, $typaram)*> Deserialize<'de> for $ty<T $(, $typaram)*>
871 where
872 T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*,
873 $($typaram: $bound1 $(+ $bound2)*,)*
874 {
875 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
876 where
877 D: Deserializer<'de>,
878 {
879 struct SeqVisitor<T $(, $typaram)*> {
880 marker: PhantomData<$ty<T $(, $typaram)*>>,
881 }
882
883 impl<'de, T $(, $typaram)*> Visitor<'de> for SeqVisitor<T $(, $typaram)*>
884 where
885 T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*,
886 $($typaram: $bound1 $(+ $bound2)*,)*
887 {
888 type Value = $ty<T $(, $typaram)*>;
889
890 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
891 formatter.write_str("a sequence")
892 }
893
894 #[inline]
895 fn visit_seq<A>(self, mut $access: A) -> Result<Self::Value, A::Error>
896 where
897 A: SeqAccess<'de>,
898 {
899 let mut values = $with_capacity;
900
901 while let Some(value) = try!($access.next_element()) {
902 $insert(&mut values, value);
903 }
904
905 Ok(values)
906 }
907 }
908
909 let visitor = SeqVisitor { marker: PhantomData };
910 deserializer.deserialize_seq(visitor)
911 }
912
913 fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
914 where
915 D: Deserializer<'de>,
916 {
917 struct SeqInPlaceVisitor<'a, T: 'a $(, $typaram: 'a)*>(&'a mut $ty<T $(, $typaram)*>);
918
919 impl<'a, 'de, T $(, $typaram)*> Visitor<'de> for SeqInPlaceVisitor<'a, T $(, $typaram)*>
920 where
921 T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*,
922 $($typaram: $bound1 $(+ $bound2)*,)*
923 {
924 type Value = ();
925
926 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
927 formatter.write_str("a sequence")
928 }
929
930 #[inline]
931 fn visit_seq<A>(mut self, mut $access: A) -> Result<Self::Value, A::Error>
932 where
933 A: SeqAccess<'de>,
934 {
935 $clear(&mut self.0);
936 $reserve(&mut self.0, size_hint::cautious($access.size_hint()));
937
938 // FIXME: try to overwrite old values here? (Vec, VecDeque, LinkedList)
939 while let Some(value) = try!($access.next_element()) {
940 $insert(&mut self.0, value);
941 }
942
943 Ok(())
944 }
945 }
946
947 deserializer.deserialize_seq(SeqInPlaceVisitor(place))
948 }
949 }
950 }
951 }
952
953 // Dummy impl of reserve
954 #[cfg(any(feature = "std", feature = "alloc"))]
nop_reserve<T>(_seq: T, _n: usize)955 fn nop_reserve<T>(_seq: T, _n: usize) {}
956
957 #[cfg(any(feature = "std", feature = "alloc"))]
958 seq_impl!(
959 BinaryHeap<T: Ord>,
960 seq,
961 BinaryHeap::clear,
962 BinaryHeap::with_capacity(size_hint::cautious(seq.size_hint())),
963 BinaryHeap::reserve,
964 BinaryHeap::push
965 );
966
967 #[cfg(any(feature = "std", feature = "alloc"))]
968 seq_impl!(
969 BTreeSet<T: Eq + Ord>,
970 seq,
971 BTreeSet::clear,
972 BTreeSet::new(),
973 nop_reserve,
974 BTreeSet::insert
975 );
976
977 #[cfg(any(feature = "std", feature = "alloc"))]
978 seq_impl!(
979 LinkedList<T>,
980 seq,
981 LinkedList::clear,
982 LinkedList::new(),
983 nop_reserve,
984 LinkedList::push_back
985 );
986
987 #[cfg(feature = "std")]
988 seq_impl!(
989 HashSet<T: Eq + Hash, S: BuildHasher + Default>,
990 seq,
991 HashSet::clear,
992 HashSet::with_capacity_and_hasher(size_hint::cautious(seq.size_hint()), S::default()),
993 HashSet::reserve,
994 HashSet::insert);
995
996 #[cfg(any(feature = "std", feature = "alloc"))]
997 seq_impl!(
998 VecDeque<T>,
999 seq,
1000 VecDeque::clear,
1001 VecDeque::with_capacity(size_hint::cautious(seq.size_hint())),
1002 VecDeque::reserve,
1003 VecDeque::push_back
1004 );
1005
1006 ////////////////////////////////////////////////////////////////////////////////
1007
1008 #[cfg(any(feature = "std", feature = "alloc"))]
1009 impl<'de, T> Deserialize<'de> for Vec<T>
1010 where
1011 T: Deserialize<'de>,
1012 {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,1013 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1014 where
1015 D: Deserializer<'de>,
1016 {
1017 struct VecVisitor<T> {
1018 marker: PhantomData<T>,
1019 }
1020
1021 impl<'de, T> Visitor<'de> for VecVisitor<T>
1022 where
1023 T: Deserialize<'de>,
1024 {
1025 type Value = Vec<T>;
1026
1027 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1028 formatter.write_str("a sequence")
1029 }
1030
1031 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1032 where
1033 A: SeqAccess<'de>,
1034 {
1035 let mut values = Vec::with_capacity(size_hint::cautious(seq.size_hint()));
1036
1037 while let Some(value) = try!(seq.next_element()) {
1038 values.push(value);
1039 }
1040
1041 Ok(values)
1042 }
1043 }
1044
1045 let visitor = VecVisitor {
1046 marker: PhantomData,
1047 };
1048 deserializer.deserialize_seq(visitor)
1049 }
1050
deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> where D: Deserializer<'de>,1051 fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
1052 where
1053 D: Deserializer<'de>,
1054 {
1055 struct VecInPlaceVisitor<'a, T: 'a>(&'a mut Vec<T>);
1056
1057 impl<'a, 'de, T> Visitor<'de> for VecInPlaceVisitor<'a, T>
1058 where
1059 T: Deserialize<'de>,
1060 {
1061 type Value = ();
1062
1063 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1064 formatter.write_str("a sequence")
1065 }
1066
1067 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1068 where
1069 A: SeqAccess<'de>,
1070 {
1071 let hint = size_hint::cautious(seq.size_hint());
1072 if let Some(additional) = hint.checked_sub(self.0.len()) {
1073 self.0.reserve(additional);
1074 }
1075
1076 for i in 0..self.0.len() {
1077 let next = {
1078 let next_place = InPlaceSeed(&mut self.0[i]);
1079 try!(seq.next_element_seed(next_place))
1080 };
1081 if next.is_none() {
1082 self.0.truncate(i);
1083 return Ok(());
1084 }
1085 }
1086
1087 while let Some(value) = try!(seq.next_element()) {
1088 self.0.push(value);
1089 }
1090
1091 Ok(())
1092 }
1093 }
1094
1095 deserializer.deserialize_seq(VecInPlaceVisitor(place))
1096 }
1097 }
1098
1099 ////////////////////////////////////////////////////////////////////////////////
1100
1101 struct ArrayVisitor<A> {
1102 marker: PhantomData<A>,
1103 }
1104 struct ArrayInPlaceVisitor<'a, A: 'a>(&'a mut A);
1105
1106 impl<A> ArrayVisitor<A> {
new() -> Self1107 fn new() -> Self {
1108 ArrayVisitor {
1109 marker: PhantomData,
1110 }
1111 }
1112 }
1113
1114 impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]> {
1115 type Value = [T; 0];
1116
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result1117 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1118 formatter.write_str("an empty array")
1119 }
1120
1121 #[inline]
visit_seq<A>(self, _: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>,1122 fn visit_seq<A>(self, _: A) -> Result<Self::Value, A::Error>
1123 where
1124 A: SeqAccess<'de>,
1125 {
1126 Ok([])
1127 }
1128 }
1129
1130 // Does not require T: Deserialize<'de>.
1131 impl<'de, T> Deserialize<'de> for [T; 0] {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,1132 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1133 where
1134 D: Deserializer<'de>,
1135 {
1136 deserializer.deserialize_tuple(0, ArrayVisitor::<[T; 0]>::new())
1137 }
1138 }
1139
1140 macro_rules! array_impls {
1141 ($($len:expr => ($($n:tt)+))+) => {
1142 $(
1143 impl<'de, T> Visitor<'de> for ArrayVisitor<[T; $len]>
1144 where
1145 T: Deserialize<'de>,
1146 {
1147 type Value = [T; $len];
1148
1149 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1150 formatter.write_str(concat!("an array of length ", $len))
1151 }
1152
1153 #[inline]
1154 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1155 where
1156 A: SeqAccess<'de>,
1157 {
1158 Ok([$(
1159 match try!(seq.next_element()) {
1160 Some(val) => val,
1161 None => return Err(Error::invalid_length($n, &self)),
1162 }
1163 ),+])
1164 }
1165 }
1166
1167 impl<'a, 'de, T> Visitor<'de> for ArrayInPlaceVisitor<'a, [T; $len]>
1168 where
1169 T: Deserialize<'de>,
1170 {
1171 type Value = ();
1172
1173 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1174 formatter.write_str(concat!("an array of length ", $len))
1175 }
1176
1177 #[inline]
1178 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1179 where
1180 A: SeqAccess<'de>,
1181 {
1182 let mut fail_idx = None;
1183 for (idx, dest) in self.0[..].iter_mut().enumerate() {
1184 if try!(seq.next_element_seed(InPlaceSeed(dest))).is_none() {
1185 fail_idx = Some(idx);
1186 break;
1187 }
1188 }
1189 if let Some(idx) = fail_idx {
1190 return Err(Error::invalid_length(idx, &self));
1191 }
1192 Ok(())
1193 }
1194 }
1195
1196 impl<'de, T> Deserialize<'de> for [T; $len]
1197 where
1198 T: Deserialize<'de>,
1199 {
1200 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1201 where
1202 D: Deserializer<'de>,
1203 {
1204 deserializer.deserialize_tuple($len, ArrayVisitor::<[T; $len]>::new())
1205 }
1206
1207 fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
1208 where
1209 D: Deserializer<'de>,
1210 {
1211 deserializer.deserialize_tuple($len, ArrayInPlaceVisitor(place))
1212 }
1213 }
1214 )+
1215 }
1216 }
1217
1218 array_impls! {
1219 1 => (0)
1220 2 => (0 1)
1221 3 => (0 1 2)
1222 4 => (0 1 2 3)
1223 5 => (0 1 2 3 4)
1224 6 => (0 1 2 3 4 5)
1225 7 => (0 1 2 3 4 5 6)
1226 8 => (0 1 2 3 4 5 6 7)
1227 9 => (0 1 2 3 4 5 6 7 8)
1228 10 => (0 1 2 3 4 5 6 7 8 9)
1229 11 => (0 1 2 3 4 5 6 7 8 9 10)
1230 12 => (0 1 2 3 4 5 6 7 8 9 10 11)
1231 13 => (0 1 2 3 4 5 6 7 8 9 10 11 12)
1232 14 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13)
1233 15 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14)
1234 16 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)
1235 17 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16)
1236 18 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17)
1237 19 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18)
1238 20 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19)
1239 21 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20)
1240 22 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21)
1241 23 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22)
1242 24 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23)
1243 25 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24)
1244 26 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25)
1245 27 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26)
1246 28 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27)
1247 29 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28)
1248 30 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29)
1249 31 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30)
1250 32 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31)
1251 }
1252
1253 ////////////////////////////////////////////////////////////////////////////////
1254
1255 macro_rules! tuple_impls {
1256 ($($len:tt => ($($n:tt $name:ident)+))+) => {
1257 $(
1258 impl<'de, $($name: Deserialize<'de>),+> Deserialize<'de> for ($($name,)+) {
1259 #[inline]
1260 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1261 where
1262 D: Deserializer<'de>,
1263 {
1264 struct TupleVisitor<$($name,)+> {
1265 marker: PhantomData<($($name,)+)>,
1266 }
1267
1268 impl<'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleVisitor<$($name,)+> {
1269 type Value = ($($name,)+);
1270
1271 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1272 formatter.write_str(concat!("a tuple of size ", $len))
1273 }
1274
1275 #[inline]
1276 #[allow(non_snake_case)]
1277 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1278 where
1279 A: SeqAccess<'de>,
1280 {
1281 $(
1282 let $name = match try!(seq.next_element()) {
1283 Some(value) => value,
1284 None => return Err(Error::invalid_length($n, &self)),
1285 };
1286 )+
1287
1288 Ok(($($name,)+))
1289 }
1290 }
1291
1292 deserializer.deserialize_tuple($len, TupleVisitor { marker: PhantomData })
1293 }
1294
1295 #[inline]
1296 fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
1297 where
1298 D: Deserializer<'de>,
1299 {
1300 struct TupleInPlaceVisitor<'a, $($name: 'a,)+>(&'a mut ($($name,)+));
1301
1302 impl<'a, 'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleInPlaceVisitor<'a, $($name,)+> {
1303 type Value = ();
1304
1305 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1306 formatter.write_str(concat!("a tuple of size ", $len))
1307 }
1308
1309 #[inline]
1310 #[allow(non_snake_case)]
1311 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1312 where
1313 A: SeqAccess<'de>,
1314 {
1315 $(
1316 if try!(seq.next_element_seed(InPlaceSeed(&mut (self.0).$n))).is_none() {
1317 return Err(Error::invalid_length($n, &self));
1318 }
1319 )+
1320
1321 Ok(())
1322 }
1323 }
1324
1325 deserializer.deserialize_tuple($len, TupleInPlaceVisitor(place))
1326 }
1327 }
1328 )+
1329 }
1330 }
1331
1332 tuple_impls! {
1333 1 => (0 T0)
1334 2 => (0 T0 1 T1)
1335 3 => (0 T0 1 T1 2 T2)
1336 4 => (0 T0 1 T1 2 T2 3 T3)
1337 5 => (0 T0 1 T1 2 T2 3 T3 4 T4)
1338 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5)
1339 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6)
1340 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7)
1341 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8)
1342 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9)
1343 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10)
1344 12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11)
1345 13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12)
1346 14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13)
1347 15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14)
1348 16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15)
1349 }
1350
1351 ////////////////////////////////////////////////////////////////////////////////
1352
1353 #[cfg(any(feature = "std", feature = "alloc"))]
1354 macro_rules! map_impl {
1355 (
1356 $ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)*>,
1357 $access:ident,
1358 $with_capacity:expr
1359 ) => {
1360 impl<'de, K, V $(, $typaram)*> Deserialize<'de> for $ty<K, V $(, $typaram)*>
1361 where
1362 K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*,
1363 V: Deserialize<'de>,
1364 $($typaram: $bound1 $(+ $bound2)*),*
1365 {
1366 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1367 where
1368 D: Deserializer<'de>,
1369 {
1370 struct MapVisitor<K, V $(, $typaram)*> {
1371 marker: PhantomData<$ty<K, V $(, $typaram)*>>,
1372 }
1373
1374 impl<'de, K, V $(, $typaram)*> Visitor<'de> for MapVisitor<K, V $(, $typaram)*>
1375 where
1376 K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*,
1377 V: Deserialize<'de>,
1378 $($typaram: $bound1 $(+ $bound2)*),*
1379 {
1380 type Value = $ty<K, V $(, $typaram)*>;
1381
1382 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1383 formatter.write_str("a map")
1384 }
1385
1386 #[inline]
1387 fn visit_map<A>(self, mut $access: A) -> Result<Self::Value, A::Error>
1388 where
1389 A: MapAccess<'de>,
1390 {
1391 let mut values = $with_capacity;
1392
1393 while let Some((key, value)) = try!($access.next_entry()) {
1394 values.insert(key, value);
1395 }
1396
1397 Ok(values)
1398 }
1399 }
1400
1401 let visitor = MapVisitor { marker: PhantomData };
1402 deserializer.deserialize_map(visitor)
1403 }
1404 }
1405 }
1406 }
1407
1408 #[cfg(any(feature = "std", feature = "alloc"))]
1409 map_impl!(
1410 BTreeMap<K: Ord, V>,
1411 map,
1412 BTreeMap::new());
1413
1414 #[cfg(feature = "std")]
1415 map_impl!(
1416 HashMap<K: Eq + Hash, V, S: BuildHasher + Default>,
1417 map,
1418 HashMap::with_capacity_and_hasher(size_hint::cautious(map.size_hint()), S::default()));
1419
1420 ////////////////////////////////////////////////////////////////////////////////
1421
1422 #[cfg(feature = "std")]
1423 macro_rules! parse_ip_impl {
1424 ($expecting:tt $ty:ty; $size:tt) => {
1425 impl<'de> Deserialize<'de> for $ty {
1426 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1427 where
1428 D: Deserializer<'de>,
1429 {
1430 if deserializer.is_human_readable() {
1431 deserializer.deserialize_str(FromStrVisitor::new($expecting))
1432 } else {
1433 <[u8; $size]>::deserialize(deserializer).map(<$ty>::from)
1434 }
1435 }
1436 }
1437 };
1438 }
1439
1440 #[cfg(feature = "std")]
1441 macro_rules! variant_identifier {
1442 (
1443 $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*)
1444 $expecting_message:expr,
1445 $variants_name:ident
1446 ) => {
1447 enum $name_kind {
1448 $($variant),*
1449 }
1450
1451 static $variants_name: &'static [&'static str] = &[$(stringify!($variant)),*];
1452
1453 impl<'de> Deserialize<'de> for $name_kind {
1454 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1455 where
1456 D: Deserializer<'de>,
1457 {
1458 struct KindVisitor;
1459
1460 impl<'de> Visitor<'de> for KindVisitor {
1461 type Value = $name_kind;
1462
1463 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1464 formatter.write_str($expecting_message)
1465 }
1466
1467 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1468 where
1469 E: Error,
1470 {
1471 match value {
1472 $(
1473 $index => Ok($name_kind :: $variant),
1474 )*
1475 _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self),),
1476 }
1477 }
1478
1479 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1480 where
1481 E: Error,
1482 {
1483 match value {
1484 $(
1485 stringify!($variant) => Ok($name_kind :: $variant),
1486 )*
1487 _ => Err(Error::unknown_variant(value, $variants_name)),
1488 }
1489 }
1490
1491 fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
1492 where
1493 E: Error,
1494 {
1495 match value {
1496 $(
1497 $bytes => Ok($name_kind :: $variant),
1498 )*
1499 _ => {
1500 match str::from_utf8(value) {
1501 Ok(value) => Err(Error::unknown_variant(value, $variants_name)),
1502 Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),
1503 }
1504 }
1505 }
1506 }
1507 }
1508
1509 deserializer.deserialize_identifier(KindVisitor)
1510 }
1511 }
1512 }
1513 }
1514
1515 #[cfg(feature = "std")]
1516 macro_rules! deserialize_enum {
1517 (
1518 $name:ident $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*)
1519 $expecting_message:expr,
1520 $deserializer:expr
1521 ) => {
1522 variant_identifier! {
1523 $name_kind ($($variant; $bytes; $index),*)
1524 $expecting_message,
1525 VARIANTS
1526 }
1527
1528 struct EnumVisitor;
1529 impl<'de> Visitor<'de> for EnumVisitor {
1530 type Value = $name;
1531
1532 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1533 formatter.write_str(concat!("a ", stringify!($name)))
1534 }
1535
1536
1537 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
1538 where
1539 A: EnumAccess<'de>,
1540 {
1541 match try!(data.variant()) {
1542 $(
1543 ($name_kind :: $variant, v) => v.newtype_variant().map($name :: $variant),
1544 )*
1545 }
1546 }
1547 }
1548 $deserializer.deserialize_enum(stringify!($name), VARIANTS, EnumVisitor)
1549 }
1550 }
1551
1552 #[cfg(feature = "std")]
1553 impl<'de> Deserialize<'de> for net::IpAddr {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,1554 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1555 where
1556 D: Deserializer<'de>,
1557 {
1558 if deserializer.is_human_readable() {
1559 deserializer.deserialize_str(FromStrVisitor::new("IP address"))
1560 } else {
1561 use lib::net::IpAddr;
1562 deserialize_enum! {
1563 IpAddr IpAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)
1564 "`V4` or `V6`",
1565 deserializer
1566 }
1567 }
1568 }
1569 }
1570
1571 #[cfg(feature = "std")]
1572 parse_ip_impl!("IPv4 address" net::Ipv4Addr; 4);
1573
1574 #[cfg(feature = "std")]
1575 parse_ip_impl!("IPv6 address" net::Ipv6Addr; 16);
1576
1577 #[cfg(feature = "std")]
1578 macro_rules! parse_socket_impl {
1579 ($expecting:tt $ty:ty, $new:expr) => {
1580 impl<'de> Deserialize<'de> for $ty {
1581 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1582 where
1583 D: Deserializer<'de>,
1584 {
1585 if deserializer.is_human_readable() {
1586 deserializer.deserialize_str(FromStrVisitor::new($expecting))
1587 } else {
1588 <(_, u16)>::deserialize(deserializer).map(|(ip, port)| $new(ip, port))
1589 }
1590 }
1591 }
1592 };
1593 }
1594
1595 #[cfg(feature = "std")]
1596 impl<'de> Deserialize<'de> for net::SocketAddr {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,1597 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1598 where
1599 D: Deserializer<'de>,
1600 {
1601 if deserializer.is_human_readable() {
1602 deserializer.deserialize_str(FromStrVisitor::new("socket address"))
1603 } else {
1604 use lib::net::SocketAddr;
1605 deserialize_enum! {
1606 SocketAddr SocketAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)
1607 "`V4` or `V6`",
1608 deserializer
1609 }
1610 }
1611 }
1612 }
1613
1614 #[cfg(feature = "std")]
1615 parse_socket_impl!("IPv4 socket address" net::SocketAddrV4, net::SocketAddrV4::new);
1616
1617 #[cfg(feature = "std")]
1618 parse_socket_impl!("IPv6 socket address" net::SocketAddrV6, |ip, port| net::SocketAddrV6::new(
1619 ip, port, 0, 0
1620 ));
1621
1622 ////////////////////////////////////////////////////////////////////////////////
1623
1624 #[cfg(feature = "std")]
1625 struct PathVisitor;
1626
1627 #[cfg(feature = "std")]
1628 impl<'a> Visitor<'a> for PathVisitor {
1629 type Value = &'a Path;
1630
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result1631 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1632 formatter.write_str("a borrowed path")
1633 }
1634
visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> where E: Error,1635 fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
1636 where
1637 E: Error,
1638 {
1639 Ok(v.as_ref())
1640 }
1641
visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> where E: Error,1642 fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
1643 where
1644 E: Error,
1645 {
1646 str::from_utf8(v)
1647 .map(AsRef::as_ref)
1648 .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
1649 }
1650 }
1651
1652 #[cfg(feature = "std")]
1653 impl<'de: 'a, 'a> Deserialize<'de> for &'a Path {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,1654 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1655 where
1656 D: Deserializer<'de>,
1657 {
1658 deserializer.deserialize_str(PathVisitor)
1659 }
1660 }
1661
1662 #[cfg(feature = "std")]
1663 struct PathBufVisitor;
1664
1665 #[cfg(feature = "std")]
1666 impl<'de> Visitor<'de> for PathBufVisitor {
1667 type Value = PathBuf;
1668
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result1669 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1670 formatter.write_str("path string")
1671 }
1672
visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: Error,1673 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1674 where
1675 E: Error,
1676 {
1677 Ok(From::from(v))
1678 }
1679
visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: Error,1680 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1681 where
1682 E: Error,
1683 {
1684 Ok(From::from(v))
1685 }
1686
visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> where E: Error,1687 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1688 where
1689 E: Error,
1690 {
1691 str::from_utf8(v)
1692 .map(From::from)
1693 .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
1694 }
1695
visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> where E: Error,1696 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1697 where
1698 E: Error,
1699 {
1700 String::from_utf8(v)
1701 .map(From::from)
1702 .map_err(|e| Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self))
1703 }
1704 }
1705
1706 #[cfg(feature = "std")]
1707 impl<'de> Deserialize<'de> for PathBuf {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,1708 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1709 where
1710 D: Deserializer<'de>,
1711 {
1712 deserializer.deserialize_string(PathBufVisitor)
1713 }
1714 }
1715
1716 #[cfg(all(feature = "std", not(no_de_boxed_path)))]
1717 forwarded_impl!((), Box<Path>, PathBuf::into_boxed_path);
1718
1719 ////////////////////////////////////////////////////////////////////////////////
1720
1721 // If this were outside of the serde crate, it would just use:
1722 //
1723 // #[derive(Deserialize)]
1724 // #[serde(variant_identifier)]
1725 #[cfg(all(feature = "std", any(unix, windows)))]
1726 variant_identifier! {
1727 OsStringKind (Unix; b"Unix"; 0, Windows; b"Windows"; 1)
1728 "`Unix` or `Windows`",
1729 OSSTR_VARIANTS
1730 }
1731
1732 #[cfg(all(feature = "std", any(unix, windows)))]
1733 struct OsStringVisitor;
1734
1735 #[cfg(all(feature = "std", any(unix, windows)))]
1736 impl<'de> Visitor<'de> for OsStringVisitor {
1737 type Value = OsString;
1738
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result1739 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1740 formatter.write_str("os string")
1741 }
1742
1743 #[cfg(unix)]
visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error> where A: EnumAccess<'de>,1744 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
1745 where
1746 A: EnumAccess<'de>,
1747 {
1748 use std::os::unix::ffi::OsStringExt;
1749
1750 match try!(data.variant()) {
1751 (OsStringKind::Unix, v) => v.newtype_variant().map(OsString::from_vec),
1752 (OsStringKind::Windows, _) => Err(Error::custom(
1753 "cannot deserialize Windows OS string on Unix",
1754 )),
1755 }
1756 }
1757
1758 #[cfg(windows)]
visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error> where A: EnumAccess<'de>,1759 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
1760 where
1761 A: EnumAccess<'de>,
1762 {
1763 use std::os::windows::ffi::OsStringExt;
1764
1765 match try!(data.variant()) {
1766 (OsStringKind::Windows, v) => v
1767 .newtype_variant::<Vec<u16>>()
1768 .map(|vec| OsString::from_wide(&vec)),
1769 (OsStringKind::Unix, _) => Err(Error::custom(
1770 "cannot deserialize Unix OS string on Windows",
1771 )),
1772 }
1773 }
1774 }
1775
1776 #[cfg(all(feature = "std", any(unix, windows)))]
1777 impl<'de> Deserialize<'de> for OsString {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,1778 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1779 where
1780 D: Deserializer<'de>,
1781 {
1782 deserializer.deserialize_enum("OsString", OSSTR_VARIANTS, OsStringVisitor)
1783 }
1784 }
1785
1786 ////////////////////////////////////////////////////////////////////////////////
1787
1788 #[cfg(any(feature = "std", feature = "alloc"))]
1789 forwarded_impl!((T), Box<T>, Box::new);
1790
1791 #[cfg(any(feature = "std", feature = "alloc"))]
1792 forwarded_impl!((T), Box<[T]>, Vec::into_boxed_slice);
1793
1794 #[cfg(any(feature = "std", feature = "alloc"))]
1795 forwarded_impl!((), Box<str>, String::into_boxed_str);
1796
1797 #[cfg(all(no_de_rc_dst, feature = "rc", any(feature = "std", feature = "alloc")))]
1798 forwarded_impl! {
1799 /// This impl requires the [`"rc"`] Cargo feature of Serde.
1800 ///
1801 /// Deserializing a data structure containing `Arc` will not attempt to
1802 /// deduplicate `Arc` references to the same data. Every deserialized `Arc`
1803 /// will end up with a strong count of 1.
1804 ///
1805 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
1806 (T), Arc<T>, Arc::new
1807 }
1808
1809 #[cfg(all(no_de_rc_dst, feature = "rc", any(feature = "std", feature = "alloc")))]
1810 forwarded_impl! {
1811 /// This impl requires the [`"rc"`] Cargo feature of Serde.
1812 ///
1813 /// Deserializing a data structure containing `Rc` will not attempt to
1814 /// deduplicate `Rc` references to the same data. Every deserialized `Rc`
1815 /// will end up with a strong count of 1.
1816 ///
1817 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
1818 (T), Rc<T>, Rc::new
1819 }
1820
1821 #[cfg(any(feature = "std", feature = "alloc"))]
1822 impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T>
1823 where
1824 T: ToOwned,
1825 T::Owned: Deserialize<'de>,
1826 {
1827 #[inline]
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,1828 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1829 where
1830 D: Deserializer<'de>,
1831 {
1832 T::Owned::deserialize(deserializer).map(Cow::Owned)
1833 }
1834 }
1835
1836 ////////////////////////////////////////////////////////////////////////////////
1837
1838 /// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting
1839 /// `Weak<T>` has a reference count of 0 and cannot be upgraded.
1840 ///
1841 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
1842 #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
1843 impl<'de, T: ?Sized> Deserialize<'de> for RcWeak<T>
1844 where
1845 T: Deserialize<'de>,
1846 {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,1847 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1848 where
1849 D: Deserializer<'de>,
1850 {
1851 try!(Option::<T>::deserialize(deserializer));
1852 Ok(RcWeak::new())
1853 }
1854 }
1855
1856 /// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting
1857 /// `Weak<T>` has a reference count of 0 and cannot be upgraded.
1858 ///
1859 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
1860 #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
1861 impl<'de, T: ?Sized> Deserialize<'de> for ArcWeak<T>
1862 where
1863 T: Deserialize<'de>,
1864 {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,1865 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1866 where
1867 D: Deserializer<'de>,
1868 {
1869 try!(Option::<T>::deserialize(deserializer));
1870 Ok(ArcWeak::new())
1871 }
1872 }
1873
1874 ////////////////////////////////////////////////////////////////////////////////
1875
1876 #[cfg(all(
1877 not(no_de_rc_dst),
1878 feature = "rc",
1879 any(feature = "std", feature = "alloc")
1880 ))]
1881 macro_rules! box_forwarded_impl {
1882 (
1883 $(#[doc = $doc:tt])*
1884 $t:ident
1885 ) => {
1886 $(#[doc = $doc])*
1887 impl<'de, T: ?Sized> Deserialize<'de> for $t<T>
1888 where
1889 Box<T>: Deserialize<'de>,
1890 {
1891 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1892 where
1893 D: Deserializer<'de>,
1894 {
1895 Box::deserialize(deserializer).map(Into::into)
1896 }
1897 }
1898 };
1899 }
1900
1901 #[cfg(all(
1902 not(no_de_rc_dst),
1903 feature = "rc",
1904 any(feature = "std", feature = "alloc")
1905 ))]
1906 box_forwarded_impl! {
1907 /// This impl requires the [`"rc"`] Cargo feature of Serde.
1908 ///
1909 /// Deserializing a data structure containing `Rc` will not attempt to
1910 /// deduplicate `Rc` references to the same data. Every deserialized `Rc`
1911 /// will end up with a strong count of 1.
1912 ///
1913 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
1914 Rc
1915 }
1916
1917 #[cfg(all(
1918 not(no_de_rc_dst),
1919 feature = "rc",
1920 any(feature = "std", feature = "alloc")
1921 ))]
1922 box_forwarded_impl! {
1923 /// This impl requires the [`"rc"`] Cargo feature of Serde.
1924 ///
1925 /// Deserializing a data structure containing `Arc` will not attempt to
1926 /// deduplicate `Arc` references to the same data. Every deserialized `Arc`
1927 /// will end up with a strong count of 1.
1928 ///
1929 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
1930 Arc
1931 }
1932
1933 ////////////////////////////////////////////////////////////////////////////////
1934
1935 impl<'de, T> Deserialize<'de> for Cell<T>
1936 where
1937 T: Deserialize<'de> + Copy,
1938 {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,1939 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1940 where
1941 D: Deserializer<'de>,
1942 {
1943 T::deserialize(deserializer).map(Cell::new)
1944 }
1945 }
1946
1947 forwarded_impl!((T), RefCell<T>, RefCell::new);
1948
1949 #[cfg(feature = "std")]
1950 forwarded_impl!((T), Mutex<T>, Mutex::new);
1951
1952 #[cfg(feature = "std")]
1953 forwarded_impl!((T), RwLock<T>, RwLock::new);
1954
1955 ////////////////////////////////////////////////////////////////////////////////
1956
1957 // This is a cleaned-up version of the impl generated by:
1958 //
1959 // #[derive(Deserialize)]
1960 // #[serde(deny_unknown_fields)]
1961 // struct Duration {
1962 // secs: u64,
1963 // nanos: u32,
1964 // }
1965 #[cfg(any(feature = "std", not(no_core_duration)))]
1966 impl<'de> Deserialize<'de> for Duration {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,1967 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1968 where
1969 D: Deserializer<'de>,
1970 {
1971 // If this were outside of the serde crate, it would just use:
1972 //
1973 // #[derive(Deserialize)]
1974 // #[serde(field_identifier, rename_all = "lowercase")]
1975 enum Field {
1976 Secs,
1977 Nanos,
1978 }
1979
1980 impl<'de> Deserialize<'de> for Field {
1981 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1982 where
1983 D: Deserializer<'de>,
1984 {
1985 struct FieldVisitor;
1986
1987 impl<'de> Visitor<'de> for FieldVisitor {
1988 type Value = Field;
1989
1990 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1991 formatter.write_str("`secs` or `nanos`")
1992 }
1993
1994 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1995 where
1996 E: Error,
1997 {
1998 match value {
1999 "secs" => Ok(Field::Secs),
2000 "nanos" => Ok(Field::Nanos),
2001 _ => Err(Error::unknown_field(value, FIELDS)),
2002 }
2003 }
2004
2005 fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2006 where
2007 E: Error,
2008 {
2009 match value {
2010 b"secs" => Ok(Field::Secs),
2011 b"nanos" => Ok(Field::Nanos),
2012 _ => {
2013 let value = ::__private::from_utf8_lossy(value);
2014 Err(Error::unknown_field(&*value, FIELDS))
2015 }
2016 }
2017 }
2018 }
2019
2020 deserializer.deserialize_identifier(FieldVisitor)
2021 }
2022 }
2023
2024 fn check_overflow<E>(secs: u64, nanos: u32) -> Result<(), E>
2025 where
2026 E: Error,
2027 {
2028 static NANOS_PER_SEC: u32 = 1_000_000_000;
2029 match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
2030 Some(_) => Ok(()),
2031 None => Err(E::custom("overflow deserializing Duration")),
2032 }
2033 }
2034
2035 struct DurationVisitor;
2036
2037 impl<'de> Visitor<'de> for DurationVisitor {
2038 type Value = Duration;
2039
2040 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2041 formatter.write_str("struct Duration")
2042 }
2043
2044 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2045 where
2046 A: SeqAccess<'de>,
2047 {
2048 let secs: u64 = match try!(seq.next_element()) {
2049 Some(value) => value,
2050 None => {
2051 return Err(Error::invalid_length(0, &self));
2052 }
2053 };
2054 let nanos: u32 = match try!(seq.next_element()) {
2055 Some(value) => value,
2056 None => {
2057 return Err(Error::invalid_length(1, &self));
2058 }
2059 };
2060 try!(check_overflow(secs, nanos));
2061 Ok(Duration::new(secs, nanos))
2062 }
2063
2064 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2065 where
2066 A: MapAccess<'de>,
2067 {
2068 let mut secs: Option<u64> = None;
2069 let mut nanos: Option<u32> = None;
2070 while let Some(key) = try!(map.next_key()) {
2071 match key {
2072 Field::Secs => {
2073 if secs.is_some() {
2074 return Err(<A::Error as Error>::duplicate_field("secs"));
2075 }
2076 secs = Some(try!(map.next_value()));
2077 }
2078 Field::Nanos => {
2079 if nanos.is_some() {
2080 return Err(<A::Error as Error>::duplicate_field("nanos"));
2081 }
2082 nanos = Some(try!(map.next_value()));
2083 }
2084 }
2085 }
2086 let secs = match secs {
2087 Some(secs) => secs,
2088 None => return Err(<A::Error as Error>::missing_field("secs")),
2089 };
2090 let nanos = match nanos {
2091 Some(nanos) => nanos,
2092 None => return Err(<A::Error as Error>::missing_field("nanos")),
2093 };
2094 try!(check_overflow(secs, nanos));
2095 Ok(Duration::new(secs, nanos))
2096 }
2097 }
2098
2099 const FIELDS: &'static [&'static str] = &["secs", "nanos"];
2100 deserializer.deserialize_struct("Duration", FIELDS, DurationVisitor)
2101 }
2102 }
2103
2104 ////////////////////////////////////////////////////////////////////////////////
2105
2106 #[cfg(feature = "std")]
2107 impl<'de> Deserialize<'de> for SystemTime {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,2108 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2109 where
2110 D: Deserializer<'de>,
2111 {
2112 // Reuse duration
2113 enum Field {
2114 Secs,
2115 Nanos,
2116 }
2117
2118 impl<'de> Deserialize<'de> for Field {
2119 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2120 where
2121 D: Deserializer<'de>,
2122 {
2123 struct FieldVisitor;
2124
2125 impl<'de> Visitor<'de> for FieldVisitor {
2126 type Value = Field;
2127
2128 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2129 formatter.write_str("`secs_since_epoch` or `nanos_since_epoch`")
2130 }
2131
2132 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2133 where
2134 E: Error,
2135 {
2136 match value {
2137 "secs_since_epoch" => Ok(Field::Secs),
2138 "nanos_since_epoch" => Ok(Field::Nanos),
2139 _ => Err(Error::unknown_field(value, FIELDS)),
2140 }
2141 }
2142
2143 fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2144 where
2145 E: Error,
2146 {
2147 match value {
2148 b"secs_since_epoch" => Ok(Field::Secs),
2149 b"nanos_since_epoch" => Ok(Field::Nanos),
2150 _ => {
2151 let value = String::from_utf8_lossy(value);
2152 Err(Error::unknown_field(&value, FIELDS))
2153 }
2154 }
2155 }
2156 }
2157
2158 deserializer.deserialize_identifier(FieldVisitor)
2159 }
2160 }
2161
2162 fn check_overflow<E>(secs: u64, nanos: u32) -> Result<(), E>
2163 where
2164 E: Error,
2165 {
2166 static NANOS_PER_SEC: u32 = 1_000_000_000;
2167 match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
2168 Some(_) => Ok(()),
2169 None => Err(E::custom("overflow deserializing SystemTime epoch offset")),
2170 }
2171 }
2172
2173 struct DurationVisitor;
2174
2175 impl<'de> Visitor<'de> for DurationVisitor {
2176 type Value = Duration;
2177
2178 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2179 formatter.write_str("struct SystemTime")
2180 }
2181
2182 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2183 where
2184 A: SeqAccess<'de>,
2185 {
2186 let secs: u64 = match try!(seq.next_element()) {
2187 Some(value) => value,
2188 None => {
2189 return Err(Error::invalid_length(0, &self));
2190 }
2191 };
2192 let nanos: u32 = match try!(seq.next_element()) {
2193 Some(value) => value,
2194 None => {
2195 return Err(Error::invalid_length(1, &self));
2196 }
2197 };
2198 try!(check_overflow(secs, nanos));
2199 Ok(Duration::new(secs, nanos))
2200 }
2201
2202 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2203 where
2204 A: MapAccess<'de>,
2205 {
2206 let mut secs: Option<u64> = None;
2207 let mut nanos: Option<u32> = None;
2208 while let Some(key) = try!(map.next_key()) {
2209 match key {
2210 Field::Secs => {
2211 if secs.is_some() {
2212 return Err(<A::Error as Error>::duplicate_field(
2213 "secs_since_epoch",
2214 ));
2215 }
2216 secs = Some(try!(map.next_value()));
2217 }
2218 Field::Nanos => {
2219 if nanos.is_some() {
2220 return Err(<A::Error as Error>::duplicate_field(
2221 "nanos_since_epoch",
2222 ));
2223 }
2224 nanos = Some(try!(map.next_value()));
2225 }
2226 }
2227 }
2228 let secs = match secs {
2229 Some(secs) => secs,
2230 None => return Err(<A::Error as Error>::missing_field("secs_since_epoch")),
2231 };
2232 let nanos = match nanos {
2233 Some(nanos) => nanos,
2234 None => return Err(<A::Error as Error>::missing_field("nanos_since_epoch")),
2235 };
2236 try!(check_overflow(secs, nanos));
2237 Ok(Duration::new(secs, nanos))
2238 }
2239 }
2240
2241 const FIELDS: &'static [&'static str] = &["secs_since_epoch", "nanos_since_epoch"];
2242 let duration = try!(deserializer.deserialize_struct("SystemTime", FIELDS, DurationVisitor));
2243 #[cfg(not(no_systemtime_checked_add))]
2244 let ret = UNIX_EPOCH
2245 .checked_add(duration)
2246 .ok_or_else(|| D::Error::custom("overflow deserializing SystemTime"));
2247 #[cfg(no_systemtime_checked_add)]
2248 let ret = Ok(UNIX_EPOCH + duration);
2249 ret
2250 }
2251 }
2252
2253 ////////////////////////////////////////////////////////////////////////////////
2254
2255 // Similar to:
2256 //
2257 // #[derive(Deserialize)]
2258 // #[serde(deny_unknown_fields)]
2259 // struct Range {
2260 // start: u64,
2261 // end: u32,
2262 // }
2263 impl<'de, Idx> Deserialize<'de> for Range<Idx>
2264 where
2265 Idx: Deserialize<'de>,
2266 {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,2267 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2268 where
2269 D: Deserializer<'de>,
2270 {
2271 let (start, end) = try!(deserializer.deserialize_struct(
2272 "Range",
2273 range::FIELDS,
2274 range::RangeVisitor {
2275 expecting: "struct Range",
2276 phantom: PhantomData,
2277 },
2278 ));
2279 Ok(start..end)
2280 }
2281 }
2282
2283 #[cfg(not(no_range_inclusive))]
2284 impl<'de, Idx> Deserialize<'de> for RangeInclusive<Idx>
2285 where
2286 Idx: Deserialize<'de>,
2287 {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,2288 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2289 where
2290 D: Deserializer<'de>,
2291 {
2292 let (start, end) = try!(deserializer.deserialize_struct(
2293 "RangeInclusive",
2294 range::FIELDS,
2295 range::RangeVisitor {
2296 expecting: "struct RangeInclusive",
2297 phantom: PhantomData,
2298 },
2299 ));
2300 Ok(RangeInclusive::new(start, end))
2301 }
2302 }
2303
2304 mod range {
2305 use lib::*;
2306
2307 use de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor};
2308
2309 pub const FIELDS: &'static [&'static str] = &["start", "end"];
2310
2311 // If this were outside of the serde crate, it would just use:
2312 //
2313 // #[derive(Deserialize)]
2314 // #[serde(field_identifier, rename_all = "lowercase")]
2315 enum Field {
2316 Start,
2317 End,
2318 }
2319
2320 impl<'de> Deserialize<'de> for Field {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,2321 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2322 where
2323 D: Deserializer<'de>,
2324 {
2325 struct FieldVisitor;
2326
2327 impl<'de> Visitor<'de> for FieldVisitor {
2328 type Value = Field;
2329
2330 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2331 formatter.write_str("`start` or `end`")
2332 }
2333
2334 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2335 where
2336 E: Error,
2337 {
2338 match value {
2339 "start" => Ok(Field::Start),
2340 "end" => Ok(Field::End),
2341 _ => Err(Error::unknown_field(value, FIELDS)),
2342 }
2343 }
2344
2345 fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2346 where
2347 E: Error,
2348 {
2349 match value {
2350 b"start" => Ok(Field::Start),
2351 b"end" => Ok(Field::End),
2352 _ => {
2353 let value = ::__private::from_utf8_lossy(value);
2354 Err(Error::unknown_field(&*value, FIELDS))
2355 }
2356 }
2357 }
2358 }
2359
2360 deserializer.deserialize_identifier(FieldVisitor)
2361 }
2362 }
2363
2364 pub struct RangeVisitor<Idx> {
2365 pub expecting: &'static str,
2366 pub phantom: PhantomData<Idx>,
2367 }
2368
2369 impl<'de, Idx> Visitor<'de> for RangeVisitor<Idx>
2370 where
2371 Idx: Deserialize<'de>,
2372 {
2373 type Value = (Idx, Idx);
2374
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result2375 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2376 formatter.write_str(self.expecting)
2377 }
2378
visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>,2379 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
2380 where
2381 A: SeqAccess<'de>,
2382 {
2383 let start: Idx = match try!(seq.next_element()) {
2384 Some(value) => value,
2385 None => {
2386 return Err(Error::invalid_length(0, &self));
2387 }
2388 };
2389 let end: Idx = match try!(seq.next_element()) {
2390 Some(value) => value,
2391 None => {
2392 return Err(Error::invalid_length(1, &self));
2393 }
2394 };
2395 Ok((start, end))
2396 }
2397
visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: MapAccess<'de>,2398 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
2399 where
2400 A: MapAccess<'de>,
2401 {
2402 let mut start: Option<Idx> = None;
2403 let mut end: Option<Idx> = None;
2404 while let Some(key) = try!(map.next_key()) {
2405 match key {
2406 Field::Start => {
2407 if start.is_some() {
2408 return Err(<A::Error as Error>::duplicate_field("start"));
2409 }
2410 start = Some(try!(map.next_value()));
2411 }
2412 Field::End => {
2413 if end.is_some() {
2414 return Err(<A::Error as Error>::duplicate_field("end"));
2415 }
2416 end = Some(try!(map.next_value()));
2417 }
2418 }
2419 }
2420 let start = match start {
2421 Some(start) => start,
2422 None => return Err(<A::Error as Error>::missing_field("start")),
2423 };
2424 let end = match end {
2425 Some(end) => end,
2426 None => return Err(<A::Error as Error>::missing_field("end")),
2427 };
2428 Ok((start, end))
2429 }
2430 }
2431 }
2432
2433 ////////////////////////////////////////////////////////////////////////////////
2434
2435 #[cfg(any(not(no_ops_bound), all(feature = "std", not(no_collections_bound))))]
2436 impl<'de, T> Deserialize<'de> for Bound<T>
2437 where
2438 T: Deserialize<'de>,
2439 {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,2440 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2441 where
2442 D: Deserializer<'de>,
2443 {
2444 enum Field {
2445 Unbounded,
2446 Included,
2447 Excluded,
2448 }
2449
2450 impl<'de> Deserialize<'de> for Field {
2451 #[inline]
2452 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2453 where
2454 D: Deserializer<'de>,
2455 {
2456 struct FieldVisitor;
2457
2458 impl<'de> Visitor<'de> for FieldVisitor {
2459 type Value = Field;
2460
2461 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2462 formatter.write_str("`Unbounded`, `Included` or `Excluded`")
2463 }
2464
2465 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
2466 where
2467 E: Error,
2468 {
2469 match value {
2470 0 => Ok(Field::Unbounded),
2471 1 => Ok(Field::Included),
2472 2 => Ok(Field::Excluded),
2473 _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self)),
2474 }
2475 }
2476
2477 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2478 where
2479 E: Error,
2480 {
2481 match value {
2482 "Unbounded" => Ok(Field::Unbounded),
2483 "Included" => Ok(Field::Included),
2484 "Excluded" => Ok(Field::Excluded),
2485 _ => Err(Error::unknown_variant(value, VARIANTS)),
2486 }
2487 }
2488
2489 fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2490 where
2491 E: Error,
2492 {
2493 match value {
2494 b"Unbounded" => Ok(Field::Unbounded),
2495 b"Included" => Ok(Field::Included),
2496 b"Excluded" => Ok(Field::Excluded),
2497 _ => match str::from_utf8(value) {
2498 Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
2499 Err(_) => {
2500 Err(Error::invalid_value(Unexpected::Bytes(value), &self))
2501 }
2502 },
2503 }
2504 }
2505 }
2506
2507 deserializer.deserialize_identifier(FieldVisitor)
2508 }
2509 }
2510
2511 struct BoundVisitor<T>(PhantomData<Bound<T>>);
2512
2513 impl<'de, T> Visitor<'de> for BoundVisitor<T>
2514 where
2515 T: Deserialize<'de>,
2516 {
2517 type Value = Bound<T>;
2518
2519 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2520 formatter.write_str("enum Bound")
2521 }
2522
2523 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
2524 where
2525 A: EnumAccess<'de>,
2526 {
2527 match try!(data.variant()) {
2528 (Field::Unbounded, v) => v.unit_variant().map(|()| Bound::Unbounded),
2529 (Field::Included, v) => v.newtype_variant().map(Bound::Included),
2530 (Field::Excluded, v) => v.newtype_variant().map(Bound::Excluded),
2531 }
2532 }
2533 }
2534
2535 const VARIANTS: &'static [&'static str] = &["Unbounded", "Included", "Excluded"];
2536
2537 deserializer.deserialize_enum("Bound", VARIANTS, BoundVisitor(PhantomData))
2538 }
2539 }
2540
2541 ////////////////////////////////////////////////////////////////////////////////
2542
2543 impl<'de, T, E> Deserialize<'de> for Result<T, E>
2544 where
2545 T: Deserialize<'de>,
2546 E: Deserialize<'de>,
2547 {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,2548 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2549 where
2550 D: Deserializer<'de>,
2551 {
2552 // If this were outside of the serde crate, it would just use:
2553 //
2554 // #[derive(Deserialize)]
2555 // #[serde(variant_identifier)]
2556 enum Field {
2557 Ok,
2558 Err,
2559 }
2560
2561 impl<'de> Deserialize<'de> for Field {
2562 #[inline]
2563 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2564 where
2565 D: Deserializer<'de>,
2566 {
2567 struct FieldVisitor;
2568
2569 impl<'de> Visitor<'de> for FieldVisitor {
2570 type Value = Field;
2571
2572 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2573 formatter.write_str("`Ok` or `Err`")
2574 }
2575
2576 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
2577 where
2578 E: Error,
2579 {
2580 match value {
2581 0 => Ok(Field::Ok),
2582 1 => Ok(Field::Err),
2583 _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self)),
2584 }
2585 }
2586
2587 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2588 where
2589 E: Error,
2590 {
2591 match value {
2592 "Ok" => Ok(Field::Ok),
2593 "Err" => Ok(Field::Err),
2594 _ => Err(Error::unknown_variant(value, VARIANTS)),
2595 }
2596 }
2597
2598 fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
2599 where
2600 E: Error,
2601 {
2602 match value {
2603 b"Ok" => Ok(Field::Ok),
2604 b"Err" => Ok(Field::Err),
2605 _ => match str::from_utf8(value) {
2606 Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
2607 Err(_) => {
2608 Err(Error::invalid_value(Unexpected::Bytes(value), &self))
2609 }
2610 },
2611 }
2612 }
2613 }
2614
2615 deserializer.deserialize_identifier(FieldVisitor)
2616 }
2617 }
2618
2619 struct ResultVisitor<T, E>(PhantomData<Result<T, E>>);
2620
2621 impl<'de, T, E> Visitor<'de> for ResultVisitor<T, E>
2622 where
2623 T: Deserialize<'de>,
2624 E: Deserialize<'de>,
2625 {
2626 type Value = Result<T, E>;
2627
2628 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2629 formatter.write_str("enum Result")
2630 }
2631
2632 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
2633 where
2634 A: EnumAccess<'de>,
2635 {
2636 match try!(data.variant()) {
2637 (Field::Ok, v) => v.newtype_variant().map(Ok),
2638 (Field::Err, v) => v.newtype_variant().map(Err),
2639 }
2640 }
2641 }
2642
2643 const VARIANTS: &'static [&'static str] = &["Ok", "Err"];
2644
2645 deserializer.deserialize_enum("Result", VARIANTS, ResultVisitor(PhantomData))
2646 }
2647 }
2648
2649 ////////////////////////////////////////////////////////////////////////////////
2650
2651 impl<'de, T> Deserialize<'de> for Wrapping<T>
2652 where
2653 T: Deserialize<'de>,
2654 {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,2655 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2656 where
2657 D: Deserializer<'de>,
2658 {
2659 Deserialize::deserialize(deserializer).map(Wrapping)
2660 }
2661 }
2662
2663 #[cfg(all(feature = "std", not(no_std_atomic)))]
2664 macro_rules! atomic_impl {
2665 ($($ty:ident $size:expr)*) => {
2666 $(
2667 #[cfg(any(no_target_has_atomic, target_has_atomic = $size))]
2668 impl<'de> Deserialize<'de> for $ty {
2669 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2670 where
2671 D: Deserializer<'de>,
2672 {
2673 Deserialize::deserialize(deserializer).map(Self::new)
2674 }
2675 }
2676 )*
2677 };
2678 }
2679
2680 #[cfg(all(feature = "std", not(no_std_atomic)))]
2681 atomic_impl! {
2682 AtomicBool "8"
2683 AtomicI8 "8"
2684 AtomicI16 "16"
2685 AtomicI32 "32"
2686 AtomicIsize "ptr"
2687 AtomicU8 "8"
2688 AtomicU16 "16"
2689 AtomicU32 "32"
2690 AtomicUsize "ptr"
2691 }
2692
2693 #[cfg(all(feature = "std", not(no_std_atomic64)))]
2694 atomic_impl! {
2695 AtomicI64 "64"
2696 AtomicU64 "64"
2697 }
2698
2699 #[cfg(feature = "std")]
2700 struct FromStrVisitor<T> {
2701 expecting: &'static str,
2702 ty: PhantomData<T>,
2703 }
2704
2705 #[cfg(feature = "std")]
2706 impl<T> FromStrVisitor<T> {
new(expecting: &'static str) -> Self2707 fn new(expecting: &'static str) -> Self {
2708 FromStrVisitor {
2709 expecting: expecting,
2710 ty: PhantomData,
2711 }
2712 }
2713 }
2714
2715 #[cfg(feature = "std")]
2716 impl<'de, T> Visitor<'de> for FromStrVisitor<T>
2717 where
2718 T: str::FromStr,
2719 T::Err: fmt::Display,
2720 {
2721 type Value = T;
2722
expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result2723 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2724 formatter.write_str(self.expecting)
2725 }
2726
visit_str<E>(self, s: &str) -> Result<Self::Value, E> where E: Error,2727 fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
2728 where
2729 E: Error,
2730 {
2731 s.parse().map_err(Error::custom)
2732 }
2733 }
2734