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