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