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
691// The handle forwards to the sink it holds.
692impl<'a, 'de> Sink<'de> for SinkHandle<'a, 'de> {
693    #[inline]
694    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
695        if self.skip_null(&atom) {
696            return Ok(());
697        }
698        if self.is_optional() && is_empty_lexical(&atom, state) {
699            if !empty_lexical_or_none(atom, state, |atom, state| self.sink_mut().atom(atom, state))?
700            {
701                *self = SinkHandle::null();
702            }
703            return Ok(());
704        }
705        self.sink_mut().atom(atom, state)
706    }
707
708    #[inline]
709    fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
710        if self.skip_null(&atom) {
711            return Ok(());
712        }
713        if self.is_optional() && is_empty_lexical(&atom, state) {
714            let delivered = empty_lexical_or_none(atom, state, |atom, state| {
715                self.sink_mut().borrowed_atom(atom, state)
716            })?;
717            if !delivered {
718                *self = SinkHandle::null();
719            }
720            return Ok(());
721        }
722        self.sink_mut().borrowed_atom(atom, state)
723    }
724
725    #[inline]
726    fn map(&mut self, state: &mut State) -> Result<(), Error> {
727        self.sink_mut().map(state)
728    }
729
730    #[inline]
731    fn seq(&mut self, state: &mut State) -> Result<(), Error> {
732        self.sink_mut().seq(state)
733    }
734
735    #[inline]
736    fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
737        self.sink_mut().next_key(state)
738    }
739
740    #[inline]
741    fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
742        self.sink_mut().next_value(state)
743    }
744
745    #[inline]
746    fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
747        self.sink_mut().__private_key_atom(atom, state)
748    }
749
750    #[inline]
751    fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
752        self.sink_mut().__private_value_atom(atom, state)
753    }
754
755    #[inline]
756    fn __private_borrowed_key_atom(
757        &mut self,
758        atom: Atom<'de>,
759        state: &mut State,
760    ) -> Result<(), Error> {
761        self.sink_mut().__private_borrowed_key_atom(atom, state)
762    }
763
764    #[inline]
765    fn __private_borrowed_value_atom(
766        &mut self,
767        atom: Atom<'de>,
768        state: &mut State,
769    ) -> Result<(), Error> {
770        self.sink_mut().__private_borrowed_value_atom(atom, state)
771    }
772
773    #[inline]
774    fn __private_seq(&mut self, state: &mut State) -> Result<bool, Error> {
775        self.sink_mut().__private_seq(state)
776    }
777
778    #[inline]
779    fn __private_inline_atom(
780        &mut self,
781        index: usize,
782        atom: Atom,
783        state: &mut State,
784    ) -> Result<(), Error> {
785        self.sink_mut().__private_inline_atom(index, atom, state)
786    }
787
788    #[inline]
789    fn __private_inline_event(
790        &mut self,
791        event: InlineEvent,
792        state: &mut State,
793    ) -> Result<(), Error> {
794        self.sink_mut().__private_inline_event(event, state)
795    }
796
797    fn value_for_key(
798        &mut self,
799        key: &str,
800        state: &mut State,
801    ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
802        self.sink_mut().value_for_key(key, state)
803    }
804
805    #[inline]
806    fn finish(&mut self, state: &mut State) -> Result<(), Error> {
807        self.sink_mut().finish(state)
808    }
809
810    fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
811        self.sink_mut().recover(err, state)
812    }
813
814    fn expecting(&self) -> Cow<'_, str> {
815        self.sink().expecting()
816    }
817}
818
819/// A trait for deserializable types.
820///
821/// A type is deserializable if it can create a [`Sink`] for its slot with
822/// [`deserialize_into`](Self::deserialize_into).  This is how values are
823/// deserialized, but there are two ways to implement it:
824///
825/// * Values that are deserialized from a single atom (like numbers or
826///   strings) implement [`deserialize_atom`](Self::deserialize_atom).  The
827///   default implementation of `deserialize_into` returns the slot itself
828///   as sink (see [`Slot`]), which passes the atom on.
829/// * All other values implement `deserialize_into` and return a sink of
830///   their own (see [`SinkHandle::arena`]), which implements the actual
831///   deserialization logic.
832///
833/// Either way, [`expecting`](Self::expecting) says what the value expects
834/// in error messages (the sink reports it).  If neither `deserialize_atom`
835/// nor `deserialize_into` is implemented, every value is rejected.  See the
836/// [module documentation](crate::de) for examples of both.
837///
838/// The lifetime `'de` is the lifetime of the data that is deserialized.
839/// Types that borrow from it (like `&'de str`) only implement
840/// `Deserialize<'de>` for that lifetime, types that do not borrow implement
841/// it for all lifetimes (see [`DeserializeOwned`]):
842///
843/// ```
844/// use deser::Deserialize;
845///
846/// #[derive(Deserialize)]
847/// struct User<'a> {
848///     name: &'a str,
849///     id: u64,
850/// }
851/// ```
852///
853/// Data can only be borrowed if the data format passes it on borrowed (see
854/// [`Sink::borrowed_atom`]).
855///
856/// # Adapters
857///
858/// The type parameter `T` is the type of the value that is deserialized.
859/// It defaults to `Self`: `impl Deserialize<'de> for Foo` deserializes
860/// `Foo` values.  A type that implements `Deserialize` for another type is
861/// an adapter, it deserializes values of that type on their behalf (see
862/// [`adapters`](crate::adapters)):
863///
864/// ```
865/// use std::borrow::Cow;
866/// use deser::de::Slot;
867/// use deser::{Atom, Deserialize, Error, State};
868///
869/// /// Deserializes a `u32` as `u16`.
870/// pub struct Small;
871///
872/// impl<'de> Deserialize<'de, u32> for Small {
873///     fn deserialize_atom(
874///         slot: &mut Slot<u32, Self>,
875///         atom: Atom,
876///         state: &mut State,
877///     ) -> Result<(), Error> {
878///         let mut value = None::<u16>;
879///         u16::deserialize_atom(Slot::wrap(&mut value), atom, state)?;
880///         **slot = value.map(u32::from);
881///         Ok(())
882///     }
883///
884///     fn expecting() -> Cow<'static, str> {
885///         Cow::Borrowed("u16")
886///     }
887/// }
888/// ```
889///
890/// Adapters are never instantiated, only their functions are used.
891///
892/// # Thread Safety
893///
894/// Deserializable values are `Send` and so are the sinks they create.  This
895/// allows an ongoing deserialization (a [`DeserializeDriver`]) to move
896/// between threads, for instance when it is suspended while waiting for more
897/// input.  Types that are not `Send` (such as `Rc`) cannot be deserialized,
898/// which is why `T` has to be `Send`.
899pub trait Deserialize<'de, T: Send = Self>: Sized + Send {
900    /// Creates a sink that deserializes the value into the given slot.
901    ///
902    /// This is how every value is deserialized, whichever way the type
903    /// implements `Deserialize`.  The default implementation returns the
904    /// slot itself as sink (see [`Slot`]), which passes atoms to
905    /// [`deserialize_atom`](Self::deserialize_atom).  This is what values
906    /// that are deserialized from atoms use.  Values that need state to be
907    /// deserialized (like maps and sequences) implement this and return
908    /// their own sink (see [`SinkHandle::arena`]).
909    #[inline]
910    fn deserialize_into<'out>(
911        out: &'out mut Option<T>,
912        state: &mut State,
913    ) -> SinkHandle<'out, 'de> {
914        // the slot is the sink, nothing is allocated in the state (the atoms
915        // come with the state)
916        let _ = state;
917        Slot::<T, Self>::handle(out)
918    }
919
920    /// Deserializes an atom into the slot.
921    ///
922    /// This is invoked by the sink of the default implementation of
923    /// [`deserialize_into`](Self::deserialize_into) (the slot itself, see
924    /// [`Slot`]) for every atom it receives.  The value is placed in the
925    /// slot, atoms which are not accepted are passed to [`default_atom`]
926    /// (with the slot as sink).  The default implementation does this for
927    /// every atom.
928    ///
929    /// Types that implement `deserialize_into` do not use this.  This also
930    /// means that calling it only deserializes values that implement it
931    /// (like the primitives), other values reject every atom.  To
932    /// deserialize an atom into any value, pass it to the sink returned by
933    /// `deserialize_into`.
934    fn deserialize_atom(
935        slot: &mut Slot<T, Self>,
936        atom: Atom,
937        state: &mut State,
938    ) -> Result<(), Error> {
939        default_atom(slot, atom, state)
940    }
941
942    /// Deserializes an atom that borrows from the data being deserialized
943    /// into the slot.
944    ///
945    /// This is like [`deserialize_atom`](Self::deserialize_atom) for
946    /// [`Sink::borrowed_atom`], which it forwards to by default.  Only values
947    /// which borrow (like `&'de str`) need to implement it.
948    fn deserialize_borrowed_atom(
949        slot: &mut Slot<T, Self>,
950        atom: Atom<'de>,
951        state: &mut State,
952    ) -> Result<(), Error> {
953        <Self as Deserialize<'de, T>>::deserialize_atom(slot, atom, state)
954    }
955
956    /// Returns what the value expects, for error messages.
957    ///
958    /// This is what the errors of values that do not match say they expect
959    /// (`unexpected map, expected u32`).  The sink of the value reports it
960    /// with [`Sink::expecting`]: the [`Slot`] returns this, sinks returned
961    /// by [`deserialize_into`](Self::deserialize_into) should return it as
962    /// well.  The derive returns the name of the type (or what
963    /// `#[deser(expecting = "...")]` says), wrappers like `Option<T>` and
964    /// `Box<T>` what their value expects.  The default implementation
965    /// returns the name of the type without the module paths (like
966    /// `Vec<Point>`), which is the name of the adapter for adapters.
967    fn expecting() -> Cow<'static, str> {
968        slot::short_type_name(core::any::type_name::<Self>())
969    }
970
971    /// Describes the Rust shape of the type.
972    ///
973    /// This is the counterpart of [`Serialize::describe`](crate::ser::Serialize::describe)
974    /// for what is known without a value: it receives the same
975    /// [`Describe`](crate::ser::Describe) calls the values of the type
976    /// describe themselves with, except the ones that depend on the value
977    /// (like [`some`](crate::ser::Describe::some) or
978    /// [`variant`](crate::ser::Describe::variant)).  The default
979    /// implementation describes nothing.  Wrappers which are deserialized as
980    /// the value they wrap (like `Box<T>`) delegate to it.
981    ///
982    /// The derive describes unit structs, which are the tag alone in newtype
983    /// variants of internally tagged enums (see
984    /// [`Describe::unit_struct`](crate::ser::Describe::unit_struct)).
985    /// Types that implement `Deserialize` by hand describe themselves as
986    /// unit structs for that:
987    ///
988    /// ```
989    /// use deser::de::{Deserialize, Slot, default_atom};
990    /// use deser::ser::Describe;
991    /// use deser::{Atom, Error, State};
992    ///
993    /// struct Marker;
994    ///
995    /// impl Deserialize<'_> for Marker {
996    ///     fn deserialize_atom(
997    ///         slot: &mut Slot<Self>,
998    ///         atom: Atom,
999    ///         state: &mut State,
1000    ///     ) -> Result<(), Error> {
1001    ///         match atom {
1002    ///             Atom::Null => {
1003    ///                 slot.set(Marker);
1004    ///                 Ok(())
1005    ///             }
1006    ///             other => default_atom(slot, other, state),
1007    ///         }
1008    ///     }
1009    ///
1010    ///     fn describe_type(d: &mut dyn Describe) {
1011    ///         d.unit_struct("Marker");
1012    ///     }
1013    /// }
1014    /// ```
1015    fn describe_type(d: &mut dyn crate::ser::Describe) {
1016        let _ = d;
1017    }
1018
1019    /// Provides the value of a missing struct field.
1020    ///
1021    /// When a struct is deserialized the slots of its fields start out with
1022    /// this value.  If a field does not appear in the data, the initial value
1023    /// is used.  If it is `None` (the default) the field is required.
1024    /// `Option<T>` returns `Some(None)` here which makes optional fields
1025    /// default to `None` when they are missing.
1026    ///
1027    /// This only controls missing values.  How null values are handled is up
1028    /// to the sink (see [`SinkHandle::ignore_null`]).  The initial value is not
1029    /// used for fields with `#[deser(default)]`.
1030    fn initial_value() -> Option<T> {
1031        None
1032    }
1033
1034    /// Creates a sink that updates an existing value.
1035    ///
1036    /// This is used to apply data on top of a value, for instance to layer a
1037    /// configuration file over the defaults (see
1038    /// [`DeserializeDriver::update`] and [`Deserializer::update`]).  The
1039    /// default implementation replaces the value with the deserialized one.
1040    /// Derived structs update the fields that are given and keep the others
1041    /// (fields are updated the same way, so nested structs are merged).
1042    /// `Option` updates the value in it if it's set, null clears it.  `Box`
1043    /// updates the value in it.  `HashMap` and `BTreeMap` insert the given
1044    /// entries, the values of keys that exist are replaced.
1045    ///
1046    /// If the update fails, the value might be partially updated.
1047    fn deserialize_update<'out>(value: &'out mut T, state: &mut State) -> SinkHandle<'out, 'de> {
1048        update::replace_handle_with(
1049            value,
1050            <Self as Deserialize<'de, T>>::deserialize_into,
1051            state,
1052        )
1053    }
1054
1055    /// Deserializes an atom into the slot.
1056    ///
1057    /// This must behave exactly like invoking [`atom`](Sink::atom) and
1058    /// [`finish`](Sink::finish) on the sink returned by
1059    /// [`deserialize_into`](Self::deserialize_into), which is what the default
1060    /// implementation does.  Types that are deserialized with a [`Slot`]
1061    /// override this so that atoms can be deserialized without dynamic
1062    /// dispatch.
1063    ///
1064    /// Internal fast path, not public API (see `lib.rs`).
1065    #[doc(hidden)]
1066    fn __private_atom_into(
1067        out: &mut Option<T>,
1068        atom: Atom,
1069        state: &mut State,
1070    ) -> Result<(), Error> {
1071        atom_into_handle(
1072            <Self as Deserialize<'de, T>>::deserialize_into(out, state),
1073            atom,
1074            state,
1075        )
1076    }
1077
1078    /// Deserializes a borrowed atom into the slot.
1079    ///
1080    /// This is like [`__private_atom_into`](Self::__private_atom_into) but
1081    /// for [`borrowed_atom`](Sink::borrowed_atom).
1082    ///
1083    /// Internal fast path, not public API (see `lib.rs`).
1084    #[doc(hidden)]
1085    fn __private_borrowed_atom_into(
1086        out: &mut Option<T>,
1087        atom: Atom<'de>,
1088        state: &mut State,
1089    ) -> Result<(), Error> {
1090        borrowed_atom_into_handle(
1091            <Self as Deserialize<'de, T>>::deserialize_into(out, state),
1092            atom,
1093            state,
1094        )
1095    }
1096
1097    /// Returns `true` if the values are `u8`.
1098    ///
1099    /// This is used to specialize the handling of bytes for vectors and
1100    /// arrays of `u8`.
1101    ///
1102    /// Internal specialization of bytes, not public API (see `lib.rs`).
1103    #[doc(hidden)]
1104    fn __private_is_bytes() -> bool {
1105        false
1106    }
1107
1108    /// Converts bytes into a vector of values.
1109    ///
1110    /// This is only implemented for `u8` and used to specialize the
1111    /// deserialization of `Vec<u8>` from bytes.
1112    ///
1113    /// Internal specialization of bytes, not public API (see `lib.rs`).
1114    #[doc(hidden)]
1115    fn __private_vec_from_bytes(bytes: Vec<u8>) -> Option<Vec<T>> {
1116        let _ = bytes;
1117        None
1118    }
1119
1120    /// Converts bytes into an array of values.
1121    ///
1122    /// This is only implemented for `u8` and used to specialize the
1123    /// deserialization of `[u8; N]` from bytes.  Returns `None` if the
1124    /// type is not `u8` or the length does not match.
1125    ///
1126    /// Internal specialization of bytes, not public API (see `lib.rs`).
1127    #[doc(hidden)]
1128    fn __private_array_from_bytes<const N: usize>(bytes: &[u8]) -> Option<[T; N]> {
1129        let _ = bytes;
1130        None
1131    }
1132
1133    /// Returns the value of a type that is only deserialized from atoms.
1134    ///
1135    /// This is implemented for numbers and booleans, sequences of them are
1136    /// built inline (see [`InlineSeq`]).  The value is a placeholder, it's
1137    /// overwritten.
1138    ///
1139    /// Internal fast path, not public API (see `lib.rs`).
1140    #[doc(hidden)]
1141    fn __private_atom_default() -> Option<T> {
1142        None
1143    }
1144
1145    /// Returns how the value is built inline if it's a sequence of atoms.
1146    ///
1147    /// Internal fast path, not public API (see `lib.rs`).
1148    #[doc(hidden)]
1149    fn __private_inline_seq() -> Option<InlineSeq<T>> {
1150        None
1151    }
1152
1153    /// Returns the format if the value is deserialized as raw value.
1154    ///
1155    /// This is the format of [`Raw`](crate::ext::Raw) values (and wrappers
1156    /// of them like `Option` and `Box`).  The sinks of containers request
1157    /// the values of such types as raw values from the format before they
1158    /// start (see [`State::__private_request_raw`]).
1159    ///
1160    /// Internal protocol, not public API yet (see `lib.rs`).
1161    #[doc(hidden)]
1162    #[inline(always)]
1163    fn __private_raw() -> Option<&'static crate::ext::RawFormatInfo> {
1164        None
1165    }
1166
1167    /// Returns `true` if the value collects the values of a repeated key.
1168    ///
1169    /// This is `true` for collections like `Vec<T>` and sets (and
1170    /// `Option`s of them).  In a multimap (see
1171    /// [`ContainerShape::set_multimap`](crate::ContainerShape::set_multimap))
1172    /// fields and map values of these types receive every value of their
1173    /// key through [`__private_collect_into`](Self::__private_collect_into)
1174    /// and [`__private_collect_update`](Self::__private_collect_update).
1175    ///
1176    /// Internal protocol, not public API yet (see `lib.rs`).
1177    #[doc(hidden)]
1178    fn __private_collects() -> bool {
1179        false
1180    }
1181
1182    /// Returns `true` if the value rejects empty lexical atoms.
1183    ///
1184    /// Optionals of such values are `None` for empty text (if it's a
1185    /// missing value, see [`LexicalRules`]) without delivering it, which
1186    /// saves creating the error that would be thrown away (optional numbers
1187    /// are empty in every other row of some CSV files).  This is `true` for
1188    /// numbers and booleans.
1189    ///
1190    /// Internal protocol, not public API yet (see `lib.rs`).
1191    #[doc(hidden)]
1192    #[inline(always)]
1193    fn __private_rejects_empty_lexical() -> bool {
1194        false
1195    }
1196
1197    /// Returns a sink for a value that is added to the collection in the
1198    /// slot.
1199    ///
1200    /// The collection is created if the slot is empty.  This is only used
1201    /// if [`__private_collects`](Self::__private_collects) returns `true`.
1202    ///
1203    /// Internal protocol, not public API yet (see `lib.rs`).
1204    #[doc(hidden)]
1205    fn __private_collect_into<'out>(
1206        out: &'out mut Option<T>,
1207        state: &mut State,
1208    ) -> SinkHandle<'out, 'de> {
1209        <Self as Deserialize<'de, T>>::deserialize_into(out, state)
1210    }
1211
1212    /// Returns a sink for a value that is added to a collection that is
1213    /// updated.
1214    ///
1215    /// The value that is added `first` replaces the collection.  This is
1216    /// only used if [`__private_collects`](Self::__private_collects) returns
1217    /// `true`.
1218    ///
1219    /// Internal protocol, not public API yet (see `lib.rs`).
1220    #[doc(hidden)]
1221    fn __private_collect_update<'out>(
1222        value: &'out mut T,
1223        first: bool,
1224        state: &mut State,
1225    ) -> SinkHandle<'out, 'de> {
1226        let _ = first;
1227        <Self as Deserialize<'de, T>>::deserialize_update(value, state)
1228    }
1229
1230    /// Returns the value of a collection whose key is missing in a
1231    /// multimap.
1232    ///
1233    /// Collections are empty then.  `None` means that the field is missing
1234    /// (or has its [`initial_value`](Self::initial_value)).
1235    ///
1236    /// Internal protocol, not public API yet (see `lib.rs`).
1237    #[doc(hidden)]
1238    fn __private_collect_empty() -> Option<T> {
1239        None
1240    }
1241}
1242
1243/// A type that can be deserialized without borrowing.
1244///
1245/// This is implemented for all types that implement [`Deserialize`] for all
1246/// lifetimes, which means that they do not borrow from the data they are
1247/// deserialized from.  It's useful as a bound where the data does not
1248/// outlive the deserialization (for instance when reading from a stream).
1249pub trait DeserializeOwned: for<'de> Deserialize<'de> {}
1250
1251impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
1252
1253/// Returns the value of a key that is missing in a multimap.
1254///
1255/// In a multimap (see
1256/// [`ContainerShape::set_multimap`](crate::ContainerShape::set_multimap))
1257/// collections like `Vec<T>` and sets are empty if their key is missing.
1258/// Other types have their [`initial_value`](Deserialize::initial_value)
1259/// (`None` for `Option<T>`).  `None` means that the value is required.
1260/// This is the counterpart of
1261/// [`DeserializeDriver::multimap_value`] for a key that is not there.
1262///
1263/// ```
1264/// use deser::de::missing_multimap_value;
1265///
1266/// assert_eq!(missing_multimap_value::<Vec<u16>>(), Some(vec![]));
1267/// assert_eq!(missing_multimap_value::<Option<u16>>(), Some(None));
1268/// assert_eq!(missing_multimap_value::<u16>(), None);
1269/// ```
1270pub fn missing_multimap_value<'de, T: Deserialize<'de>>() -> Option<T> {
1271    T::__private_collect_empty().or_else(T::initial_value)
1272}
1273
1274/// Converts a sink into a trait object.
1275///
1276/// This is implemented for all sinks.  The default methods of [`Sink`] exist
1277/// for every sink type, they use this to forward to code that exists once.
1278///
1279/// Internal fast path, not public API (see `lib.rs`).
1280#[doc(hidden)]
1281pub trait AsDynSink<'de> {
1282    fn __private_as_dyn(&mut self) -> &mut dyn Sink<'de>;
1283}
1284
1285impl<'de, T: Sink<'de>> AsDynSink<'de> for T {
1286    #[inline(always)]
1287    fn __private_as_dyn(&mut self) -> &mut dyn Sink<'de> {
1288        self
1289    }
1290}
1291
1292/// Trait to place values in a slot.
1293///
1294/// A sink acts as an abstraction to receive a value during deserialization from
1295/// the deserializer.  Sinks in deser are one-shot receivers.  A deserializer must
1296/// invoke one receiver method for a total of zero or one times.
1297///
1298/// The sink then places the received value in the slot connected to the sink.
1299///
1300/// Values that are deserialized from a single atom do not need to implement
1301/// a sink, the [`Slot`] is their sink (see
1302/// [`Deserialize::deserialize_atom`]).  Sinks are implemented for values
1303/// that need state, like structs, maps and sequences.
1304///
1305/// # Borrowed Data
1306///
1307/// Atoms are passed to [`atom`](Self::atom) with a lifetime that only lasts
1308/// for the call.  Formats pass atoms which borrow from the data that is
1309/// deserialized (which lives for `'de`) to [`borrowed_atom`](Self::borrowed_atom)
1310/// instead.  By default this forwards to [`atom`](Self::atom), only sinks of
1311/// types which want to borrow (like `&'de str`) need to implement it.
1312pub trait Sink<'de>: Send + AsDynSink<'de> {
1313    /// Receives an [`Atom`].
1314    ///
1315    /// Atoms which are not accepted are passed to [`default_atom`], the
1316    /// default handling of atoms (which is what the default implementation
1317    /// does for every atom).  This is
1318    /// particularly important for [`Atom::Ext`] as extension values are
1319    /// passed on as their fallback.  Values that are deserialized from atoms
1320    /// implement [`Deserialize::deserialize_atom`] instead of a sink.
1321    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1322        default_atom(self.__private_as_dyn(), atom, state)
1323    }
1324
1325    /// Receives an [`Atom`] that borrows from the data being deserialized.
1326    ///
1327    /// The default implementation forwards to [`atom`](Self::atom).
1328    fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
1329        self.atom(atom, state)
1330    }
1331
1332    /// Begins the deserialization of a map.
1333    ///
1334    /// While the deserialization of a map is ongoing the methods
1335    /// [`next_key`](Self::next_key) and [`next_value`](Self::next_value) are
1336    /// called alternatingly.  The map is ended by [`finish`](Self::finish).
1337    ///
1338    /// The default implementation returns an error.
1339    fn map(&mut self, state: &mut State) -> Result<(), Error> {
1340        default_container(self.__private_as_dyn(), "map", state)
1341    }
1342
1343    /// Begins the receiving process for sequences.
1344    ///
1345    /// While the deserialization of a sequence is ongoing the method
1346    /// [`next_value`](Self::next_value) is called for every new item.
1347    /// The sequence is ended by [`finish`](Self::finish).
1348    ///
1349    /// The default implementation returns an error.
1350    fn seq(&mut self, state: &mut State) -> Result<(), Error> {
1351        default_container(self.__private_as_dyn(), "sequence", state)
1352    }
1353
1354    /// Returns a sink for the next key in a map.
1355    fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1356        let _ = state;
1357        Ok(SinkHandle::null())
1358    }
1359
1360    /// Returns a sink for the next value in a map or sequence.
1361    fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1362        let _ = state;
1363        Ok(SinkHandle::null())
1364    }
1365
1366    /// Receives an atom as the next key in a map.
1367    ///
1368    /// This is a shortcut for invoking [`next_key`](Self::next_key) and then
1369    /// [`atom`](Self::atom) and [`finish`](Self::finish) on the returned sink,
1370    /// which is exactly what the default implementation does.  The driver
1371    /// uses this for keys that are atoms which is the overwhelmingly common
1372    /// case.  Sinks can override this to avoid creating a sink for the key,
1373    /// but the behavior must be the same as with the default implementation.
1374    /// In particular, sinks that override [`next_key`](Self::next_key) must
1375    /// either not override this method or apply the same logic.
1376    ///
1377    /// Internal fast path, not public API (see `lib.rs`).
1378    #[doc(hidden)]
1379    fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1380        default_key_atom(self.__private_as_dyn(), atom, state)
1381    }
1382
1383    /// Receives an atom as the next value in a map or sequence.
1384    ///
1385    /// This is a shortcut for invoking [`next_value`](Self::next_value) and
1386    /// then [`atom`](Self::atom) and [`finish`](Self::finish) on the returned
1387    /// sink, which is exactly what the default implementation does.  See
1388    /// [`__private_key_atom`](Self::__private_key_atom) for more information.
1389    ///
1390    /// Internal fast path, not public API (see `lib.rs`).
1391    #[doc(hidden)]
1392    fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1393        default_value_atom(self.__private_as_dyn(), atom, state)
1394    }
1395
1396    /// Receives a borrowed atom as the next key in a map.
1397    ///
1398    /// Like [`__private_key_atom`](Self::__private_key_atom) but the atom is
1399    /// passed to [`borrowed_atom`](Self::borrowed_atom).
1400    ///
1401    /// Internal fast path, not public API (see `lib.rs`).
1402    #[doc(hidden)]
1403    fn __private_borrowed_key_atom(
1404        &mut self,
1405        atom: Atom<'de>,
1406        state: &mut State,
1407    ) -> Result<(), Error> {
1408        default_borrowed_key_atom(self.__private_as_dyn(), atom, state)
1409    }
1410
1411    /// Receives a borrowed atom as the next value in a map or sequence.
1412    ///
1413    /// Like [`__private_value_atom`](Self::__private_value_atom) but the atom
1414    /// is passed to [`borrowed_atom`](Self::borrowed_atom).
1415    ///
1416    /// Internal fast path, not public API (see `lib.rs`).
1417    #[doc(hidden)]
1418    fn __private_borrowed_value_atom(
1419        &mut self,
1420        atom: Atom<'de>,
1421        state: &mut State,
1422    ) -> Result<(), Error> {
1423        default_borrowed_value_atom(self.__private_as_dyn(), atom, state)
1424    }
1425
1426    /// Begins a sequence like [`seq`](Self::seq).
1427    ///
1428    /// Returns `true` if the sink builds sequences that are its elements
1429    /// inline (see [`InlineSeq`]): the driver then passes their events to
1430    /// [`__private_inline_atom`](Self::__private_inline_atom) and
1431    /// [`__private_inline_event`](Self::__private_inline_event) instead of
1432    /// asking for a sink for them.  Wrappers that forward this have to
1433    /// forward those as well.
1434    ///
1435    /// Internal fast path, not public API (see `lib.rs`).
1436    #[doc(hidden)]
1437    fn __private_seq(&mut self, state: &mut State) -> Result<bool, Error> {
1438        self.seq(state)?;
1439        Ok(false)
1440    }
1441
1442    /// Receives the atom at the index of an element that is built inline.
1443    ///
1444    /// Internal fast path, not public API (see `lib.rs`).
1445    #[doc(hidden)]
1446    fn __private_inline_atom(
1447        &mut self,
1448        index: usize,
1449        atom: Atom,
1450        state: &mut State,
1451    ) -> Result<(), Error> {
1452        let _ = (index, atom, state);
1453        no_inline_seq()
1454    }
1455
1456    /// Receives the other events of an element that is built inline.
1457    ///
1458    /// Internal fast path, not public API (see `lib.rs`).
1459    #[doc(hidden)]
1460    fn __private_inline_event(
1461        &mut self,
1462        event: InlineEvent,
1463        state: &mut State,
1464    ) -> Result<(), Error> {
1465        let _ = (event, state);
1466        no_inline_seq()
1467    }
1468
1469    /// Returns a value sink for a specific struct field.
1470    ///
1471    /// This is a special method that is supposed to be implemented by structs
1472    /// if they want to support flattening.  A struct that gets flattened into
1473    /// another struct will have this method called to figure out if a key is
1474    /// used by it.  The default implementation always returns `None`.
1475    fn value_for_key(
1476        &mut self,
1477        key: &str,
1478        state: &mut State,
1479    ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
1480        let _ = key;
1481        let _ = state;
1482        Ok(None)
1483    }
1484
1485    /// Called after [`atom`](Self::atom), [`map`](Self::map) or [`seq](Self::seq).
1486    ///
1487    /// The default implementation does nothing.
1488    fn finish(&mut self, state: &mut State) -> Result<(), Error> {
1489        let _ = state;
1490        Ok(())
1491    }
1492
1493    /// Called when an item of this map or sequence failed.
1494    ///
1495    /// This is invoked by the [`DeserializeDriver`] when the key or value
1496    /// that was started last in this container failed with an error, either
1497    /// because its sink (or a sink nested in it) returned the error or
1498    /// because this sink returned it while handling the item (for instance
1499    /// from [`next_value`](Self::next_value) or [`atom`](Self::atom)).
1500    /// Errors of this sink's own [`map`](Self::map), [`seq`](Self::seq) and
1501    /// [`finish`](Self::finish) are errors of this sink's value and go to
1502    /// the container this sink is an item of.
1503    ///
1504    /// A sink that returns `Ok` recovers from the error: the driver skips
1505    /// the remaining events of the failed item (and the value of a failed
1506    /// key) and deserialization continues with the next item.  Returning
1507    /// the error (which is what the default implementation does) passes it
1508    /// on to the enclosing container.  All sinks of the failed item are
1509    /// dropped before this is invoked.  The error already has the context of
1510    /// the event that failed attached (see [`Error`]).
1511    ///
1512    /// Only errors of sinks are recoverable: errors of the format and of
1513    /// [`Layer`]s end the deserialization.
1514    ///
1515    /// Sinks that forward [`next_key`](Self::next_key) and
1516    /// [`next_value`](Self::next_value) to another sink should forward this
1517    /// as well.
1518    fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
1519        let _ = state;
1520        Err(err)
1521    }
1522
1523    /// Returns what the sink expects, for error messages.
1524    ///
1525    /// The sink of a value returns what the value expects (see
1526    /// [`Deserialize::expecting`]), sinks which pass values on to another
1527    /// sink what that sink expects.  The default implementation returns
1528    /// `"compatible type"`.
1529    fn expecting(&self) -> Cow<'_, str> {
1530        Cow::Borrowed("compatible type")
1531    }
1532}