1pub(crate) use self::macros::*;
2use crate::{formats::*, prelude::*};
3#[cfg(feature = "hashbrown_0_14")]
4use hashbrown_0_14::{HashMap as HashbrownMap014, HashSet as HashbrownSet014};
5#[cfg(feature = "hashbrown_0_15")]
6use hashbrown_0_15::{HashMap as HashbrownMap015, HashSet as HashbrownSet015};
7#[cfg(feature = "indexmap_1")]
8use indexmap_1::{IndexMap, IndexSet};
9#[cfg(feature = "indexmap_2")]
10use indexmap_2::{IndexMap as IndexMap2, IndexSet as IndexSet2};
11
12#[cfg(feature = "alloc")]
16type BoxedSlice<T> = Box<[T]>;
17
18pub(crate) mod macros {
19 #![allow(unused_imports)]
22
23 macro_rules! foreach_map {
24 ($m:ident) => {
25 #[cfg(feature = "alloc")]
26 $m!(BTreeMap<K: Ord, V>, (|_size| BTreeMap::new()));
27 #[cfg(feature = "std")]
28 $m!(
29 HashMap<K: Eq + Hash, V, S: BuildHasher + Default>,
30 (|size| HashMap::with_capacity_and_hasher(size, Default::default()))
31 );
32 #[cfg(feature = "hashbrown_0_14")]
33 $m!(
34 HashbrownMap014<K: Eq + Hash, V, S: BuildHasher + Default>,
35 (|size| HashbrownMap014::with_capacity_and_hasher(size, Default::default()))
36 );
37 #[cfg(feature = "hashbrown_0_15")]
38 $m!(
39 HashbrownMap015<K: Eq + Hash, V, S: BuildHasher + Default>,
40 (|size| HashbrownMap015::with_capacity_and_hasher(size, Default::default()))
41 );
42 #[cfg(feature = "indexmap_1")]
43 $m!(
44 IndexMap<K: Eq + Hash, V, S: BuildHasher + Default>,
45 (|size| IndexMap::with_capacity_and_hasher(size, Default::default()))
46 );
47 #[cfg(feature = "indexmap_2")]
48 $m!(
49 IndexMap2<K: Eq + Hash, V, S: BuildHasher + Default>,
50 (|size| IndexMap2::with_capacity_and_hasher(size, Default::default()))
51 );
52 };
53 }
54
55 macro_rules! foreach_set {
56 ($m:ident) => {
57 #[cfg(feature = "alloc")]
58 $m!(BTreeSet<T: Ord>, (|_| BTreeSet::new()), insert);
59 #[cfg(feature = "std")]
60 $m!(
61 HashSet<T: Eq + Hash, S: BuildHasher + Default>,
62 (|size| HashSet::with_capacity_and_hasher(size, S::default())),
63 insert
64 );
65 #[cfg(feature = "hashbrown_0_14")]
66 $m!(
67 HashbrownSet014<T: Eq + Hash, S: BuildHasher + Default>,
68 (|size| HashbrownSet014::with_capacity_and_hasher(size, S::default())),
69 insert
70 );
71 #[cfg(feature = "hashbrown_0_15")]
72 $m!(
73 HashbrownSet015<T: Eq + Hash, S: BuildHasher + Default>,
74 (|size| HashbrownSet015::with_capacity_and_hasher(size, S::default())),
75 insert
76 );
77 #[cfg(feature = "indexmap_1")]
78 $m!(
79 IndexSet<T: Eq + Hash, S: BuildHasher + Default>,
80 (|size| IndexSet::with_capacity_and_hasher(size, S::default())),
81 insert
82 );
83 #[cfg(feature = "indexmap_2")]
84 $m!(
85 IndexSet2<T: Eq + Hash, S: BuildHasher + Default>,
86 (|size| IndexSet2::with_capacity_and_hasher(size, S::default())),
87 insert
88 );
89 };
90 }
91
92 macro_rules! foreach_seq {
93 ($m:ident) => {
94 foreach_set!($m);
95
96 #[cfg(feature = "alloc")]
97 $m!(
98 BinaryHeap<T: Ord>,
99 (|size| BinaryHeap::with_capacity(size)),
100 push
101 );
102 #[cfg(feature = "alloc")]
103 $m!(BoxedSlice<T>, (|size| Vec::with_capacity(size)), push);
104 #[cfg(feature = "alloc")]
105 $m!(LinkedList<T>, (|_| LinkedList::new()), push_back);
106 #[cfg(feature = "alloc")]
107 $m!(Vec<T>, (|size| Vec::with_capacity(size)), push);
108 #[cfg(feature = "alloc")]
109 $m!(
110 VecDeque<T>,
111 (|size| VecDeque::with_capacity(size)),
112 push_back
113 );
114 };
115 }
116
117 pub(crate) use foreach_map;
119 pub(crate) use foreach_seq;
120 pub(crate) use foreach_set;
121}
122
123#[allow(unused_macros)]
127macro_rules! pinned_wrapper {
128 ($wrapper:ident) => {
129 impl<'de, T, U> DeserializeAs<'de, Pin<$wrapper<T>>> for Pin<$wrapper<U>>
130 where
131 U: DeserializeAs<'de, T>,
132 {
133 fn deserialize_as<D>(deserializer: D) -> Result<Pin<$wrapper<T>>, D::Error>
134 where
135 D: Deserializer<'de>,
136 {
137 Ok($wrapper::pin(
138 DeserializeAsWrap::<T, U>::deserialize(deserializer)?.into_inner(),
139 ))
140 }
141 }
142 };
143}
144
145#[cfg(feature = "alloc")]
146impl<'de, T, U> DeserializeAs<'de, Box<T>> for Box<U>
147where
148 U: DeserializeAs<'de, T>,
149{
150 fn deserialize_as<D>(deserializer: D) -> Result<Box<T>, D::Error>
151 where
152 D: Deserializer<'de>,
153 {
154 Ok(Box::new(
155 DeserializeAsWrap::<T, U>::deserialize(deserializer)?.into_inner(),
156 ))
157 }
158}
159
160#[cfg(feature = "alloc")]
161pinned_wrapper!(Box);
162
163impl<'de, T, U> DeserializeAs<'de, Option<T>> for Option<U>
164where
165 U: DeserializeAs<'de, T>,
166{
167 fn deserialize_as<D>(deserializer: D) -> Result<Option<T>, D::Error>
168 where
169 D: Deserializer<'de>,
170 {
171 struct OptionVisitor<T, U>(PhantomData<(T, U)>);
172
173 impl<'de, T, U> Visitor<'de> for OptionVisitor<T, U>
174 where
175 U: DeserializeAs<'de, T>,
176 {
177 type Value = Option<T>;
178
179 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
180 formatter.write_str("option")
181 }
182
183 #[inline]
184 fn visit_unit<E>(self) -> Result<Self::Value, E>
185 where
186 E: DeError,
187 {
188 Ok(None)
189 }
190
191 #[inline]
192 fn visit_none<E>(self) -> Result<Self::Value, E>
193 where
194 E: DeError,
195 {
196 Ok(None)
197 }
198
199 #[inline]
200 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
201 where
202 D: Deserializer<'de>,
203 {
204 U::deserialize_as(deserializer).map(Some)
205 }
206 }
207
208 deserializer.deserialize_option(OptionVisitor::<T, U>(PhantomData))
209 }
210}
211
212impl<'de, T, U> DeserializeAs<'de, Bound<T>> for Bound<U>
213where
214 U: DeserializeAs<'de, T>,
215{
216 fn deserialize_as<D>(deserializer: D) -> Result<Bound<T>, D::Error>
217 where
218 D: Deserializer<'de>,
219 {
220 Ok(
221 match Bound::<DeserializeAsWrap<T, U>>::deserialize(deserializer)? {
222 Bound::Unbounded => Bound::Unbounded,
223 Bound::Included(v) => Bound::Included(v.into_inner()),
224 Bound::Excluded(v) => Bound::Excluded(v.into_inner()),
225 },
226 )
227 }
228}
229
230#[cfg(feature = "alloc")]
231impl<'de, T, U> DeserializeAs<'de, Rc<T>> for Rc<U>
232where
233 U: DeserializeAs<'de, T>,
234{
235 fn deserialize_as<D>(deserializer: D) -> Result<Rc<T>, D::Error>
236 where
237 D: Deserializer<'de>,
238 {
239 Ok(Rc::new(
240 DeserializeAsWrap::<T, U>::deserialize(deserializer)?.into_inner(),
241 ))
242 }
243}
244
245#[cfg(feature = "alloc")]
246pinned_wrapper!(Rc);
247
248#[cfg(feature = "alloc")]
249impl<'de, T, U> DeserializeAs<'de, RcWeak<T>> for RcWeak<U>
250where
251 U: DeserializeAs<'de, T>,
252{
253 fn deserialize_as<D>(deserializer: D) -> Result<RcWeak<T>, D::Error>
254 where
255 D: Deserializer<'de>,
256 {
257 DeserializeAsWrap::<Option<Rc<T>>, Option<Rc<U>>>::deserialize(deserializer)?;
258 Ok(RcWeak::new())
259 }
260}
261
262#[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
263impl<'de, T, U> DeserializeAs<'de, Arc<T>> for Arc<U>
264where
265 U: DeserializeAs<'de, T>,
266{
267 fn deserialize_as<D>(deserializer: D) -> Result<Arc<T>, D::Error>
268 where
269 D: Deserializer<'de>,
270 {
271 Ok(Arc::new(
272 DeserializeAsWrap::<T, U>::deserialize(deserializer)?.into_inner(),
273 ))
274 }
275}
276
277#[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
278pinned_wrapper!(Arc);
279
280#[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
281impl<'de, T, U> DeserializeAs<'de, ArcWeak<T>> for ArcWeak<U>
282where
283 U: DeserializeAs<'de, T>,
284{
285 fn deserialize_as<D>(deserializer: D) -> Result<ArcWeak<T>, D::Error>
286 where
287 D: Deserializer<'de>,
288 {
289 DeserializeAsWrap::<Option<Arc<T>>, Option<Arc<U>>>::deserialize(deserializer)?;
290 Ok(ArcWeak::new())
291 }
292}
293
294impl<'de, T, U> DeserializeAs<'de, Cell<T>> for Cell<U>
295where
296 U: DeserializeAs<'de, T>,
297{
298 fn deserialize_as<D>(deserializer: D) -> Result<Cell<T>, D::Error>
299 where
300 D: Deserializer<'de>,
301 {
302 Ok(Cell::new(
303 DeserializeAsWrap::<T, U>::deserialize(deserializer)?.into_inner(),
304 ))
305 }
306}
307
308impl<'de, T, U> DeserializeAs<'de, RefCell<T>> for RefCell<U>
309where
310 U: DeserializeAs<'de, T>,
311{
312 fn deserialize_as<D>(deserializer: D) -> Result<RefCell<T>, D::Error>
313 where
314 D: Deserializer<'de>,
315 {
316 Ok(RefCell::new(
317 DeserializeAsWrap::<T, U>::deserialize(deserializer)?.into_inner(),
318 ))
319 }
320}
321
322#[cfg(feature = "std")]
323impl<'de, T, U> DeserializeAs<'de, Mutex<T>> for Mutex<U>
324where
325 U: DeserializeAs<'de, T>,
326{
327 fn deserialize_as<D>(deserializer: D) -> Result<Mutex<T>, D::Error>
328 where
329 D: Deserializer<'de>,
330 {
331 Ok(Mutex::new(
332 DeserializeAsWrap::<T, U>::deserialize(deserializer)?.into_inner(),
333 ))
334 }
335}
336
337#[cfg(feature = "std")]
338impl<'de, T, U> DeserializeAs<'de, RwLock<T>> for RwLock<U>
339where
340 U: DeserializeAs<'de, T>,
341{
342 fn deserialize_as<D>(deserializer: D) -> Result<RwLock<T>, D::Error>
343 where
344 D: Deserializer<'de>,
345 {
346 Ok(RwLock::new(
347 DeserializeAsWrap::<T, U>::deserialize(deserializer)?.into_inner(),
348 ))
349 }
350}
351
352impl<'de, T, TAs, E, EAs> DeserializeAs<'de, Result<T, E>> for Result<TAs, EAs>
353where
354 TAs: DeserializeAs<'de, T>,
355 EAs: DeserializeAs<'de, E>,
356{
357 fn deserialize_as<D>(deserializer: D) -> Result<Result<T, E>, D::Error>
358 where
359 D: Deserializer<'de>,
360 {
361 Ok(
362 match Result::<DeserializeAsWrap<T, TAs>, DeserializeAsWrap<E, EAs>>::deserialize(
363 deserializer,
364 )? {
365 Ok(value) => Ok(value.into_inner()),
366 Err(err) => Err(err.into_inner()),
367 },
368 )
369 }
370}
371
372impl<'de, T, As, const N: usize> DeserializeAs<'de, [T; N]> for [As; N]
373where
374 As: DeserializeAs<'de, T>,
375{
376 fn deserialize_as<D>(deserializer: D) -> Result<[T; N], D::Error>
377 where
378 D: Deserializer<'de>,
379 {
380 struct ArrayVisitor<T, const M: usize>(PhantomData<T>);
381
382 impl<'de, T, As, const M: usize> Visitor<'de> for ArrayVisitor<DeserializeAsWrap<T, As>, M>
383 where
384 As: DeserializeAs<'de, T>,
385 {
386 type Value = [T; M];
387
388 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
389 formatter.write_fmt(format_args!("an array of size {M}"))
390 }
391
392 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
393 where
394 A: SeqAccess<'de>,
395 {
396 utils::array_from_iterator(
397 utils::SeqIter::new(seq).map(
398 |res: Result<DeserializeAsWrap<T, As>, A::Error>| {
399 res.map(DeserializeAsWrap::into_inner)
400 },
401 ),
402 &self,
403 )
404 }
405 }
406
407 deserializer.deserialize_tuple(N, ArrayVisitor::<DeserializeAsWrap<T, As>, N>(PhantomData))
408 }
409}
410
411impl<'de, Idx, IdxAs> DeserializeAs<'de, Range<Idx>> for Range<IdxAs>
416where
417 IdxAs: DeserializeAs<'de, Idx>,
418{
419 fn deserialize_as<D>(deserializer: D) -> Result<Range<Idx>, D::Error>
420 where
421 D: Deserializer<'de>,
422 {
423 let Range::<DeserializeAsWrap<Idx, IdxAs>> { start, end } =
424 Deserialize::deserialize(deserializer)?;
425
426 Ok(Range {
427 start: start.into_inner(),
428 end: end.into_inner(),
429 })
430 }
431}
432
433impl<'de, Idx, IdxAs> DeserializeAs<'de, RangeFrom<Idx>> for RangeFrom<IdxAs>
434where
435 IdxAs: DeserializeAs<'de, Idx>,
436{
437 fn deserialize_as<D>(deserializer: D) -> Result<RangeFrom<Idx>, D::Error>
438 where
439 D: Deserializer<'de>,
440 {
441 let RangeFrom::<DeserializeAsWrap<Idx, IdxAs>> { start } =
442 Deserialize::deserialize(deserializer)?;
443
444 Ok(RangeFrom {
445 start: start.into_inner(),
446 })
447 }
448}
449
450impl<'de, Idx, IdxAs> DeserializeAs<'de, RangeInclusive<Idx>> for RangeInclusive<IdxAs>
451where
452 IdxAs: DeserializeAs<'de, Idx>,
453{
454 fn deserialize_as<D>(deserializer: D) -> Result<RangeInclusive<Idx>, D::Error>
455 where
456 D: Deserializer<'de>,
457 {
458 let (start, end) =
459 RangeInclusive::<DeserializeAsWrap<Idx, IdxAs>>::deserialize(deserializer)?
460 .into_inner();
461
462 Ok(RangeInclusive::new(start.into_inner(), end.into_inner()))
463 }
464}
465
466impl<'de, Idx, IdxAs> DeserializeAs<'de, RangeTo<Idx>> for RangeTo<IdxAs>
467where
468 IdxAs: DeserializeAs<'de, Idx>,
469{
470 fn deserialize_as<D>(deserializer: D) -> Result<RangeTo<Idx>, D::Error>
471 where
472 D: Deserializer<'de>,
473 {
474 let RangeTo::<DeserializeAsWrap<Idx, IdxAs>> { end } =
475 Deserialize::deserialize(deserializer)?;
476
477 Ok(RangeTo {
478 end: end.into_inner(),
479 })
480 }
481}
482
483#[cfg(feature = "alloc")]
488macro_rules! seq_impl {
489 (
490 $ty:ident < T $(: $tbound1:ident $(+ $tbound2:ident)*)? $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)* )* >,
491 $with_capacity:expr,
492 $append:ident
493 ) => {
494 impl<'de, T, U $(, $typaram)*> DeserializeAs<'de, $ty<T $(, $typaram)*>> for $ty<U $(, $typaram)*>
495 where
496 U: DeserializeAs<'de, T>,
497 $(T: $tbound1 $(+ $tbound2)*,)?
498 $($typaram: $bound1 $(+ $bound2)*),*
499 {
500 fn deserialize_as<D>(deserializer: D) -> Result<$ty<T $(, $typaram)*>, D::Error>
501 where
502 D: Deserializer<'de>,
503 {
504 struct SeqVisitor<T, U $(, $typaram)*> {
505 marker: PhantomData<(T, U $(, $typaram)*)>,
506 }
507
508 impl<'de, T, U $(, $typaram)*> Visitor<'de> for SeqVisitor<T, U $(, $typaram)*>
509 where
510 U: DeserializeAs<'de, T>,
511 $(T: $tbound1 $(+ $tbound2)*,)?
512 $($typaram: $bound1 $(+ $bound2)*),*
513 {
514 type Value = $ty<T $(, $typaram)*>;
515
516 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
517 formatter.write_str("a sequence")
518 }
519
520 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
521 where
522 A: SeqAccess<'de>,
523 {
524 #[allow(clippy::redundant_closure_call)]
525 let mut values = ($with_capacity)(utils::size_hint_cautious::<T>(seq.size_hint()));
526
527 while let Some(value) = seq
528 .next_element()?
529 .map(|v: DeserializeAsWrap<T, U>| v.into_inner())
530 {
531 values.$append(value);
532 }
533
534 Ok(values.into())
535 }
536 }
537
538 let visitor = SeqVisitor::<T, U $(, $typaram)*> {
539 marker: PhantomData,
540 };
541 deserializer.deserialize_seq(visitor)
542 }
543 }
544 };
545}
546foreach_seq!(seq_impl);
547
548#[cfg(feature = "alloc")]
549macro_rules! map_impl {
550 (
551 $ty:ident < K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >,
552 $with_capacity:expr
553 ) => {
554 impl<'de, K, V, KU, VU $(, $typaram)*> DeserializeAs<'de, $ty<K, V $(, $typaram)*>> for $ty<KU, VU $(, $typaram)*>
555 where
556 KU: DeserializeAs<'de, K>,
557 VU: DeserializeAs<'de, V>,
558 $(K: $kbound1 $(+ $kbound2)*,)*
559 $($typaram: $bound1 $(+ $bound2)*),*
560 {
561 fn deserialize_as<D>(deserializer: D) -> Result<$ty<K, V $(, $typaram)*>, D::Error>
562 where
563 D: Deserializer<'de>,
564 {
565 struct MapVisitor<K, V, KU, VU $(, $typaram)*>(PhantomData<(K, V, KU, VU $(, $typaram)*)>);
566
567 impl<'de, K, V, KU, VU $(, $typaram)*> Visitor<'de> for MapVisitor<K, V, KU, VU $(, $typaram)*>
568 where
569 KU: DeserializeAs<'de, K>,
570 VU: DeserializeAs<'de, V>,
571 $(K: $kbound1 $(+ $kbound2)*,)*
572 $($typaram: $bound1 $(+ $bound2)*),*
573 {
574 type Value = $ty<K, V $(, $typaram)*>;
575
576 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
577 formatter.write_str("a map")
578 }
579
580 #[inline]
581 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
582 where
583 A: MapAccess<'de>,
584 {
585 #[allow(clippy::redundant_closure_call)]
586 let mut values = ($with_capacity)(utils::size_hint_cautious::<(K, V)>(map.size_hint()));
587
588 while let Some((key, value)) = (map.next_entry())?.map(|(k, v): (DeserializeAsWrap::<K, KU>, DeserializeAsWrap::<V, VU>)| (k.into_inner(), v.into_inner())) {
589 values.insert(key, value);
590 }
591
592 Ok(values)
593 }
594 }
595
596 let visitor = MapVisitor::<K, V, KU, VU $(, $typaram)*> (PhantomData);
597 deserializer.deserialize_map(visitor)
598 }
599 }
600 }
601}
602foreach_map!(map_impl);
603
604macro_rules! tuple_impl {
605 ($len:literal $($n:tt $t:ident $tas:ident)+) => {
606 impl<'de, $($t, $tas,)+> DeserializeAs<'de, ($($t,)+)> for ($($tas,)+)
607 where
608 $($tas: DeserializeAs<'de, $t>,)+
609 {
610 fn deserialize_as<D>(deserializer: D) -> Result<($($t,)+), D::Error>
611 where
612 D: Deserializer<'de>,
613 {
614 struct TupleVisitor<$($t,)+>(PhantomData<($($t,)+)>);
615
616 impl<'de, $($t, $tas,)+> Visitor<'de>
617 for TupleVisitor<$(DeserializeAsWrap<$t, $tas>,)+>
618 where
619 $($tas: DeserializeAs<'de, $t>,)+
620 {
621 type Value = ($($t,)+);
622
623 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
624 formatter.write_str(concat!("a tuple of size ", $len))
625 }
626
627 #[allow(non_snake_case)]
628 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
629 where
630 A: SeqAccess<'de>,
631 {
632 $(
633 let $t: DeserializeAsWrap<$t, $tas> = match seq.next_element()? {
634 Some(value) => value,
635 None => return Err(DeError::invalid_length($n, &self)),
636 };
637 )+
638
639 Ok(($($t.into_inner(),)+))
640 }
641 }
642
643 deserializer.deserialize_tuple(
644 $len,
645 TupleVisitor::<$(DeserializeAsWrap<$t, $tas>,)+>(PhantomData),
646 )
647 }
648 }
649 };
650}
651
652tuple_impl!(1 0 T0 As0);
653tuple_impl!(2 0 T0 As0 1 T1 As1);
654tuple_impl!(3 0 T0 As0 1 T1 As1 2 T2 As2);
655tuple_impl!(4 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3);
656tuple_impl!(5 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3 4 T4 As4);
657tuple_impl!(6 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3 4 T4 As4 5 T5 As5);
658tuple_impl!(7 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3 4 T4 As4 5 T5 As5 6 T6 As6);
659tuple_impl!(8 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3 4 T4 As4 5 T5 As5 6 T6 As6 7 T7 As7);
660tuple_impl!(9 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3 4 T4 As4 5 T5 As5 6 T6 As6 7 T7 As7 8 T8 As8);
661tuple_impl!(10 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3 4 T4 As4 5 T5 As5 6 T6 As6 7 T7 As7 8 T8 As8 9 T9 As9);
662tuple_impl!(11 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3 4 T4 As4 5 T5 As5 6 T6 As6 7 T7 As7 8 T8 As8 9 T9 As9 10 T10 As10);
663tuple_impl!(12 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3 4 T4 As4 5 T5 As5 6 T6 As6 7 T7 As7 8 T8 As8 9 T9 As9 10 T10 As10 11 T11 As11);
664tuple_impl!(13 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3 4 T4 As4 5 T5 As5 6 T6 As6 7 T7 As7 8 T8 As8 9 T9 As9 10 T10 As10 11 T11 As11 12 T12 As12);
665tuple_impl!(14 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3 4 T4 As4 5 T5 As5 6 T6 As6 7 T7 As7 8 T8 As8 9 T9 As9 10 T10 As10 11 T11 As11 12 T12 As12 13 T13 As13);
666tuple_impl!(15 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3 4 T4 As4 5 T5 As5 6 T6 As6 7 T7 As7 8 T8 As8 9 T9 As9 10 T10 As10 11 T11 As11 12 T12 As12 13 T13 As13 14 T14 As14);
667tuple_impl!(16 0 T0 As0 1 T1 As1 2 T2 As2 3 T3 As3 4 T4 As4 5 T5 As5 6 T6 As6 7 T7 As7 8 T8 As8 9 T9 As9 10 T10 As10 11 T11 As11 12 T12 As12 13 T13 As13 14 T14 As14 15 T15 As15);
668
669#[cfg(feature = "alloc")]
670macro_rules! map_as_tuple_seq_intern {
671 (
672 $tyorig:ident < K $(: $kbound1:ident $(+ $kbound2:ident)*)?, V $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >,
673 $with_capacity:expr,
674 $ty:ident <(KAs, VAs)>
675 ) => {
676 impl<'de, K, KAs, V, VAs $(, $typaram)*> DeserializeAs<'de, $tyorig<K, V $(, $typaram)*>> for $ty<(KAs, VAs)>
677 where
678 KAs: DeserializeAs<'de, K>,
679 VAs: DeserializeAs<'de, V>,
680 $(K: $kbound1 $(+ $kbound2)*,)?
681 $($typaram: $bound1 $(+ $bound2)*,)*
682 {
683 fn deserialize_as<D>(deserializer: D) -> Result<$tyorig<K, V $(, $typaram)*>, D::Error>
684 where
685 D: Deserializer<'de>,
686 {
687 struct SeqVisitor<K, KAs, V, VAs $(, $typaram)*> {
688 marker: PhantomData<(K, KAs, V, VAs $(, $typaram)*)>,
689 }
690
691 impl<'de, K, KAs, V, VAs $(, $typaram)*> Visitor<'de> for SeqVisitor<K, KAs, V, VAs $(, $typaram)*>
692 where
693 KAs: DeserializeAs<'de, K>,
694 VAs: DeserializeAs<'de, V>,
695 $(K: $kbound1 $(+ $kbound2)*,)?
696 $($typaram: $bound1 $(+ $bound2)*,)*
697 {
698 type Value = $tyorig<K, V $(, $typaram)*>;
699
700 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
701 formatter.write_str("a sequence")
702 }
703
704 #[inline]
705 fn visit_seq<A>(self, access: A) -> Result<Self::Value, A::Error>
706 where
707 A: SeqAccess<'de>,
708 {
709 let iter = utils::SeqIter::new(access);
710 iter.map(|res| {
711 res.map(
712 |(k, v): (DeserializeAsWrap<K, KAs>, DeserializeAsWrap<V, VAs>)| {
713 (k.into_inner(), v.into_inner())
714 },
715 )
716 })
717 .collect()
718 }
719 }
720
721 let visitor = SeqVisitor::<K, KAs, V, VAs $(, $typaram)*> {
722 marker: PhantomData,
723 };
724 deserializer.deserialize_seq(visitor)
725 }
726 }
727 };
728}
729#[cfg(feature = "alloc")]
730macro_rules! map_as_tuple_seq {
731 (
732 $tyorig:ident < K $(: $kbound1:ident $(+ $kbound2:ident)*)?, V $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >,
733 $with_capacity:expr
734 ) => {
735 map_as_tuple_seq_intern!($tyorig < K $(: $kbound1 $(+ $kbound2)*)? , V $(, $typaram : $bound1 $(+ $bound2)*)* >, $with_capacity, Seq<(KAs, VAs)>);
736 #[cfg(feature = "alloc")]
737 map_as_tuple_seq_intern!($tyorig < K $(: $kbound1 $(+ $kbound2)*)? , V $(, $typaram : $bound1 $(+ $bound2)*)* >, $with_capacity, Vec<(KAs, VAs)>);
738 }
739}
740foreach_map!(map_as_tuple_seq);
741
742#[cfg(feature = "alloc")]
743macro_rules! tuple_seq_as_map_impl_intern {
744 (
745 $tyorig:ident < (K, V) $(: $($bound:ident $(+)?)+)? $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)* )* >,
746 $with_capacity:expr,
747 $append:ident,
748 $ty:ident <KAs, VAs>
749 ) => {
750 #[allow(clippy::implicit_hasher)]
751 impl<'de, K, KAs, V, VAs $(, $typaram)*> DeserializeAs<'de, $tyorig < (K, V) $(, $typaram)* >> for $ty<KAs, VAs>
752 where
753 KAs: DeserializeAs<'de, K>,
754 VAs: DeserializeAs<'de, V>,
755 (K, V): $($($bound +)*)?,
756 $($typaram: $bound1 $(+ $bound2)*,)*
757 {
758 fn deserialize_as<D>(deserializer: D) -> Result<$tyorig < (K, V) $(, $typaram)* >, D::Error>
759 where
760 D: Deserializer<'de>,
761 {
762 struct MapVisitor<K, KAs, V, VAs $(, $typaram)*> {
763 marker: PhantomData<(K, KAs, V, VAs $(, $typaram)*)>,
764 }
765
766 impl<'de, K, KAs, V, VAs $(, $typaram)*> Visitor<'de> for MapVisitor<K, KAs, V, VAs $(, $typaram)*>
767 where
768 KAs: DeserializeAs<'de, K>,
769 VAs: DeserializeAs<'de, V>,
770 (K, V): $($($bound +)*)?,
771 $($typaram: $bound1 $(+ $bound2)*,)*
772 {
773 type Value = $tyorig < (K, V) $(, $typaram)* >;
774
775 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
776 formatter.write_str("a map")
777 }
778
779 #[inline]
780 fn visit_map<A>(self, access: A) -> Result<Self::Value, A::Error>
781 where
782 A: MapAccess<'de>,
783 {
784 let iter = utils::MapIter::new(access);
785 iter.map(|res| {
786 res.map(
787 |(k, v): (DeserializeAsWrap<K, KAs>, DeserializeAsWrap<V, VAs>)| {
788 (k.into_inner(), v.into_inner())
789 },
790 )
791 })
792 .collect()
793 }
794 }
795
796 let visitor = MapVisitor::<K, KAs, V, VAs $(, $typaram)*> {
797 marker: PhantomData,
798 };
799 deserializer.deserialize_map(visitor)
800 }
801 }
802 }
803}
804#[cfg(feature = "alloc")]
805macro_rules! tuple_seq_as_map_impl {
806 (
807 $tyorig:ident < T $(: $($bound:ident $(+)?)+)? $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)* )* >,
808 $with_capacity:expr,
809 $append:ident
810 ) => {
811 tuple_seq_as_map_impl_intern!($tyorig < (K, V) $(: $($bound +)+)? $(, $typaram: $bound1 $(+ $bound2)*)*>, $with_capacity, $append, Map<KAs, VAs>);
812 #[cfg(feature = "alloc")]
813 tuple_seq_as_map_impl_intern!($tyorig < (K, V) $(: $($bound +)+)? $(, $typaram: $bound1 $(+ $bound2)*)*>, $with_capacity, $append, BTreeMap<KAs, VAs>);
814 #[cfg(feature = "std")]
815 tuple_seq_as_map_impl_intern!($tyorig < (K, V) $(: $($bound +)+)? $(, $typaram: $bound1 $(+ $bound2)*)*>, $with_capacity, $append, HashMap<KAs, VAs>);
816 }
817}
818foreach_seq!(tuple_seq_as_map_impl);
819
820#[cfg(feature = "alloc")]
822macro_rules! tuple_seq_as_map_option_impl {
823 ($ty:ident) => {
824 #[allow(clippy::implicit_hasher)]
825 impl<'de, K, KAs, V, VAs> DeserializeAs<'de, Option<(K, V)>> for $ty<KAs, VAs>
826 where
827 KAs: DeserializeAs<'de, K>,
828 VAs: DeserializeAs<'de, V>,
829 {
830 fn deserialize_as<D>(deserializer: D) -> Result<Option<(K, V)>, D::Error>
831 where
832 D: Deserializer<'de>,
833 {
834 struct MapVisitor<K, KAs, V, VAs> {
835 marker: PhantomData<(K, KAs, V, VAs)>,
836 }
837
838 impl<'de, K, KAs, V, VAs> Visitor<'de> for MapVisitor<K, KAs, V, VAs>
839 where
840 KAs: DeserializeAs<'de, K>,
841 VAs: DeserializeAs<'de, V>,
842 {
843 type Value = Option<(K, V)>;
844
845 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
846 formatter.write_str("a map of size 1")
847 }
848
849 #[inline]
850 fn visit_map<A>(self, access: A) -> Result<Self::Value, A::Error>
851 where
852 A: MapAccess<'de>,
853 {
854 let iter = utils::MapIter::new(access);
855 iter.map(|res| {
856 res.map(
857 |(k, v): (DeserializeAsWrap<K, KAs>, DeserializeAsWrap<V, VAs>)| {
858 (k.into_inner(), v.into_inner())
859 },
860 )
861 })
862 .next()
863 .transpose()
864 }
865 }
866
867 let visitor = MapVisitor::<K, KAs, V, VAs> {
868 marker: PhantomData,
869 };
870 deserializer.deserialize_map(visitor)
871 }
872 }
873 };
874}
875#[cfg(feature = "alloc")]
876tuple_seq_as_map_option_impl!(BTreeMap);
877#[cfg(feature = "std")]
878tuple_seq_as_map_option_impl!(HashMap);
879
880macro_rules! tuple_seq_as_map_arr {
881 ($ty:ident <KAs, VAs>) => {
882 #[allow(clippy::implicit_hasher)]
883 impl<'de, K, KAs, V, VAs, const N: usize> DeserializeAs<'de, [(K, V); N]> for $ty<KAs, VAs>
884 where
885 KAs: DeserializeAs<'de, K>,
886 VAs: DeserializeAs<'de, V>,
887 {
888 fn deserialize_as<D>(deserializer: D) -> Result<[(K, V); N], D::Error>
889 where
890 D: Deserializer<'de>,
891 {
892 struct MapVisitor<K, KAs, V, VAs, const M: usize> {
893 marker: PhantomData<(K, KAs, V, VAs)>,
894 }
895
896 impl<'de, K, KAs, V, VAs, const M: usize> Visitor<'de> for MapVisitor<K, KAs, V, VAs, M>
897 where
898 KAs: DeserializeAs<'de, K>,
899 VAs: DeserializeAs<'de, V>,
900 {
901 type Value = [(K, V); M];
902
903 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
904 formatter.write_fmt(format_args!("a map of length {}", M))
905 }
906
907 fn visit_map<A>(self, access: A) -> Result<Self::Value, A::Error>
908 where
909 A: MapAccess<'de>,
910 {
911 utils::array_from_iterator(utils::MapIter::new(access).map(
912 |res: Result<(DeserializeAsWrap<K, KAs>, DeserializeAsWrap<V, VAs>), A::Error>| {
913 res.map(|(k, v)| (k.into_inner(), v.into_inner()))
914 }
915 ), &self)
916 }
917 }
918
919 let visitor = MapVisitor::<K, KAs, V, VAs, N> {
920 marker: PhantomData,
921 };
922 deserializer.deserialize_map(visitor)
923 }
924 }
925 }
926}
927tuple_seq_as_map_arr!(Map<KAs, VAs>);
928#[cfg(feature = "alloc")]
929tuple_seq_as_map_arr!(BTreeMap<KAs, VAs>);
930#[cfg(feature = "std")]
931tuple_seq_as_map_arr!(HashMap<KAs, VAs>);
932
933impl<'de, T: Deserialize<'de>> DeserializeAs<'de, T> for Same {
938 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
939 where
940 D: Deserializer<'de>,
941 {
942 T::deserialize(deserializer)
943 }
944}
945
946impl<'de, T> DeserializeAs<'de, T> for DisplayFromStr
947where
948 T: FromStr,
949 T::Err: Display,
950{
951 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
952 where
953 D: Deserializer<'de>,
954 {
955 struct Helper<S>(PhantomData<S>);
956 impl<S> Visitor<'_> for Helper<S>
957 where
958 S: FromStr,
959 <S as FromStr>::Err: Display,
960 {
961 type Value = S;
962
963 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
964 formatter.write_str("a string")
965 }
966
967 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
968 where
969 E: DeError,
970 {
971 value.parse::<Self::Value>().map_err(DeError::custom)
972 }
973 }
974
975 deserializer.deserialize_str(Helper(PhantomData))
976 }
977}
978
979impl<'de, T, H, F> DeserializeAs<'de, T> for IfIsHumanReadable<H, F>
980where
981 H: DeserializeAs<'de, T>,
982 F: DeserializeAs<'de, T>,
983{
984 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
985 where
986 D: Deserializer<'de>,
987 {
988 if deserializer.is_human_readable() {
989 H::deserialize_as(deserializer)
990 } else {
991 F::deserialize_as(deserializer)
992 }
993 }
994}
995
996impl<'de, Str> DeserializeAs<'de, Option<Str>> for NoneAsEmptyString
997where
998 Str: FromStr,
999 Str::Err: Display,
1000{
1001 fn deserialize_as<D>(deserializer: D) -> Result<Option<Str>, D::Error>
1002 where
1003 D: Deserializer<'de>,
1004 {
1005 struct OptionStringEmptyNone<S>(PhantomData<S>);
1006 impl<S> Visitor<'_> for OptionStringEmptyNone<S>
1007 where
1008 S: FromStr,
1009 S::Err: Display,
1010 {
1011 type Value = Option<S>;
1012
1013 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1014 formatter.write_str("a string")
1015 }
1016
1017 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1018 where
1019 E: DeError,
1020 {
1021 match value {
1022 "" => Ok(None),
1023 v => S::from_str(v).map(Some).map_err(DeError::custom),
1024 }
1025 }
1026
1027 fn visit_unit<E>(self) -> Result<Self::Value, E>
1029 where
1030 E: DeError,
1031 {
1032 Ok(None)
1033 }
1034 }
1035
1036 deserializer.deserialize_any(OptionStringEmptyNone(PhantomData))
1037 }
1038}
1039
1040#[cfg(feature = "alloc")]
1041impl<'de, T, TAs> DeserializeAs<'de, T> for DefaultOnError<TAs>
1042where
1043 TAs: DeserializeAs<'de, T>,
1044 T: Default,
1045{
1046 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1047 where
1048 D: Deserializer<'de>,
1049 {
1050 let is_hr = deserializer.is_human_readable();
1051 let content: content::de::Content<'de> = match Deserialize::deserialize(deserializer) {
1052 Ok(content) => content,
1053 Err(_) => return Ok(Default::default()),
1054 };
1055
1056 Ok(
1057 match <DeserializeAsWrap<T, TAs>>::deserialize(content::de::ContentDeserializer::<
1058 D::Error,
1059 >::new(content, is_hr))
1060 {
1061 Ok(elem) => elem.into_inner(),
1062 Err(_) => Default::default(),
1063 },
1064 )
1065 }
1066}
1067
1068#[cfg(feature = "alloc")]
1069impl<'de> DeserializeAs<'de, Vec<u8>> for BytesOrString {
1070 fn deserialize_as<D>(deserializer: D) -> Result<Vec<u8>, D::Error>
1071 where
1072 D: Deserializer<'de>,
1073 {
1074 struct BytesOrStringVisitor;
1075 impl<'de> Visitor<'de> for BytesOrStringVisitor {
1076 type Value = Vec<u8>;
1077
1078 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1079 formatter.write_str("a list of bytes or a string")
1080 }
1081
1082 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> {
1083 Ok(v.to_vec())
1084 }
1085
1086 #[cfg(feature = "alloc")]
1087 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> {
1088 Ok(v)
1089 }
1090
1091 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> {
1092 Ok(v.as_bytes().to_vec())
1093 }
1094
1095 #[cfg(feature = "alloc")]
1096 fn visit_string<E>(self, v: String) -> Result<Self::Value, E> {
1097 Ok(v.into_bytes())
1098 }
1099
1100 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1101 where
1102 A: SeqAccess<'de>,
1103 {
1104 utils::SeqIter::new(seq).collect()
1105 }
1106 }
1107 deserializer.deserialize_any(BytesOrStringVisitor)
1108 }
1109}
1110
1111impl<'de, SEPARATOR, I, T> DeserializeAs<'de, I> for StringWithSeparator<SEPARATOR, T>
1112where
1113 SEPARATOR: Separator,
1114 I: FromIterator<T>,
1115 T: FromStr,
1116 T::Err: Display,
1117{
1118 fn deserialize_as<D>(deserializer: D) -> Result<I, D::Error>
1119 where
1120 D: Deserializer<'de>,
1121 {
1122 struct Helper<SEPARATOR, I, T>(PhantomData<(SEPARATOR, I, T)>);
1123
1124 impl<SEPARATOR, I, T> Visitor<'_> for Helper<SEPARATOR, I, T>
1125 where
1126 SEPARATOR: Separator,
1127 I: FromIterator<T>,
1128 T: FromStr,
1129 T::Err: Display,
1130 {
1131 type Value = I;
1132
1133 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1134 formatter.write_str("a string")
1135 }
1136
1137 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1138 where
1139 E: DeError,
1140 {
1141 if value.is_empty() {
1142 Ok(None.into_iter().collect())
1143 } else {
1144 value
1145 .split(SEPARATOR::separator())
1146 .map(FromStr::from_str)
1147 .collect::<Result<_, _>>()
1148 .map_err(DeError::custom)
1149 }
1150 }
1151 }
1152
1153 deserializer.deserialize_str(Helper::<SEPARATOR, I, T>(PhantomData))
1154 }
1155}
1156
1157macro_rules! use_signed_duration {
1158 (
1159 $main_trait:ident $internal_trait:ident =>
1160 {
1161 $ty:ty; $converter:ident =>
1162 $({
1163 $format:ty, $strictness:ty =>
1164 $($tbound:ident: $bound:ident $(,)?)*
1165 })*
1166 }
1167 ) => {
1168 $(
1169 impl<'de, $($tbound,)*> DeserializeAs<'de, $ty> for $main_trait<$format, $strictness>
1170 where
1171 $($tbound: $bound,)*
1172 {
1173 fn deserialize_as<D>(deserializer: D) -> Result<$ty, D::Error>
1174 where
1175 D: Deserializer<'de>,
1176 {
1177 let dur: DurationSigned = $internal_trait::<$format, $strictness>::deserialize_as(deserializer)?;
1178 dur.$converter::<D>()
1179 }
1180 }
1181 )*
1182 };
1183 (
1184 $( $main_trait:ident $internal_trait:ident, )+ => $rest:tt
1185 ) => {
1186 $( use_signed_duration!($main_trait $internal_trait => $rest); )+
1187 };
1188}
1189
1190use_signed_duration!(
1191 DurationSeconds DurationSeconds,
1192 DurationMilliSeconds DurationMilliSeconds,
1193 DurationMicroSeconds DurationMicroSeconds,
1194 DurationNanoSeconds DurationNanoSeconds,
1195 => {
1196 Duration; to_std_duration =>
1197 {u64, Strict =>}
1198 {FORMAT, Flexible => FORMAT: Format}
1199 }
1200);
1201#[cfg(feature = "alloc")]
1202use_signed_duration!(
1203 DurationSeconds DurationSeconds,
1204 DurationMilliSeconds DurationMilliSeconds,
1205 DurationMicroSeconds DurationMicroSeconds,
1206 DurationNanoSeconds DurationNanoSeconds,
1207 => {
1208 Duration; to_std_duration =>
1209 {String, Strict =>}
1210 }
1211);
1212#[cfg(feature = "std")]
1213use_signed_duration!(
1214 DurationSeconds DurationSeconds,
1215 DurationMilliSeconds DurationMilliSeconds,
1216 DurationMicroSeconds DurationMicroSeconds,
1217 DurationNanoSeconds DurationNanoSeconds,
1218 => {
1219 Duration; to_std_duration =>
1220 {f64, Strict =>}
1222 }
1223);
1224use_signed_duration!(
1225 DurationSecondsWithFrac DurationSecondsWithFrac,
1226 DurationMilliSecondsWithFrac DurationMilliSecondsWithFrac,
1227 DurationMicroSecondsWithFrac DurationMicroSecondsWithFrac,
1228 DurationNanoSecondsWithFrac DurationNanoSecondsWithFrac,
1229 => {
1230 Duration; to_std_duration =>
1231 {f64, Strict =>}
1232 {FORMAT, Flexible => FORMAT: Format}
1233 }
1234);
1235#[cfg(feature = "alloc")]
1236use_signed_duration!(
1237 DurationSecondsWithFrac DurationSecondsWithFrac,
1238 DurationMilliSecondsWithFrac DurationMilliSecondsWithFrac,
1239 DurationMicroSecondsWithFrac DurationMicroSecondsWithFrac,
1240 DurationNanoSecondsWithFrac DurationNanoSecondsWithFrac,
1241 => {
1242 Duration; to_std_duration =>
1243 {String, Strict =>}
1244 }
1245);
1246
1247#[cfg(feature = "std")]
1248use_signed_duration!(
1249 TimestampSeconds DurationSeconds,
1250 TimestampMilliSeconds DurationMilliSeconds,
1251 TimestampMicroSeconds DurationMicroSeconds,
1252 TimestampNanoSeconds DurationNanoSeconds,
1253 => {
1254 SystemTime; to_system_time =>
1255 {i64, Strict =>}
1256 {f64, Strict =>}
1257 {String, Strict =>}
1258 {FORMAT, Flexible => FORMAT: Format}
1259 }
1260);
1261#[cfg(feature = "std")]
1262use_signed_duration!(
1263 TimestampSecondsWithFrac DurationSecondsWithFrac,
1264 TimestampMilliSecondsWithFrac DurationMilliSecondsWithFrac,
1265 TimestampMicroSecondsWithFrac DurationMicroSecondsWithFrac,
1266 TimestampNanoSecondsWithFrac DurationNanoSecondsWithFrac,
1267 => {
1268 SystemTime; to_system_time =>
1269 {f64, Strict =>}
1270 {String, Strict =>}
1271 {FORMAT, Flexible => FORMAT: Format}
1272 }
1273);
1274
1275impl<'de, T, U> DeserializeAs<'de, T> for DefaultOnNull<U>
1276where
1277 U: DeserializeAs<'de, T>,
1278 T: Default,
1279{
1280 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1281 where
1282 D: Deserializer<'de>,
1283 {
1284 Ok(Option::<U>::deserialize_as(deserializer)?.unwrap_or_default())
1285 }
1286}
1287
1288impl<'de> DeserializeAs<'de, &'de [u8]> for Bytes {
1289 fn deserialize_as<D>(deserializer: D) -> Result<&'de [u8], D::Error>
1290 where
1291 D: Deserializer<'de>,
1292 {
1293 <&'de [u8]>::deserialize(deserializer)
1294 }
1295}
1296
1297#[cfg(feature = "alloc")]
1307impl<'de> DeserializeAs<'de, Vec<u8>> for Bytes {
1308 fn deserialize_as<D>(deserializer: D) -> Result<Vec<u8>, D::Error>
1309 where
1310 D: Deserializer<'de>,
1311 {
1312 struct VecVisitor;
1313
1314 impl<'de> Visitor<'de> for VecVisitor {
1315 type Value = Vec<u8>;
1316
1317 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1318 formatter.write_str("a byte array")
1319 }
1320
1321 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1322 where
1323 A: SeqAccess<'de>,
1324 {
1325 utils::SeqIter::new(seq).collect::<Result<_, _>>()
1326 }
1327
1328 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1329 where
1330 E: DeError,
1331 {
1332 Ok(v.to_vec())
1333 }
1334
1335 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1336 where
1337 E: DeError,
1338 {
1339 Ok(v)
1340 }
1341
1342 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1343 where
1344 E: DeError,
1345 {
1346 Ok(v.as_bytes().to_vec())
1347 }
1348
1349 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1350 where
1351 E: DeError,
1352 {
1353 Ok(v.into_bytes())
1354 }
1355 }
1356
1357 deserializer.deserialize_byte_buf(VecVisitor)
1358 }
1359}
1360
1361#[cfg(feature = "alloc")]
1362impl<'de> DeserializeAs<'de, Box<[u8]>> for Bytes {
1363 fn deserialize_as<D>(deserializer: D) -> Result<Box<[u8]>, D::Error>
1364 where
1365 D: Deserializer<'de>,
1366 {
1367 <Bytes as DeserializeAs<'de, Vec<u8>>>::deserialize_as(deserializer)
1368 .map(Vec::into_boxed_slice)
1369 }
1370}
1371
1372#[cfg(feature = "alloc")]
1384impl<'de> DeserializeAs<'de, Cow<'de, [u8]>> for Bytes {
1385 fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8]>, D::Error>
1386 where
1387 D: Deserializer<'de>,
1388 {
1389 struct CowVisitor;
1390
1391 impl<'de> Visitor<'de> for CowVisitor {
1392 type Value = Cow<'de, [u8]>;
1393
1394 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1395 formatter.write_str("a byte array")
1396 }
1397
1398 fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
1399 where
1400 E: DeError,
1401 {
1402 Ok(Cow::Borrowed(v))
1403 }
1404
1405 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
1406 where
1407 E: DeError,
1408 {
1409 Ok(Cow::Borrowed(v.as_bytes()))
1410 }
1411
1412 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1413 where
1414 E: DeError,
1415 {
1416 Ok(Cow::Owned(v.to_vec()))
1417 }
1418
1419 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1420 where
1421 E: DeError,
1422 {
1423 Ok(Cow::Owned(v.as_bytes().to_vec()))
1424 }
1425
1426 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1427 where
1428 E: DeError,
1429 {
1430 Ok(Cow::Owned(v))
1431 }
1432
1433 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1434 where
1435 E: DeError,
1436 {
1437 Ok(Cow::Owned(v.into_bytes()))
1438 }
1439
1440 fn visit_seq<V>(self, seq: V) -> Result<Self::Value, V::Error>
1441 where
1442 V: SeqAccess<'de>,
1443 {
1444 Ok(Cow::Owned(
1445 utils::SeqIter::new(seq).collect::<Result<_, _>>()?,
1446 ))
1447 }
1448 }
1449
1450 deserializer.deserialize_bytes(CowVisitor)
1451 }
1452}
1453
1454impl<'de, const N: usize> DeserializeAs<'de, [u8; N]> for Bytes {
1455 fn deserialize_as<D>(deserializer: D) -> Result<[u8; N], D::Error>
1456 where
1457 D: Deserializer<'de>,
1458 {
1459 struct ArrayVisitor<const M: usize>;
1460
1461 impl<'de, const M: usize> Visitor<'de> for ArrayVisitor<M> {
1462 type Value = [u8; M];
1463
1464 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1465 formatter.write_fmt(format_args!("an byte array of size {M}"))
1466 }
1467
1468 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1469 where
1470 A: SeqAccess<'de>,
1471 {
1472 utils::array_from_iterator(utils::SeqIter::new(seq), &self)
1473 }
1474
1475 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1476 where
1477 E: DeError,
1478 {
1479 v.try_into()
1480 .map_err(|_| DeError::invalid_length(v.len(), &self))
1481 }
1482
1483 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1484 where
1485 E: DeError,
1486 {
1487 v.as_bytes()
1488 .try_into()
1489 .map_err(|_| DeError::invalid_length(v.len(), &self))
1490 }
1491 }
1492
1493 deserializer.deserialize_bytes(ArrayVisitor::<N>)
1494 }
1495}
1496
1497impl<'de, const N: usize> DeserializeAs<'de, &'de [u8; N]> for Bytes {
1498 fn deserialize_as<D>(deserializer: D) -> Result<&'de [u8; N], D::Error>
1499 where
1500 D: Deserializer<'de>,
1501 {
1502 struct ArrayVisitor<const M: usize>;
1503
1504 impl<'de, const M: usize> Visitor<'de> for ArrayVisitor<M> {
1505 type Value = &'de [u8; M];
1506
1507 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1508 formatter.write_fmt(format_args!("a borrowed byte array of size {M}"))
1509 }
1510
1511 fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
1512 where
1513 E: DeError,
1514 {
1515 v.try_into()
1516 .map_err(|_| DeError::invalid_length(v.len(), &self))
1517 }
1518
1519 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
1520 where
1521 E: DeError,
1522 {
1523 v.as_bytes()
1524 .try_into()
1525 .map_err(|_| DeError::invalid_length(v.len(), &self))
1526 }
1527 }
1528
1529 deserializer.deserialize_bytes(ArrayVisitor::<N>)
1530 }
1531}
1532
1533#[cfg(feature = "alloc")]
1534impl<'de, const N: usize> DeserializeAs<'de, Cow<'de, [u8; N]>> for Bytes {
1535 fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8; N]>, D::Error>
1536 where
1537 D: Deserializer<'de>,
1538 {
1539 struct CowVisitor<const M: usize>;
1540
1541 impl<'de, const M: usize> Visitor<'de> for CowVisitor<M> {
1542 type Value = Cow<'de, [u8; M]>;
1543
1544 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1545 formatter.write_str("a byte array")
1546 }
1547
1548 fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
1549 where
1550 E: DeError,
1551 {
1552 Ok(Cow::Borrowed(
1553 v.try_into()
1554 .map_err(|_| DeError::invalid_length(v.len(), &self))?,
1555 ))
1556 }
1557
1558 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
1559 where
1560 E: DeError,
1561 {
1562 Ok(Cow::Borrowed(
1563 v.as_bytes()
1564 .try_into()
1565 .map_err(|_| DeError::invalid_length(v.len(), &self))?,
1566 ))
1567 }
1568
1569 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1570 where
1571 E: DeError,
1572 {
1573 Ok(Cow::Owned(
1574 v.to_vec()
1575 .try_into()
1576 .map_err(|_| DeError::invalid_length(v.len(), &self))?,
1577 ))
1578 }
1579
1580 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1581 where
1582 E: DeError,
1583 {
1584 Ok(Cow::Owned(
1585 v.as_bytes()
1586 .to_vec()
1587 .try_into()
1588 .map_err(|_| DeError::invalid_length(v.len(), &self))?,
1589 ))
1590 }
1591
1592 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1593 where
1594 E: DeError,
1595 {
1596 let len = v.len();
1597 Ok(Cow::Owned(
1598 v.try_into()
1599 .map_err(|_| DeError::invalid_length(len, &self))?,
1600 ))
1601 }
1602
1603 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1604 where
1605 E: DeError,
1606 {
1607 let len = v.len();
1608 Ok(Cow::Owned(
1609 v.into_bytes()
1610 .try_into()
1611 .map_err(|_| DeError::invalid_length(len, &self))?,
1612 ))
1613 }
1614
1615 fn visit_seq<V>(self, seq: V) -> Result<Self::Value, V::Error>
1616 where
1617 V: SeqAccess<'de>,
1618 {
1619 Ok(Cow::Owned(utils::array_from_iterator(
1620 utils::SeqIter::new(seq),
1621 &self,
1622 )?))
1623 }
1624 }
1625
1626 deserializer.deserialize_bytes(CowVisitor)
1627 }
1628}
1629
1630#[cfg(feature = "alloc")]
1631impl<'de, const N: usize> DeserializeAs<'de, Box<[u8; N]>> for Bytes {
1632 fn deserialize_as<D>(deserializer: D) -> Result<Box<[u8; N]>, D::Error>
1633 where
1634 D: Deserializer<'de>,
1635 {
1636 Bytes::deserialize_as(deserializer).map(Box::new)
1637 }
1638}
1639
1640#[cfg(feature = "alloc")]
1641impl<'de, T, TAs, FORMAT> DeserializeAs<'de, Vec<T>> for OneOrMany<TAs, FORMAT>
1642where
1643 TAs: DeserializeAs<'de, T>,
1644 FORMAT: Format,
1645{
1646 fn deserialize_as<D>(deserializer: D) -> Result<Vec<T>, D::Error>
1647 where
1648 D: Deserializer<'de>,
1649 {
1650 let is_hr = deserializer.is_human_readable();
1651 let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1652
1653 let one_err: D::Error = match <DeserializeAsWrap<T, TAs>>::deserialize(
1654 content::de::ContentRefDeserializer::new(&content, is_hr),
1655 ) {
1656 Ok(one) => return Ok(alloc::vec![one.into_inner()]),
1657 Err(err) => err,
1658 };
1659 let many_err: D::Error = match <DeserializeAsWrap<Vec<T>, Vec<TAs>>>::deserialize(
1660 content::de::ContentDeserializer::new(content, is_hr),
1661 ) {
1662 Ok(many) => return Ok(many.into_inner()),
1663 Err(err) => err,
1664 };
1665 Err(DeError::custom(format_args!(
1666 "OneOrMany could not deserialize any variant:\n One: {one_err}\n Many: {many_err}"
1667 )))
1668 }
1669}
1670
1671#[cfg(feature = "alloc")]
1672impl<'de, T, TAs1> DeserializeAs<'de, T> for PickFirst<(TAs1,)>
1673where
1674 TAs1: DeserializeAs<'de, T>,
1675{
1676 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1677 where
1678 D: Deserializer<'de>,
1679 {
1680 Ok(DeserializeAsWrap::<T, TAs1>::deserialize(deserializer)?.into_inner())
1681 }
1682}
1683
1684#[cfg(feature = "alloc")]
1685impl<'de, T, TAs1, TAs2> DeserializeAs<'de, T> for PickFirst<(TAs1, TAs2)>
1686where
1687 TAs1: DeserializeAs<'de, T>,
1688 TAs2: DeserializeAs<'de, T>,
1689{
1690 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1691 where
1692 D: Deserializer<'de>,
1693 {
1694 let is_hr = deserializer.is_human_readable();
1695 let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1696
1697 let first_err: D::Error = match <DeserializeAsWrap<T, TAs1>>::deserialize(
1698 content::de::ContentRefDeserializer::new(&content, is_hr),
1699 ) {
1700 Ok(first) => return Ok(first.into_inner()),
1701 Err(err) => err,
1702 };
1703 let second_err: D::Error = match <DeserializeAsWrap<T, TAs2>>::deserialize(
1704 content::de::ContentDeserializer::new(content, is_hr),
1705 ) {
1706 Ok(second) => return Ok(second.into_inner()),
1707 Err(err) => err,
1708 };
1709 Err(DeError::custom(format_args!(
1710 "PickFirst could not deserialize any variant:\n First: {first_err}\n Second: {second_err}"
1711 )))
1712 }
1713}
1714
1715#[cfg(feature = "alloc")]
1716impl<'de, T, TAs1, TAs2, TAs3> DeserializeAs<'de, T> for PickFirst<(TAs1, TAs2, TAs3)>
1717where
1718 TAs1: DeserializeAs<'de, T>,
1719 TAs2: DeserializeAs<'de, T>,
1720 TAs3: DeserializeAs<'de, T>,
1721{
1722 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1723 where
1724 D: Deserializer<'de>,
1725 {
1726 let is_hr = deserializer.is_human_readable();
1727 let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1728
1729 let first_err: D::Error = match <DeserializeAsWrap<T, TAs1>>::deserialize(
1730 content::de::ContentRefDeserializer::new(&content, is_hr),
1731 ) {
1732 Ok(first) => return Ok(first.into_inner()),
1733 Err(err) => err,
1734 };
1735 let second_err: D::Error = match <DeserializeAsWrap<T, TAs2>>::deserialize(
1736 content::de::ContentRefDeserializer::new(&content, is_hr),
1737 ) {
1738 Ok(second) => return Ok(second.into_inner()),
1739 Err(err) => err,
1740 };
1741 let third_err: D::Error = match <DeserializeAsWrap<T, TAs3>>::deserialize(
1742 content::de::ContentDeserializer::new(content, is_hr),
1743 ) {
1744 Ok(third) => return Ok(third.into_inner()),
1745 Err(err) => err,
1746 };
1747 Err(DeError::custom(format_args!(
1748 "PickFirst could not deserialize any variant:\n First: {first_err}\n Second: {second_err}\n Third: {third_err}",
1749 )))
1750 }
1751}
1752
1753#[cfg(feature = "alloc")]
1754impl<'de, T, TAs1, TAs2, TAs3, TAs4> DeserializeAs<'de, T> for PickFirst<(TAs1, TAs2, TAs3, TAs4)>
1755where
1756 TAs1: DeserializeAs<'de, T>,
1757 TAs2: DeserializeAs<'de, T>,
1758 TAs3: DeserializeAs<'de, T>,
1759 TAs4: DeserializeAs<'de, T>,
1760{
1761 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1762 where
1763 D: Deserializer<'de>,
1764 {
1765 let is_hr = deserializer.is_human_readable();
1766 let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1767
1768 let first_err: D::Error = match <DeserializeAsWrap<T, TAs1>>::deserialize(
1769 content::de::ContentRefDeserializer::new(&content, is_hr),
1770 ) {
1771 Ok(first) => return Ok(first.into_inner()),
1772 Err(err) => err,
1773 };
1774 let second_err: D::Error = match <DeserializeAsWrap<T, TAs2>>::deserialize(
1775 content::de::ContentRefDeserializer::new(&content, is_hr),
1776 ) {
1777 Ok(second) => return Ok(second.into_inner()),
1778 Err(err) => err,
1779 };
1780 let third_err: D::Error = match <DeserializeAsWrap<T, TAs3>>::deserialize(
1781 content::de::ContentRefDeserializer::new(&content, is_hr),
1782 ) {
1783 Ok(third) => return Ok(third.into_inner()),
1784 Err(err) => err,
1785 };
1786 let fourth_err: D::Error = match <DeserializeAsWrap<T, TAs4>>::deserialize(
1787 content::de::ContentDeserializer::new(content, is_hr),
1788 ) {
1789 Ok(fourth) => return Ok(fourth.into_inner()),
1790 Err(err) => err,
1791 };
1792 Err(DeError::custom(format_args!(
1793 "PickFirst could not deserialize any variant:\n First: {first_err}\n Second: {second_err}\n Third: {third_err}\n Fourth: {fourth_err}",
1794 )))
1795 }
1796}
1797
1798impl<'de, T, U> DeserializeAs<'de, T> for FromInto<U>
1799where
1800 U: Into<T>,
1801 U: Deserialize<'de>,
1802{
1803 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1804 where
1805 D: Deserializer<'de>,
1806 {
1807 Ok(U::deserialize(deserializer)?.into())
1808 }
1809}
1810
1811impl<'de, T, U> DeserializeAs<'de, T> for TryFromInto<U>
1812where
1813 U: TryInto<T>,
1814 <U as TryInto<T>>::Error: Display,
1815 U: Deserialize<'de>,
1816{
1817 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1818 where
1819 D: Deserializer<'de>,
1820 {
1821 U::deserialize(deserializer)?
1822 .try_into()
1823 .map_err(DeError::custom)
1824 }
1825}
1826
1827impl<'de, T, U> DeserializeAs<'de, T> for FromIntoRef<U>
1828where
1829 U: Into<T>,
1830 U: Deserialize<'de>,
1831{
1832 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1833 where
1834 D: Deserializer<'de>,
1835 {
1836 Ok(U::deserialize(deserializer)?.into())
1837 }
1838}
1839
1840impl<'de, T, U> DeserializeAs<'de, T> for TryFromIntoRef<U>
1841where
1842 U: TryInto<T>,
1843 <U as TryInto<T>>::Error: Display,
1844 U: Deserialize<'de>,
1845{
1846 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1847 where
1848 D: Deserializer<'de>,
1849 {
1850 U::deserialize(deserializer)?
1851 .try_into()
1852 .map_err(DeError::custom)
1853 }
1854}
1855
1856#[cfg(feature = "alloc")]
1857impl<'de> DeserializeAs<'de, Cow<'de, str>> for BorrowCow {
1858 fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, str>, D::Error>
1859 where
1860 D: Deserializer<'de>,
1861 {
1862 struct CowVisitor;
1863
1864 impl<'de> Visitor<'de> for CowVisitor {
1865 type Value = Cow<'de, str>;
1866
1867 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1868 formatter.write_str("an optionally borrowed string")
1869 }
1870
1871 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
1872 where
1873 E: DeError,
1874 {
1875 Ok(Cow::Borrowed(v))
1876 }
1877
1878 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1879 where
1880 E: DeError,
1881 {
1882 Ok(Cow::Owned(v.to_owned()))
1883 }
1884
1885 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1886 where
1887 E: DeError,
1888 {
1889 Ok(Cow::Owned(v))
1890 }
1891 }
1892
1893 deserializer.deserialize_string(CowVisitor)
1894 }
1895}
1896
1897#[cfg(feature = "alloc")]
1898impl<'de> DeserializeAs<'de, Cow<'de, [u8]>> for BorrowCow {
1899 fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8]>, D::Error>
1900 where
1901 D: Deserializer<'de>,
1902 {
1903 Bytes::deserialize_as(deserializer)
1904 }
1905}
1906
1907#[cfg(feature = "alloc")]
1908impl<'de, const N: usize> DeserializeAs<'de, Cow<'de, [u8; N]>> for BorrowCow {
1909 fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8; N]>, D::Error>
1910 where
1911 D: Deserializer<'de>,
1912 {
1913 Bytes::deserialize_as(deserializer)
1914 }
1915}
1916
1917impl<'de> DeserializeAs<'de, bool> for BoolFromInt<Strict> {
1918 fn deserialize_as<D>(deserializer: D) -> Result<bool, D::Error>
1919 where
1920 D: Deserializer<'de>,
1921 {
1922 struct U8Visitor;
1923 impl Visitor<'_> for U8Visitor {
1924 type Value = bool;
1925
1926 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1927 formatter.write_str("an integer 0 or 1")
1928 }
1929
1930 fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
1931 where
1932 E: DeError,
1933 {
1934 match v {
1935 0 => Ok(false),
1936 1 => Ok(true),
1937 unexp => Err(DeError::invalid_value(
1938 Unexpected::Unsigned(u64::from(unexp)),
1939 &"0 or 1",
1940 )),
1941 }
1942 }
1943
1944 fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
1945 where
1946 E: DeError,
1947 {
1948 match v {
1949 0 => Ok(false),
1950 1 => Ok(true),
1951 unexp => Err(DeError::invalid_value(
1952 Unexpected::Signed(i64::from(unexp)),
1953 &"0 or 1",
1954 )),
1955 }
1956 }
1957
1958 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
1959 where
1960 E: DeError,
1961 {
1962 match v {
1963 0 => Ok(false),
1964 1 => Ok(true),
1965 unexp => Err(DeError::invalid_value(
1966 Unexpected::Unsigned(unexp),
1967 &"0 or 1",
1968 )),
1969 }
1970 }
1971
1972 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
1973 where
1974 E: DeError,
1975 {
1976 match v {
1977 0 => Ok(false),
1978 1 => Ok(true),
1979 unexp => Err(DeError::invalid_value(Unexpected::Signed(unexp), &"0 or 1")),
1980 }
1981 }
1982
1983 fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
1984 where
1985 E: DeError,
1986 {
1987 match v {
1988 0 => Ok(false),
1989 1 => Ok(true),
1990 unexp => {
1991 let mut buf: [u8; 58] = [0u8; 58];
1992 Err(DeError::invalid_value(
1993 crate::utils::get_unexpected_u128(unexp, &mut buf),
1994 &self,
1995 ))
1996 }
1997 }
1998 }
1999
2000 fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
2001 where
2002 E: DeError,
2003 {
2004 match v {
2005 0 => Ok(false),
2006 1 => Ok(true),
2007 unexp => {
2008 let mut buf: [u8; 58] = [0u8; 58];
2009 Err(DeError::invalid_value(
2010 crate::utils::get_unexpected_i128(unexp, &mut buf),
2011 &"0 or 1",
2012 ))
2013 }
2014 }
2015 }
2016 }
2017
2018 deserializer.deserialize_u8(U8Visitor)
2019 }
2020}
2021
2022impl<'de> DeserializeAs<'de, bool> for BoolFromInt<Flexible> {
2023 fn deserialize_as<D>(deserializer: D) -> Result<bool, D::Error>
2024 where
2025 D: Deserializer<'de>,
2026 {
2027 struct U8Visitor;
2028 impl Visitor<'_> for U8Visitor {
2029 type Value = bool;
2030
2031 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2032 formatter.write_str("an integer")
2033 }
2034
2035 fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
2036 where
2037 E: DeError,
2038 {
2039 Ok(v != 0)
2040 }
2041
2042 fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
2043 where
2044 E: DeError,
2045 {
2046 Ok(v != 0)
2047 }
2048
2049 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
2050 where
2051 E: DeError,
2052 {
2053 Ok(v != 0)
2054 }
2055
2056 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
2057 where
2058 E: DeError,
2059 {
2060 Ok(v != 0)
2061 }
2062
2063 fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
2064 where
2065 E: DeError,
2066 {
2067 Ok(v != 0)
2068 }
2069
2070 fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
2071 where
2072 E: DeError,
2073 {
2074 Ok(v != 0)
2075 }
2076 }
2077
2078 deserializer.deserialize_u8(U8Visitor)
2079 }
2080}
2081
2082