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::adapters::Same;
19use crate::de::impls::{MapTarget, SeqTarget};
20use crate::de::lexical::parse_bool_with;
21use crate::de::mapped::MappedSink;
22use crate::de::{Deserialize, DuplicateKeys, OwnedSink, Sink, SinkHandle, Slot, default_atom};
23use crate::error::{Error, ErrorKind, conversion_error};
24use crate::event::{Atom, Bytes, ContainerShape};
25use crate::ser::{Begin, Describe, Emit, Serialize, SerializeHandle};
26
27/// Deserializes a `Cow<str>` or `Cow<[u8]>` borrowed from the data.
28///
29/// `Cow` is deserialized owned by default so that `Cow<'static, str>` can
30/// be deserialized from any data.  With this adapter the data is borrowed
31/// if the data format passes it on borrowed (see
32/// [`Sink::borrowed_atom`]).  Otherwise it's owned.  Serialization is not
33/// affected.
34///
35/// ```
36/// use std::borrow::Cow;
37/// use deser::{Deserialize, Serialize};
38/// use deser::adapters::Borrowed;
39///
40/// #[derive(Serialize, Deserialize)]
41/// pub struct Message<'a> {
42///     #[deser(as = Borrowed)]
43///     text: Cow<'a, str>,
44///     #[deser(as = Vec<Borrowed>)]
45///     tags: Vec<Cow<'a, str>>,
46/// }
47/// ```
48pub struct Borrowed;
49
50impl<'de: 'a, 'a> Deserialize<'de, Cow<'a, str>> for Borrowed {
51    fn deserialize_atom(
52        slot: &mut Slot<Cow<'a, str>, Self>,
53        atom: Atom,
54        state: &mut State,
55    ) -> Result<(), Error> {
56        match atom {
57            Atom::Str(value) | Atom::Lexical(value) => {
58                slot.set(Cow::Owned(value.into_owned()));
59                Ok(())
60            }
61            Atom::Char(value) => {
62                slot.set(Cow::Owned(value.to_string()));
63                Ok(())
64            }
65            other => default_atom(slot, other, state),
66        }
67    }
68
69    fn deserialize_borrowed_atom(
70        slot: &mut Slot<Cow<'a, str>, Self>,
71        atom: Atom<'de>,
72        state: &mut State,
73    ) -> Result<(), Error> {
74        match atom {
75            Atom::Str(value) | Atom::Lexical(value) => {
76                slot.set(value.into_cow());
77                Ok(())
78            }
79            // strings take the text of values whose type was inferred
80            Atom::Implicit(value) => {
81                slot.set(value.into_parts().0.into_cow());
82                Ok(())
83            }
84            other => Self::deserialize_atom(slot, other, state),
85        }
86    }
87
88    fn expecting() -> Cow<'static, str> {
89        Cow::Borrowed("string")
90    }
91}
92
93impl<'de: 'a, 'a> Deserialize<'de, Cow<'a, [u8]>> for Borrowed {
94    fn deserialize_atom(
95        slot: &mut Slot<Cow<'a, [u8]>, Self>,
96        atom: Atom,
97        state: &mut State,
98    ) -> Result<(), Error> {
99        match atom {
100            Atom::Bytes(value) => {
101                slot.set(Cow::Owned(value.into_owned()));
102                Ok(())
103            }
104            // formats without native bytes represent them as strings
105            Atom::Str(ref value) => {
106                slot.set(Cow::Owned(crate::adapters::bytes::decode_str(
107                    value, state,
108                )?));
109                Ok(())
110            }
111            other => default_atom(slot, other, state),
112        }
113    }
114
115    fn deserialize_borrowed_atom(
116        slot: &mut Slot<Cow<'a, [u8]>, Self>,
117        atom: Atom<'de>,
118        state: &mut State,
119    ) -> Result<(), Error> {
120        match atom {
121            Atom::Bytes(value) => {
122                slot.set(value.into_data());
123                Ok(())
124            }
125            other => Self::deserialize_atom(slot, other, state),
126        }
127    }
128
129    fn expecting() -> Cow<'static, str> {
130        Cow::Borrowed("bytes")
131    }
132}
133
134impl<'a> Serialize<Cow<'a, str>> for Borrowed {
135    fn serialize<'b>(value: &'b Cow<'a, str>, _state: &mut State) -> Result<Emit<'b>, Error> {
136        Ok(Emit::Atom(Atom::Str(Text::borrowed(value))))
137    }
138}
139
140impl<'a> Serialize<Cow<'a, [u8]>> for Borrowed {
141    fn serialize<'b>(value: &'b Cow<'a, [u8]>, _state: &mut State) -> Result<Emit<'b>, Error> {
142        Ok(Emit::Atom(Atom::Bytes(Bytes::borrowed(value))))
143    }
144}
145
146/// Serializes with [`Display`] and deserializes with [`FromStr`].
147///
148/// The value is represented as a string.  Only strings are accepted when
149/// deserializing.
150///
151/// ```
152/// use std::net::IpAddr;
153/// use deser::{Deserialize, Serialize};
154/// use deser::adapters::DisplayFromStr;
155///
156/// #[derive(Serialize, Deserialize)]
157/// pub struct Server {
158///     #[deser(as = DisplayFromStr)]
159///     addr: IpAddr,
160/// }
161/// ```
162pub struct DisplayFromStr;
163
164impl<'de, T> Deserialize<'de, T> for DisplayFromStr
165where
166    T: FromStr + Send,
167    T::Err: Display,
168{
169    fn deserialize_atom(
170        slot: &mut Slot<T, Self>,
171        atom: Atom,
172        state: &mut State,
173    ) -> Result<(), Error> {
174        match atom {
175            Atom::Str(ref value) => match value.parse::<T>() {
176                Ok(value) => {
177                    slot.set(value);
178                    Ok(())
179                }
180                Err(err) => Err(Error::new(
181                    ErrorKind::InvalidValue,
182                    format!("invalid value: {}", err),
183                )),
184            },
185            other => default_atom(slot, other, state),
186        }
187    }
188
189    fn expecting() -> Cow<'static, str> {
190        Cow::Borrowed("string")
191    }
192
193    slot_atom_into!(T);
194}
195
196impl<T: Display + ?Sized> Serialize<T> for DisplayFromStr {
197    fn serialize<'a>(value: &'a T, _state: &mut State) -> Result<Emit<'a>, Error> {
198        Ok(Emit::Atom(Atom::Str(Text::owned(value.to_string()))))
199    }
200
201    #[inline]
202    fn __private_begin<'a>(value: &'a T, state: &mut State) -> Result<Begin<'a>, Error> {
203        Ok(Begin::emit(
204            Self::serialize(value, state)?,
205            ContainerShape::new(),
206            false,
207        ))
208    }
209}
210
211/// A flag that is set if its key is given.
212///
213/// This is for `bool` fields that are switched on by giving their key,
214/// like `?recursive` in a query string:
215///
216/// * if the key is missing, the flag is `false` (no `#[deser(default)]` is
217///   needed)
218/// * an empty value (`?recursive` or `?recursive=`) or null is `true`
219/// * other values are booleans, strings are parsed like
220///   [lexical atoms](crate::Atom::Lexical) (`?recursive=0` is `false`)
221///
222/// The flag is serialized as boolean.
223///
224/// ```
225/// use deser::adapters::Flag;
226///
227/// #[derive(deser::Deserialize, deser::Serialize)]
228/// pub struct Tree {
229///     #[deser(as = Flag, skip_serializing_if = std::ops::Not::not)]
230///     recursive: bool,
231/// }
232/// ```
233pub struct Flag;
234
235impl<'de> Deserialize<'de, bool> for Flag {
236    fn deserialize_atom(
237        slot: &mut Slot<bool, Self>,
238        atom: Atom,
239        state: &mut State,
240    ) -> Result<(), Error> {
241        let value = match atom {
242            Atom::Bool(value) => value,
243            Atom::Null => true,
244            Atom::Str(ref value) | Atom::Lexical(ref value) if value.is_empty() => true,
245            Atom::Str(ref value) | Atom::Lexical(ref value) => parse_bool_with(value, true, state)?,
246            other => return default_atom(slot, other, state),
247        };
248        slot.set(value);
249        Ok(())
250    }
251
252    fn expecting() -> Cow<'static, str> {
253        Cow::Borrowed("flag")
254    }
255
256    fn initial_value() -> Option<bool> {
257        Some(false)
258    }
259
260    slot_atom_into!(bool);
261}
262
263impl Serialize<bool> for Flag {
264    fn serialize<'a>(value: &'a bool, _state: &mut State) -> Result<Emit<'a>, Error> {
265        Ok(Emit::Atom(Atom::Bool(*value)))
266    }
267}
268
269/// Converts from and into another type.
270///
271/// The value is deserialized as `U` and converted with [`Into`] and it's
272/// serialized by cloning it and converting it into `U`.  The value is
273/// [optional](Serialize::is_optional) if the converted value is, which means
274/// that with `#[deser(skip_serializing_optionals)]` the value is cloned and
275/// converted once more to find out.
276///
277/// ```
278/// use deser::{Deserialize, Serialize};
279/// use deser::adapters::FromInto;
280///
281/// #[derive(Clone)]
282/// pub struct Rgb(u8, u8, u8);
283///
284/// impl From<(u8, u8, u8)> for Rgb {
285///     fn from(value: (u8, u8, u8)) -> Rgb {
286///         Rgb(value.0, value.1, value.2)
287///     }
288/// }
289///
290/// impl From<Rgb> for (u8, u8, u8) {
291///     fn from(value: Rgb) -> (u8, u8, u8) {
292///         (value.0, value.1, value.2)
293///     }
294/// }
295///
296/// #[derive(Serialize, Deserialize)]
297/// pub struct Theme {
298///     #[deser(as = FromInto<(u8, u8, u8)>)]
299///     background: Rgb,
300/// }
301/// ```
302pub struct FromInto<U>(PhantomData<fn() -> U>);
303
304impl<'de, T, U> Deserialize<'de, T> for FromInto<U>
305where
306    T: Send,
307    U: Deserialize<'de> + Into<T> + 'static,
308{
309    fn deserialize_into<'out>(
310        out: &'out mut Option<T>,
311        state: &mut State,
312    ) -> SinkHandle<'out, 'de> {
313        MappedSink::handle(
314            out,
315            OwnedSink::<U>::deserialize(state),
316            |value| Ok(value.into()),
317            state,
318        )
319    }
320
321    fn expecting() -> Cow<'static, str> {
322        U::expecting()
323    }
324
325    fn initial_value() -> Option<T> {
326        U::initial_value().map(Into::into)
327    }
328
329    #[inline]
330    fn __private_atom_into(
331        out: &mut Option<T>,
332        atom: Atom,
333        state: &mut State,
334    ) -> Result<(), Error> {
335        let mut inner = None;
336        U::__private_atom_into(&mut inner, atom, state)?;
337        *out = inner.map(Into::into);
338        Ok(())
339    }
340
341    #[inline]
342    fn __private_borrowed_atom_into(
343        out: &mut Option<T>,
344        atom: Atom<'de>,
345        state: &mut State,
346    ) -> Result<(), Error> {
347        let mut inner = None;
348        U::__private_borrowed_atom_into(&mut inner, atom, state)?;
349        *out = inner.map(Into::into);
350        Ok(())
351    }
352}
353
354impl<T, U> Serialize<T> for FromInto<U>
355where
356    T: Clone + Into<U>,
357    U: Serialize + Send + 'static,
358{
359    fn serialize<'a>(value: &'a T, state: &mut State) -> Result<Emit<'a>, Error> {
360        Ok(Emit::Forward(SerializeHandle::arena(
361            Into::<U>::into(value.clone()),
362            state,
363        )))
364    }
365
366    // this clones once more, but only `skip_serializing_optionals` asks.
367    // Without converting there is no way to know as `()` is optional too.
368    fn is_optional(value: &T) -> bool {
369        U::is_optional(&Into::<U>::into(value.clone()))
370    }
371}
372
373/// Converts from and into another type with fallible conversions.
374///
375/// This is like [`FromInto`] but uses [`TryFrom`] and [`TryInto`].  Failed
376/// conversions are reported as errors.  Like with [`FromInto`] the value is
377/// cloned and converted once more with `#[deser(skip_serializing_optionals)]`
378/// to find out if it's optional.
379///
380/// ```
381/// use deser::{Deserialize, Serialize};
382/// use deser::adapters::TryFromInto;
383///
384/// #[derive(Clone)]
385/// pub struct Percent(u8);
386///
387/// impl TryFrom<u64> for Percent {
388///     type Error = &'static str;
389///     fn try_from(value: u64) -> Result<Percent, Self::Error> {
390///         if value <= 100 {
391///             Ok(Percent(value as u8))
392///         } else {
393///             Err("out of range")
394///         }
395///     }
396/// }
397///
398/// impl TryFrom<Percent> for u64 {
399///     type Error = std::convert::Infallible;
400///     fn try_from(value: Percent) -> Result<u64, Self::Error> {
401///         Ok(value.0 as u64)
402///     }
403/// }
404///
405/// #[derive(Serialize, Deserialize)]
406/// pub struct Progress {
407///     #[deser(as = TryFromInto<u64>)]
408///     done: Percent,
409/// }
410/// ```
411pub struct TryFromInto<U>(PhantomData<fn() -> U>);
412
413impl<'de, T, U> Deserialize<'de, T> for TryFromInto<U>
414where
415    U: Deserialize<'de> + 'static,
416    T: TryFrom<U> + Send,
417    T::Error: Display,
418{
419    fn deserialize_into<'out>(
420        out: &'out mut Option<T>,
421        state: &mut State,
422    ) -> SinkHandle<'out, 'de> {
423        MappedSink::handle(
424            out,
425            OwnedSink::<U>::deserialize(state),
426            |value| T::try_from(value).map_err(conversion_error),
427            state,
428        )
429    }
430
431    fn expecting() -> Cow<'static, str> {
432        U::expecting()
433    }
434
435    fn initial_value() -> Option<T> {
436        U::initial_value().and_then(|value| T::try_from(value).ok())
437    }
438
439    #[inline]
440    fn __private_atom_into(
441        out: &mut Option<T>,
442        atom: Atom,
443        state: &mut State,
444    ) -> Result<(), Error> {
445        let mut inner = None;
446        U::__private_atom_into(&mut inner, atom, state)?;
447        *out = match inner {
448            Some(value) => Some(T::try_from(value).map_err(conversion_error)?),
449            None => None,
450        };
451        Ok(())
452    }
453
454    #[inline]
455    fn __private_borrowed_atom_into(
456        out: &mut Option<T>,
457        atom: Atom<'de>,
458        state: &mut State,
459    ) -> Result<(), Error> {
460        let mut inner = None;
461        U::__private_borrowed_atom_into(&mut inner, atom, state)?;
462        *out = match inner {
463            Some(value) => Some(T::try_from(value).map_err(conversion_error)?),
464            None => None,
465        };
466        Ok(())
467    }
468}
469
470impl<T, U> Serialize<T> for TryFromInto<U>
471where
472    T: Clone + TryInto<U>,
473    <T as TryInto<U>>::Error: Display,
474    U: Serialize + Send + 'static,
475{
476    fn serialize<'a>(value: &'a T, state: &mut State) -> Result<Emit<'a>, Error> {
477        let value: U = value.clone().try_into().map_err(conversion_error)?;
478        Ok(Emit::Forward(SerializeHandle::arena(value, state)))
479    }
480
481    fn is_optional(value: &T) -> bool {
482        TryInto::<U>::try_into(value.clone()).is_ok_and(|x| U::is_optional(&x))
483    }
484}
485
486/// Uses the [`Default`] if a value cannot be deserialized.
487///
488/// The value is deserialized with the adapter `A` (by default [`Same`]).  If
489/// that fails, the default value is used instead and the rest of the value
490/// is skipped (see [`Sink::recover`]).  Only errors of the value are
491/// handled, errors of the data format and of layers (such as
492/// [`Limits`](crate::de::Limits)) still fail the deserialization.  Missing
493/// values are handled by the inner adapter.  Serialization uses the inner
494/// adapter.
495///
496/// ```
497/// use deser::Deserialize;
498/// use deser::adapters::DefaultOnError;
499///
500/// #[derive(Deserialize)]
501/// pub enum Kind {
502///     A,
503///     B,
504/// }
505///
506/// #[derive(Deserialize)]
507/// pub struct Item {
508///     // unknown kinds become `None`
509///     #[deser(as = DefaultOnError)]
510///     kind: Option<Kind>,
511/// }
512/// ```
513pub struct DefaultOnError<A = Same>(PhantomData<fn() -> A>);
514
515impl<'de, T: Default + Send, A: Deserialize<'de, T>> Deserialize<'de, T> for DefaultOnError<A> {
516    fn deserialize_into<'out>(
517        out: &'out mut Option<T>,
518        state: &mut State,
519    ) -> SinkHandle<'out, 'de> {
520        SinkHandle::arena(
521            DefaultOnErrorSink {
522                out,
523                sink: Some(OwnedSink::deserialize_as::<A>(state)),
524            },
525            state,
526        )
527    }
528
529    fn expecting() -> Cow<'static, str> {
530        A::expecting()
531    }
532
533    fn describe_type(d: &mut dyn Describe) {
534        A::describe_type(d)
535    }
536
537    fn initial_value() -> Option<T> {
538        A::initial_value()
539    }
540
541    // Collections collect the values of a repeated key, a value that fails
542    // resets the collection to the default.
543
544    fn __private_collects() -> bool {
545        A::__private_collects()
546    }
547
548    fn __private_collect_into<'out>(
549        out: &'out mut Option<T>,
550        state: &mut State,
551    ) -> SinkHandle<'out, 'de> {
552        let collected = out.take();
553        let sink = OwnedSink::with_slot(collected, A::__private_collect_into, state);
554        SinkHandle::arena(
555            DefaultOnErrorSink {
556                out,
557                sink: Some(sink),
558            },
559            state,
560        )
561    }
562
563    fn __private_collect_empty() -> Option<T> {
564        A::__private_collect_empty()
565    }
566
567    #[inline]
568    fn __private_atom_into(
569        out: &mut Option<T>,
570        atom: Atom,
571        state: &mut State,
572    ) -> Result<(), Error> {
573        let mut value = None;
574        let rv = state.discard_errors(|state| A::__private_atom_into(&mut value, atom, state));
575        *out = Some(match (rv, value) {
576            (Ok(()), Some(value)) => value,
577            _ => T::default(),
578        });
579        Ok(())
580    }
581
582    #[inline]
583    fn __private_borrowed_atom_into(
584        out: &mut Option<T>,
585        atom: Atom<'de>,
586        state: &mut State,
587    ) -> Result<(), Error> {
588        let mut value = None;
589        let rv =
590            state.discard_errors(|state| A::__private_borrowed_atom_into(&mut value, atom, state));
591        *out = Some(match (rv, value) {
592            (Ok(()), Some(value)) => value,
593            _ => T::default(),
594        });
595        Ok(())
596    }
597}
598
599/// The sink of [`DefaultOnError`].
600struct DefaultOnErrorSink<'a, 'de, T> {
601    out: &'a mut Option<T>,
602    // `None` once the value failed, the rest of it is ignored then
603    sink: Option<OwnedSink<'de, T>>,
604}
605
606impl<'a, 'de, T> DefaultOnErrorSink<'a, 'de, T> {
607    /// Returns the sink of the value unless it failed.
608    fn sink(&mut self) -> Option<&mut (dyn Sink<'de> + '_)> {
609        self.sink.as_mut().map(|sink| sink.get_mut())
610    }
611
612    /// Discards the value if the result is an error.
613    fn check(&mut self, rv: Result<(), Error>) -> Result<(), Error> {
614        if rv.is_err() {
615            self.sink = None;
616        }
617        Ok(())
618    }
619}
620
621impl<'a, 'de, T: Default + Send> Sink<'de> for DefaultOnErrorSink<'a, 'de, T> {
622    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
623        let rv = match self.sink() {
624            Some(sink) => sink.atom(atom, state),
625            None => Ok(()),
626        };
627        self.check(rv)
628    }
629
630    fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
631        let rv = match self.sink() {
632            Some(sink) => sink.borrowed_atom(atom, state),
633            None => Ok(()),
634        };
635        self.check(rv)
636    }
637
638    fn map(&mut self, state: &mut State) -> Result<(), Error> {
639        let rv = match self.sink() {
640            Some(sink) => sink.map(state),
641            None => Ok(()),
642        };
643        self.check(rv)
644    }
645
646    fn seq(&mut self, state: &mut State) -> Result<(), Error> {
647        let rv = match self.sink() {
648            Some(sink) => sink.seq(state),
649            None => Ok(()),
650        };
651        self.check(rv)
652    }
653
654    // Errors of the items are handled in `recover`.
655
656    forward_to_optional!(sink);
657
658    fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
659        // the value might recover itself, otherwise it failed
660        if let Some(sink) = self.sink()
661            && sink.recover(err, state).is_ok()
662        {
663            return Ok(());
664        }
665        self.sink = None;
666        Ok(())
667    }
668
669    fn finish(&mut self, state: &mut State) -> Result<(), Error> {
670        let rv = match self.sink() {
671            Some(sink) => sink.finish(state),
672            None => Ok(()),
673        };
674        self.check(rv)?;
675        let value = self.sink.as_mut().and_then(|sink| sink.take());
676        *self.out = Some(value.unwrap_or_default());
677        Ok(())
678    }
679
680    fn expecting(&self) -> Cow<'_, str> {
681        match self.sink {
682            Some(ref sink) => sink.get().expecting(),
683            None => Cow::Borrowed("compatible type"),
684        }
685    }
686}
687
688impl<T: ?Sized, A: Serialize<T>> Serialize<T> for DefaultOnError<A> {
689    fn serialize<'a>(value: &'a T, state: &mut State) -> Result<Emit<'a>, Error> {
690        A::serialize(value, state)
691    }
692
693    fn finish(value: &T, state: &mut State) -> Result<(), Error> {
694        A::finish(value, state)
695    }
696
697    fn is_optional(value: &T) -> bool {
698        A::is_optional(value)
699    }
700
701    fn container_shape(value: &T) -> ContainerShape {
702        A::container_shape(value)
703    }
704
705    fn describe(value: &T, d: &mut dyn Describe) {
706        A::describe(value, d)
707    }
708
709    #[inline]
710    fn __private_begin<'a>(value: &'a T, state: &mut State) -> Result<Begin<'a>, Error> {
711        A::__private_begin(value, state)
712    }
713}
714
715/// Deserializes an atom and returns the value unless it failed.
716fn try_atom<'de, T: Send, A: Deserialize<'de, T>>(atom: Atom, state: &mut State) -> Option<T> {
717    let mut value = None;
718    match state.discard_errors(|state| A::__private_atom_into(&mut value, atom, state)) {
719        Ok(()) => value,
720        Err(_) => None,
721    }
722}
723
724/// Deserializes a borrowed atom and returns the value unless it failed.
725fn try_borrowed_atom<'de, T: Send, A: Deserialize<'de, T>>(
726    atom: Atom<'de>,
727    state: &mut State,
728) -> Option<T> {
729    let mut value = None;
730    match state.discard_errors(|state| A::__private_borrowed_atom_into(&mut value, atom, state)) {
731        Ok(()) => value,
732        Err(_) => None,
733    }
734}
735
736/// Skips elements of a vector which cannot be deserialized.
737///
738/// The elements are deserialized with the adapter `A` (by default
739/// [`Same`]).  If an element fails, the rest of it is skipped (see
740/// [`Sink::recover`]).  Only errors of the elements are handled, errors of
741/// the data format and of layers still fail the deserialization.
742/// Serialization uses the inner adapter for the elements.
743///
744/// ```
745/// use deser::Deserialize;
746/// use deser::adapters::VecSkipError;
747///
748/// #[derive(Deserialize)]
749/// pub enum Kind {
750///     A,
751///     B,
752/// }
753///
754/// #[derive(Deserialize)]
755/// pub struct Item {
756///     // unknown kinds are skipped
757///     #[deser(as = VecSkipError)]
758///     kinds: Vec<Kind>,
759/// }
760/// ```
761pub struct VecSkipError<A = Same>(PhantomData<fn() -> A>);
762
763impl<'de, T: Send, A: Deserialize<'de, T>> Deserialize<'de, Vec<T>> for VecSkipError<A> {
764    fn expecting() -> Cow<'static, str> {
765        Cow::Borrowed(<Vec<T> as SeqTarget<T>>::NAME)
766    }
767
768    fn deserialize_into<'out>(
769        out: &'out mut Option<Vec<T>>,
770        state: &mut State,
771    ) -> SinkHandle<'out, 'de> {
772        struct SkipSink<'a, T, A> {
773            slot: &'a mut Option<Vec<T>>,
774            vec: Vec<T>,
775            // the current element, added once the next one starts
776            item: Option<T>,
777            _marker: PhantomData<fn() -> A>,
778        }
779
780        impl<'a, T, A> SkipSink<'a, T, A> {
781            fn flush(&mut self) {
782                if let Some(item) = self.item.take() {
783                    self.vec.push(item);
784                }
785            }
786        }
787
788        impl<'a, 'de, T: Send, A: Deserialize<'de, T>> Sink<'de> for SkipSink<'a, T, A> {
789            fn expecting(&self) -> Cow<'_, str> {
790                Cow::Borrowed(<Vec<T> as SeqTarget<T>>::NAME)
791            }
792
793            fn seq(&mut self, _state: &mut State) -> Result<(), Error> {
794                Ok(())
795            }
796
797            fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
798                self.flush();
799                Ok(A::deserialize_into(&mut self.item, state))
800            }
801
802            fn recover(&mut self, _err: Error, _state: &mut State) -> Result<(), Error> {
803                self.item = None;
804                Ok(())
805            }
806
807            fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
808                self.flush();
809                if let Some(value) = try_atom::<T, A>(atom, state) {
810                    self.vec.push(value);
811                }
812                Ok(())
813            }
814
815            fn __private_borrowed_value_atom(
816                &mut self,
817                atom: Atom<'de>,
818                state: &mut State,
819            ) -> Result<(), Error> {
820                self.flush();
821                if let Some(value) = try_borrowed_atom::<T, A>(atom, state) {
822                    self.vec.push(value);
823                }
824                Ok(())
825            }
826
827            fn finish(&mut self, _state: &mut State) -> Result<(), Error> {
828                self.flush();
829                *self.slot = Some(take(&mut self.vec));
830                Ok(())
831            }
832        }
833
834        // SAFETY: `A` is an adapter, the sink only holds a marker of it
835        unsafe {
836            SinkHandle::arena_unbounded(
837                SkipSink::<T, A> {
838                    slot: out,
839                    vec: Vec::new(),
840                    item: None,
841                    _marker: PhantomData,
842                },
843                state,
844            )
845        }
846    }
847}
848
849impl<T: Sync, A: Serialize<T>> Serialize<Vec<T>> for VecSkipError<A> {
850    fn serialize<'a>(value: &'a Vec<T>, state: &mut State) -> Result<Emit<'a>, Error> {
851        <Vec<A> as Serialize<Vec<T>>>::serialize(value, state)
852    }
853
854    fn container_shape(value: &Vec<T>) -> ContainerShape {
855        <Vec<A> as Serialize<Vec<T>>>::container_shape(value)
856    }
857
858    fn describe(value: &Vec<T>, d: &mut dyn Describe) {
859        <Vec<A> as Serialize<Vec<T>>>::describe(value, d)
860    }
861
862    #[inline]
863    fn __private_begin<'a>(value: &'a Vec<T>, state: &mut State) -> Result<Begin<'a>, Error> {
864        <Vec<A> as Serialize<Vec<T>>>::__private_begin(value, state)
865    }
866}
867
868/// Skips entries of a map which cannot be deserialized.
869///
870/// Keys are deserialized with the adapter `KA` and values with `VA` (both
871/// [`Same`] by default).  If either of them fails, the rest of the entry is
872/// skipped (see [`Sink::recover`]).  Only errors of the entries are
873/// handled, errors of the data format and of layers still fail the
874/// deserialization.  Supported are [`BTreeMap`] and [`HashMap`].
875/// Serialization uses the inner adapters.
876///
877/// ```
878/// use std::collections::BTreeMap;
879/// use deser::Deserialize;
880/// use deser::adapters::MapSkipError;
881///
882/// #[derive(Deserialize, PartialEq, Eq, PartialOrd, Ord)]
883/// pub enum Kind {
884///     A,
885///     B,
886/// }
887///
888/// #[derive(Deserialize)]
889/// pub struct Weights {
890///     // entries with unknown kinds are skipped
891///     #[deser(as = MapSkipError)]
892///     weights: BTreeMap<Kind, f64>,
893/// }
894/// ```
895///
896#[cfg_attr(
897    not(feature = "std"),
898    doc = "[`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html"
899)]
900pub struct MapSkipError<KA = Same, VA = Same>(PhantomData<fn() -> (KA, VA)>);
901
902pub(crate) fn skip_map_sink<'a, 'de, M, K, V, KA, VA>(
903    out: &'a mut Option<M>,
904    state: &mut State,
905) -> SinkHandle<'a, 'de>
906where
907    M: MapTarget<K, V> + 'a,
908    K: Send + 'a,
909    V: Send + 'a,
910    KA: Deserialize<'de, K>,
911    VA: Deserialize<'de, V>,
912{
913    #[allow(clippy::type_complexity)]
914    struct SkipMapSink<'a, M, K, V, KA, VA> {
915        slot: &'a mut Option<M>,
916        map: M,
917        // the key of the current entry, `None` if it failed
918        key: Option<K>,
919        // the value of the current entry if it's not an atom, the entry is
920        // added once the next one starts
921        value: Option<V>,
922        // if the values of duplicate keys replace earlier ones.  With
923        // `DuplicateKeys::Error` duplicate entries fail and are skipped.
924        replace: bool,
925        _marker: PhantomData<fn() -> (V, KA, VA)>,
926    }
927
928    impl<'a, M: MapTarget<K, V>, K, V, KA, VA> SkipMapSink<'a, M, K, V, KA, VA> {
929        fn flush(&mut self) {
930            if let Some(value) = self.value.take()
931                && let Some(key) = self.key.take()
932            {
933                self.map.insert_entry(key, value, self.replace);
934            }
935            self.key = None;
936        }
937    }
938
939    impl<'a, 'de, M, K, V, KA, VA> Sink<'de> for SkipMapSink<'a, M, K, V, KA, VA>
940    where
941        M: MapTarget<K, V>,
942        K: Send,
943        V: Send,
944        KA: Deserialize<'de, K>,
945        VA: Deserialize<'de, V>,
946    {
947        fn expecting(&self) -> Cow<'_, str> {
948            Cow::Borrowed(M::NAME)
949        }
950
951        fn map(&mut self, state: &mut State) -> Result<(), Error> {
952            self.replace = DuplicateKeys::of(state) == DuplicateKeys::Last;
953            Ok(())
954        }
955
956        fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
957            self.flush();
958            Ok(KA::deserialize_into(&mut self.key, state))
959        }
960
961        fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
962            self.flush();
963            self.key = try_atom::<K, KA>(atom, state);
964            Ok(())
965        }
966
967        fn __private_borrowed_key_atom(
968            &mut self,
969            atom: Atom<'de>,
970            state: &mut State,
971        ) -> Result<(), Error> {
972            self.flush();
973            self.key = try_borrowed_atom::<K, KA>(atom, state);
974            Ok(())
975        }
976
977        fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
978            if self.key.is_none() {
979                return Ok(SinkHandle::null());
980            }
981            Ok(VA::deserialize_into(&mut self.value, state))
982        }
983
984        fn recover(&mut self, _err: Error, _state: &mut State) -> Result<(), Error> {
985            // the key or the value of the entry failed
986            self.key = None;
987            self.value = None;
988            Ok(())
989        }
990
991        fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
992            if let Some(key) = self.key.take()
993                && let Some(value) = try_atom::<V, VA>(atom, state)
994            {
995                self.map.insert_entry(key, value, self.replace);
996            }
997            Ok(())
998        }
999
1000        fn __private_borrowed_value_atom(
1001            &mut self,
1002            atom: Atom<'de>,
1003            state: &mut State,
1004        ) -> Result<(), Error> {
1005            if let Some(key) = self.key.take()
1006                && let Some(value) = try_borrowed_atom::<V, VA>(atom, state)
1007            {
1008                self.map.insert_entry(key, value, self.replace);
1009            }
1010            Ok(())
1011        }
1012
1013        fn finish(&mut self, _state: &mut State) -> Result<(), Error> {
1014            self.flush();
1015            *self.slot = Some(take(&mut self.map));
1016            Ok(())
1017        }
1018    }
1019
1020    // SAFETY: `KA` and `VA` are adapters, the sink only holds a marker of
1021    // them
1022    unsafe {
1023        SinkHandle::arena_unbounded(
1024            SkipMapSink::<M, K, V, KA, VA> {
1025                slot: out,
1026                map: M::default(),
1027                key: None,
1028                value: None,
1029                replace: true,
1030                _marker: PhantomData,
1031            },
1032            state,
1033        )
1034    }
1035}
1036
1037impl<'de, K, V, KA, VA> Deserialize<'de, BTreeMap<K, V>> for MapSkipError<KA, VA>
1038where
1039    K: Ord + Send,
1040    V: Send,
1041    KA: Deserialize<'de, K>,
1042    VA: Deserialize<'de, V>,
1043{
1044    fn deserialize_into<'out>(
1045        out: &'out mut Option<BTreeMap<K, V>>,
1046        state: &mut State,
1047    ) -> SinkHandle<'out, 'de> {
1048        skip_map_sink::<_, K, V, KA, VA>(out, state)
1049    }
1050
1051    fn expecting() -> Cow<'static, str> {
1052        Cow::Borrowed(<BTreeMap<K, V> as MapTarget<K, V>>::NAME)
1053    }
1054}
1055
1056#[cfg(feature = "std")]
1057impl<'de, K, V, H, KA, VA> Deserialize<'de, HashMap<K, V, H>> for MapSkipError<KA, VA>
1058where
1059    K: Hash + Eq + Send,
1060    V: Send,
1061    H: BuildHasher + Default + Send,
1062    KA: Deserialize<'de, K>,
1063    VA: Deserialize<'de, V>,
1064{
1065    fn deserialize_into<'out>(
1066        out: &'out mut Option<HashMap<K, V, H>>,
1067        state: &mut State,
1068    ) -> SinkHandle<'out, 'de> {
1069        skip_map_sink::<_, K, V, KA, VA>(out, state)
1070    }
1071
1072    fn expecting() -> Cow<'static, str> {
1073        Cow::Borrowed(<HashMap<K, V, H> as MapTarget<K, V>>::NAME)
1074    }
1075}
1076
1077impl<K, V, KA, VA> Serialize<BTreeMap<K, V>> for MapSkipError<KA, VA>
1078where
1079    K: Sync,
1080    V: Sync,
1081    KA: Serialize<K>,
1082    VA: Serialize<V>,
1083{
1084    fn serialize<'a>(value: &'a BTreeMap<K, V>, state: &mut State) -> Result<Emit<'a>, Error> {
1085        <BTreeMap<KA, VA> as Serialize<BTreeMap<K, V>>>::serialize(value, state)
1086    }
1087
1088    fn container_shape(value: &BTreeMap<K, V>) -> ContainerShape {
1089        <BTreeMap<KA, VA> as Serialize<BTreeMap<K, V>>>::container_shape(value)
1090    }
1091
1092    fn describe(value: &BTreeMap<K, V>, d: &mut dyn Describe) {
1093        <BTreeMap<KA, VA> as Serialize<BTreeMap<K, V>>>::describe(value, d)
1094    }
1095}
1096
1097#[cfg(feature = "std")]
1098impl<K, V, H, KA, VA> Serialize<HashMap<K, V, H>> for MapSkipError<KA, VA>
1099where
1100    K: Sync,
1101    V: Sync,
1102    H: BuildHasher + Sync,
1103    KA: Serialize<K>,
1104    VA: Serialize<V>,
1105{
1106    fn serialize<'a>(value: &'a HashMap<K, V, H>, state: &mut State) -> Result<Emit<'a>, Error> {
1107        <HashMap<KA, VA> as Serialize<HashMap<K, V, H>>>::serialize(value, state)
1108    }
1109
1110    fn container_shape(value: &HashMap<K, V, H>) -> ContainerShape {
1111        <HashMap<KA, VA> as Serialize<HashMap<K, V, H>>>::container_shape(value)
1112    }
1113
1114    fn describe(value: &HashMap<K, V, H>, d: &mut dyn Describe) {
1115        <HashMap<KA, VA> as Serialize<HashMap<K, V, H>>>::describe(value, d)
1116    }
1117}