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