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