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