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