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