Skip to main content

deser_core/de/
mod.rs

1//! Generic data structure deserialization framework.
2//!
3//! Deserialization is based on the [`Sink`] and [`Deserialize`] traits.
4//! When deserialization is started the target deserializable object
5//! is attached to a destination slot.  As deserialization is happening
6//! the value is placed there.
7//!
8//! # Slots and Sinks
9//!
10//! Deserialization is based on "slots" and "sinks".  The basic idea is that when a
11//! type should be deserialized a slot in the form of an `Option<T>` is passed
12//! to it where the deserialized value will be placed.  The events of the
13//! value are received by a [`Sink`] which places the value in the slot.
14//! [`Deserialize::deserialize_into`] returns the sink of a slot in a
15//! [`SinkHandle`].  There are two ways to implement [`Deserialize`]:
16//!
17//! * Values that are deserialized from a single [`Atom`] (like numbers or
18//!   strings) implement [`Deserialize::deserialize_atom`].  They need no
19//!   state: the slot itself (a [`Slot`], which dereferences to the
20//!   `Option<T>`) is their sink and nothing needs to be allocated (see
21//!   [Deserializing Primitives](#deserializing-primitives)).
22//! * All other values (like structs, maps and sequences) implement
23//!   [`Deserialize::deserialize_into`] and return a sink of their own which
24//!   holds the state of the deserialization (see
25//!   [Struct Deserialization](#struct-deserialization)).
26//!
27//! # Streaming Deserialization
28//!
29//! Driving sinks by hand is tricky due to their lifetimes, so a safe
30//! abstraction is provided with the [`DeserializeDriver`].  It drives the
31//! deserialization without using the call stack for nesting: you emit
32//! events into it and the driver passes them on to the right sinks.
33//!
34//! ```rust
35//! use std::collections::BTreeMap;
36//! use deser::de::DeserializeDriver;
37//! use deser::Event;
38//!
39//! let mut out = None::<BTreeMap<u32, String>>;
40//! {
41//!     let mut driver = DeserializeDriver::new(&mut out);
42//!     // emit takes values that implement Into<Event>
43//!     driver.emit(Event::map_start()).unwrap();
44//!     driver.emit(1i64).unwrap();
45//!     driver.emit("Hello").unwrap();
46//!     driver.emit(2i64).unwrap();
47//!     driver.emit("World").unwrap();
48//!     driver.emit(Event::MapEnd).unwrap();
49//! }
50//!
51//! let map = out.unwrap();
52//! assert_eq!(map[&1], "Hello");
53//! assert_eq!(map[&2], "World");
54//! ```
55//!
56//! The deserializers of data formats implement the [`Deserializer`] trait
57//! which feeds the events of a value into a driver.  Functions like
58//! `from_str` are implemented with [`deserialize_value`] so that only the
59//! code that depends on the type of the value exists once per type.
60//!
61//! # Layers and Wrapped Sinks
62//!
63//! There are two ways to change how a deserialization is processed without
64//! support by the format or the types:
65//!
66//! * [`Layer`]s sit between the format and the driver and see the events.
67//!   They are useful for everything that can be derived from the events,
68//!   for instance to track the current path or to rewrite values.
69//!   [`Limits`] (which are given in the [`Context`](crate::Context)) are
70//!   enforced the same way.
71//! * Wrapped sinks (see [`DeserializeDriver::wrap_sink`]) sit between the
72//!   driver and the sinks of the values.  They are useful for changes that
73//!   depend on the target types.
74//!
75//! Both are set up with [`Deserializer::deserialize_with`].
76//!
77//! # Deserializing Primitives
78//!
79//! Primitives are deserialized from [`Atom`]s.  As no state is needed for
80//! this, you only implement [`Deserialize::deserialize_atom`] which receives
81//! the atom and the [`Slot`] the resulting value must be placed in.  In this
82//! example we want to accept a `bool`:
83//!
84//! ```rust
85//! use std::borrow::Cow;
86//! use deser::de::{Deserialize, Slot, default_atom};
87//! use deser::{Atom, Error, State};
88//!
89//! struct MyBool(bool);
90//!
91//! impl<'de> Deserialize<'de> for MyBool {
92//!     fn deserialize_atom(
93//!         slot: &mut Slot<Self>,
94//!         atom: Atom,
95//!         state: &mut State,
96//!     ) -> Result<(), Error> {
97//!         match atom {
98//!             Atom::Bool(value) => {
99//!                 slot.set(MyBool(value));
100//!                 Ok(())
101//!             }
102//!             // any other atom goes to the default handling, which passes
103//!             // some atoms on in another form (like extension values as
104//!             // their fallback) and rejects the rest
105//!             other => default_atom(slot, other, state),
106//!         }
107//!     }
108//!
109//!     // what is expected in error messages, this defaults to the name
110//!     // of the type
111//!     fn expecting() -> Cow<'static, str> {
112//!         Cow::Borrowed("bool")
113//!     }
114//! }
115//! ```
116//!
117//! # Struct Deserialization
118//!
119//! If you want to deserialize a struct you need a sink that implements the
120//! map methods.  As the sink keeps track of state, you implement
121//! [`deserialize_into`](Deserialize::deserialize_into) which returns a sink
122//! that is owned by the handle (allocated in the arena of the
123//! deserialization with [`SinkHandle::arena`]).
124//!
125//! ```rust
126//! use std::borrow::Cow;
127//! use deser::de::{Deserialize, Sink, SinkHandle};
128//! use deser::State;
129//! use deser::{Error, ErrorKind};
130//!
131//! struct Flag {
132//!     enabled: bool,
133//!     name: String,
134//! }
135//!
136//! impl<'de> Deserialize<'de> for Flag {
137//!     fn deserialize_into<'out>(
138//!         out: &'out mut Option<Self>,
139//!         state: &mut State,
140//!     ) -> SinkHandle<'out, 'de> {
141//!         let sink = FlagSink {
142//!             out,
143//!             key: None,
144//!             enabled: None,
145//!             name: None,
146//!         };
147//!         SinkHandle::arena(sink, state)
148//!     }
149//!
150//!     // what is expected in error messages (like for a string that is
151//!     // passed instead of the map)
152//!     fn expecting() -> Cow<'static, str> {
153//!         Cow::Borrowed("flag")
154//!     }
155//! }
156//!
157//! struct FlagSink<'a> {
158//!     out: &'a mut Option<Flag>,
159//!     key: Option<String>,
160//!     enabled: Option<bool>,
161//!     name: Option<String>,
162//! }
163//!
164//! impl<'a, 'de> Sink<'de> for FlagSink<'a> {
165//!     // the sink of a value reports what the value expects
166//!     fn expecting(&self) -> Cow<'_, str> {
167//!         Flag::expecting()
168//!     }
169//!
170//!     fn map(&mut self, _state: &mut State) -> Result<(), Error> {
171//!         // the default implementation returns an error, so we need to
172//!         // override it to remove this error.
173//!         Ok(())
174//!     }
175//!
176//!     fn next_key(
177//!         &mut self,
178//!         state: &mut State,
179//!     ) -> Result<SinkHandle<'_, 'de>, Error> {
180//!         // directly attach to the key field which can hold any
181//!         // string value.  This means that any string is accepted
182//!         // as key.
183//!         Ok(String::deserialize_into(&mut self.key, state))
184//!     }
185//!
186//!     fn next_value(
187//!         &mut self,
188//!         state: &mut State,
189//!     ) -> Result<SinkHandle<'_, 'de>, Error> {
190//!         let key = self.key.take().unwrap();
191//!         // since we implement a sink for a struct, move the actual logic
192//!         // for matching into `value_for_key` so that our deserializer can
193//!         // support struct flattening.  If we don't know the key, just
194//!         // return a null handle to ignore it.
195//!         let handle = self.value_for_key(&key, state)?;
196//!         Ok(handle.unwrap_or_else(SinkHandle::null))
197//!     }
198//!
199//!     fn value_for_key(
200//!         &mut self,
201//!         key: &str,
202//!         state: &mut State,
203//!     ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
204//!         Ok(Some(match key {
205//!             "enabled" => bool::deserialize_into(&mut self.enabled, state),
206//!             "name" => String::deserialize_into(&mut self.name, state),
207//!             _ => return Ok(None),
208//!         }))
209//!     }
210//!
211//!     fn finish(&mut self, _state: &mut State) -> Result<(), Error> {
212//!         // when we're done, write the final value into the output slot.
213//!         let enabled = self.enabled.take().ok_or_else(|| {
214//!             Error::new(ErrorKind::MissingField, "field 'enabled' missing")
215//!         })?;
216//!         let name = self.name.take().ok_or_else(|| {
217//!             Error::new(ErrorKind::MissingField, "field 'name' missing")
218//!         })?;
219//!         *self.out = Some(Flag { enabled, name });
220//!         Ok(())
221//!     }
222//! }
223//! ```
224//!
225//! # Owned Sinks and Slots
226//!
227//! From the above model you can see that deserialization requires a
228//! mutable reference to an `Option`.  In certain situations it can become
229//! necessary to "make up a slot on the spot" to temporarily deserialize
230//! into.  [`OwnedSink`] bundles a sink with its slot and [`OwnedDriver`]
231//! a driver with the slot of the value it deserializes.
232use alloc::borrow::Cow;
233use alloc::vec::Vec;
234
235use crate::error::Error;
236use crate::event::Atom;
237
238pub(crate) mod atoms;
239mod collect;
240mod deserializer;
241mod driver;
242pub(crate) mod duplicates;
243#[cfg(feature = "derive")]
244pub(crate) mod enums;
245#[cfg(feature = "derive")]
246pub(crate) mod fields;
247mod ignore;
248pub(crate) mod impls;
249mod layer;
250pub(crate) mod lexical;
251mod limits;
252pub(crate) mod mapped;
253mod owned;
254pub(crate) mod recording;
255mod sinkbox;
256pub(crate) mod slot;
257mod stream;
258pub(crate) mod unknown;
259pub(crate) mod update;
260
261pub use self::atoms::default_atom;
262pub(crate) use self::atoms::{atom_into_handle, borrowed_atom_into_handle};
263use self::atoms::{
264    default_borrowed_key_atom, default_borrowed_value_atom, default_container, default_key_atom,
265    default_value_atom,
266};
267pub use self::collect::{CollectErrors, CollectedErrors};
268pub use self::deserializer::{Deserializer, deserialize_value};
269pub use self::driver::DeserializeDriver;
270pub use self::duplicates::DuplicateKeys;
271#[doc(hidden)]
272pub use self::impls::DeserializeArc;
273pub use self::layer::{Layer, LayerEvent, Next};
274pub use self::lexical::{ContentKey, LexicalRules};
275pub use self::limits::{Limits, LimitsBuilder};
276pub use self::owned::{OwnedDriver, OwnedSink};
277pub use self::recording::{RecordBuf, Recording};
278#[cfg(feature = "derive")]
279use self::sinkbox::ArenaStruct;
280use self::sinkbox::{ArenaSink, HeapSink, arena_sink};
281pub use self::slot::Slot;
282pub use self::stream::{Frame, Progress, StreamDeserializer};
283pub use self::unknown::{IgnoredFields, UnknownFields};
284pub use self::update::checked_update;
285use crate::State;
286
287/// Builds a sequence of atoms in the sink of the sequence it's an element
288/// of.
289///
290/// Sequences of a fixed number of atoms (like `[f32; 2]` or `(u8, u8)`)
291/// are small containers that appear in large numbers.  Instead of creating
292/// a sink for every one of them, the sink of the sequence they are
293/// elements of (see [`Sink::__private_seq`]) builds them in its slot for
294/// the element, the driver passes their events to it.  This has to behave
295/// exactly like the sink of the element.
296///
297/// Internal fast path, not public API (see `lib.rs`).
298#[doc(hidden)]
299pub struct InlineSeq<T> {
300    /// Starts the sequence in the slot.
301    pub start: fn(&mut Option<T>),
302    /// Deserializes the atom at the index.
303    pub atom: fn(&mut Option<T>, usize, Atom, &mut State) -> Result<(), Error>,
304    /// Ends the sequence with the given length.
305    pub end: fn(&mut Option<T>, usize) -> Result<(), Error>,
306    /// Returns the error for a map (`true`) or sequence at the index.
307    pub container: fn(usize, bool, &mut State) -> Error,
308}
309
310/// An event of a sequence that is built inline (see [`InlineSeq`]).
311///
312/// Internal fast path, not public API (see `lib.rs`).
313#[doc(hidden)]
314#[derive(Clone, Copy)]
315pub enum InlineEvent {
316    /// The sequence starts.
317    Start,
318    /// The sequence ends with the given length.
319    End(usize),
320    /// A map (`true`) or sequence starts at the index.
321    Container(usize, bool),
322}
323
324/// Panics as the sink does not build sequences inline.
325#[cold]
326#[inline(never)]
327fn no_inline_seq() -> ! {
328    panic!("the sink does not build sequences inline")
329}
330
331/// A handle to a [`Sink`].
332///
333/// During deserialization the sinks often need to return other sinks
334/// to recurse into structures.  This poses a challenge if the target
335/// sink cannot be directly borrowed.  This is where [`SinkHandle`]
336/// comes in.  In cases where the [`Sink`] cannot be borrowed it's owned
337/// by the handle, either in the arena of the state
338/// ([`arena`](Self::arena), which is what sinks typically use) or on the
339/// heap ([`heap`](Self::heap)).
340///
341/// The handle itself implements [`Sink`] and forwards all calls to the
342/// sink it holds.
343///
344/// Unlike the [`SerializeHandle`](crate::ser::SerializeHandle) of
345/// serialization, which holds a value that is not serialized yet, this
346/// holds a sink that is already deserializing a value.  The serialization
347/// equivalent of a sink is an emitter in a [`Emit`](crate::ser::Emit).
348/// The constructors line up: [`to`](Self::to) borrows,
349/// [`arena`](Self::arena) and [`heap`](Self::heap) own in the same way for
350/// both handles.
351pub struct SinkHandle<'a, 'de: 'a>(HandleInner<'a, 'de>);
352
353enum HandleInner<'a, 'de> {
354    Borrowed(&'a mut dyn Sink<'de>),
355    Arena(ArenaSink<'a, 'de>),
356    Heap(HeapSink<'a, 'de>),
357    #[cfg(feature = "derive")]
358    Struct(ArenaStruct<'a, 'de>),
359    Null(ignore::Ignore),
360    // The optional variants are used to implement `Option<T>` without an
361    // extra allocation: a null atom is not forwarded but turns the handle
362    // into a null handle so that `finish` is not forwarded either.
363    OptionalBorrowed(&'a mut dyn Sink<'de>),
364    OptionalArena(ArenaSink<'a, 'de>),
365    OptionalHeap(HeapSink<'a, 'de>),
366    #[cfg(feature = "derive")]
367    OptionalStruct(ArenaStruct<'a, 'de>),
368}
369
370impl<'a, 'de> SinkHandle<'a, 'de> {
371    /// Create a borrowed handle to a [`Sink`].
372    pub fn to(sink: &'a mut dyn Sink<'de>) -> SinkHandle<'a, 'de> {
373        SinkHandle(HandleInner::Borrowed(sink))
374    }
375
376    /// Creates an owned handle to a sink in the arena of the state.
377    ///
378    /// This is how sinks are typically created: the arena belongs to the
379    /// state of the deserialization and the sinks of the containers that
380    /// are open are on top of each other in it, allocating one is little
381    /// more than bumping a pointer.  Its space is reused once the handle is
382    /// dropped (and the sinks allocated after it are dropped too).
383    ///
384    /// A sink can outlive the deserialization it was created for (the
385    /// state).  The arena then frees its memory except for the chunk the
386    /// sink is in, which is freed when the sink is dropped (and the other
387    /// sinks in it).  A sink that is meant to be kept for longer should
388    /// rather be created with [`heap`](Self::heap).
389    ///
390    /// ```
391    /// use deser::de::{Deserialize, DeserializeDriver, Sink, SinkHandle};
392    /// use deser::{Error, Event, State};
393    ///
394    /// /// The number of items of a sequence.
395    /// struct Count(usize);
396    ///
397    /// struct CountSink<'a> {
398    ///     out: &'a mut Option<Count>,
399    ///     count: usize,
400    /// }
401    ///
402    /// impl<'de> Sink<'de> for CountSink<'_> {
403    ///     fn seq(&mut self, _state: &mut State) -> Result<(), Error> {
404    ///         Ok(())
405    ///     }
406    ///
407    ///     fn next_value(
408    ///         &mut self,
409    ///         _state: &mut State,
410    ///     ) -> Result<SinkHandle<'_, 'de>, Error> {
411    ///         self.count += 1;
412    ///         // the items themselves are ignored
413    ///         Ok(SinkHandle::null())
414    ///     }
415    ///
416    ///     fn finish(&mut self, _state: &mut State) -> Result<(), Error> {
417    ///         *self.out = Some(Count(self.count));
418    ///         Ok(())
419    ///     }
420    /// }
421    ///
422    /// impl<'de> Deserialize<'de> for Count {
423    ///     fn deserialize_into<'a>(
424    ///         out: &'a mut Option<Self>,
425    ///         state: &mut State,
426    ///     ) -> SinkHandle<'a, 'de> {
427    ///         SinkHandle::arena(CountSink { out, count: 0 }, state)
428    ///     }
429    /// }
430    ///
431    /// let mut out = None::<Count>;
432    /// let mut driver = DeserializeDriver::new(&mut out);
433    /// for event in [Event::seq_start(), "a".into(), "b".into(), Event::SeqEnd] {
434    ///     driver.emit(event).unwrap();
435    /// }
436    /// drop(driver);
437    /// assert_eq!(out.unwrap().0, 2);
438    /// ```
439    #[inline(always)]
440    pub fn arena<S: Sink<'de> + 'a>(sink: S, state: &mut State) -> SinkHandle<'a, 'de> {
441        SinkHandle(HandleInner::Arena(arena_sink(sink, &mut state.arena)))
442    }
443
444    /// Like [`arena`](Self::arena) but the sink does not need to outlive the
445    /// handle.
446    ///
447    /// This is how the implementations that are generic over adapters (like
448    /// `Vec<A>` for `Vec<T>`) create their sinks.  The compiler requires
449    /// the sink to outlive the handle, which includes the adapter.  The
450    /// adapter always does: it's either the type of the value, which
451    /// outlives the slot, or a marker type.  But this cannot be expressed.
452    ///
453    /// # Safety
454    ///
455    /// Everything the sink holds has to outlive `'a`.  The type parameters
456    /// that do not need to outlive it are the ones of adapters, which are
457    /// only used for their functions and never instantiated (the sink holds
458    /// no values of them, only markers like `PhantomData<fn() -> A>`).
459    /// Functions cannot hold borrowed data.
460    #[inline(always)]
461    pub(crate) unsafe fn arena_unbounded<S: Sink<'de>>(
462        sink: S,
463        state: &mut State,
464    ) -> SinkHandle<'a, 'de> {
465        // SAFETY: guaranteed by the caller
466        SinkHandle(HandleInner::Arena(unsafe {
467            sinkbox::arena_sink_unbounded(sink, &mut state.arena)
468        }))
469    }
470
471    /// Drops the handle, the block of an owned sink is returned to the arena
472    /// of the state right away if it's the top block.
473    ///
474    /// Dropping the handle has the same effect, but the block is only
475    /// reused when the next sink is allocated.  The driver does this with
476    /// the sinks of the containers it closes.
477    #[inline(always)]
478    pub(crate) fn release(self, state: &mut State) {
479        match self.0 {
480            HandleInner::Arena(sink) | HandleInner::OptionalArena(sink) => {
481                crate::arena::ArenaBox::release_in(sink, &mut state.arena)
482            }
483            #[cfg(feature = "derive")]
484            HandleInner::Struct(sink) | HandleInner::OptionalStruct(sink) => {
485                sink.release_in(&mut state.arena)
486            }
487            _ => {}
488        }
489    }
490
491    /// Creates an owned handle to a sink on the heap.
492    ///
493    /// Unlike [`arena`](Self::arena) the sink does not need a state and is
494    /// independent of any deserialization, but every sink is a separate
495    /// allocation.
496    pub fn heap<S: Sink<'de> + 'a>(sink: S) -> SinkHandle<'a, 'de> {
497        SinkHandle(HandleInner::Heap(HeapSink::new(sink)))
498    }
499
500    /// Creates an owned handle to the sink of a derived struct.
501    #[cfg(feature = "derive")]
502    #[inline]
503    pub(crate) fn from_arena_struct(sink: ArenaStruct<'a, 'de>) -> SinkHandle<'a, 'de> {
504        SinkHandle(HandleInner::Struct(sink))
505    }
506
507    /// Creates a sink handle that drops all values.
508    ///
509    /// This can be used in places where a sink is required but no value
510    /// wants to be collected.  For instance it can be tricky to provide a
511    /// mutable reference to a sink from a function that doesn't have a way
512    /// to put a slot somewhere.
513    pub fn null() -> SinkHandle<'a, 'de> {
514        SinkHandle(HandleInner::Null(ignore::Ignore))
515    }
516
517    /// Shortens the lifetime of the handle.
518    ///
519    /// Handles are invariant over their lifetime, this performs the
520    /// conversion explicitly.
521    pub fn shorten<'b>(self) -> SinkHandle<'b, 'de>
522    where
523        'a: 'b,
524    {
525        SinkHandle(match self.0 {
526            HandleInner::Borrowed(sink) => HandleInner::Borrowed(sink),
527            HandleInner::Arena(sink) => HandleInner::Arena(sink),
528            HandleInner::Heap(sink) => HandleInner::Heap(sink),
529            HandleInner::Null(sink) => HandleInner::Null(sink),
530            HandleInner::OptionalBorrowed(sink) => HandleInner::OptionalBorrowed(sink),
531            HandleInner::OptionalArena(sink) => HandleInner::OptionalArena(sink),
532            HandleInner::OptionalHeap(sink) => HandleInner::OptionalHeap(sink),
533            #[cfg(feature = "derive")]
534            HandleInner::Struct(sink) => HandleInner::Struct(sink),
535            #[cfg(feature = "derive")]
536            HandleInner::OptionalStruct(sink) => HandleInner::OptionalStruct(sink),
537        })
538    }
539
540    /// Returns `true` if this is a null handle.
541    pub fn is_null(&self) -> bool {
542        matches!(self.0, HandleInner::Null(_))
543    }
544
545    /// Converts the handle into one that ignores null atoms.
546    ///
547    /// When a null atom is received the wrapped sink is not invoked (not even
548    /// [`finish`](Sink::finish)) and the handle turns into a null handle.  An
549    /// atom counts as null if it is [`Atom::Null`] or an extension value which
550    /// falls back to null.  An empty [`Atom::Lexical`] (like the value of
551    /// `?limit=` in a query string) is passed to the wrapped sink, if the
552    /// sink rejects it the handle turns into a null handle too.
553    ///
554    /// This is used to implement `Option<T>`: the slot is set to `Some(None)`
555    /// before the handle of the inner value is created and made to ignore
556    /// nulls.
557    ///
558    /// ```
559    /// use deser::State;
560    /// use deser::de::{Deserialize, SinkHandle};
561    ///
562    /// /// Deserializes like an `Option<T>`.
563    /// fn deserialize_optional<'a, 'de, T: Deserialize<'de>>(
564    ///     out: &'a mut Option<Option<T>>,
565    ///     state: &mut State,
566    /// ) -> SinkHandle<'a, 'de> {
567    ///     T::deserialize_into(out.insert(None), state).ignore_null()
568    /// }
569    /// ```
570    pub fn ignore_null(self) -> SinkHandle<'a, 'de> {
571        SinkHandle(match self.0 {
572            HandleInner::Borrowed(sink) => HandleInner::OptionalBorrowed(sink),
573            HandleInner::Arena(sink) => HandleInner::OptionalArena(sink),
574            HandleInner::Heap(sink) => HandleInner::OptionalHeap(sink),
575            #[cfg(feature = "derive")]
576            HandleInner::Struct(sink) => HandleInner::OptionalStruct(sink),
577            other => other,
578        })
579    }
580
581    /// Returns `true` if the handle ignores the atom because it's null.
582    ///
583    /// In that case the handle turned into a null handle.
584    #[inline(always)]
585    fn skip_null(&mut self, atom: &Atom) -> bool {
586        if self.is_optional() && is_null_atom(atom) {
587            *self = SinkHandle::null();
588            return true;
589        }
590        false
591    }
592
593    #[inline(always)]
594    fn sink(&self) -> &(dyn Sink<'de> + 'a) {
595        match self.0 {
596            HandleInner::Borrowed(ref sink) | HandleInner::OptionalBorrowed(ref sink) => &**sink,
597            HandleInner::Arena(ref sink) | HandleInner::OptionalArena(ref sink) => sink.get(),
598            HandleInner::Heap(ref sink) | HandleInner::OptionalHeap(ref sink) => sink.get(),
599            #[cfg(feature = "derive")]
600            HandleInner::Struct(ref sink) | HandleInner::OptionalStruct(ref sink) => sink.get(),
601            HandleInner::Null(ref sink) => sink,
602        }
603    }
604
605    #[inline(always)]
606    fn sink_mut(&mut self) -> &mut (dyn Sink<'de> + 'a) {
607        match self.0 {
608            HandleInner::Borrowed(ref mut sink) | HandleInner::OptionalBorrowed(ref mut sink) => {
609                &mut **sink
610            }
611            HandleInner::Arena(ref mut sink) | HandleInner::OptionalArena(ref mut sink) => {
612                sink.get_mut()
613            }
614            HandleInner::Heap(ref mut sink) | HandleInner::OptionalHeap(ref mut sink) => {
615                sink.get_mut()
616            }
617            #[cfg(feature = "derive")]
618            HandleInner::Struct(ref mut sink) | HandleInner::OptionalStruct(ref mut sink) => {
619                sink.get_mut()
620            }
621            HandleInner::Null(ref mut sink) => sink,
622        }
623    }
624}
625
626#[cold]
627fn is_null_ext(ext: &crate::ext::ExtValue) -> bool {
628    matches!(ext.fallback(), Atom::Null)
629}
630
631/// Checks if an atom is a null for the purpose of optionals.
632#[inline]
633pub(crate) fn is_null_atom(atom: &Atom) -> bool {
634    match atom {
635        Atom::Null => true,
636        // an extension value that falls back to null (for instance a
637        // null with additional information attached) is a null too.
638        Atom::Ext(ext) => is_null_ext(ext),
639        Atom::Implicit(value) => value.value() == crate::ImplicitValue::Null,
640        _ => false,
641    }
642}
643
644/// Checks if an atom is an empty lexical atom that is a missing value.
645///
646/// Optionals are `None` for these if the value rejects them (like the
647/// empty value of a number in a query string), see [`LexicalRules`].
648#[inline]
649pub(crate) fn is_empty_lexical(atom: &Atom, state: &State) -> bool {
650    matches!(atom, Atom::Lexical(value) if lexical::is_empty_null(value, state))
651}
652
653/// Delivers an empty lexical atom to an optional value.
654///
655/// Returns `false` if the value rejects it (see `ErrorKind::is_rejection`),
656/// the optional is `None` then.  As that error is thrown away, it's created
657/// without a message (optional numbers are empty in every other row of
658/// some CSV files).  Other errors are passed on with their message (the
659/// atom is delivered again for this).
660#[inline]
661pub(crate) fn empty_lexical_or_none<'a>(
662    atom: Atom<'a>,
663    state: &mut State,
664    mut deliver: impl FnMut(Atom<'a>, &mut State) -> Result<(), Error>,
665) -> Result<bool, Error> {
666    let retry = atom.clone();
667    match state.discard_errors(|state| deliver(atom, state)) {
668        Ok(()) => Ok(true),
669        Err(err) if err.kind().is_rejection() => Ok(false),
670        Err(err) if state.discards_errors => Err(err),
671        Err(_) => deliver(retry, state).map(|()| true),
672    }
673}
674
675impl<'a, 'de> SinkHandle<'a, 'de> {
676    /// Returns `true` if the handle ignores null atoms (see
677    /// [`ignore_null`](Self::ignore_null)).
678    #[inline(always)]
679    fn is_optional(&self) -> bool {
680        match self.0 {
681            HandleInner::OptionalBorrowed(_)
682            | HandleInner::OptionalArena(_)
683            | HandleInner::OptionalHeap(_) => true,
684            #[cfg(feature = "derive")]
685            HandleInner::OptionalStruct(_) => true,
686            _ => false,
687        }
688    }
689
690    // The handling of empty lexical atoms by optionals is not inlined into
691    // `atom` and `borrowed_atom`: it clones and retries the atom, which
692    // made every copy of them (and of the functions they are inlined into,
693    // like `atom_into_handle`) much larger.
694
695    /// Delivers an empty lexical atom to an optional handle (see
696    /// `empty_lexical_or_none`).
697    #[cold]
698    #[inline(never)]
699    fn empty_lexical_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
700        if !empty_lexical_or_none(atom, state, |atom, state| self.sink_mut().atom(atom, state))? {
701            *self = SinkHandle::null();
702        }
703        Ok(())
704    }
705
706    /// Delivers an empty borrowed lexical atom to an optional handle (see
707    /// `empty_lexical_or_none`).
708    #[cold]
709    #[inline(never)]
710    fn empty_lexical_borrowed_atom(
711        &mut self,
712        atom: Atom<'de>,
713        state: &mut State,
714    ) -> Result<(), Error> {
715        let delivered = empty_lexical_or_none(atom, state, |atom, state| {
716            self.sink_mut().borrowed_atom(atom, state)
717        })?;
718        if !delivered {
719            *self = SinkHandle::null();
720        }
721        Ok(())
722    }
723}
724
725// The handle forwards to the sink it holds.
726impl<'a, 'de> Sink<'de> for SinkHandle<'a, 'de> {
727    #[inline]
728    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
729        if self.skip_null(&atom) {
730            return Ok(());
731        }
732        if self.is_optional() && is_empty_lexical(&atom, state) {
733            return self.empty_lexical_atom(atom, state);
734        }
735        self.sink_mut().atom(atom, state)
736    }
737
738    #[inline]
739    fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
740        if self.skip_null(&atom) {
741            return Ok(());
742        }
743        if self.is_optional() && is_empty_lexical(&atom, state) {
744            return self.empty_lexical_borrowed_atom(atom, state);
745        }
746        self.sink_mut().borrowed_atom(atom, state)
747    }
748
749    #[inline]
750    fn map(&mut self, state: &mut State) -> Result<(), Error> {
751        self.sink_mut().map(state)
752    }
753
754    #[inline]
755    fn seq(&mut self, state: &mut State) -> Result<(), Error> {
756        self.sink_mut().seq(state)
757    }
758
759    #[inline]
760    fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
761        self.sink_mut().next_key(state)
762    }
763
764    #[inline]
765    fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
766        self.sink_mut().next_value(state)
767    }
768
769    #[inline]
770    fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
771        self.sink_mut().__private_key_atom(atom, state)
772    }
773
774    #[inline]
775    fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
776        self.sink_mut().__private_value_atom(atom, state)
777    }
778
779    #[inline]
780    fn __private_borrowed_key_atom(
781        &mut self,
782        atom: Atom<'de>,
783        state: &mut State,
784    ) -> Result<(), Error> {
785        self.sink_mut().__private_borrowed_key_atom(atom, state)
786    }
787
788    #[inline]
789    fn __private_borrowed_value_atom(
790        &mut self,
791        atom: Atom<'de>,
792        state: &mut State,
793    ) -> Result<(), Error> {
794        self.sink_mut().__private_borrowed_value_atom(atom, state)
795    }
796
797    #[inline]
798    fn __private_seq(&mut self, state: &mut State) -> Result<bool, Error> {
799        self.sink_mut().__private_seq(state)
800    }
801
802    #[inline]
803    fn __private_inline_atom(
804        &mut self,
805        index: usize,
806        atom: Atom,
807        state: &mut State,
808    ) -> Result<(), Error> {
809        self.sink_mut().__private_inline_atom(index, atom, state)
810    }
811
812    #[inline]
813    fn __private_inline_event(
814        &mut self,
815        event: InlineEvent,
816        state: &mut State,
817    ) -> Result<(), Error> {
818        self.sink_mut().__private_inline_event(event, state)
819    }
820
821    fn value_for_key(
822        &mut self,
823        key: &str,
824        state: &mut State,
825    ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
826        self.sink_mut().value_for_key(key, state)
827    }
828
829    #[inline]
830    fn finish(&mut self, state: &mut State) -> Result<(), Error> {
831        self.sink_mut().finish(state)
832    }
833
834    fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
835        self.sink_mut().recover(err, state)
836    }
837
838    fn expecting(&self) -> Cow<'_, str> {
839        self.sink().expecting()
840    }
841}
842
843/// A trait for deserializable types.
844///
845/// A type is deserializable if it can create a [`Sink`] for its slot with
846/// [`deserialize_into`](Self::deserialize_into).  This is how values are
847/// deserialized, but there are two ways to implement it:
848///
849/// * Values that are deserialized from a single atom (like numbers or
850///   strings) implement [`deserialize_atom`](Self::deserialize_atom).  The
851///   default implementation of `deserialize_into` returns the slot itself
852///   as sink (see [`Slot`]), which passes the atom on.
853/// * All other values implement `deserialize_into` and return a sink of
854///   their own (see [`SinkHandle::arena`]), which implements the actual
855///   deserialization logic.
856///
857/// Either way, [`expecting`](Self::expecting) says what the value expects
858/// in error messages (the sink reports it).  If neither `deserialize_atom`
859/// nor `deserialize_into` is implemented, every value is rejected.  See the
860/// [module documentation](crate::de) for examples of both.
861///
862/// The lifetime `'de` is the lifetime of the data that is deserialized.
863/// Types that borrow from it (like `&'de str`) only implement
864/// `Deserialize<'de>` for that lifetime, types that do not borrow implement
865/// it for all lifetimes (see [`DeserializeOwned`]):
866///
867/// ```
868/// use deser::Deserialize;
869///
870/// #[derive(Deserialize)]
871/// struct User<'a> {
872///     name: &'a str,
873///     id: u64,
874/// }
875/// ```
876///
877/// Data can only be borrowed if the data format passes it on borrowed (see
878/// [`Sink::borrowed_atom`]).
879///
880/// # Adapters
881///
882/// The type parameter `T` is the type of the value that is deserialized.
883/// It defaults to `Self`: `impl Deserialize<'de> for Foo` deserializes
884/// `Foo` values.  A type that implements `Deserialize` for another type is
885/// an adapter, it deserializes values of that type on their behalf (see
886/// [`adapters`](crate::adapters)):
887///
888/// ```
889/// use std::borrow::Cow;
890/// use deser::de::Slot;
891/// use deser::{Atom, Deserialize, Error, State};
892///
893/// /// Deserializes a `u32` as `u16`.
894/// pub struct Small;
895///
896/// impl<'de> Deserialize<'de, u32> for Small {
897///     fn deserialize_atom(
898///         slot: &mut Slot<u32, Self>,
899///         atom: Atom,
900///         state: &mut State,
901///     ) -> Result<(), Error> {
902///         let mut value = None::<u16>;
903///         u16::deserialize_atom(Slot::wrap(&mut value), atom, state)?;
904///         **slot = value.map(u32::from);
905///         Ok(())
906///     }
907///
908///     fn expecting() -> Cow<'static, str> {
909///         Cow::Borrowed("u16")
910///     }
911/// }
912/// ```
913///
914/// Adapters are never instantiated, only their functions are used.
915///
916/// # Thread Safety
917///
918/// Deserializable values are `Send` and so are the sinks they create.  This
919/// allows an ongoing deserialization (a [`DeserializeDriver`]) to move
920/// between threads, for instance when it is suspended while waiting for more
921/// input.  Types that are not `Send` (such as `Rc`) cannot be deserialized,
922/// which is why `T` has to be `Send`.
923pub trait Deserialize<'de, T: Send = Self>: Sized + Send {
924    /// Creates a sink that deserializes the value into the given slot.
925    ///
926    /// This is how every value is deserialized, whichever way the type
927    /// implements `Deserialize`.  The default implementation returns the
928    /// slot itself as sink (see [`Slot`]), which passes atoms to
929    /// [`deserialize_atom`](Self::deserialize_atom).  This is what values
930    /// that are deserialized from atoms use.  Values that need state to be
931    /// deserialized (like maps and sequences) implement this and return
932    /// their own sink (see [`SinkHandle::arena`]).
933    #[inline]
934    fn deserialize_into<'out>(
935        out: &'out mut Option<T>,
936        state: &mut State,
937    ) -> SinkHandle<'out, 'de> {
938        // the slot is the sink, nothing is allocated in the state (the atoms
939        // come with the state)
940        let _ = state;
941        Slot::<T, Self>::handle(out)
942    }
943
944    /// Deserializes an atom into the slot.
945    ///
946    /// This is invoked by the sink of the default implementation of
947    /// [`deserialize_into`](Self::deserialize_into) (the slot itself, see
948    /// [`Slot`]) for every atom it receives.  The value is placed in the
949    /// slot, atoms which are not accepted are passed to [`default_atom`]
950    /// (with the slot as sink).  The default implementation does this for
951    /// every atom.
952    ///
953    /// Types that implement `deserialize_into` do not use this.  This also
954    /// means that calling it only deserializes values that implement it
955    /// (like the primitives), other values reject every atom.  To
956    /// deserialize an atom into any value, pass it to the sink returned by
957    /// `deserialize_into`.
958    fn deserialize_atom(
959        slot: &mut Slot<T, Self>,
960        atom: Atom,
961        state: &mut State,
962    ) -> Result<(), Error> {
963        default_atom(slot, atom, state)
964    }
965
966    /// Deserializes an atom that borrows from the data being deserialized
967    /// into the slot.
968    ///
969    /// This is like [`deserialize_atom`](Self::deserialize_atom) for
970    /// [`Sink::borrowed_atom`], which it forwards to by default.  Only values
971    /// which borrow (like `&'de str`) need to implement it.
972    fn deserialize_borrowed_atom(
973        slot: &mut Slot<T, Self>,
974        atom: Atom<'de>,
975        state: &mut State,
976    ) -> Result<(), Error> {
977        <Self as Deserialize<'de, T>>::deserialize_atom(slot, atom, state)
978    }
979
980    /// Returns what the value expects, for error messages.
981    ///
982    /// This is what the errors of values that do not match say they expect
983    /// (`unexpected map, expected u32`).  The sink of the value reports it
984    /// with [`Sink::expecting`]: the [`Slot`] returns this, sinks returned
985    /// by [`deserialize_into`](Self::deserialize_into) should return it as
986    /// well.  The derive returns the name of the type (or what
987    /// `#[deser(expecting = "...")]` says), wrappers like `Option<T>` and
988    /// `Box<T>` what their value expects.  The default implementation
989    /// returns the name of the type without the module paths (like
990    /// `Vec<Point>`), which is the name of the adapter for adapters.
991    fn expecting() -> Cow<'static, str> {
992        slot::short_type_name(core::any::type_name::<Self>())
993    }
994
995    /// Describes the Rust shape of the type.
996    ///
997    /// This is the counterpart of [`Serialize::describe`](crate::ser::Serialize::describe)
998    /// for what is known without a value: it receives the same
999    /// [`Describe`](crate::ser::Describe) calls the values of the type
1000    /// describe themselves with, except the ones that depend on the value
1001    /// (like [`some`](crate::ser::Describe::some) or
1002    /// [`variant`](crate::ser::Describe::variant)).  The default
1003    /// implementation describes nothing.  Wrappers which are deserialized as
1004    /// the value they wrap (like `Box<T>`) delegate to it.
1005    ///
1006    /// The derive describes unit structs, which are the tag alone in newtype
1007    /// variants of internally tagged enums (see
1008    /// [`Describe::unit_struct`](crate::ser::Describe::unit_struct)).
1009    /// Types that implement `Deserialize` by hand describe themselves as
1010    /// unit structs for that:
1011    ///
1012    /// ```
1013    /// use deser::de::{Deserialize, Slot, default_atom};
1014    /// use deser::ser::Describe;
1015    /// use deser::{Atom, Error, State};
1016    ///
1017    /// struct Marker;
1018    ///
1019    /// impl Deserialize<'_> for Marker {
1020    ///     fn deserialize_atom(
1021    ///         slot: &mut Slot<Self>,
1022    ///         atom: Atom,
1023    ///         state: &mut State,
1024    ///     ) -> Result<(), Error> {
1025    ///         match atom {
1026    ///             Atom::Null => {
1027    ///                 slot.set(Marker);
1028    ///                 Ok(())
1029    ///             }
1030    ///             other => default_atom(slot, other, state),
1031    ///         }
1032    ///     }
1033    ///
1034    ///     fn describe_type(d: &mut dyn Describe) {
1035    ///         d.unit_struct("Marker");
1036    ///     }
1037    /// }
1038    /// ```
1039    fn describe_type(d: &mut dyn crate::ser::Describe) {
1040        let _ = d;
1041    }
1042
1043    /// Provides the value of a missing struct field.
1044    ///
1045    /// When a struct is deserialized the slots of its fields start out with
1046    /// this value.  If a field does not appear in the data, the initial value
1047    /// is used.  If it is `None` (the default) the field is required.
1048    /// `Option<T>` returns `Some(None)` here which makes optional fields
1049    /// default to `None` when they are missing.
1050    ///
1051    /// This only controls missing values.  How null values are handled is up
1052    /// to the sink (see [`SinkHandle::ignore_null`]).  The initial value is not
1053    /// used for fields with `#[deser(default)]`.
1054    fn initial_value() -> Option<T> {
1055        None
1056    }
1057
1058    /// Creates a sink that updates an existing value.
1059    ///
1060    /// This is used to apply data on top of a value, for instance to layer a
1061    /// configuration file over the defaults (see
1062    /// [`DeserializeDriver::update`] and [`Deserializer::update`]).  The
1063    /// default implementation replaces the value with the deserialized one.
1064    /// Derived structs update the fields that are given and keep the others
1065    /// (fields are updated the same way, so nested structs are merged).
1066    /// `Option` updates the value in it if it's set, null clears it.  `Box`
1067    /// updates the value in it.  `HashMap` and `BTreeMap` insert the given
1068    /// entries, the values of keys that exist are replaced.
1069    ///
1070    /// If the update fails, the value might be partially updated.
1071    fn deserialize_update<'out>(value: &'out mut T, state: &mut State) -> SinkHandle<'out, 'de> {
1072        update::replace_handle_with(
1073            value,
1074            <Self as Deserialize<'de, T>>::deserialize_into,
1075            state,
1076        )
1077    }
1078
1079    /// Deserializes an atom into the slot.
1080    ///
1081    /// This must behave exactly like invoking [`atom`](Sink::atom) and
1082    /// [`finish`](Sink::finish) on the sink returned by
1083    /// [`deserialize_into`](Self::deserialize_into), which is what the default
1084    /// implementation does.  Types that are deserialized with a [`Slot`]
1085    /// override this so that atoms can be deserialized without dynamic
1086    /// dispatch.
1087    ///
1088    /// Internal fast path, not public API (see `lib.rs`).
1089    #[doc(hidden)]
1090    fn __private_atom_into(
1091        out: &mut Option<T>,
1092        atom: Atom,
1093        state: &mut State,
1094    ) -> Result<(), Error> {
1095        atom_into_handle(
1096            <Self as Deserialize<'de, T>>::deserialize_into(out, state),
1097            atom,
1098            state,
1099        )
1100    }
1101
1102    /// Deserializes a borrowed atom into the slot.
1103    ///
1104    /// This is like [`__private_atom_into`](Self::__private_atom_into) but
1105    /// for [`borrowed_atom`](Sink::borrowed_atom).
1106    ///
1107    /// Internal fast path, not public API (see `lib.rs`).
1108    #[doc(hidden)]
1109    fn __private_borrowed_atom_into(
1110        out: &mut Option<T>,
1111        atom: Atom<'de>,
1112        state: &mut State,
1113    ) -> Result<(), Error> {
1114        borrowed_atom_into_handle(
1115            <Self as Deserialize<'de, T>>::deserialize_into(out, state),
1116            atom,
1117            state,
1118        )
1119    }
1120
1121    /// Returns `true` if the values are `u8`.
1122    ///
1123    /// This is used to specialize the handling of bytes for vectors and
1124    /// arrays of `u8`.
1125    ///
1126    /// Internal specialization of bytes, not public API (see `lib.rs`).
1127    #[doc(hidden)]
1128    fn __private_is_bytes() -> bool {
1129        false
1130    }
1131
1132    /// Converts bytes into a vector of values.
1133    ///
1134    /// This is only implemented for `u8` and used to specialize the
1135    /// deserialization of `Vec<u8>` from bytes.
1136    ///
1137    /// Internal specialization of bytes, not public API (see `lib.rs`).
1138    #[doc(hidden)]
1139    fn __private_vec_from_bytes(bytes: Vec<u8>) -> Option<Vec<T>> {
1140        let _ = bytes;
1141        None
1142    }
1143
1144    /// Converts bytes into an array of values.
1145    ///
1146    /// This is only implemented for `u8` and used to specialize the
1147    /// deserialization of `[u8; N]` from bytes.  Returns `None` if the
1148    /// type is not `u8` or the length does not match.
1149    ///
1150    /// Internal specialization of bytes, not public API (see `lib.rs`).
1151    #[doc(hidden)]
1152    fn __private_array_from_bytes<const N: usize>(bytes: &[u8]) -> Option<[T; N]> {
1153        let _ = bytes;
1154        None
1155    }
1156
1157    /// Returns the value of a type that is only deserialized from atoms.
1158    ///
1159    /// This is implemented for numbers and booleans, sequences of them are
1160    /// built inline (see [`InlineSeq`]).  The value is a placeholder, it's
1161    /// overwritten.
1162    ///
1163    /// Internal fast path, not public API (see `lib.rs`).
1164    #[doc(hidden)]
1165    fn __private_atom_default() -> Option<T> {
1166        None
1167    }
1168
1169    /// Returns how the value is built inline if it's a sequence of atoms.
1170    ///
1171    /// Internal fast path, not public API (see `lib.rs`).
1172    #[doc(hidden)]
1173    fn __private_inline_seq() -> Option<InlineSeq<T>> {
1174        None
1175    }
1176
1177    /// Returns the format if the value is deserialized as raw value.
1178    ///
1179    /// This is the format of [`Raw`](crate::ext::Raw) values (and wrappers
1180    /// of them like `Option` and `Box`).  The sinks of containers request
1181    /// the values of such types as raw values from the format before they
1182    /// start (see [`State::__private_request_raw`]).
1183    ///
1184    /// Internal protocol, not public API yet (see `lib.rs`).
1185    #[doc(hidden)]
1186    #[inline(always)]
1187    fn __private_raw() -> Option<&'static crate::ext::RawFormatInfo> {
1188        None
1189    }
1190
1191    /// Returns `true` if the value collects the values of a repeated key.
1192    ///
1193    /// This is `true` for collections like `Vec<T>` and sets (and
1194    /// `Option`s of them).  In a multimap (see
1195    /// [`ContainerShape::set_multimap`](crate::ContainerShape::set_multimap))
1196    /// fields and map values of these types receive every value of their
1197    /// key through [`__private_collect_into`](Self::__private_collect_into)
1198    /// and [`__private_collect_update`](Self::__private_collect_update).
1199    ///
1200    /// Internal protocol, not public API yet (see `lib.rs`).
1201    #[doc(hidden)]
1202    fn __private_collects() -> bool {
1203        false
1204    }
1205
1206    /// Returns `true` if the value rejects empty lexical atoms.
1207    ///
1208    /// Optionals of such values are `None` for empty text (if it's a
1209    /// missing value, see [`LexicalRules`]) without delivering it, which
1210    /// saves creating the error that would be thrown away (optional numbers
1211    /// are empty in every other row of some CSV files).  This is `true` for
1212    /// numbers and booleans.
1213    ///
1214    /// Internal protocol, not public API yet (see `lib.rs`).
1215    #[doc(hidden)]
1216    #[inline(always)]
1217    fn __private_rejects_empty_lexical() -> bool {
1218        false
1219    }
1220
1221    /// Returns a sink for a value that is added to the collection in the
1222    /// slot.
1223    ///
1224    /// The collection is created if the slot is empty.  This is only used
1225    /// if [`__private_collects`](Self::__private_collects) returns `true`.
1226    ///
1227    /// Internal protocol, not public API yet (see `lib.rs`).
1228    #[doc(hidden)]
1229    fn __private_collect_into<'out>(
1230        out: &'out mut Option<T>,
1231        state: &mut State,
1232    ) -> SinkHandle<'out, 'de> {
1233        <Self as Deserialize<'de, T>>::deserialize_into(out, state)
1234    }
1235
1236    /// Returns a sink for a value that is added to a collection that is
1237    /// updated.
1238    ///
1239    /// The value that is added `first` replaces the collection.  This is
1240    /// only used if [`__private_collects`](Self::__private_collects) returns
1241    /// `true`.
1242    ///
1243    /// Internal protocol, not public API yet (see `lib.rs`).
1244    #[doc(hidden)]
1245    fn __private_collect_update<'out>(
1246        value: &'out mut T,
1247        first: bool,
1248        state: &mut State,
1249    ) -> SinkHandle<'out, 'de> {
1250        let _ = first;
1251        <Self as Deserialize<'de, T>>::deserialize_update(value, state)
1252    }
1253
1254    /// Returns the value of a collection whose key is missing in a
1255    /// multimap.
1256    ///
1257    /// Collections are empty then.  `None` means that the field is missing
1258    /// (or has its [`initial_value`](Self::initial_value)).
1259    ///
1260    /// Internal protocol, not public API yet (see `lib.rs`).
1261    #[doc(hidden)]
1262    fn __private_collect_empty() -> Option<T> {
1263        None
1264    }
1265}
1266
1267/// A type that can be deserialized without borrowing.
1268///
1269/// This is implemented for all types that implement [`Deserialize`] for all
1270/// lifetimes, which means that they do not borrow from the data they are
1271/// deserialized from.  It's useful as a bound where the data does not
1272/// outlive the deserialization (for instance when reading from a stream).
1273pub trait DeserializeOwned: for<'de> Deserialize<'de> {}
1274
1275impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
1276
1277/// Returns the value of a key that is missing in a multimap.
1278///
1279/// In a multimap (see
1280/// [`ContainerShape::set_multimap`](crate::ContainerShape::set_multimap))
1281/// collections like `Vec<T>` and sets are empty if their key is missing.
1282/// Other types have their [`initial_value`](Deserialize::initial_value)
1283/// (`None` for `Option<T>`).  `None` means that the value is required.
1284/// This is the counterpart of
1285/// [`DeserializeDriver::multimap_value`] for a key that is not there.
1286///
1287/// ```
1288/// use deser::de::missing_multimap_value;
1289///
1290/// assert_eq!(missing_multimap_value::<Vec<u16>>(), Some(vec![]));
1291/// assert_eq!(missing_multimap_value::<Option<u16>>(), Some(None));
1292/// assert_eq!(missing_multimap_value::<u16>(), None);
1293/// ```
1294pub fn missing_multimap_value<'de, T: Deserialize<'de>>() -> Option<T> {
1295    T::__private_collect_empty().or_else(T::initial_value)
1296}
1297
1298/// Converts a sink into a trait object.
1299///
1300/// This is implemented for all sinks.  The default methods of [`Sink`] exist
1301/// for every sink type, they use this to forward to code that exists once.
1302///
1303/// Internal fast path, not public API (see `lib.rs`).
1304#[doc(hidden)]
1305pub trait AsDynSink<'de> {
1306    fn __private_as_dyn(&mut self) -> &mut dyn Sink<'de>;
1307}
1308
1309impl<'de, T: Sink<'de>> AsDynSink<'de> for T {
1310    #[inline(always)]
1311    fn __private_as_dyn(&mut self) -> &mut dyn Sink<'de> {
1312        self
1313    }
1314}
1315
1316/// Trait to place values in a slot.
1317///
1318/// A sink acts as an abstraction to receive a value during deserialization from
1319/// the deserializer.  Sinks in deser are one-shot receivers.  A deserializer must
1320/// invoke one receiver method for a total of zero or one times.
1321///
1322/// The sink then places the received value in the slot connected to the sink.
1323///
1324/// Values that are deserialized from a single atom do not need to implement
1325/// a sink, the [`Slot`] is their sink (see
1326/// [`Deserialize::deserialize_atom`]).  Sinks are implemented for values
1327/// that need state, like structs, maps and sequences.
1328///
1329/// # Borrowed Data
1330///
1331/// Atoms are passed to [`atom`](Self::atom) with a lifetime that only lasts
1332/// for the call.  Formats pass atoms which borrow from the data that is
1333/// deserialized (which lives for `'de`) to [`borrowed_atom`](Self::borrowed_atom)
1334/// instead.  By default this forwards to [`atom`](Self::atom), only sinks of
1335/// types which want to borrow (like `&'de str`) need to implement it.
1336pub trait Sink<'de>: Send + AsDynSink<'de> {
1337    /// Receives an [`Atom`].
1338    ///
1339    /// Atoms which are not accepted are passed to [`default_atom`], the
1340    /// default handling of atoms (which is what the default implementation
1341    /// does for every atom).  This is
1342    /// particularly important for [`Atom::Ext`] as extension values are
1343    /// passed on as their fallback.  Values that are deserialized from atoms
1344    /// implement [`Deserialize::deserialize_atom`] instead of a sink.
1345    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1346        default_atom(self.__private_as_dyn(), atom, state)
1347    }
1348
1349    /// Receives an [`Atom`] that borrows from the data being deserialized.
1350    ///
1351    /// The default implementation forwards to [`atom`](Self::atom).
1352    fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
1353        self.atom(atom, state)
1354    }
1355
1356    /// Begins the deserialization of a map.
1357    ///
1358    /// While the deserialization of a map is ongoing the methods
1359    /// [`next_key`](Self::next_key) and [`next_value`](Self::next_value) are
1360    /// called alternatingly.  The map is ended by [`finish`](Self::finish).
1361    ///
1362    /// The default implementation returns an error.
1363    fn map(&mut self, state: &mut State) -> Result<(), Error> {
1364        default_container(self.__private_as_dyn(), "map", state)
1365    }
1366
1367    /// Begins the receiving process for sequences.
1368    ///
1369    /// While the deserialization of a sequence is ongoing the method
1370    /// [`next_value`](Self::next_value) is called for every new item.
1371    /// The sequence is ended by [`finish`](Self::finish).
1372    ///
1373    /// The default implementation returns an error.
1374    fn seq(&mut self, state: &mut State) -> Result<(), Error> {
1375        default_container(self.__private_as_dyn(), "sequence", state)
1376    }
1377
1378    /// Returns a sink for the next key in a map.
1379    fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1380        let _ = state;
1381        Ok(SinkHandle::null())
1382    }
1383
1384    /// Returns a sink for the next value in a map or sequence.
1385    fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1386        let _ = state;
1387        Ok(SinkHandle::null())
1388    }
1389
1390    /// Receives an atom as the next key in a map.
1391    ///
1392    /// This is a shortcut for invoking [`next_key`](Self::next_key) and then
1393    /// [`atom`](Self::atom) and [`finish`](Self::finish) on the returned sink,
1394    /// which is exactly what the default implementation does.  The driver
1395    /// uses this for keys that are atoms which is the overwhelmingly common
1396    /// case.  Sinks can override this to avoid creating a sink for the key,
1397    /// but the behavior must be the same as with the default implementation.
1398    /// In particular, sinks that override [`next_key`](Self::next_key) must
1399    /// either not override this method or apply the same logic.
1400    ///
1401    /// Internal fast path, not public API (see `lib.rs`).
1402    #[doc(hidden)]
1403    fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1404        default_key_atom(self.__private_as_dyn(), atom, state)
1405    }
1406
1407    /// Receives an atom as the next value in a map or sequence.
1408    ///
1409    /// This is a shortcut for invoking [`next_value`](Self::next_value) and
1410    /// then [`atom`](Self::atom) and [`finish`](Self::finish) on the returned
1411    /// sink, which is exactly what the default implementation does.  See
1412    /// [`__private_key_atom`](Self::__private_key_atom) for more information.
1413    ///
1414    /// Internal fast path, not public API (see `lib.rs`).
1415    #[doc(hidden)]
1416    fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1417        default_value_atom(self.__private_as_dyn(), atom, state)
1418    }
1419
1420    /// Receives a borrowed atom as the next key in a map.
1421    ///
1422    /// Like [`__private_key_atom`](Self::__private_key_atom) but the atom is
1423    /// passed to [`borrowed_atom`](Self::borrowed_atom).
1424    ///
1425    /// Internal fast path, not public API (see `lib.rs`).
1426    #[doc(hidden)]
1427    fn __private_borrowed_key_atom(
1428        &mut self,
1429        atom: Atom<'de>,
1430        state: &mut State,
1431    ) -> Result<(), Error> {
1432        default_borrowed_key_atom(self.__private_as_dyn(), atom, state)
1433    }
1434
1435    /// Receives a borrowed atom as the next value in a map or sequence.
1436    ///
1437    /// Like [`__private_value_atom`](Self::__private_value_atom) but the atom
1438    /// is passed to [`borrowed_atom`](Self::borrowed_atom).
1439    ///
1440    /// Internal fast path, not public API (see `lib.rs`).
1441    #[doc(hidden)]
1442    fn __private_borrowed_value_atom(
1443        &mut self,
1444        atom: Atom<'de>,
1445        state: &mut State,
1446    ) -> Result<(), Error> {
1447        default_borrowed_value_atom(self.__private_as_dyn(), atom, state)
1448    }
1449
1450    /// Begins a sequence like [`seq`](Self::seq).
1451    ///
1452    /// Returns `true` if the sink builds sequences that are its elements
1453    /// inline (see [`InlineSeq`]): the driver then passes their events to
1454    /// [`__private_inline_atom`](Self::__private_inline_atom) and
1455    /// [`__private_inline_event`](Self::__private_inline_event) instead of
1456    /// asking for a sink for them.  Wrappers that forward this have to
1457    /// forward those as well.
1458    ///
1459    /// Internal fast path, not public API (see `lib.rs`).
1460    #[doc(hidden)]
1461    fn __private_seq(&mut self, state: &mut State) -> Result<bool, Error> {
1462        self.seq(state)?;
1463        Ok(false)
1464    }
1465
1466    /// Receives the atom at the index of an element that is built inline.
1467    ///
1468    /// Internal fast path, not public API (see `lib.rs`).
1469    #[doc(hidden)]
1470    fn __private_inline_atom(
1471        &mut self,
1472        index: usize,
1473        atom: Atom,
1474        state: &mut State,
1475    ) -> Result<(), Error> {
1476        let _ = (index, atom, state);
1477        no_inline_seq()
1478    }
1479
1480    /// Receives the other events of an element that is built inline.
1481    ///
1482    /// Internal fast path, not public API (see `lib.rs`).
1483    #[doc(hidden)]
1484    fn __private_inline_event(
1485        &mut self,
1486        event: InlineEvent,
1487        state: &mut State,
1488    ) -> Result<(), Error> {
1489        let _ = (event, state);
1490        no_inline_seq()
1491    }
1492
1493    /// Returns a value sink for a specific struct field.
1494    ///
1495    /// This is a special method that is supposed to be implemented by structs
1496    /// if they want to support flattening.  A struct that gets flattened into
1497    /// another struct will have this method called to figure out if a key is
1498    /// used by it.  The default implementation always returns `None`.
1499    fn value_for_key(
1500        &mut self,
1501        key: &str,
1502        state: &mut State,
1503    ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
1504        let _ = key;
1505        let _ = state;
1506        Ok(None)
1507    }
1508
1509    /// Called after [`atom`](Self::atom), [`map`](Self::map) or [`seq](Self::seq).
1510    ///
1511    /// The default implementation does nothing.
1512    fn finish(&mut self, state: &mut State) -> Result<(), Error> {
1513        let _ = state;
1514        Ok(())
1515    }
1516
1517    /// Called when an item of this map or sequence failed.
1518    ///
1519    /// This is invoked by the [`DeserializeDriver`] when the key or value
1520    /// that was started last in this container failed with an error, either
1521    /// because its sink (or a sink nested in it) returned the error or
1522    /// because this sink returned it while handling the item (for instance
1523    /// from [`next_value`](Self::next_value) or [`atom`](Self::atom)).
1524    /// Errors of this sink's own [`map`](Self::map), [`seq`](Self::seq) and
1525    /// [`finish`](Self::finish) are errors of this sink's value and go to
1526    /// the container this sink is an item of.
1527    ///
1528    /// A sink that returns `Ok` recovers from the error: the driver skips
1529    /// the remaining events of the failed item (and the value of a failed
1530    /// key) and deserialization continues with the next item.  Returning
1531    /// the error (which is what the default implementation does) passes it
1532    /// on to the enclosing container.  All sinks of the failed item are
1533    /// dropped before this is invoked.  The error already has the context of
1534    /// the event that failed attached (see [`Error`]).
1535    ///
1536    /// Only errors of sinks are recoverable: errors of the format and of
1537    /// [`Layer`]s end the deserialization.
1538    ///
1539    /// Sinks that forward [`next_key`](Self::next_key) and
1540    /// [`next_value`](Self::next_value) to another sink should forward this
1541    /// as well.
1542    fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
1543        let _ = state;
1544        Err(err)
1545    }
1546
1547    /// Returns what the sink expects, for error messages.
1548    ///
1549    /// The sink of a value returns what the value expects (see
1550    /// [`Deserialize::expecting`]), sinks which pass values on to another
1551    /// sink what that sink expects.  The default implementation returns
1552    /// `"compatible type"`.
1553    fn expecting(&self) -> Cow<'_, str> {
1554        Cow::Borrowed("compatible type")
1555    }
1556}