serde_with/de/
impls.rs

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///////////////////////////////////////////////////////////////////////////////
13// Helper macro used internally
14
15#[cfg(feature = "alloc")]
16type BoxedSlice<T> = Box<[T]>;
17
18pub(crate) mod macros {
19    // The unused_imports lint has false-positives around macros
20    // https://github.com/rust-lang/rust/issues/78894
21    #![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    // Make the macros available to the rest of the crate
118    pub(crate) use foreach_map;
119    pub(crate) use foreach_seq;
120    pub(crate) use foreach_set;
121}
122
123///////////////////////////////////////////////////////////////////////////////
124// region: Simple Wrapper types (e.g., Box, Option)
125
126#[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// endregion
412///////////////////////////////////////////////////////////////////////////////
413// region: Collection Types (e.g., Maps, Sets, Vec)
414
415#[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// Option does not implement FromIterator directly, so we need a different implementation
749#[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
861// endregion
862///////////////////////////////////////////////////////////////////////////////
863// region: Conversion types which cause different serialization behavior
864
865impl<'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            // handles the `null` case
956            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
1085macro_rules! use_signed_duration {
1086    (
1087        $main_trait:ident $internal_trait:ident =>
1088        {
1089            $ty:ty; $converter:ident =>
1090            $({
1091                $format:ty, $strictness:ty =>
1092                $($tbound:ident: $bound:ident $(,)?)*
1093            })*
1094        }
1095    ) => {
1096        $(
1097            impl<'de, $($tbound,)*> DeserializeAs<'de, $ty> for $main_trait<$format, $strictness>
1098            where
1099                $($tbound: $bound,)*
1100            {
1101                fn deserialize_as<D>(deserializer: D) -> Result<$ty, D::Error>
1102                where
1103                    D: Deserializer<'de>,
1104                {
1105                    let dur: DurationSigned = $internal_trait::<$format, $strictness>::deserialize_as(deserializer)?;
1106                    dur.$converter::<D>()
1107                }
1108            }
1109        )*
1110    };
1111    (
1112        $( $main_trait:ident $internal_trait:ident, )+ => $rest:tt
1113    ) => {
1114        $( use_signed_duration!($main_trait $internal_trait => $rest); )+
1115    };
1116}
1117
1118use_signed_duration!(
1119    DurationSeconds DurationSeconds,
1120    DurationMilliSeconds DurationMilliSeconds,
1121    DurationMicroSeconds DurationMicroSeconds,
1122    DurationNanoSeconds DurationNanoSeconds,
1123    => {
1124        Duration; to_std_duration =>
1125        {u64, Strict =>}
1126        {FORMAT, Flexible => FORMAT: Format}
1127    }
1128);
1129#[cfg(feature = "alloc")]
1130use_signed_duration!(
1131    DurationSeconds DurationSeconds,
1132    DurationMilliSeconds DurationMilliSeconds,
1133    DurationMicroSeconds DurationMicroSeconds,
1134    DurationNanoSeconds DurationNanoSeconds,
1135    => {
1136        Duration; to_std_duration =>
1137        {String, Strict =>}
1138    }
1139);
1140#[cfg(feature = "std")]
1141use_signed_duration!(
1142    DurationSeconds DurationSeconds,
1143    DurationMilliSeconds DurationMilliSeconds,
1144    DurationMicroSeconds DurationMicroSeconds,
1145    DurationNanoSeconds DurationNanoSeconds,
1146    => {
1147        Duration; to_std_duration =>
1148        // round() only works on std
1149        {f64, Strict =>}
1150    }
1151);
1152use_signed_duration!(
1153    DurationSecondsWithFrac DurationSecondsWithFrac,
1154    DurationMilliSecondsWithFrac DurationMilliSecondsWithFrac,
1155    DurationMicroSecondsWithFrac DurationMicroSecondsWithFrac,
1156    DurationNanoSecondsWithFrac DurationNanoSecondsWithFrac,
1157    => {
1158        Duration; to_std_duration =>
1159        {f64, Strict =>}
1160        {FORMAT, Flexible => FORMAT: Format}
1161    }
1162);
1163#[cfg(feature = "alloc")]
1164use_signed_duration!(
1165    DurationSecondsWithFrac DurationSecondsWithFrac,
1166    DurationMilliSecondsWithFrac DurationMilliSecondsWithFrac,
1167    DurationMicroSecondsWithFrac DurationMicroSecondsWithFrac,
1168    DurationNanoSecondsWithFrac DurationNanoSecondsWithFrac,
1169    => {
1170        Duration; to_std_duration =>
1171        {String, Strict =>}
1172    }
1173);
1174
1175#[cfg(feature = "std")]
1176use_signed_duration!(
1177    TimestampSeconds DurationSeconds,
1178    TimestampMilliSeconds DurationMilliSeconds,
1179    TimestampMicroSeconds DurationMicroSeconds,
1180    TimestampNanoSeconds DurationNanoSeconds,
1181    => {
1182        SystemTime; to_system_time =>
1183        {i64, Strict =>}
1184        {f64, Strict =>}
1185        {String, Strict =>}
1186        {FORMAT, Flexible => FORMAT: Format}
1187    }
1188);
1189#[cfg(feature = "std")]
1190use_signed_duration!(
1191    TimestampSecondsWithFrac DurationSecondsWithFrac,
1192    TimestampMilliSecondsWithFrac DurationMilliSecondsWithFrac,
1193    TimestampMicroSecondsWithFrac DurationMicroSecondsWithFrac,
1194    TimestampNanoSecondsWithFrac DurationNanoSecondsWithFrac,
1195    => {
1196        SystemTime; to_system_time =>
1197        {f64, Strict =>}
1198        {String, Strict =>}
1199        {FORMAT, Flexible => FORMAT: Format}
1200    }
1201);
1202
1203impl<'de, T, U> DeserializeAs<'de, T> for DefaultOnNull<U>
1204where
1205    U: DeserializeAs<'de, T>,
1206    T: Default,
1207{
1208    fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1209    where
1210        D: Deserializer<'de>,
1211    {
1212        Ok(Option::<U>::deserialize_as(deserializer)?.unwrap_or_default())
1213    }
1214}
1215
1216impl<'de> DeserializeAs<'de, &'de [u8]> for Bytes {
1217    fn deserialize_as<D>(deserializer: D) -> Result<&'de [u8], D::Error>
1218    where
1219        D: Deserializer<'de>,
1220    {
1221        <&'de [u8]>::deserialize(deserializer)
1222    }
1223}
1224
1225// serde_bytes implementation for ByteBuf
1226// https://github.com/serde-rs/bytes/blob/cbae606b9dc225fc094b031cc84eac9493da2058/src/bytebuf.rs#L196
1227//
1228// Implements:
1229// * visit_seq
1230// * visit_bytes
1231// * visit_byte_buf
1232// * visit_str
1233// * visit_string
1234#[cfg(feature = "alloc")]
1235impl<'de> DeserializeAs<'de, Vec<u8>> for Bytes {
1236    fn deserialize_as<D>(deserializer: D) -> Result<Vec<u8>, D::Error>
1237    where
1238        D: Deserializer<'de>,
1239    {
1240        struct VecVisitor;
1241
1242        impl<'de> Visitor<'de> for VecVisitor {
1243            type Value = Vec<u8>;
1244
1245            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1246                formatter.write_str("a byte array")
1247            }
1248
1249            fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1250            where
1251                A: SeqAccess<'de>,
1252            {
1253                utils::SeqIter::new(seq).collect::<Result<_, _>>()
1254            }
1255
1256            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1257            where
1258                E: DeError,
1259            {
1260                Ok(v.to_vec())
1261            }
1262
1263            fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1264            where
1265                E: DeError,
1266            {
1267                Ok(v)
1268            }
1269
1270            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1271            where
1272                E: DeError,
1273            {
1274                Ok(v.as_bytes().to_vec())
1275            }
1276
1277            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1278            where
1279                E: DeError,
1280            {
1281                Ok(v.into_bytes())
1282            }
1283        }
1284
1285        deserializer.deserialize_byte_buf(VecVisitor)
1286    }
1287}
1288
1289#[cfg(feature = "alloc")]
1290impl<'de> DeserializeAs<'de, Box<[u8]>> for Bytes {
1291    fn deserialize_as<D>(deserializer: D) -> Result<Box<[u8]>, D::Error>
1292    where
1293        D: Deserializer<'de>,
1294    {
1295        <Bytes as DeserializeAs<'de, Vec<u8>>>::deserialize_as(deserializer)
1296            .map(Vec::into_boxed_slice)
1297    }
1298}
1299
1300// serde_bytes implementation for Cow<'a, [u8]>
1301// https://github.com/serde-rs/bytes/blob/cbae606b9dc225fc094b031cc84eac9493da2058/src/de.rs#L77
1302//
1303// Implements:
1304// * visit_borrowed_bytes
1305// * visit_borrowed_str
1306// * visit_bytes
1307// * visit_str
1308// * visit_byte_buf
1309// * visit_string
1310// * visit_seq
1311#[cfg(feature = "alloc")]
1312impl<'de> DeserializeAs<'de, Cow<'de, [u8]>> for Bytes {
1313    fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8]>, D::Error>
1314    where
1315        D: Deserializer<'de>,
1316    {
1317        struct CowVisitor;
1318
1319        impl<'de> Visitor<'de> for CowVisitor {
1320            type Value = Cow<'de, [u8]>;
1321
1322            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1323                formatter.write_str("a byte array")
1324            }
1325
1326            fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
1327            where
1328                E: DeError,
1329            {
1330                Ok(Cow::Borrowed(v))
1331            }
1332
1333            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
1334            where
1335                E: DeError,
1336            {
1337                Ok(Cow::Borrowed(v.as_bytes()))
1338            }
1339
1340            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1341            where
1342                E: DeError,
1343            {
1344                Ok(Cow::Owned(v.to_vec()))
1345            }
1346
1347            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1348            where
1349                E: DeError,
1350            {
1351                Ok(Cow::Owned(v.as_bytes().to_vec()))
1352            }
1353
1354            fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1355            where
1356                E: DeError,
1357            {
1358                Ok(Cow::Owned(v))
1359            }
1360
1361            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1362            where
1363                E: DeError,
1364            {
1365                Ok(Cow::Owned(v.into_bytes()))
1366            }
1367
1368            fn visit_seq<V>(self, seq: V) -> Result<Self::Value, V::Error>
1369            where
1370                V: SeqAccess<'de>,
1371            {
1372                Ok(Cow::Owned(
1373                    utils::SeqIter::new(seq).collect::<Result<_, _>>()?,
1374                ))
1375            }
1376        }
1377
1378        deserializer.deserialize_bytes(CowVisitor)
1379    }
1380}
1381
1382impl<'de, const N: usize> DeserializeAs<'de, [u8; N]> for Bytes {
1383    fn deserialize_as<D>(deserializer: D) -> Result<[u8; N], D::Error>
1384    where
1385        D: Deserializer<'de>,
1386    {
1387        struct ArrayVisitor<const M: usize>;
1388
1389        impl<'de, const M: usize> Visitor<'de> for ArrayVisitor<M> {
1390            type Value = [u8; M];
1391
1392            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1393                formatter.write_fmt(format_args!("an byte array of size {M}"))
1394            }
1395
1396            fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1397            where
1398                A: SeqAccess<'de>,
1399            {
1400                utils::array_from_iterator(utils::SeqIter::new(seq), &self)
1401            }
1402
1403            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1404            where
1405                E: DeError,
1406            {
1407                v.try_into()
1408                    .map_err(|_| DeError::invalid_length(v.len(), &self))
1409            }
1410
1411            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1412            where
1413                E: DeError,
1414            {
1415                v.as_bytes()
1416                    .try_into()
1417                    .map_err(|_| DeError::invalid_length(v.len(), &self))
1418            }
1419        }
1420
1421        deserializer.deserialize_bytes(ArrayVisitor::<N>)
1422    }
1423}
1424
1425impl<'de, const N: usize> DeserializeAs<'de, &'de [u8; N]> for Bytes {
1426    fn deserialize_as<D>(deserializer: D) -> Result<&'de [u8; N], D::Error>
1427    where
1428        D: Deserializer<'de>,
1429    {
1430        struct ArrayVisitor<const M: usize>;
1431
1432        impl<'de, const M: usize> Visitor<'de> for ArrayVisitor<M> {
1433            type Value = &'de [u8; M];
1434
1435            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1436                formatter.write_fmt(format_args!("a borrowed byte array of size {M}"))
1437            }
1438
1439            fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
1440            where
1441                E: DeError,
1442            {
1443                v.try_into()
1444                    .map_err(|_| DeError::invalid_length(v.len(), &self))
1445            }
1446
1447            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
1448            where
1449                E: DeError,
1450            {
1451                v.as_bytes()
1452                    .try_into()
1453                    .map_err(|_| DeError::invalid_length(v.len(), &self))
1454            }
1455        }
1456
1457        deserializer.deserialize_bytes(ArrayVisitor::<N>)
1458    }
1459}
1460
1461#[cfg(feature = "alloc")]
1462impl<'de, const N: usize> DeserializeAs<'de, Cow<'de, [u8; N]>> for Bytes {
1463    fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8; N]>, D::Error>
1464    where
1465        D: Deserializer<'de>,
1466    {
1467        struct CowVisitor<const M: usize>;
1468
1469        impl<'de, const M: usize> Visitor<'de> for CowVisitor<M> {
1470            type Value = Cow<'de, [u8; M]>;
1471
1472            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1473                formatter.write_str("a byte array")
1474            }
1475
1476            fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
1477            where
1478                E: DeError,
1479            {
1480                Ok(Cow::Borrowed(
1481                    v.try_into()
1482                        .map_err(|_| DeError::invalid_length(v.len(), &self))?,
1483                ))
1484            }
1485
1486            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
1487            where
1488                E: DeError,
1489            {
1490                Ok(Cow::Borrowed(
1491                    v.as_bytes()
1492                        .try_into()
1493                        .map_err(|_| DeError::invalid_length(v.len(), &self))?,
1494                ))
1495            }
1496
1497            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1498            where
1499                E: DeError,
1500            {
1501                Ok(Cow::Owned(
1502                    v.to_vec()
1503                        .try_into()
1504                        .map_err(|_| DeError::invalid_length(v.len(), &self))?,
1505                ))
1506            }
1507
1508            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1509            where
1510                E: DeError,
1511            {
1512                Ok(Cow::Owned(
1513                    v.as_bytes()
1514                        .to_vec()
1515                        .try_into()
1516                        .map_err(|_| DeError::invalid_length(v.len(), &self))?,
1517                ))
1518            }
1519
1520            fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
1521            where
1522                E: DeError,
1523            {
1524                let len = v.len();
1525                Ok(Cow::Owned(
1526                    v.try_into()
1527                        .map_err(|_| DeError::invalid_length(len, &self))?,
1528                ))
1529            }
1530
1531            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1532            where
1533                E: DeError,
1534            {
1535                let len = v.len();
1536                Ok(Cow::Owned(
1537                    v.into_bytes()
1538                        .try_into()
1539                        .map_err(|_| DeError::invalid_length(len, &self))?,
1540                ))
1541            }
1542
1543            fn visit_seq<V>(self, seq: V) -> Result<Self::Value, V::Error>
1544            where
1545                V: SeqAccess<'de>,
1546            {
1547                Ok(Cow::Owned(utils::array_from_iterator(
1548                    utils::SeqIter::new(seq),
1549                    &self,
1550                )?))
1551            }
1552        }
1553
1554        deserializer.deserialize_bytes(CowVisitor)
1555    }
1556}
1557
1558#[cfg(feature = "alloc")]
1559impl<'de, const N: usize> DeserializeAs<'de, Box<[u8; N]>> for Bytes {
1560    fn deserialize_as<D>(deserializer: D) -> Result<Box<[u8; N]>, D::Error>
1561    where
1562        D: Deserializer<'de>,
1563    {
1564        Bytes::deserialize_as(deserializer).map(Box::new)
1565    }
1566}
1567
1568#[cfg(feature = "alloc")]
1569impl<'de, T, TAs, FORMAT> DeserializeAs<'de, Vec<T>> for OneOrMany<TAs, FORMAT>
1570where
1571    TAs: DeserializeAs<'de, T>,
1572    FORMAT: Format,
1573{
1574    fn deserialize_as<D>(deserializer: D) -> Result<Vec<T>, D::Error>
1575    where
1576        D: Deserializer<'de>,
1577    {
1578        let is_hr = deserializer.is_human_readable();
1579        let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1580
1581        let one_err: D::Error = match <DeserializeAsWrap<T, TAs>>::deserialize(
1582            content::de::ContentRefDeserializer::new(&content, is_hr),
1583        ) {
1584            Ok(one) => return Ok(alloc::vec![one.into_inner()]),
1585            Err(err) => err,
1586        };
1587        let many_err: D::Error = match <DeserializeAsWrap<Vec<T>, Vec<TAs>>>::deserialize(
1588            content::de::ContentDeserializer::new(content, is_hr),
1589        ) {
1590            Ok(many) => return Ok(many.into_inner()),
1591            Err(err) => err,
1592        };
1593        Err(DeError::custom(format_args!(
1594            "OneOrMany could not deserialize any variant:\n  One: {one_err}\n  Many: {many_err}"
1595        )))
1596    }
1597}
1598
1599#[cfg(feature = "alloc")]
1600impl<'de, T, TAs1> DeserializeAs<'de, T> for PickFirst<(TAs1,)>
1601where
1602    TAs1: DeserializeAs<'de, T>,
1603{
1604    fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1605    where
1606        D: Deserializer<'de>,
1607    {
1608        Ok(DeserializeAsWrap::<T, TAs1>::deserialize(deserializer)?.into_inner())
1609    }
1610}
1611
1612#[cfg(feature = "alloc")]
1613impl<'de, T, TAs1, TAs2> DeserializeAs<'de, T> for PickFirst<(TAs1, TAs2)>
1614where
1615    TAs1: DeserializeAs<'de, T>,
1616    TAs2: DeserializeAs<'de, T>,
1617{
1618    fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1619    where
1620        D: Deserializer<'de>,
1621    {
1622        let is_hr = deserializer.is_human_readable();
1623        let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1624
1625        let first_err: D::Error = match <DeserializeAsWrap<T, TAs1>>::deserialize(
1626            content::de::ContentRefDeserializer::new(&content, is_hr),
1627        ) {
1628            Ok(first) => return Ok(first.into_inner()),
1629            Err(err) => err,
1630        };
1631        let second_err: D::Error = match <DeserializeAsWrap<T, TAs2>>::deserialize(
1632            content::de::ContentDeserializer::new(content, is_hr),
1633        ) {
1634            Ok(second) => return Ok(second.into_inner()),
1635            Err(err) => err,
1636        };
1637        Err(DeError::custom(format_args!(
1638            "PickFirst could not deserialize any variant:\n  First: {first_err}\n  Second: {second_err}"
1639        )))
1640    }
1641}
1642
1643#[cfg(feature = "alloc")]
1644impl<'de, T, TAs1, TAs2, TAs3> DeserializeAs<'de, T> for PickFirst<(TAs1, TAs2, TAs3)>
1645where
1646    TAs1: DeserializeAs<'de, T>,
1647    TAs2: DeserializeAs<'de, T>,
1648    TAs3: DeserializeAs<'de, T>,
1649{
1650    fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1651    where
1652        D: Deserializer<'de>,
1653    {
1654        let is_hr = deserializer.is_human_readable();
1655        let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1656
1657        let first_err: D::Error = match <DeserializeAsWrap<T, TAs1>>::deserialize(
1658            content::de::ContentRefDeserializer::new(&content, is_hr),
1659        ) {
1660            Ok(first) => return Ok(first.into_inner()),
1661            Err(err) => err,
1662        };
1663        let second_err: D::Error = match <DeserializeAsWrap<T, TAs2>>::deserialize(
1664            content::de::ContentRefDeserializer::new(&content, is_hr),
1665        ) {
1666            Ok(second) => return Ok(second.into_inner()),
1667            Err(err) => err,
1668        };
1669        let third_err: D::Error = match <DeserializeAsWrap<T, TAs3>>::deserialize(
1670            content::de::ContentDeserializer::new(content, is_hr),
1671        ) {
1672            Ok(third) => return Ok(third.into_inner()),
1673            Err(err) => err,
1674        };
1675        Err(DeError::custom(format_args!(
1676            "PickFirst could not deserialize any variant:\n  First: {first_err}\n  Second: {second_err}\n  Third: {third_err}",
1677        )))
1678    }
1679}
1680
1681#[cfg(feature = "alloc")]
1682impl<'de, T, TAs1, TAs2, TAs3, TAs4> DeserializeAs<'de, T> for PickFirst<(TAs1, TAs2, TAs3, TAs4)>
1683where
1684    TAs1: DeserializeAs<'de, T>,
1685    TAs2: DeserializeAs<'de, T>,
1686    TAs3: DeserializeAs<'de, T>,
1687    TAs4: DeserializeAs<'de, T>,
1688{
1689    fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1690    where
1691        D: Deserializer<'de>,
1692    {
1693        let is_hr = deserializer.is_human_readable();
1694        let content: content::de::Content<'de> = Deserialize::deserialize(deserializer)?;
1695
1696        let first_err: D::Error = match <DeserializeAsWrap<T, TAs1>>::deserialize(
1697            content::de::ContentRefDeserializer::new(&content, is_hr),
1698        ) {
1699            Ok(first) => return Ok(first.into_inner()),
1700            Err(err) => err,
1701        };
1702        let second_err: D::Error = match <DeserializeAsWrap<T, TAs2>>::deserialize(
1703            content::de::ContentRefDeserializer::new(&content, is_hr),
1704        ) {
1705            Ok(second) => return Ok(second.into_inner()),
1706            Err(err) => err,
1707        };
1708        let third_err: D::Error = match <DeserializeAsWrap<T, TAs3>>::deserialize(
1709            content::de::ContentRefDeserializer::new(&content, is_hr),
1710        ) {
1711            Ok(third) => return Ok(third.into_inner()),
1712            Err(err) => err,
1713        };
1714        let fourth_err: D::Error = match <DeserializeAsWrap<T, TAs4>>::deserialize(
1715            content::de::ContentDeserializer::new(content, is_hr),
1716        ) {
1717            Ok(fourth) => return Ok(fourth.into_inner()),
1718            Err(err) => err,
1719        };
1720        Err(DeError::custom(format_args!(
1721            "PickFirst could not deserialize any variant:\n  First: {first_err}\n  Second: {second_err}\n  Third: {third_err}\n  Fourth: {fourth_err}",
1722        )))
1723    }
1724}
1725
1726impl<'de, T, U> DeserializeAs<'de, T> for FromInto<U>
1727where
1728    U: Into<T>,
1729    U: Deserialize<'de>,
1730{
1731    fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1732    where
1733        D: Deserializer<'de>,
1734    {
1735        Ok(U::deserialize(deserializer)?.into())
1736    }
1737}
1738
1739impl<'de, T, U> DeserializeAs<'de, T> for TryFromInto<U>
1740where
1741    U: TryInto<T>,
1742    <U as TryInto<T>>::Error: Display,
1743    U: Deserialize<'de>,
1744{
1745    fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1746    where
1747        D: Deserializer<'de>,
1748    {
1749        U::deserialize(deserializer)?
1750            .try_into()
1751            .map_err(DeError::custom)
1752    }
1753}
1754
1755impl<'de, T, U> DeserializeAs<'de, T> for FromIntoRef<U>
1756where
1757    U: Into<T>,
1758    U: Deserialize<'de>,
1759{
1760    fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1761    where
1762        D: Deserializer<'de>,
1763    {
1764        Ok(U::deserialize(deserializer)?.into())
1765    }
1766}
1767
1768impl<'de, T, U> DeserializeAs<'de, T> for TryFromIntoRef<U>
1769where
1770    U: TryInto<T>,
1771    <U as TryInto<T>>::Error: Display,
1772    U: Deserialize<'de>,
1773{
1774    fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
1775    where
1776        D: Deserializer<'de>,
1777    {
1778        U::deserialize(deserializer)?
1779            .try_into()
1780            .map_err(DeError::custom)
1781    }
1782}
1783
1784#[cfg(feature = "alloc")]
1785impl<'de> DeserializeAs<'de, Cow<'de, str>> for BorrowCow {
1786    fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, str>, D::Error>
1787    where
1788        D: Deserializer<'de>,
1789    {
1790        struct CowVisitor;
1791
1792        impl<'de> Visitor<'de> for CowVisitor {
1793            type Value = Cow<'de, str>;
1794
1795            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1796                formatter.write_str("an optionally borrowed string")
1797            }
1798
1799            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
1800            where
1801                E: DeError,
1802            {
1803                Ok(Cow::Borrowed(v))
1804            }
1805
1806            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1807            where
1808                E: DeError,
1809            {
1810                Ok(Cow::Owned(v.to_owned()))
1811            }
1812
1813            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
1814            where
1815                E: DeError,
1816            {
1817                Ok(Cow::Owned(v))
1818            }
1819        }
1820
1821        deserializer.deserialize_string(CowVisitor)
1822    }
1823}
1824
1825#[cfg(feature = "alloc")]
1826impl<'de> DeserializeAs<'de, Cow<'de, [u8]>> for BorrowCow {
1827    fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8]>, D::Error>
1828    where
1829        D: Deserializer<'de>,
1830    {
1831        Bytes::deserialize_as(deserializer)
1832    }
1833}
1834
1835#[cfg(feature = "alloc")]
1836impl<'de, const N: usize> DeserializeAs<'de, Cow<'de, [u8; N]>> for BorrowCow {
1837    fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8; N]>, D::Error>
1838    where
1839        D: Deserializer<'de>,
1840    {
1841        Bytes::deserialize_as(deserializer)
1842    }
1843}
1844
1845impl<'de> DeserializeAs<'de, bool> for BoolFromInt<Strict> {
1846    fn deserialize_as<D>(deserializer: D) -> Result<bool, D::Error>
1847    where
1848        D: Deserializer<'de>,
1849    {
1850        struct U8Visitor;
1851        impl Visitor<'_> for U8Visitor {
1852            type Value = bool;
1853
1854            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1855                formatter.write_str("an integer 0 or 1")
1856            }
1857
1858            fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
1859            where
1860                E: DeError,
1861            {
1862                match v {
1863                    0 => Ok(false),
1864                    1 => Ok(true),
1865                    unexp => Err(DeError::invalid_value(
1866                        Unexpected::Unsigned(u64::from(unexp)),
1867                        &"0 or 1",
1868                    )),
1869                }
1870            }
1871
1872            fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
1873            where
1874                E: DeError,
1875            {
1876                match v {
1877                    0 => Ok(false),
1878                    1 => Ok(true),
1879                    unexp => Err(DeError::invalid_value(
1880                        Unexpected::Signed(i64::from(unexp)),
1881                        &"0 or 1",
1882                    )),
1883                }
1884            }
1885
1886            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
1887            where
1888                E: DeError,
1889            {
1890                match v {
1891                    0 => Ok(false),
1892                    1 => Ok(true),
1893                    unexp => Err(DeError::invalid_value(
1894                        Unexpected::Unsigned(unexp),
1895                        &"0 or 1",
1896                    )),
1897                }
1898            }
1899
1900            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
1901            where
1902                E: DeError,
1903            {
1904                match v {
1905                    0 => Ok(false),
1906                    1 => Ok(true),
1907                    unexp => Err(DeError::invalid_value(Unexpected::Signed(unexp), &"0 or 1")),
1908                }
1909            }
1910
1911            fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
1912            where
1913                E: DeError,
1914            {
1915                match v {
1916                    0 => Ok(false),
1917                    1 => Ok(true),
1918                    unexp => {
1919                        let mut buf: [u8; 58] = [0u8; 58];
1920                        Err(DeError::invalid_value(
1921                            crate::utils::get_unexpected_u128(unexp, &mut buf),
1922                            &self,
1923                        ))
1924                    }
1925                }
1926            }
1927
1928            fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
1929            where
1930                E: DeError,
1931            {
1932                match v {
1933                    0 => Ok(false),
1934                    1 => Ok(true),
1935                    unexp => {
1936                        let mut buf: [u8; 58] = [0u8; 58];
1937                        Err(DeError::invalid_value(
1938                            crate::utils::get_unexpected_i128(unexp, &mut buf),
1939                            &"0 or 1",
1940                        ))
1941                    }
1942                }
1943            }
1944        }
1945
1946        deserializer.deserialize_u8(U8Visitor)
1947    }
1948}
1949
1950impl<'de> DeserializeAs<'de, bool> for BoolFromInt<Flexible> {
1951    fn deserialize_as<D>(deserializer: D) -> Result<bool, D::Error>
1952    where
1953        D: Deserializer<'de>,
1954    {
1955        struct U8Visitor;
1956        impl Visitor<'_> for U8Visitor {
1957            type Value = bool;
1958
1959            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1960                formatter.write_str("an integer")
1961            }
1962
1963            fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
1964            where
1965                E: DeError,
1966            {
1967                Ok(v != 0)
1968            }
1969
1970            fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
1971            where
1972                E: DeError,
1973            {
1974                Ok(v != 0)
1975            }
1976
1977            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
1978            where
1979                E: DeError,
1980            {
1981                Ok(v != 0)
1982            }
1983
1984            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
1985            where
1986                E: DeError,
1987            {
1988                Ok(v != 0)
1989            }
1990
1991            fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
1992            where
1993                E: DeError,
1994            {
1995                Ok(v != 0)
1996            }
1997
1998            fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
1999            where
2000                E: DeError,
2001            {
2002                Ok(v != 0)
2003            }
2004        }
2005
2006        deserializer.deserialize_u8(U8Visitor)
2007    }
2008}
2009
2010// endregion