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(crate::utils::size_hint_cautious::<(K,V)>(Some(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(crate::utils::size_hint_cautious::<(K,V)>(Some(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(crate::utils::size_hint_cautious::<(K,V)>(Some(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(crate::utils::size_hint_cautious::<(K,V)>(Some(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(crate::utils::size_hint_cautious::<(K,V)>(Some(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(crate::utils::size_hint_cautious::<(K,V)>(Some(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(crate::utils::size_hint_cautious::<(K,V)>(Some(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(crate::utils::size_hint_cautious::<T>(Some(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(crate::utils::size_hint_cautious::<T>(Some(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(crate::utils::size_hint_cautious::<T>(Some(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(crate::utils::size_hint_cautious::<T>(Some(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(crate::utils::size_hint_cautious::<T>(Some(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(crate::utils::size_hint_cautious::<T>(Some(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(crate::utils::size_hint_cautious::<T>(Some(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(crate::utils::size_hint_cautious::<T>(Some(size)))),
128 push
129 );
130 #[cfg(feature = "alloc")]
131 $m!(BoxedSlice<T>, (|size| crate::utils::vec_with_capacity_cautious(Some(size))), push);
132 #[cfg(feature = "alloc")]
133 $m!(LinkedList<T>, (|_| LinkedList::new()), push_back);
134 #[cfg(feature = "alloc")]
135 $m!(Vec<T>, (|size| crate::utils::vec_with_capacity_cautious(Some(size))), push);
136 #[cfg(feature = "alloc")]
137 $m!(
138 VecDeque<T>,
139 (|size| VecDeque::with_capacity(crate::utils::size_hint_cautious::<T>(Some(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
1120macro_rules! none_as_zero_deserialize {
1121 ($($nonzero:ident => $primitive:ident),* $(,)?) => {
1122 $(
1123 impl<'de> DeserializeAs<'de, Option<core::num::$nonzero>> for NoneAsZero {
1124 fn deserialize_as<D>(
1125 deserializer: D,
1126 ) -> Result<Option<core::num::$nonzero>, D::Error>
1127 where
1128 D: Deserializer<'de>,
1129 {
1130 let value = <$primitive>::deserialize(deserializer)?;
1131 Ok(core::num::$nonzero::new(value))
1132 }
1133 }
1134 )*
1135 };
1136}
1137
1138none_as_zero_deserialize! {
1139 NonZeroU8 => u8,
1140 NonZeroU16 => u16,
1141 NonZeroU32 => u32,
1142 NonZeroU64 => u64,
1143 NonZeroU128 => u128,
1144 NonZeroUsize => usize,
1145 NonZeroI8 => i8,
1146 NonZeroI16 => i16,
1147 NonZeroI32 => i32,
1148 NonZeroI64 => i64,
1149 NonZeroI128 => i128,
1150 NonZeroIsize => isize,
1151}
1152
1153#[cfg(feature = "alloc")]
1154impl<'de, T, TAs> DeserializeAs<'de, T> for DefaultOnError<TAs>
1155where
1156 TAs: DeserializeAs<'de, T>,
1157 T: Default,
1158{
1159 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1160 where
1161 D: Deserializer<'de>,
1162 {
1163 let is_hr = deserializer.is_human_readable();
1164 let content: content::de::Content<'de> = match Deserialize::deserialize(deserializer) {
1165 Ok(content) => content,
1166 Err(_) => return Ok(Default::default()),
1167 };
1168
1169 Ok(
1170 match <DeserializeAsWrap<T, TAs>>::deserialize(content::de::ContentDeserializer::<
1171 D::Error,
1172 >::new(content, is_hr))
1173 {
1174 Ok(elem) => elem.into_inner(),
1175 Err(_) => Default::default(),
1176 },
1177 )
1178 }
1179}
1180
1181#[cfg(feature = "alloc")]
1182impl<'de> DeserializeAs<'de, Vec<u8>> for BytesOrString {
1183 fn deserialize_as<D>(deserializer: D) -> Result<Vec<u8>, D::Error>
1184 where
1185 D: Deserializer<'de>,
1186 {
1187 struct BytesOrStringVisitor;
1188 impl<'de> Visitor<'de> for BytesOrStringVisitor {
1189 type Value = Vec<u8>;
1190
1191 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1192 formatter.write_str("a list of bytes or a string")
1193 }
1194
1195 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> {
1196 Ok(v.to_vec())
1197 }
1198
1199 #[cfg(feature = "alloc")]
1200 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> {
1201 Ok(v)
1202 }
1203
1204 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> {
1205 Ok(v.as_bytes().to_vec())
1206 }
1207
1208 #[cfg(feature = "alloc")]
1209 fn visit_string<E>(self, v: String) -> Result<Self::Value, E> {
1210 Ok(v.into_bytes())
1211 }
1212
1213 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1214 where
1215 A: SeqAccess<'de>,
1216 {
1217 utils::SeqIter::new(seq).collect()
1218 }
1219 }
1220 deserializer.deserialize_any(BytesOrStringVisitor)
1221 }
1222}
1223
1224impl<'de, SEPARATOR, I, T> DeserializeAs<'de, I> for StringWithSeparator<SEPARATOR, T>
1225where
1226 SEPARATOR: Separator,
1227 I: FromIterator<T>,
1228 T: FromStr,
1229 T::Err: Display,
1230{
1231 fn deserialize_as<D>(deserializer: D) -> Result<I, D::Error>
1232 where
1233 D: Deserializer<'de>,
1234 {
1235 struct Helper<SEPARATOR, I, T>(PhantomData<(SEPARATOR, I, T)>);
1236
1237 impl<SEPARATOR, I, T> Visitor<'_> for Helper<SEPARATOR, I, T>
1238 where
1239 SEPARATOR: Separator,
1240 I: FromIterator<T>,
1241 T: FromStr,
1242 T::Err: Display,
1243 {
1244 type Value = I;
1245
1246 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1247 formatter.write_str("a string")
1248 }
1249
1250 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1251 where
1252 E: DeError,
1253 {
1254 if value.is_empty() {
1255 Ok(None.into_iter().collect())
1256 } else {
1257 value
1258 .split(SEPARATOR::separator())
1259 .map(FromStr::from_str)
1260 .collect::<Result<_, _>>()
1261 .map_err(DeError::custom)
1262 }
1263 }
1264 }
1265
1266 deserializer.deserialize_str(Helper::<SEPARATOR, I, T>(PhantomData))
1267 }
1268}
1269
1270macro_rules! use_signed_duration {
1271 (
1272 $main_trait:ident $internal_trait:ident =>
1273 {
1274 $ty:ty; $converter:ident =>
1275 $({
1276 $format:ty, $strictness:ty =>
1277 $($tbound:ident: $bound:ident $(,)?)*
1278 })*
1279 }
1280 ) => {
1281 $(
1282 impl<'de, $($tbound,)*> DeserializeAs<'de, $ty> for $main_trait<$format, $strictness>
1283 where
1284 $($tbound: $bound,)*
1285 {
1286 fn deserialize_as<D>(deserializer: D) -> Result<$ty, D::Error>
1287 where
1288 D: Deserializer<'de>,
1289 {
1290 let dur: DurationSigned = $internal_trait::<$format, $strictness>::deserialize_as(deserializer)?;
1291 dur.$converter::<D>()
1292 }
1293 }
1294 )*
1295 };
1296 (
1297 $( $main_trait:ident $internal_trait:ident, )+ => $rest:tt
1298 ) => {
1299 $( use_signed_duration!($main_trait $internal_trait => $rest); )+
1300 };
1301}
1302
1303use_signed_duration!(
1304 DurationSeconds DurationSeconds,
1305 DurationMilliSeconds DurationMilliSeconds,
1306 DurationMicroSeconds DurationMicroSeconds,
1307 DurationNanoSeconds DurationNanoSeconds,
1308 => {
1309 Duration; to_std_duration =>
1310 {u64, Strict =>}
1311 {FORMAT, Flexible => FORMAT: Format}
1312 }
1313);
1314#[cfg(feature = "alloc")]
1315use_signed_duration!(
1316 DurationSeconds DurationSeconds,
1317 DurationMilliSeconds DurationMilliSeconds,
1318 DurationMicroSeconds DurationMicroSeconds,
1319 DurationNanoSeconds DurationNanoSeconds,
1320 => {
1321 Duration; to_std_duration =>
1322 {String, Strict =>}
1323 }
1324);
1325#[cfg(feature = "std")]
1326use_signed_duration!(
1327 DurationSeconds DurationSeconds,
1328 DurationMilliSeconds DurationMilliSeconds,
1329 DurationMicroSeconds DurationMicroSeconds,
1330 DurationNanoSeconds DurationNanoSeconds,
1331 => {
1332 Duration; to_std_duration =>
1333 {f64, Strict =>}
1335 }
1336);
1337use_signed_duration!(
1338 DurationSecondsWithFrac DurationSecondsWithFrac,
1339 DurationMilliSecondsWithFrac DurationMilliSecondsWithFrac,
1340 DurationMicroSecondsWithFrac DurationMicroSecondsWithFrac,
1341 DurationNanoSecondsWithFrac DurationNanoSecondsWithFrac,
1342 => {
1343 Duration; to_std_duration =>
1344 {f64, Strict =>}
1345 {FORMAT, Flexible => FORMAT: Format}
1346 }
1347);
1348#[cfg(feature = "alloc")]
1349use_signed_duration!(
1350 DurationSecondsWithFrac DurationSecondsWithFrac,
1351 DurationMilliSecondsWithFrac DurationMilliSecondsWithFrac,
1352 DurationMicroSecondsWithFrac DurationMicroSecondsWithFrac,
1353 DurationNanoSecondsWithFrac DurationNanoSecondsWithFrac,
1354 => {
1355 Duration; to_std_duration =>
1356 {String, Strict =>}
1357 }
1358);
1359
1360#[cfg(feature = "std")]
1361use_signed_duration!(
1362 TimestampSeconds DurationSeconds,
1363 TimestampMilliSeconds DurationMilliSeconds,
1364 TimestampMicroSeconds DurationMicroSeconds,
1365 TimestampNanoSeconds DurationNanoSeconds,
1366 => {
1367 SystemTime; to_system_time =>
1368 {i64, Strict =>}
1369 {f64, Strict =>}
1370 {String, Strict =>}
1371 {FORMAT, Flexible => FORMAT: Format}
1372 }
1373);
1374#[cfg(feature = "std")]
1375use_signed_duration!(
1376 TimestampSecondsWithFrac DurationSecondsWithFrac,
1377 TimestampMilliSecondsWithFrac DurationMilliSecondsWithFrac,
1378 TimestampMicroSecondsWithFrac DurationMicroSecondsWithFrac,
1379 TimestampNanoSecondsWithFrac DurationNanoSecondsWithFrac,
1380 => {
1381 SystemTime; to_system_time =>
1382 {f64, Strict =>}
1383 {String, Strict =>}
1384 {FORMAT, Flexible => FORMAT: Format}
1385 }
1386);
1387
1388impl<'de, T, U> DeserializeAs<'de, T> for DefaultOnNull<U>
1389where
1390 U: DeserializeAs<'de, T>,
1391 T: Default,
1392{
1393 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1394 where
1395 D: Deserializer<'de>,
1396 {
1397 Ok(Option::<U>::deserialize_as(deserializer)?.unwrap_or_default())
1398 }
1399}
1400
1401impl<'de> DeserializeAs<'de, &'de [u8]> for Bytes {
1402 fn deserialize_as<D>(deserializer: D) -> Result<&'de [u8], D::Error>
1403 where
1404 D: Deserializer<'de>,
1405 {
1406 <&'de [u8]>::deserialize(deserializer)
1407 }
1408}
1409
1410#[cfg(feature = "alloc")]
1420impl<'de> DeserializeAs<'de, Vec<u8>> for Bytes {
1421 fn deserialize_as<D>(deserializer: D) -> Result<Vec<u8>, D::Error>
1422 where
1423 D: Deserializer<'de>,
1424 {
1425 struct VecVisitor;
1426
1427 impl<'de> Visitor<'de> for VecVisitor {
1428 type Value = Vec<u8>;
1429
1430 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1431 formatter.write_str("a byte array")
1432 }
1433
1434 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1435 where
1436 A: SeqAccess<'de>,
1437 {
1438 utils::SeqIter::new(seq).collect::<Result<_, _>>()
1439 }
1440
1441 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1442 where
1443 E: DeError,
1444 {
1445 Ok(v.to_vec())
1446 }
1447
1448 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1449 where
1450 E: DeError,
1451 {
1452 Ok(v)
1453 }
1454
1455 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1456 where
1457 E: DeError,
1458 {
1459 Ok(v.as_bytes().to_vec())
1460 }
1461
1462 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1463 where
1464 E: DeError,
1465 {
1466 Ok(v.into_bytes())
1467 }
1468 }
1469
1470 deserializer.deserialize_byte_buf(VecVisitor)
1471 }
1472}
1473
1474#[cfg(feature = "alloc")]
1475impl<'de> DeserializeAs<'de, Box<[u8]>> for Bytes {
1476 fn deserialize_as<D>(deserializer: D) -> Result<Box<[u8]>, D::Error>
1477 where
1478 D: Deserializer<'de>,
1479 {
1480 <Bytes as DeserializeAs<'de, Vec<u8>>>::deserialize_as(deserializer)
1481 .map(Vec::into_boxed_slice)
1482 }
1483}
1484
1485#[cfg(feature = "alloc")]
1497impl<'de> DeserializeAs<'de, Cow<'de, [u8]>> for Bytes {
1498 fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8]>, D::Error>
1499 where
1500 D: Deserializer<'de>,
1501 {
1502 struct CowVisitor;
1503
1504 impl<'de> Visitor<'de> for CowVisitor {
1505 type Value = Cow<'de, [u8]>;
1506
1507 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1508 formatter.write_str("a byte array")
1509 }
1510
1511 fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
1512 where
1513 E: DeError,
1514 {
1515 Ok(Cow::Borrowed(v))
1516 }
1517
1518 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
1519 where
1520 E: DeError,
1521 {
1522 Ok(Cow::Borrowed(v.as_bytes()))
1523 }
1524
1525 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1526 where
1527 E: DeError,
1528 {
1529 Ok(Cow::Owned(v.to_vec()))
1530 }
1531
1532 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1533 where
1534 E: DeError,
1535 {
1536 Ok(Cow::Owned(v.as_bytes().to_vec()))
1537 }
1538
1539 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1540 where
1541 E: DeError,
1542 {
1543 Ok(Cow::Owned(v))
1544 }
1545
1546 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1547 where
1548 E: DeError,
1549 {
1550 Ok(Cow::Owned(v.into_bytes()))
1551 }
1552
1553 fn visit_seq<V>(self, seq: V) -> Result<Self::Value, V::Error>
1554 where
1555 V: SeqAccess<'de>,
1556 {
1557 Ok(Cow::Owned(
1558 utils::SeqIter::new(seq).collect::<Result<_, _>>()?,
1559 ))
1560 }
1561 }
1562
1563 deserializer.deserialize_bytes(CowVisitor)
1564 }
1565}
1566
1567impl<'de, const N: usize> DeserializeAs<'de, [u8; N]> for Bytes {
1568 fn deserialize_as<D>(deserializer: D) -> Result<[u8; N], D::Error>
1569 where
1570 D: Deserializer<'de>,
1571 {
1572 struct ArrayVisitor<const M: usize>;
1573
1574 impl<'de, const M: usize> Visitor<'de> for ArrayVisitor<M> {
1575 type Value = [u8; M];
1576
1577 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1578 formatter.write_fmt(format_args!("an byte array of size {M}"))
1579 }
1580
1581 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1582 where
1583 A: SeqAccess<'de>,
1584 {
1585 utils::array_from_iterator(utils::SeqIter::new(seq), &self)
1586 }
1587
1588 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1589 where
1590 E: DeError,
1591 {
1592 v.try_into()
1593 .map_err(|_| DeError::invalid_length(v.len(), &self))
1594 }
1595
1596 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1597 where
1598 E: DeError,
1599 {
1600 v.as_bytes()
1601 .try_into()
1602 .map_err(|_| DeError::invalid_length(v.len(), &self))
1603 }
1604 }
1605
1606 deserializer.deserialize_bytes(ArrayVisitor::<N>)
1607 }
1608}
1609
1610impl<'de, const N: usize> DeserializeAs<'de, &'de [u8; N]> for Bytes {
1611 fn deserialize_as<D>(deserializer: D) -> Result<&'de [u8; N], D::Error>
1612 where
1613 D: Deserializer<'de>,
1614 {
1615 struct ArrayVisitor<const M: usize>;
1616
1617 impl<'de, const M: usize> Visitor<'de> for ArrayVisitor<M> {
1618 type Value = &'de [u8; M];
1619
1620 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1621 formatter.write_fmt(format_args!("a borrowed byte array of size {M}"))
1622 }
1623
1624 fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
1625 where
1626 E: DeError,
1627 {
1628 v.try_into()
1629 .map_err(|_| DeError::invalid_length(v.len(), &self))
1630 }
1631
1632 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
1633 where
1634 E: DeError,
1635 {
1636 v.as_bytes()
1637 .try_into()
1638 .map_err(|_| DeError::invalid_length(v.len(), &self))
1639 }
1640 }
1641
1642 deserializer.deserialize_bytes(ArrayVisitor::<N>)
1643 }
1644}
1645
1646#[cfg(feature = "alloc")]
1647impl<'de, const N: usize> DeserializeAs<'de, Cow<'de, [u8; N]>> for Bytes {
1648 fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8; N]>, D::Error>
1649 where
1650 D: Deserializer<'de>,
1651 {
1652 struct CowVisitor<const M: usize>;
1653
1654 impl<'de, const M: usize> Visitor<'de> for CowVisitor<M> {
1655 type Value = Cow<'de, [u8; M]>;
1656
1657 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1658 formatter.write_str("a byte array")
1659 }
1660
1661 fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
1662 where
1663 E: DeError,
1664 {
1665 Ok(Cow::Borrowed(
1666 v.try_into()
1667 .map_err(|_| DeError::invalid_length(v.len(), &self))?,
1668 ))
1669 }
1670
1671 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
1672 where
1673 E: DeError,
1674 {
1675 Ok(Cow::Borrowed(
1676 v.as_bytes()
1677 .try_into()
1678 .map_err(|_| DeError::invalid_length(v.len(), &self))?,
1679 ))
1680 }
1681
1682 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1683 where
1684 E: DeError,
1685 {
1686 Ok(Cow::Owned(
1687 v.to_vec()
1688 .try_into()
1689 .map_err(|_| DeError::invalid_length(v.len(), &self))?,
1690 ))
1691 }
1692
1693 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1694 where
1695 E: DeError,
1696 {
1697 Ok(Cow::Owned(
1698 v.as_bytes()
1699 .to_vec()
1700 .try_into()
1701 .map_err(|_| DeError::invalid_length(v.len(), &self))?,
1702 ))
1703 }
1704
1705 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1706 where
1707 E: DeError,
1708 {
1709 let len = v.len();
1710 Ok(Cow::Owned(
1711 v.try_into()
1712 .map_err(|_| DeError::invalid_length(len, &self))?,
1713 ))
1714 }
1715
1716 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1717 where
1718 E: DeError,
1719 {
1720 let len = v.len();
1721 Ok(Cow::Owned(
1722 v.into_bytes()
1723 .try_into()
1724 .map_err(|_| DeError::invalid_length(len, &self))?,
1725 ))
1726 }
1727
1728 fn visit_seq<V>(self, seq: V) -> Result<Self::Value, V::Error>
1729 where
1730 V: SeqAccess<'de>,
1731 {
1732 Ok(Cow::Owned(utils::array_from_iterator(
1733 utils::SeqIter::new(seq),
1734 &self,
1735 )?))
1736 }
1737 }
1738
1739 deserializer.deserialize_bytes(CowVisitor)
1740 }
1741}
1742
1743#[cfg(feature = "alloc")]
1744impl<'de, const N: usize> DeserializeAs<'de, Box<[u8; N]>> for Bytes {
1745 fn deserialize_as<D>(deserializer: D) -> Result<Box<[u8; N]>, D::Error>
1746 where
1747 D: Deserializer<'de>,
1748 {
1749 Bytes::deserialize_as(deserializer).map(Box::new)
1750 }
1751}
1752
1753#[cfg(feature = "alloc")]
1754macro_rules! one_or_many_impl {
1755 (
1756 $ty:ident < T $(: $tbound1:ident $(+ $tbound2:ident)*)? $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)* )* >,
1757 $with_capacity:expr,
1758 $append:ident
1759 ) => {
1760 impl<'de, T, TAs, FORMAT $(, $typaram)*> DeserializeAs<'de, $ty<T $(, $typaram)*>> for OneOrMany<TAs, FORMAT>
1761 where
1762 TAs: DeserializeAs<'de, T>,
1763 FORMAT: Format,
1764 $(T: $tbound1 $(+ $tbound2)*,)?
1765 $($typaram: $bound1 $(+ $bound2)*),*
1766 {
1767 fn deserialize_as<D>(deserializer: D) -> Result<$ty<T $(, $typaram)*>, D::Error>
1768 where
1769 D: Deserializer<'de>,
1770 {
1771 let is_hr = deserializer.is_human_readable();
1772 let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1773
1774 let one_err: D::Error = match <DeserializeAsWrap<T, TAs>>::deserialize(
1775 content::de::ContentRefDeserializer::new(&content, is_hr),
1776 ) {
1777 Ok(one) => {
1778 #[allow(clippy::redundant_closure_call)]
1779 let mut values = ($with_capacity)(1);
1780 values.$append(one.into_inner());
1781 return Ok(values.into());
1782 }
1783 Err(err) => err,
1784 };
1785 let many_err: D::Error = match <DeserializeAsWrap<$ty<T $(, $typaram)*>, $ty<TAs $(, $typaram)*>>>::deserialize(
1786 content::de::ContentDeserializer::new(content, is_hr),
1787 ) {
1788 Ok(many) => return Ok(many.into_inner()),
1789 Err(err) => err,
1790 };
1791 Err(DeError::custom(format_args!(
1792 "OneOrMany could not deserialize any variant:\n One: {one_err}\n Many: {many_err}"
1793 )))
1794 }
1795 }
1796 };
1797}
1798#[cfg(feature = "alloc")]
1799foreach_seq!(one_or_many_impl);
1800
1801#[cfg(all(feature = "alloc", feature = "smallvec_1"))]
1802impl<'de, T, TAs, FORMAT, A> DeserializeAs<'de, SmallVec<A>> for OneOrMany<TAs, FORMAT>
1803where
1804 A: smallvec_1::Array<Item = T>,
1805 TAs: DeserializeAs<'de, T>,
1806 FORMAT: Format,
1807{
1808 fn deserialize_as<D>(deserializer: D) -> Result<SmallVec<A>, D::Error>
1809 where
1810 D: Deserializer<'de>,
1811 {
1812 let is_hr = deserializer.is_human_readable();
1813 let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1814
1815 let one_err: D::Error = match <DeserializeAsWrap<T, TAs>>::deserialize(
1816 content::de::ContentRefDeserializer::new(&content, is_hr),
1817 ) {
1818 Ok(one) => {
1819 let mut res = SmallVec::<A>::new();
1820 res.push(one.into_inner());
1821 return Ok(res);
1822 }
1823 Err(err) => err,
1824 };
1825 let many_err: D::Error = match <DeserializeAsWrap<Vec<T>, Vec<TAs>>>::deserialize(
1826 content::de::ContentDeserializer::new(content, is_hr),
1827 ) {
1828 Ok(many) => return Ok(SmallVec::from_vec(many.into_inner())),
1829 Err(err) => err,
1830 };
1831 Err(DeError::custom(format_args!(
1832 "OneOrMany could not deserialize any variant:\n One: {one_err}\n Many: {many_err}"
1833 )))
1834 }
1835}
1836
1837#[cfg(feature = "alloc")]
1838impl<'de, T, TAs1> DeserializeAs<'de, T> for PickFirst<(TAs1,)>
1839where
1840 TAs1: DeserializeAs<'de, T>,
1841{
1842 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1843 where
1844 D: Deserializer<'de>,
1845 {
1846 Ok(DeserializeAsWrap::<T, TAs1>::deserialize(deserializer)?.into_inner())
1847 }
1848}
1849
1850#[cfg(feature = "alloc")]
1851impl<'de, T, TAs1, TAs2> DeserializeAs<'de, T> for PickFirst<(TAs1, TAs2)>
1852where
1853 TAs1: DeserializeAs<'de, T>,
1854 TAs2: DeserializeAs<'de, T>,
1855{
1856 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1857 where
1858 D: Deserializer<'de>,
1859 {
1860 let is_hr = deserializer.is_human_readable();
1861 let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1862
1863 let first_err: D::Error = match <DeserializeAsWrap<T, TAs1>>::deserialize(
1864 content::de::ContentRefDeserializer::new(&content, is_hr),
1865 ) {
1866 Ok(first) => return Ok(first.into_inner()),
1867 Err(err) => err,
1868 };
1869 let second_err: D::Error = match <DeserializeAsWrap<T, TAs2>>::deserialize(
1870 content::de::ContentDeserializer::new(content, is_hr),
1871 ) {
1872 Ok(second) => return Ok(second.into_inner()),
1873 Err(err) => err,
1874 };
1875 Err(DeError::custom(format_args!(
1876 "PickFirst could not deserialize any variant:\n First: {first_err}\n Second: {second_err}"
1877 )))
1878 }
1879}
1880
1881#[cfg(feature = "alloc")]
1882impl<'de, T, TAs1, TAs2, TAs3> DeserializeAs<'de, T> for PickFirst<(TAs1, TAs2, TAs3)>
1883where
1884 TAs1: DeserializeAs<'de, T>,
1885 TAs2: DeserializeAs<'de, T>,
1886 TAs3: DeserializeAs<'de, T>,
1887{
1888 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1889 where
1890 D: Deserializer<'de>,
1891 {
1892 let is_hr = deserializer.is_human_readable();
1893 let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1894
1895 let first_err: D::Error = match <DeserializeAsWrap<T, TAs1>>::deserialize(
1896 content::de::ContentRefDeserializer::new(&content, is_hr),
1897 ) {
1898 Ok(first) => return Ok(first.into_inner()),
1899 Err(err) => err,
1900 };
1901 let second_err: D::Error = match <DeserializeAsWrap<T, TAs2>>::deserialize(
1902 content::de::ContentRefDeserializer::new(&content, is_hr),
1903 ) {
1904 Ok(second) => return Ok(second.into_inner()),
1905 Err(err) => err,
1906 };
1907 let third_err: D::Error = match <DeserializeAsWrap<T, TAs3>>::deserialize(
1908 content::de::ContentDeserializer::new(content, is_hr),
1909 ) {
1910 Ok(third) => return Ok(third.into_inner()),
1911 Err(err) => err,
1912 };
1913 Err(DeError::custom(format_args!(
1914 "PickFirst could not deserialize any variant:\n First: {first_err}\n Second: {second_err}\n Third: {third_err}",
1915 )))
1916 }
1917}
1918
1919#[cfg(feature = "alloc")]
1920impl<'de, T, TAs1, TAs2, TAs3, TAs4> DeserializeAs<'de, T> for PickFirst<(TAs1, TAs2, TAs3, TAs4)>
1921where
1922 TAs1: DeserializeAs<'de, T>,
1923 TAs2: DeserializeAs<'de, T>,
1924 TAs3: DeserializeAs<'de, T>,
1925 TAs4: DeserializeAs<'de, T>,
1926{
1927 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1928 where
1929 D: Deserializer<'de>,
1930 {
1931 let is_hr = deserializer.is_human_readable();
1932 let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1933
1934 let first_err: D::Error = match <DeserializeAsWrap<T, TAs1>>::deserialize(
1935 content::de::ContentRefDeserializer::new(&content, is_hr),
1936 ) {
1937 Ok(first) => return Ok(first.into_inner()),
1938 Err(err) => err,
1939 };
1940 let second_err: D::Error = match <DeserializeAsWrap<T, TAs2>>::deserialize(
1941 content::de::ContentRefDeserializer::new(&content, is_hr),
1942 ) {
1943 Ok(second) => return Ok(second.into_inner()),
1944 Err(err) => err,
1945 };
1946 let third_err: D::Error = match <DeserializeAsWrap<T, TAs3>>::deserialize(
1947 content::de::ContentRefDeserializer::new(&content, is_hr),
1948 ) {
1949 Ok(third) => return Ok(third.into_inner()),
1950 Err(err) => err,
1951 };
1952 let fourth_err: D::Error = match <DeserializeAsWrap<T, TAs4>>::deserialize(
1953 content::de::ContentDeserializer::new(content, is_hr),
1954 ) {
1955 Ok(fourth) => return Ok(fourth.into_inner()),
1956 Err(err) => err,
1957 };
1958 Err(DeError::custom(format_args!(
1959 "PickFirst could not deserialize any variant:\n First: {first_err}\n Second: {second_err}\n Third: {third_err}\n Fourth: {fourth_err}",
1960 )))
1961 }
1962}
1963
1964impl<'de, T, U> DeserializeAs<'de, T> for FromInto<U>
1965where
1966 U: Into<T>,
1967 U: Deserialize<'de>,
1968{
1969 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1970 where
1971 D: Deserializer<'de>,
1972 {
1973 Ok(U::deserialize(deserializer)?.into())
1974 }
1975}
1976
1977impl<'de, T, U> DeserializeAs<'de, T> for TryFromInto<U>
1978where
1979 U: TryInto<T>,
1980 <U as TryInto<T>>::Error: Display,
1981 U: Deserialize<'de>,
1982{
1983 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1984 where
1985 D: Deserializer<'de>,
1986 {
1987 U::deserialize(deserializer)?
1988 .try_into()
1989 .map_err(DeError::custom)
1990 }
1991}
1992
1993impl<'de, T, U> DeserializeAs<'de, T> for FromIntoRef<U>
1994where
1995 U: Into<T>,
1996 U: Deserialize<'de>,
1997{
1998 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1999 where
2000 D: Deserializer<'de>,
2001 {
2002 Ok(U::deserialize(deserializer)?.into())
2003 }
2004}
2005
2006impl<'de, T, U> DeserializeAs<'de, T> for TryFromIntoRef<U>
2007where
2008 U: TryInto<T>,
2009 <U as TryInto<T>>::Error: Display,
2010 U: Deserialize<'de>,
2011{
2012 fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
2013 where
2014 D: Deserializer<'de>,
2015 {
2016 U::deserialize(deserializer)?
2017 .try_into()
2018 .map_err(DeError::custom)
2019 }
2020}
2021
2022#[cfg(feature = "alloc")]
2023impl<'de> DeserializeAs<'de, Cow<'de, str>> for BorrowCow {
2024 fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, str>, D::Error>
2025 where
2026 D: Deserializer<'de>,
2027 {
2028 struct CowVisitor;
2029
2030 impl<'de> Visitor<'de> for CowVisitor {
2031 type Value = Cow<'de, str>;
2032
2033 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2034 formatter.write_str("an optionally borrowed string")
2035 }
2036
2037 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
2038 where
2039 E: DeError,
2040 {
2041 Ok(Cow::Borrowed(v))
2042 }
2043
2044 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
2045 where
2046 E: DeError,
2047 {
2048 Ok(Cow::Owned(v.to_owned()))
2049 }
2050
2051 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
2052 where
2053 E: DeError,
2054 {
2055 Ok(Cow::Owned(v))
2056 }
2057 }
2058
2059 deserializer.deserialize_string(CowVisitor)
2060 }
2061}
2062
2063#[cfg(feature = "alloc")]
2064impl<'de> DeserializeAs<'de, Cow<'de, [u8]>> for BorrowCow {
2065 fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8]>, D::Error>
2066 where
2067 D: Deserializer<'de>,
2068 {
2069 Bytes::deserialize_as(deserializer)
2070 }
2071}
2072
2073#[cfg(feature = "alloc")]
2074impl<'de, const N: usize> DeserializeAs<'de, Cow<'de, [u8; N]>> for BorrowCow {
2075 fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8; N]>, D::Error>
2076 where
2077 D: Deserializer<'de>,
2078 {
2079 Bytes::deserialize_as(deserializer)
2080 }
2081}
2082
2083impl<'de> DeserializeAs<'de, bool> for BoolFromInt<Strict> {
2084 fn deserialize_as<D>(deserializer: D) -> Result<bool, D::Error>
2085 where
2086 D: Deserializer<'de>,
2087 {
2088 struct U8Visitor;
2089 impl Visitor<'_> for U8Visitor {
2090 type Value = bool;
2091
2092 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2093 formatter.write_str("an integer 0 or 1")
2094 }
2095
2096 fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
2097 where
2098 E: DeError,
2099 {
2100 match v {
2101 0 => Ok(false),
2102 1 => Ok(true),
2103 unexp => Err(DeError::invalid_value(
2104 Unexpected::Unsigned(u64::from(unexp)),
2105 &"0 or 1",
2106 )),
2107 }
2108 }
2109
2110 fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
2111 where
2112 E: DeError,
2113 {
2114 match v {
2115 0 => Ok(false),
2116 1 => Ok(true),
2117 unexp => Err(DeError::invalid_value(
2118 Unexpected::Signed(i64::from(unexp)),
2119 &"0 or 1",
2120 )),
2121 }
2122 }
2123
2124 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
2125 where
2126 E: DeError,
2127 {
2128 match v {
2129 0 => Ok(false),
2130 1 => Ok(true),
2131 unexp => Err(DeError::invalid_value(
2132 Unexpected::Unsigned(unexp),
2133 &"0 or 1",
2134 )),
2135 }
2136 }
2137
2138 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
2139 where
2140 E: DeError,
2141 {
2142 match v {
2143 0 => Ok(false),
2144 1 => Ok(true),
2145 unexp => Err(DeError::invalid_value(Unexpected::Signed(unexp), &"0 or 1")),
2146 }
2147 }
2148
2149 fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
2150 where
2151 E: DeError,
2152 {
2153 match v {
2154 0 => Ok(false),
2155 1 => Ok(true),
2156 unexp => {
2157 let mut buf: [u8; 58] = [0u8; 58];
2158 Err(DeError::invalid_value(
2159 utils::get_unexpected_u128(unexp, &mut buf),
2160 &self,
2161 ))
2162 }
2163 }
2164 }
2165
2166 fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
2167 where
2168 E: DeError,
2169 {
2170 match v {
2171 0 => Ok(false),
2172 1 => Ok(true),
2173 unexp => {
2174 let mut buf: [u8; 58] = [0u8; 58];
2175 Err(DeError::invalid_value(
2176 utils::get_unexpected_i128(unexp, &mut buf),
2177 &"0 or 1",
2178 ))
2179 }
2180 }
2181 }
2182 }
2183
2184 deserializer.deserialize_u8(U8Visitor)
2185 }
2186}
2187
2188impl<'de> DeserializeAs<'de, bool> for BoolFromInt<Flexible> {
2189 fn deserialize_as<D>(deserializer: D) -> Result<bool, D::Error>
2190 where
2191 D: Deserializer<'de>,
2192 {
2193 struct U8Visitor;
2194 impl Visitor<'_> for U8Visitor {
2195 type Value = bool;
2196
2197 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2198 formatter.write_str("an integer")
2199 }
2200
2201 fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
2202 where
2203 E: DeError,
2204 {
2205 Ok(v != 0)
2206 }
2207
2208 fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
2209 where
2210 E: DeError,
2211 {
2212 Ok(v != 0)
2213 }
2214
2215 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
2216 where
2217 E: DeError,
2218 {
2219 Ok(v != 0)
2220 }
2221
2222 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
2223 where
2224 E: DeError,
2225 {
2226 Ok(v != 0)
2227 }
2228
2229 fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
2230 where
2231 E: DeError,
2232 {
2233 Ok(v != 0)
2234 }
2235
2236 fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
2237 where
2238 E: DeError,
2239 {
2240 Ok(v != 0)
2241 }
2242 }
2243
2244 deserializer.deserialize_u8(U8Visitor)
2245 }
2246}
2247
2248