Skip to main content

deser_core/adapters/
stock.rs

1//! The adapters provided by deser.
2use alloc::borrow::Cow;
3use alloc::collections::BTreeMap;
4use alloc::format;
5use alloc::string::ToString;
6use alloc::vec::Vec;
7use core::fmt::Display;
8#[cfg(feature = "std")]
9use core::hash::{BuildHasher, Hash};
10use core::marker::PhantomData;
11use core::mem::take;
12use core::str::FromStr;
13#[cfg(feature = "std")]
14use std::collections::HashMap;
15
16use crate::State;
17use crate::Text;
18use crate::adapted::{self, Adapted};
19use crate::adapters::Same;
20use crate::de::impls::{MapTarget, SeqTarget};
21use crate::de::lexical::parse_bool_with;
22use crate::de::mapped::MappedSink;
23use crate::de::{
24    Deserialize, DuplicateKeys, OwnedSink, Sink, SinkHandle, Slot, default_atom, is_null_atom,
25};
26use crate::error::{Error, ErrorKind, conversion_error};
27use crate::event::{Atom, Bytes, ContainerShape};
28use crate::ser::{Begin, Describe, Emit, Serialize, SerializeHandle};
29
30/// Deserializes a `Cow<str>` or `Cow<[u8]>` borrowed from the data.
31///
32/// `Cow` is deserialized owned by default so that `Cow<'static, str>` can
33/// be deserialized from any data.  With this adapter the data is borrowed
34/// if the data format passes it on borrowed (see
35/// [`Sink::borrowed_atom`]).  Otherwise it's owned.  Serialization is not
36/// affected.
37///
38/// ```
39/// use std::borrow::Cow;
40/// use deser::{Deserialize, Serialize};
41/// use deser::adapters::Borrowed;
42///
43/// #[derive(Serialize, Deserialize)]
44/// pub struct Message<'a> {
45///     #[deser(as = Borrowed)]
46///     text: Cow<'a, str>,
47///     #[deser(as = Vec<Borrowed>)]
48///     tags: Vec<Cow<'a, str>>,
49/// }
50/// ```
51pub struct Borrowed;
52
53impl<'de: 'a, 'a> Deserialize<'de, Cow<'a, str>> for Borrowed {
54    fn deserialize_atom(
55        slot: &mut Slot<Cow<'a, str>, Self>,
56        atom: Atom,
57        state: &mut State,
58    ) -> Result<(), Error> {
59        match atom {
60            Atom::Str(value) | Atom::Lexical(value) => {
61                slot.set(Cow::Owned(value.into_owned()));
62                Ok(())
63            }
64            Atom::Char(value) => {
65                slot.set(Cow::Owned(value.to_string()));
66                Ok(())
67            }
68            other => default_atom(slot, other, state),
69        }
70    }
71
72    fn deserialize_borrowed_atom(
73        slot: &mut Slot<Cow<'a, str>, Self>,
74        atom: Atom<'de>,
75        state: &mut State,
76    ) -> Result<(), Error> {
77        match atom {
78            Atom::Str(value) | Atom::Lexical(value) => {
79                slot.set(value.into_cow());
80                Ok(())
81            }
82            // strings take the text of values whose type was inferred
83            Atom::Implicit(value) => {
84                slot.set(value.into_parts().0.into_cow());
85                Ok(())
86            }
87            other => Self::deserialize_atom(slot, other, state),
88        }
89    }
90
91    fn expecting() -> Cow<'static, str> {
92        Cow::Borrowed("string")
93    }
94}
95
96impl<'de: 'a, 'a> Deserialize<'de, Cow<'a, [u8]>> for Borrowed {
97    fn deserialize_atom(
98        slot: &mut Slot<Cow<'a, [u8]>, Self>,
99        atom: Atom,
100        state: &mut State,
101    ) -> Result<(), Error> {
102        match atom {
103            Atom::Bytes(value) => {
104                slot.set(Cow::Owned(value.into_owned()));
105                Ok(())
106            }
107            // formats without native bytes represent them as strings
108            Atom::Str(ref value) => {
109                slot.set(Cow::Owned(crate::adapters::bytes::decode_str(
110                    value, state,
111                )?));
112                Ok(())
113            }
114            other => default_atom(slot, other, state),
115        }
116    }
117
118    fn deserialize_borrowed_atom(
119        slot: &mut Slot<Cow<'a, [u8]>, Self>,
120        atom: Atom<'de>,
121        state: &mut State,
122    ) -> Result<(), Error> {
123        match atom {
124            Atom::Bytes(value) => {
125                slot.set(value.into_data());
126                Ok(())
127            }
128            other => Self::deserialize_atom(slot, other, state),
129        }
130    }
131
132    fn expecting() -> Cow<'static, str> {
133        Cow::Borrowed("bytes")
134    }
135}
136
137impl<'a> Serialize<Cow<'a, str>> for Borrowed {
138    fn serialize<'b>(value: &'b Cow<'a, str>, _state: &mut State) -> Result<Emit<'b>, Error> {
139        Ok(Emit::Atom(Atom::Str(Text::borrowed(value))))
140    }
141}
142
143impl<'a> Serialize<Cow<'a, [u8]>> for Borrowed {
144    fn serialize<'b>(value: &'b Cow<'a, [u8]>, _state: &mut State) -> Result<Emit<'b>, Error> {
145        Ok(Emit::Atom(Atom::Bytes(Bytes::borrowed(value))))
146    }
147}
148
149/// Serializes with [`Display`] and deserializes with [`FromStr`].
150///
151/// The value is represented as a string.  Only strings are accepted when
152/// deserializing.
153///
154/// ```
155/// use std::net::IpAddr;
156/// use deser::{Deserialize, Serialize};
157/// use deser::adapters::DisplayFromStr;
158///
159/// #[derive(Serialize, Deserialize)]
160/// pub struct Server {
161///     #[deser(as = DisplayFromStr)]
162///     addr: IpAddr,
163/// }
164/// ```
165pub struct DisplayFromStr;
166
167impl<'de, T> Deserialize<'de, T> for DisplayFromStr
168where
169    T: FromStr + Send,
170    T::Err: Display,
171{
172    fn deserialize_atom(
173        slot: &mut Slot<T, Self>,
174        atom: Atom,
175        state: &mut State,
176    ) -> Result<(), Error> {
177        match atom {
178            Atom::Str(ref value) => match value.parse::<T>() {
179                Ok(value) => {
180                    slot.set(value);
181                    Ok(())
182                }
183                Err(err) => Err(Error::new(
184                    ErrorKind::InvalidValue,
185                    format!("invalid value: {}", err),
186                )),
187            },
188            other => default_atom(slot, other, state),
189        }
190    }
191
192    fn expecting() -> Cow<'static, str> {
193        Cow::Borrowed("string")
194    }
195
196    slot_atom_into!(T);
197}
198
199impl<T: Display + ?Sized> Serialize<T> for DisplayFromStr {
200    fn serialize<'a>(value: &'a T, _state: &mut State) -> Result<Emit<'a>, Error> {
201        Ok(Emit::Atom(Atom::Str(Text::owned(value.to_string()))))
202    }
203
204    #[inline]
205    fn __private_begin<'a>(value: &'a T, state: &mut State) -> Result<Begin<'a>, Error> {
206        Ok(Begin::emit(
207            Self::serialize(value, state)?,
208            ContainerShape::new(),
209            false,
210        ))
211    }
212}
213
214/// A flag that is set if its key is given.
215///
216/// This is for `bool` fields that are switched on by giving their key,
217/// like `?recursive` in a query string:
218///
219/// * if the key is missing, the flag is `false` (no `#[deser(default)]` is
220///   needed)
221/// * an empty value (`?recursive` or `?recursive=`) or null is `true`
222/// * other values are booleans, strings are parsed like
223///   [lexical atoms](crate::Atom::Lexical) (`?recursive=0` is `false`)
224///
225/// The flag is serialized as boolean.
226///
227/// ```
228/// use deser::adapters::Flag;
229///
230/// #[derive(deser::Deserialize, deser::Serialize)]
231/// pub struct Tree {
232///     #[deser(as = Flag, skip_serializing_if = std::ops::Not::not)]
233///     recursive: bool,
234/// }
235/// ```
236pub struct Flag;
237
238impl<'de> Deserialize<'de, bool> for Flag {
239    fn deserialize_atom(
240        slot: &mut Slot<bool, Self>,
241        atom: Atom,
242        state: &mut State,
243    ) -> Result<(), Error> {
244        let value = match atom {
245            Atom::Bool(value) => value,
246            Atom::Null => true,
247            Atom::Str(ref value) | Atom::Lexical(ref value) if value.is_empty() => true,
248            Atom::Str(ref value) | Atom::Lexical(ref value) => parse_bool_with(value, true, state)?,
249            other => return default_atom(slot, other, state),
250        };
251        slot.set(value);
252        Ok(())
253    }
254
255    fn expecting() -> Cow<'static, str> {
256        Cow::Borrowed("flag")
257    }
258
259    fn initial_value() -> Option<bool> {
260        Some(false)
261    }
262
263    slot_atom_into!(bool);
264}
265
266impl Serialize<bool> for Flag {
267    fn serialize<'a>(value: &'a bool, _state: &mut State) -> Result<Emit<'a>, Error> {
268        Ok(Emit::Atom(Atom::Bool(*value)))
269    }
270}
271
272/// Converts from and into another type.
273///
274/// The value is deserialized as `U` and converted with [`Into`] and it's
275/// serialized by cloning it and converting it into `U`.  The value is
276/// [optional](Serialize::is_optional) if the converted value is, which means
277/// that with `#[deser(skip_serializing_optionals)]` the value is cloned and
278/// converted once more to find out.
279///
280/// ```
281/// use deser::{Deserialize, Serialize};
282/// use deser::adapters::FromInto;
283///
284/// #[derive(Clone)]
285/// pub struct Rgb(u8, u8, u8);
286///
287/// impl From<(u8, u8, u8)> for Rgb {
288///     fn from(value: (u8, u8, u8)) -> Rgb {
289///         Rgb(value.0, value.1, value.2)
290///     }
291/// }
292///
293/// impl From<Rgb> for (u8, u8, u8) {
294///     fn from(value: Rgb) -> (u8, u8, u8) {
295///         (value.0, value.1, value.2)
296///     }
297/// }
298///
299/// #[derive(Serialize, Deserialize)]
300/// pub struct Theme {
301///     #[deser(as = FromInto<(u8, u8, u8)>)]
302///     background: Rgb,
303/// }
304/// ```
305pub struct FromInto<U>(PhantomData<fn() -> U>);
306
307impl<'de, T, U> Deserialize<'de, T> for FromInto<U>
308where
309    T: Send,
310    U: Deserialize<'de> + Into<T> + 'static,
311{
312    fn deserialize_into<'out>(
313        out: &'out mut Option<T>,
314        state: &mut State,
315    ) -> SinkHandle<'out, 'de> {
316        MappedSink::handle(
317            out,
318            OwnedSink::<U>::deserialize(state),
319            |value| Ok(value.into()),
320            state,
321        )
322    }
323
324    fn expecting() -> Cow<'static, str> {
325        U::expecting()
326    }
327
328    fn initial_value() -> Option<T> {
329        U::initial_value().map(Into::into)
330    }
331
332    #[inline]
333    fn __private_atom_into(
334        out: &mut Option<T>,
335        atom: Atom,
336        state: &mut State,
337    ) -> Result<(), Error> {
338        let mut inner = None;
339        U::__private_atom_into(&mut inner, atom, state)?;
340        *out = inner.map(Into::into);
341        Ok(())
342    }
343
344    #[inline]
345    fn __private_borrowed_atom_into(
346        out: &mut Option<T>,
347        atom: Atom<'de>,
348        state: &mut State,
349    ) -> Result<(), Error> {
350        let mut inner = None;
351        U::__private_borrowed_atom_into(&mut inner, atom, state)?;
352        *out = inner.map(Into::into);
353        Ok(())
354    }
355}
356
357impl<T, U> Serialize<T> for FromInto<U>
358where
359    T: Clone + Into<U>,
360    U: Serialize + Send + 'static,
361{
362    fn serialize<'a>(value: &'a T, state: &mut State) -> Result<Emit<'a>, Error> {
363        Ok(Emit::Forward(SerializeHandle::arena(
364            Into::<U>::into(value.clone()),
365            state,
366        )))
367    }
368
369    // this clones once more, but only `skip_serializing_optionals` asks.
370    // Without converting there is no way to know as `()` is optional too.
371    fn is_optional(value: &T) -> bool {
372        U::is_optional(&Into::<U>::into(value.clone()))
373    }
374}
375
376/// Converts from and into another type with fallible conversions.
377///
378/// This is like [`FromInto`] but uses [`TryFrom`] and [`TryInto`].  Failed
379/// conversions are reported as errors.  Like with [`FromInto`] the value is
380/// cloned and converted once more with `#[deser(skip_serializing_optionals)]`
381/// to find out if it's optional.
382///
383/// ```
384/// use deser::{Deserialize, Serialize};
385/// use deser::adapters::TryFromInto;
386///
387/// #[derive(Clone)]
388/// pub struct Percent(u8);
389///
390/// impl TryFrom<u64> for Percent {
391///     type Error = &'static str;
392///     fn try_from(value: u64) -> Result<Percent, Self::Error> {
393///         if value <= 100 {
394///             Ok(Percent(value as u8))
395///         } else {
396///             Err("out of range")
397///         }
398///     }
399/// }
400///
401/// impl TryFrom<Percent> for u64 {
402///     type Error = std::convert::Infallible;
403///     fn try_from(value: Percent) -> Result<u64, Self::Error> {
404///         Ok(value.0 as u64)
405///     }
406/// }
407///
408/// #[derive(Serialize, Deserialize)]
409/// pub struct Progress {
410///     #[deser(as = TryFromInto<u64>)]
411///     done: Percent,
412/// }
413/// ```
414pub struct TryFromInto<U>(PhantomData<fn() -> U>);
415
416impl<'de, T, U> Deserialize<'de, T> for TryFromInto<U>
417where
418    U: Deserialize<'de> + 'static,
419    T: TryFrom<U> + Send,
420    T::Error: Display,
421{
422    fn deserialize_into<'out>(
423        out: &'out mut Option<T>,
424        state: &mut State,
425    ) -> SinkHandle<'out, 'de> {
426        MappedSink::handle(
427            out,
428            OwnedSink::<U>::deserialize(state),
429            |value| T::try_from(value).map_err(conversion_error),
430            state,
431        )
432    }
433
434    fn expecting() -> Cow<'static, str> {
435        U::expecting()
436    }
437
438    fn initial_value() -> Option<T> {
439        U::initial_value().and_then(|value| T::try_from(value).ok())
440    }
441
442    #[inline]
443    fn __private_atom_into(
444        out: &mut Option<T>,
445        atom: Atom,
446        state: &mut State,
447    ) -> Result<(), Error> {
448        let mut inner = None;
449        U::__private_atom_into(&mut inner, atom, state)?;
450        *out = match inner {
451            Some(value) => Some(T::try_from(value).map_err(conversion_error)?),
452            None => None,
453        };
454        Ok(())
455    }
456
457    #[inline]
458    fn __private_borrowed_atom_into(
459        out: &mut Option<T>,
460        atom: Atom<'de>,
461        state: &mut State,
462    ) -> Result<(), Error> {
463        let mut inner = None;
464        U::__private_borrowed_atom_into(&mut inner, atom, state)?;
465        *out = match inner {
466            Some(value) => Some(T::try_from(value).map_err(conversion_error)?),
467            None => None,
468        };
469        Ok(())
470    }
471}
472
473impl<T, U> Serialize<T> for TryFromInto<U>
474where
475    T: Clone + TryInto<U>,
476    <T as TryInto<U>>::Error: Display,
477    U: Serialize + Send + 'static,
478{
479    fn serialize<'a>(value: &'a T, state: &mut State) -> Result<Emit<'a>, Error> {
480        let value: U = value.clone().try_into().map_err(conversion_error)?;
481        Ok(Emit::Forward(SerializeHandle::arena(value, state)))
482    }
483
484    fn is_optional(value: &T) -> bool {
485        TryInto::<U>::try_into(value.clone()).is_ok_and(|x| U::is_optional(&x))
486    }
487}
488
489/// Converts from another type and into it from a reference.
490///
491/// This is like [`FromInto`] but the value is serialized by converting a
492/// reference to it (`&T: Into<U>`), so it does not need to be cloned.
493/// Deserialization is the same as with [`FromInto`]: the value is
494/// deserialized as `U` and converted with [`Into`].
495///
496/// ```
497/// use deser::{Deserialize, Serialize};
498/// use deser::adapters::FromIntoRef;
499///
500/// pub struct Rgb(u8, u8, u8);
501///
502/// impl From<(u8, u8, u8)> for Rgb {
503///     fn from(value: (u8, u8, u8)) -> Rgb {
504///         Rgb(value.0, value.1, value.2)
505///     }
506/// }
507///
508/// impl From<&Rgb> for (u8, u8, u8) {
509///     fn from(value: &Rgb) -> (u8, u8, u8) {
510///         (value.0, value.1, value.2)
511///     }
512/// }
513///
514/// #[derive(Serialize, Deserialize)]
515/// pub struct Theme {
516///     #[deser(as = FromIntoRef<(u8, u8, u8)>)]
517///     background: Rgb,
518/// }
519/// ```
520pub struct FromIntoRef<U>(PhantomData<fn() -> U>);
521
522impl<'de, T, U> Deserialize<'de, T> for FromIntoRef<U>
523where
524    T: Send,
525    U: Deserialize<'de> + Into<T> + 'static,
526{
527    fn deserialize_into<'out>(
528        out: &'out mut Option<T>,
529        state: &mut State,
530    ) -> SinkHandle<'out, 'de> {
531        <FromInto<U> as Deserialize<'de, T>>::deserialize_into(out, state)
532    }
533
534    fn expecting() -> Cow<'static, str> {
535        U::expecting()
536    }
537
538    fn initial_value() -> Option<T> {
539        U::initial_value().map(Into::into)
540    }
541
542    #[inline]
543    fn __private_atom_into(
544        out: &mut Option<T>,
545        atom: Atom,
546        state: &mut State,
547    ) -> Result<(), Error> {
548        <FromInto<U> as Deserialize<'de, T>>::__private_atom_into(out, atom, state)
549    }
550
551    #[inline]
552    fn __private_borrowed_atom_into(
553        out: &mut Option<T>,
554        atom: Atom<'de>,
555        state: &mut State,
556    ) -> Result<(), Error> {
557        <FromInto<U> as Deserialize<'de, T>>::__private_borrowed_atom_into(out, atom, state)
558    }
559}
560
561impl<T, U> Serialize<T> for FromIntoRef<U>
562where
563    T: Sync + ?Sized,
564    for<'x> &'x T: Into<U>,
565    U: Serialize + Send + 'static,
566{
567    fn serialize<'a>(value: &'a T, state: &mut State) -> Result<Emit<'a>, Error> {
568        Ok(Emit::Forward(SerializeHandle::arena(
569            Into::<U>::into(value),
570            state,
571        )))
572    }
573
574    // converts once more, but only `skip_serializing_optionals` asks
575    fn is_optional(value: &T) -> bool {
576        U::is_optional(&Into::<U>::into(value))
577    }
578}
579
580/// Converts from another type and into it from a reference with fallible
581/// conversions.
582///
583/// This is like [`TryFromInto`] but the value is serialized by converting
584/// a reference to it (`&T: TryInto<U>`), so it does not need to be cloned.
585/// Failed conversions are reported as errors.
586///
587/// ```
588/// use deser::{Deserialize, Serialize};
589/// use deser::adapters::TryFromIntoRef;
590///
591/// pub struct Percent(u8);
592///
593/// impl TryFrom<u64> for Percent {
594///     type Error = &'static str;
595///     fn try_from(value: u64) -> Result<Percent, Self::Error> {
596///         if value <= 100 {
597///             Ok(Percent(value as u8))
598///         } else {
599///             Err("out of range")
600///         }
601///     }
602/// }
603///
604/// impl TryFrom<&Percent> for u64 {
605///     type Error = std::convert::Infallible;
606///     fn try_from(value: &Percent) -> Result<u64, Self::Error> {
607///         Ok(value.0 as u64)
608///     }
609/// }
610///
611/// #[derive(Serialize, Deserialize)]
612/// pub struct Progress {
613///     #[deser(as = TryFromIntoRef<u64>)]
614///     done: Percent,
615/// }
616/// ```
617pub struct TryFromIntoRef<U>(PhantomData<fn() -> U>);
618
619impl<'de, T, U> Deserialize<'de, T> for TryFromIntoRef<U>
620where
621    U: Deserialize<'de> + 'static,
622    T: TryFrom<U> + Send,
623    T::Error: Display,
624{
625    fn deserialize_into<'out>(
626        out: &'out mut Option<T>,
627        state: &mut State,
628    ) -> SinkHandle<'out, 'de> {
629        <TryFromInto<U> as Deserialize<'de, T>>::deserialize_into(out, state)
630    }
631
632    fn expecting() -> Cow<'static, str> {
633        U::expecting()
634    }
635
636    fn initial_value() -> Option<T> {
637        <TryFromInto<U> as Deserialize<'de, T>>::initial_value()
638    }
639
640    #[inline]
641    fn __private_atom_into(
642        out: &mut Option<T>,
643        atom: Atom,
644        state: &mut State,
645    ) -> Result<(), Error> {
646        <TryFromInto<U> as Deserialize<'de, T>>::__private_atom_into(out, atom, state)
647    }
648
649    #[inline]
650    fn __private_borrowed_atom_into(
651        out: &mut Option<T>,
652        atom: Atom<'de>,
653        state: &mut State,
654    ) -> Result<(), Error> {
655        <TryFromInto<U> as Deserialize<'de, T>>::__private_borrowed_atom_into(out, atom, state)
656    }
657}
658
659impl<T, U> Serialize<T> for TryFromIntoRef<U>
660where
661    T: Sync + ?Sized,
662    for<'x> &'x T: TryInto<U>,
663    for<'x> <&'x T as TryInto<U>>::Error: Display,
664    U: Serialize + Send + 'static,
665{
666    fn serialize<'a>(value: &'a T, state: &mut State) -> Result<Emit<'a>, Error> {
667        let value: U = value.try_into().map_err(conversion_error)?;
668        Ok(Emit::Forward(SerializeHandle::arena(value, state)))
669    }
670
671    fn is_optional(value: &T) -> bool {
672        TryInto::<U>::try_into(value).is_ok_and(|x| U::is_optional(&x))
673    }
674}
675
676/// Uses the [`Default`] if the value is null.
677///
678/// A null (or a value that is null in the format, like `~` in YAML) is
679/// replaced with the default value, everything else is deserialized with
680/// the adapter `A` (by default [`Same`]).  This is for data that sends
681/// `null` instead of an empty list or a zero.  Missing values are handled
682/// by the inner adapter, combine it with `#[deser(default)]` to also
683/// accept them.  Serialization uses the inner adapter.
684///
685/// ```
686/// use deser::Deserialize;
687/// use deser::adapters::DefaultOnNull;
688///
689/// #[derive(Deserialize)]
690/// pub struct Item {
691///     #[deser(as = DefaultOnNull)]
692///     tags: Vec<String>,
693///     #[deser(as = DefaultOnNull, default)]
694///     count: u32,
695/// }
696///
697/// let item: Item = deser_json::from_str(r#"{"tags": null}"#).unwrap();
698/// assert!(item.tags.is_empty());
699/// assert_eq!(item.count, 0);
700/// ```
701///
702/// In formats where keys can be given more than once (see
703/// [`ContainerShape::set_multimap`]) collections receive the values of all
704/// occurrences of their key from the inner adapter, nulls among them are
705/// not replaced.
706pub struct DefaultOnNull<A = Same>(PhantomData<fn() -> A>);
707
708/// The sink of [`DefaultOnNull`].
709///
710/// The sink of the value is only created once a value arrives that is not
711/// null, as creating it can already set the slot (like it does for
712/// optionals).
713enum DefaultOnNullSink<'a, 'de, T> {
714    Pending(&'a mut Option<T>),
715    Active(SinkHandle<'a, 'de>),
716}
717
718impl<'a, 'de, T: Default + Send> DefaultOnNullSink<'a, 'de, T> {
719    /// Returns the sink of the value, creates it with the adapter `A` if
720    /// needed.
721    fn active<A: Deserialize<'de, T>>(&mut self, state: &mut State) -> &mut SinkHandle<'a, 'de> {
722        if let DefaultOnNullSink::Pending(..) = self
723            && let DefaultOnNullSink::Pending(out) =
724                core::mem::replace(self, DefaultOnNullSink::Active(SinkHandle::null()))
725        {
726            *self = DefaultOnNullSink::Active(A::deserialize_into(out, state));
727        }
728        match self {
729            DefaultOnNullSink::Active(sink) => sink,
730            DefaultOnNullSink::Pending(..) => unreachable!(),
731        }
732    }
733
734    /// Uses the default if the atom is null and the first event.
735    fn default_on_null(&mut self, atom: &Atom) -> bool {
736        if let DefaultOnNullSink::Pending(..) = self
737            && is_null_atom(atom)
738            && let DefaultOnNullSink::Pending(out) =
739                core::mem::replace(self, DefaultOnNullSink::Active(SinkHandle::null()))
740        {
741            *out = Some(T::default());
742            return true;
743        }
744        false
745    }
746}
747
748impl<'a, 'de, T, A> Sink<'de> for Adapted<A, DefaultOnNullSink<'a, 'de, T>>
749where
750    T: Default + Send,
751    A: Deserialize<'de, T>,
752{
753    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
754        if self.default_on_null(&atom) {
755            return Ok(());
756        }
757        self.active::<A>(state).atom(atom, state)
758    }
759
760    fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
761        if self.default_on_null(&atom) {
762            return Ok(());
763        }
764        self.active::<A>(state).borrowed_atom(atom, state)
765    }
766
767    fn map(&mut self, state: &mut State) -> Result<(), Error> {
768        self.active::<A>(state).map(state)
769    }
770
771    fn seq(&mut self, state: &mut State) -> Result<(), Error> {
772        self.active::<A>(state).seq(state)
773    }
774
775    fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
776        self.active::<A>(state).next_key(state)
777    }
778
779    fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
780        self.active::<A>(state).next_value(state)
781    }
782
783    fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
784        self.active::<A>(state).__private_key_atom(atom, state)
785    }
786
787    fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
788        self.active::<A>(state).__private_value_atom(atom, state)
789    }
790
791    fn __private_borrowed_key_atom(
792        &mut self,
793        atom: Atom<'de>,
794        state: &mut State,
795    ) -> Result<(), Error> {
796        self.active::<A>(state)
797            .__private_borrowed_key_atom(atom, state)
798    }
799
800    fn __private_borrowed_value_atom(
801        &mut self,
802        atom: Atom<'de>,
803        state: &mut State,
804    ) -> Result<(), Error> {
805        self.active::<A>(state)
806            .__private_borrowed_value_atom(atom, state)
807    }
808
809    fn value_for_key(
810        &mut self,
811        key: &str,
812        state: &mut State,
813    ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
814        self.active::<A>(state).value_for_key(key, state)
815    }
816
817    fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
818        self.active::<A>(state).recover(err, state)
819    }
820
821    fn finish(&mut self, state: &mut State) -> Result<(), Error> {
822        self.active::<A>(state).finish(state)
823    }
824
825    fn expecting(&self) -> Cow<'_, str> {
826        match &**self {
827            DefaultOnNullSink::Active(sink) => sink.expecting(),
828            // the sink of the value does not exist yet
829            DefaultOnNullSink::Pending(..) => A::expecting(),
830        }
831    }
832}
833
834impl<'de, T: Default + Send, A: Deserialize<'de, T>> Deserialize<'de, T> for DefaultOnNull<A> {
835    fn deserialize_into<'out>(
836        out: &'out mut Option<T>,
837        state: &mut State,
838    ) -> SinkHandle<'out, 'de> {
839        adapted::arena_sink::<A, _>(DefaultOnNullSink::Pending(out), state)
840    }
841
842    fn expecting() -> Cow<'static, str> {
843        A::expecting()
844    }
845
846    fn describe_type(d: &mut dyn Describe) {
847        A::describe_type(d)
848    }
849
850    fn initial_value() -> Option<T> {
851        A::initial_value()
852    }
853
854    #[inline]
855    fn __private_atom_into(
856        out: &mut Option<T>,
857        atom: Atom,
858        state: &mut State,
859    ) -> Result<(), Error> {
860        if is_null_atom(&atom) {
861            *out = Some(T::default());
862            return Ok(());
863        }
864        A::__private_atom_into(out, atom, state)
865    }
866
867    #[inline]
868    fn __private_borrowed_atom_into(
869        out: &mut Option<T>,
870        atom: Atom<'de>,
871        state: &mut State,
872    ) -> Result<(), Error> {
873        if is_null_atom(&atom) {
874            *out = Some(T::default());
875            return Ok(());
876        }
877        A::__private_borrowed_atom_into(out, atom, state)
878    }
879
880    fn __private_is_bytes() -> bool {
881        A::__private_is_bytes()
882    }
883
884    fn __private_vec_from_bytes(bytes: Vec<u8>) -> Option<Vec<T>> {
885        A::__private_vec_from_bytes(bytes)
886    }
887
888    fn __private_array_from_bytes<const N: usize>(bytes: &[u8]) -> Option<[T; N]> {
889        A::__private_array_from_bytes::<N>(bytes)
890    }
891
892    // the occurrences of a repeated key go to the inner adapter
893
894    fn __private_collects() -> bool {
895        A::__private_collects()
896    }
897
898    fn __private_collect_into<'out>(
899        out: &'out mut Option<T>,
900        state: &mut State,
901    ) -> SinkHandle<'out, 'de> {
902        A::__private_collect_into(out, state)
903    }
904
905    fn __private_collect_update<'out>(
906        value: &'out mut T,
907        first: bool,
908        state: &mut State,
909    ) -> SinkHandle<'out, 'de> {
910        A::__private_collect_update(value, first, state)
911    }
912
913    fn __private_collect_empty() -> Option<T> {
914        A::__private_collect_empty()
915    }
916}
917
918impl<T: ?Sized, A: Serialize<T>> Serialize<T> for DefaultOnNull<A> {
919    fn serialize<'a>(value: &'a T, state: &mut State) -> Result<Emit<'a>, Error> {
920        A::serialize(value, state)
921    }
922
923    fn finish(value: &T, state: &mut State) -> Result<(), Error> {
924        A::finish(value, state)
925    }
926
927    fn is_optional(value: &T) -> bool {
928        A::is_optional(value)
929    }
930
931    fn container_shape(value: &T) -> ContainerShape {
932        A::container_shape(value)
933    }
934
935    fn describe(value: &T, d: &mut dyn Describe) {
936        A::describe(value, d)
937    }
938
939    #[inline]
940    fn __private_begin<'a>(value: &'a T, state: &mut State) -> Result<Begin<'a>, Error> {
941        A::__private_begin(value, state)
942    }
943
944    fn __private_slice_as_bytes(val: &[T]) -> Option<Cow<'_, [u8]>>
945    where
946        T: Sized,
947    {
948        A::__private_slice_as_bytes(val)
949    }
950}
951
952/// Uses the [`Default`] if a value cannot be deserialized.
953///
954/// The value is deserialized with the adapter `A` (by default [`Same`]).  If
955/// that fails, the default value is used instead and the rest of the value
956/// is skipped (see [`Sink::recover`]).  Only errors of the value are
957/// handled, errors of the data format and of layers (such as
958/// [`Limits`](crate::de::Limits)) still fail the deserialization.  Missing
959/// values are handled by the inner adapter.  Serialization uses the inner
960/// adapter.
961///
962/// ```
963/// use deser::Deserialize;
964/// use deser::adapters::DefaultOnError;
965///
966/// #[derive(Deserialize)]
967/// pub enum Kind {
968///     A,
969///     B,
970/// }
971///
972/// #[derive(Deserialize)]
973/// pub struct Item {
974///     // unknown kinds become `None`
975///     #[deser(as = DefaultOnError)]
976///     kind: Option<Kind>,
977/// }
978/// ```
979pub struct DefaultOnError<A = Same>(PhantomData<fn() -> A>);
980
981impl<'de, T: Default + Send, A: Deserialize<'de, T>> Deserialize<'de, T> for DefaultOnError<A> {
982    fn deserialize_into<'out>(
983        out: &'out mut Option<T>,
984        state: &mut State,
985    ) -> SinkHandle<'out, 'de> {
986        SinkHandle::arena(
987            DefaultOnErrorSink {
988                out,
989                sink: Some(OwnedSink::deserialize_as::<A>(state)),
990            },
991            state,
992        )
993    }
994
995    fn expecting() -> Cow<'static, str> {
996        A::expecting()
997    }
998
999    fn describe_type(d: &mut dyn Describe) {
1000        A::describe_type(d)
1001    }
1002
1003    fn initial_value() -> Option<T> {
1004        A::initial_value()
1005    }
1006
1007    // Collections collect the values of a repeated key, a value that fails
1008    // resets the collection to the default.
1009
1010    fn __private_collects() -> bool {
1011        A::__private_collects()
1012    }
1013
1014    fn __private_collect_into<'out>(
1015        out: &'out mut Option<T>,
1016        state: &mut State,
1017    ) -> SinkHandle<'out, 'de> {
1018        let collected = out.take();
1019        let sink = OwnedSink::with_slot(collected, A::__private_collect_into, state);
1020        SinkHandle::arena(
1021            DefaultOnErrorSink {
1022                out,
1023                sink: Some(sink),
1024            },
1025            state,
1026        )
1027    }
1028
1029    fn __private_collect_empty() -> Option<T> {
1030        A::__private_collect_empty()
1031    }
1032
1033    #[inline]
1034    fn __private_atom_into(
1035        out: &mut Option<T>,
1036        atom: Atom,
1037        state: &mut State,
1038    ) -> Result<(), Error> {
1039        let mut value = None;
1040        let rv = state.discard_errors(|state| A::__private_atom_into(&mut value, atom, state));
1041        *out = Some(match (rv, value) {
1042            (Ok(()), Some(value)) => value,
1043            _ => T::default(),
1044        });
1045        Ok(())
1046    }
1047
1048    #[inline]
1049    fn __private_borrowed_atom_into(
1050        out: &mut Option<T>,
1051        atom: Atom<'de>,
1052        state: &mut State,
1053    ) -> Result<(), Error> {
1054        let mut value = None;
1055        let rv =
1056            state.discard_errors(|state| A::__private_borrowed_atom_into(&mut value, atom, state));
1057        *out = Some(match (rv, value) {
1058            (Ok(()), Some(value)) => value,
1059            _ => T::default(),
1060        });
1061        Ok(())
1062    }
1063}
1064
1065/// The sink of [`DefaultOnError`].
1066struct DefaultOnErrorSink<'a, 'de, T> {
1067    out: &'a mut Option<T>,
1068    // `None` once the value failed, the rest of it is ignored then
1069    sink: Option<OwnedSink<'de, T>>,
1070}
1071
1072impl<'a, 'de, T> DefaultOnErrorSink<'a, 'de, T> {
1073    /// Returns the sink of the value unless it failed.
1074    fn sink(&mut self) -> Option<&mut (dyn Sink<'de> + '_)> {
1075        self.sink.as_mut().map(|sink| sink.get_mut())
1076    }
1077
1078    /// Discards the value if the result is an error.
1079    fn check(&mut self, rv: Result<(), Error>) -> Result<(), Error> {
1080        if rv.is_err() {
1081            self.sink = None;
1082        }
1083        Ok(())
1084    }
1085}
1086
1087impl<'a, 'de, T: Default + Send> Sink<'de> for DefaultOnErrorSink<'a, 'de, T> {
1088    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1089        let rv = match self.sink() {
1090            Some(sink) => sink.atom(atom, state),
1091            None => Ok(()),
1092        };
1093        self.check(rv)
1094    }
1095
1096    fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
1097        let rv = match self.sink() {
1098            Some(sink) => sink.borrowed_atom(atom, state),
1099            None => Ok(()),
1100        };
1101        self.check(rv)
1102    }
1103
1104    fn map(&mut self, state: &mut State) -> Result<(), Error> {
1105        let rv = match self.sink() {
1106            Some(sink) => sink.map(state),
1107            None => Ok(()),
1108        };
1109        self.check(rv)
1110    }
1111
1112    fn seq(&mut self, state: &mut State) -> Result<(), Error> {
1113        let rv = match self.sink() {
1114            Some(sink) => sink.seq(state),
1115            None => Ok(()),
1116        };
1117        self.check(rv)
1118    }
1119
1120    // Errors of the items are handled in `recover`.
1121
1122    forward_to_optional!(sink);
1123
1124    fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
1125        // the value might recover itself, otherwise it failed
1126        if let Some(sink) = self.sink()
1127            && sink.recover(err, state).is_ok()
1128        {
1129            return Ok(());
1130        }
1131        self.sink = None;
1132        Ok(())
1133    }
1134
1135    fn finish(&mut self, state: &mut State) -> Result<(), Error> {
1136        let rv = match self.sink() {
1137            Some(sink) => sink.finish(state),
1138            None => Ok(()),
1139        };
1140        self.check(rv)?;
1141        let value = self.sink.as_mut().and_then(|sink| sink.take());
1142        *self.out = Some(value.unwrap_or_default());
1143        Ok(())
1144    }
1145
1146    fn expecting(&self) -> Cow<'_, str> {
1147        match self.sink {
1148            Some(ref sink) => sink.get().expecting(),
1149            None => Cow::Borrowed("compatible type"),
1150        }
1151    }
1152}
1153
1154impl<T: ?Sized, A: Serialize<T>> Serialize<T> for DefaultOnError<A> {
1155    fn serialize<'a>(value: &'a T, state: &mut State) -> Result<Emit<'a>, Error> {
1156        A::serialize(value, state)
1157    }
1158
1159    fn finish(value: &T, state: &mut State) -> Result<(), Error> {
1160        A::finish(value, state)
1161    }
1162
1163    fn is_optional(value: &T) -> bool {
1164        A::is_optional(value)
1165    }
1166
1167    fn container_shape(value: &T) -> ContainerShape {
1168        A::container_shape(value)
1169    }
1170
1171    fn describe(value: &T, d: &mut dyn Describe) {
1172        A::describe(value, d)
1173    }
1174
1175    #[inline]
1176    fn __private_begin<'a>(value: &'a T, state: &mut State) -> Result<Begin<'a>, Error> {
1177        A::__private_begin(value, state)
1178    }
1179}
1180
1181/// Deserializes an atom and returns the value unless it failed.
1182fn try_atom<'de, T: Send, A: Deserialize<'de, T>>(atom: Atom, state: &mut State) -> Option<T> {
1183    let mut value = None;
1184    match state.discard_errors(|state| A::__private_atom_into(&mut value, atom, state)) {
1185        Ok(()) => value,
1186        Err(_) => None,
1187    }
1188}
1189
1190/// Deserializes a borrowed atom and returns the value unless it failed.
1191fn try_borrowed_atom<'de, T: Send, A: Deserialize<'de, T>>(
1192    atom: Atom<'de>,
1193    state: &mut State,
1194) -> Option<T> {
1195    let mut value = None;
1196    match state.discard_errors(|state| A::__private_borrowed_atom_into(&mut value, atom, state)) {
1197        Ok(()) => value,
1198        Err(_) => None,
1199    }
1200}
1201
1202/// Skips elements of a vector which cannot be deserialized.
1203///
1204/// The elements are deserialized with the adapter `A` (by default
1205/// [`Same`]).  If an element fails, the rest of it is skipped (see
1206/// [`Sink::recover`]).  Only errors of the elements are handled, errors of
1207/// the data format and of layers still fail the deserialization.
1208/// Serialization uses the inner adapter for the elements.
1209///
1210/// ```
1211/// use deser::Deserialize;
1212/// use deser::adapters::VecSkipError;
1213///
1214/// #[derive(Deserialize)]
1215/// pub enum Kind {
1216///     A,
1217///     B,
1218/// }
1219///
1220/// #[derive(Deserialize)]
1221/// pub struct Item {
1222///     // unknown kinds are skipped
1223///     #[deser(as = VecSkipError)]
1224///     kinds: Vec<Kind>,
1225/// }
1226/// ```
1227pub struct VecSkipError<A = Same>(PhantomData<fn() -> A>);
1228
1229impl<'de, T: Send, A: Deserialize<'de, T>> Deserialize<'de, Vec<T>> for VecSkipError<A> {
1230    fn expecting() -> Cow<'static, str> {
1231        Cow::Borrowed(<Vec<T> as SeqTarget<T>>::NAME)
1232    }
1233
1234    fn deserialize_into<'out>(
1235        out: &'out mut Option<Vec<T>>,
1236        state: &mut State,
1237    ) -> SinkHandle<'out, 'de> {
1238        struct SkipSink<'a, T> {
1239            slot: &'a mut Option<Vec<T>>,
1240            vec: Vec<T>,
1241            // the current element, added once the next one starts
1242            item: Option<T>,
1243        }
1244
1245        impl<'a, T> SkipSink<'a, T> {
1246            fn flush(&mut self) {
1247                if let Some(item) = self.item.take() {
1248                    self.vec.push(item);
1249                }
1250            }
1251        }
1252
1253        impl<'a, 'de, T: Send, A: Deserialize<'de, T>> Sink<'de> for Adapted<A, SkipSink<'a, T>> {
1254            fn expecting(&self) -> Cow<'_, str> {
1255                Cow::Borrowed(<Vec<T> as SeqTarget<T>>::NAME)
1256            }
1257
1258            fn seq(&mut self, _state: &mut State) -> Result<(), Error> {
1259                Ok(())
1260            }
1261
1262            fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1263                self.flush();
1264                Ok(A::deserialize_into(&mut self.item, state))
1265            }
1266
1267            fn recover(&mut self, _err: Error, _state: &mut State) -> Result<(), Error> {
1268                self.item = None;
1269                Ok(())
1270            }
1271
1272            fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1273                self.flush();
1274                if let Some(value) = try_atom::<T, A>(atom, state) {
1275                    self.vec.push(value);
1276                }
1277                Ok(())
1278            }
1279
1280            fn __private_borrowed_value_atom(
1281                &mut self,
1282                atom: Atom<'de>,
1283                state: &mut State,
1284            ) -> Result<(), Error> {
1285                self.flush();
1286                if let Some(value) = try_borrowed_atom::<T, A>(atom, state) {
1287                    self.vec.push(value);
1288                }
1289                Ok(())
1290            }
1291
1292            fn finish(&mut self, _state: &mut State) -> Result<(), Error> {
1293                self.flush();
1294                *self.slot = Some(take(&mut self.vec));
1295                Ok(())
1296            }
1297        }
1298
1299        adapted::arena_sink::<A, _>(
1300            SkipSink {
1301                slot: out,
1302                vec: Vec::new(),
1303                item: None,
1304            },
1305            state,
1306        )
1307    }
1308}
1309
1310impl<T: Sync, A: Serialize<T>> Serialize<Vec<T>> for VecSkipError<A> {
1311    fn serialize<'a>(value: &'a Vec<T>, state: &mut State) -> Result<Emit<'a>, Error> {
1312        <Vec<A> as Serialize<Vec<T>>>::serialize(value, state)
1313    }
1314
1315    fn container_shape(value: &Vec<T>) -> ContainerShape {
1316        <Vec<A> as Serialize<Vec<T>>>::container_shape(value)
1317    }
1318
1319    fn describe(value: &Vec<T>, d: &mut dyn Describe) {
1320        <Vec<A> as Serialize<Vec<T>>>::describe(value, d)
1321    }
1322
1323    #[inline]
1324    fn __private_begin<'a>(value: &'a Vec<T>, state: &mut State) -> Result<Begin<'a>, Error> {
1325        <Vec<A> as Serialize<Vec<T>>>::__private_begin(value, state)
1326    }
1327}
1328
1329/// Skips entries of a map which cannot be deserialized.
1330///
1331/// Keys are deserialized with the adapter `KA` and values with `VA` (both
1332/// [`Same`] by default).  If either of them fails, the rest of the entry is
1333/// skipped (see [`Sink::recover`]).  Only errors of the entries are
1334/// handled, errors of the data format and of layers still fail the
1335/// deserialization.  Supported are [`BTreeMap`] and [`HashMap`].
1336/// Serialization uses the inner adapters.
1337///
1338/// ```
1339/// use std::collections::BTreeMap;
1340/// use deser::Deserialize;
1341/// use deser::adapters::MapSkipError;
1342///
1343/// #[derive(Deserialize, PartialEq, Eq, PartialOrd, Ord)]
1344/// pub enum Kind {
1345///     A,
1346///     B,
1347/// }
1348///
1349/// #[derive(Deserialize)]
1350/// pub struct Weights {
1351///     // entries with unknown kinds are skipped
1352///     #[deser(as = MapSkipError)]
1353///     weights: BTreeMap<Kind, f64>,
1354/// }
1355/// ```
1356///
1357#[cfg_attr(
1358    not(feature = "std"),
1359    doc = "[`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html"
1360)]
1361pub struct MapSkipError<KA = Same, VA = Same>(PhantomData<fn() -> (KA, VA)>);
1362
1363pub(crate) fn skip_map_sink<'a, 'de, M, K, V, KA, VA>(
1364    out: &'a mut Option<M>,
1365    state: &mut State,
1366) -> SinkHandle<'a, 'de>
1367where
1368    M: MapTarget<K, V> + 'a,
1369    K: Send + 'a,
1370    V: Send + 'a,
1371    KA: Deserialize<'de, K>,
1372    VA: Deserialize<'de, V>,
1373{
1374    struct SkipMapSink<'a, M, K, V> {
1375        slot: &'a mut Option<M>,
1376        map: M,
1377        // the key of the current entry, `None` if it failed
1378        key: Option<K>,
1379        // the value of the current entry if it's not an atom, the entry is
1380        // added once the next one starts
1381        value: Option<V>,
1382        // if the values of duplicate keys replace earlier ones.  With
1383        // `DuplicateKeys::Error` duplicate entries fail and are skipped.
1384        replace: bool,
1385    }
1386
1387    impl<'a, M: MapTarget<K, V>, K, V> SkipMapSink<'a, M, K, V> {
1388        fn flush(&mut self) {
1389            if let Some(value) = self.value.take()
1390                && let Some(key) = self.key.take()
1391            {
1392                self.map.insert_entry(key, value, self.replace);
1393            }
1394            self.key = None;
1395        }
1396    }
1397
1398    impl<'a, 'de, M, K, V, KA, VA> Sink<'de> for Adapted<(KA, VA), SkipMapSink<'a, M, K, V>>
1399    where
1400        M: MapTarget<K, V>,
1401        K: Send,
1402        V: Send,
1403        KA: Deserialize<'de, K>,
1404        VA: Deserialize<'de, V>,
1405    {
1406        fn expecting(&self) -> Cow<'_, str> {
1407            Cow::Borrowed(M::NAME)
1408        }
1409
1410        fn map(&mut self, state: &mut State) -> Result<(), Error> {
1411            self.replace = DuplicateKeys::of(state) == DuplicateKeys::Last;
1412            Ok(())
1413        }
1414
1415        fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1416            self.flush();
1417            Ok(KA::deserialize_into(&mut self.key, state))
1418        }
1419
1420        fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1421            self.flush();
1422            self.key = try_atom::<K, KA>(atom, state);
1423            Ok(())
1424        }
1425
1426        fn __private_borrowed_key_atom(
1427            &mut self,
1428            atom: Atom<'de>,
1429            state: &mut State,
1430        ) -> Result<(), Error> {
1431            self.flush();
1432            self.key = try_borrowed_atom::<K, KA>(atom, state);
1433            Ok(())
1434        }
1435
1436        fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1437            if self.key.is_none() {
1438                return Ok(SinkHandle::null());
1439            }
1440            Ok(VA::deserialize_into(&mut self.value, state))
1441        }
1442
1443        fn recover(&mut self, _err: Error, _state: &mut State) -> Result<(), Error> {
1444            // the key or the value of the entry failed
1445            self.key = None;
1446            self.value = None;
1447            Ok(())
1448        }
1449
1450        fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1451            if let Some(key) = self.key.take()
1452                && let Some(value) = try_atom::<V, VA>(atom, state)
1453            {
1454                let replace = self.replace;
1455                self.map.insert_entry(key, value, replace);
1456            }
1457            Ok(())
1458        }
1459
1460        fn __private_borrowed_value_atom(
1461            &mut self,
1462            atom: Atom<'de>,
1463            state: &mut State,
1464        ) -> Result<(), Error> {
1465            if let Some(key) = self.key.take()
1466                && let Some(value) = try_borrowed_atom::<V, VA>(atom, state)
1467            {
1468                let replace = self.replace;
1469                self.map.insert_entry(key, value, replace);
1470            }
1471            Ok(())
1472        }
1473
1474        fn finish(&mut self, _state: &mut State) -> Result<(), Error> {
1475            self.flush();
1476            *self.slot = Some(take(&mut self.map));
1477            Ok(())
1478        }
1479    }
1480
1481    adapted::arena_sink::<(KA, VA), _>(
1482        SkipMapSink {
1483            slot: out,
1484            map: M::default(),
1485            key: None,
1486            value: None,
1487            replace: true,
1488        },
1489        state,
1490    )
1491}
1492
1493impl<'de, K, V, KA, VA> Deserialize<'de, BTreeMap<K, V>> for MapSkipError<KA, VA>
1494where
1495    K: Ord + Send,
1496    V: Send,
1497    KA: Deserialize<'de, K>,
1498    VA: Deserialize<'de, V>,
1499{
1500    fn deserialize_into<'out>(
1501        out: &'out mut Option<BTreeMap<K, V>>,
1502        state: &mut State,
1503    ) -> SinkHandle<'out, 'de> {
1504        skip_map_sink::<_, K, V, KA, VA>(out, state)
1505    }
1506
1507    fn expecting() -> Cow<'static, str> {
1508        Cow::Borrowed(<BTreeMap<K, V> as MapTarget<K, V>>::NAME)
1509    }
1510}
1511
1512#[cfg(feature = "std")]
1513impl<'de, K, V, H, KA, VA> Deserialize<'de, HashMap<K, V, H>> for MapSkipError<KA, VA>
1514where
1515    K: Hash + Eq + Send,
1516    V: Send,
1517    H: BuildHasher + Default + Send,
1518    KA: Deserialize<'de, K>,
1519    VA: Deserialize<'de, V>,
1520{
1521    fn deserialize_into<'out>(
1522        out: &'out mut Option<HashMap<K, V, H>>,
1523        state: &mut State,
1524    ) -> SinkHandle<'out, 'de> {
1525        skip_map_sink::<_, K, V, KA, VA>(out, state)
1526    }
1527
1528    fn expecting() -> Cow<'static, str> {
1529        Cow::Borrowed(<HashMap<K, V, H> as MapTarget<K, V>>::NAME)
1530    }
1531}
1532
1533impl<K, V, KA, VA> Serialize<BTreeMap<K, V>> for MapSkipError<KA, VA>
1534where
1535    K: Sync,
1536    V: Sync,
1537    KA: Serialize<K>,
1538    VA: Serialize<V>,
1539{
1540    fn serialize<'a>(value: &'a BTreeMap<K, V>, state: &mut State) -> Result<Emit<'a>, Error> {
1541        <BTreeMap<KA, VA> as Serialize<BTreeMap<K, V>>>::serialize(value, state)
1542    }
1543
1544    fn container_shape(value: &BTreeMap<K, V>) -> ContainerShape {
1545        <BTreeMap<KA, VA> as Serialize<BTreeMap<K, V>>>::container_shape(value)
1546    }
1547
1548    fn describe(value: &BTreeMap<K, V>, d: &mut dyn Describe) {
1549        <BTreeMap<KA, VA> as Serialize<BTreeMap<K, V>>>::describe(value, d)
1550    }
1551}
1552
1553#[cfg(feature = "std")]
1554impl<K, V, H, KA, VA> Serialize<HashMap<K, V, H>> for MapSkipError<KA, VA>
1555where
1556    K: Sync,
1557    V: Sync,
1558    H: BuildHasher + Sync,
1559    KA: Serialize<K>,
1560    VA: Serialize<V>,
1561{
1562    fn serialize<'a>(value: &'a HashMap<K, V, H>, state: &mut State) -> Result<Emit<'a>, Error> {
1563        <HashMap<KA, VA> as Serialize<HashMap<K, V, H>>>::serialize(value, state)
1564    }
1565
1566    fn container_shape(value: &HashMap<K, V, H>) -> ContainerShape {
1567        <HashMap<KA, VA> as Serialize<HashMap<K, V, H>>>::container_shape(value)
1568    }
1569
1570    fn describe(value: &HashMap<K, V, H>, d: &mut dyn Describe) {
1571        <HashMap<KA, VA> as Serialize<HashMap<K, V, H>>>::describe(value, d)
1572    }
1573}