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 abstraction that
13//! places these values there is called a [`Sink`] which is returned within a
14//! [`SinkHandle`] from the deserializer.
15//!
16//! If you can get away with stateless deserialization you can avoid an
17//! allocation by using a newtype wrapper around `Option<T>`.  You can
18//! get such a wrapper by using the
19//! [`make_slot_wrapper`](crate::make_slot_wrapper`) macro ([more
20//! information](https://doc.rust-lang.org/error-index.html#E0117))
21//! which will create a type [`SlotWrapper`].  Due to Rust's orphan rules
22//! you need to create your own type in your crate and you can't use the
23//! one from this module directly.  ([more
24//! information](https://doc.rust-lang.org/error-index.html#E0117)).
25//!
26//! This [`SlotWrapper`] derefs into an `Option<T>` which makes it quite
27//! convenient to use.  By calling [`SlotWrapper::make_handle`] with a slot, one
28//! can directly retrieve a [`SinkHandle`].
29//!
30//! # Streaming Deserialization
31//!
32//! Because the serialization interface of Deser is tricky due to use of
33//! lifetimes, a safe abstraction is provided with the [`DeserializeDriver`].
34//! This type which allow you to drive the deserialization process without using
35//! stack space.  You feed it events and internally the driver ensures that the
36//! deserlization system is driven in the right way.
37//!
38//! ```rust
39//! use std::collections::BTreeMap;
40//! use deser::de::DeserializeDriver;
41//! use deser::Event;
42//!
43//! let mut out = None::<BTreeMap<u32, String>>;
44//! {
45//!     let mut driver = DeserializeDriver::new(&mut out);
46//!     // emit takes values that implement Into<Event>
47//!     driver.emit(Event::map_start()).unwrap();
48//!     driver.emit(1i64).unwrap();
49//!     driver.emit("Hello").unwrap();
50//!     driver.emit(2i64).unwrap();
51//!     driver.emit("World").unwrap();
52//!     driver.emit(Event::MapEnd).unwrap();
53//! }
54//!
55//! let map = out.unwrap();
56//! assert_eq!(map[&1], "Hello");
57//! assert_eq!(map[&2], "World");
58//! ```
59//!
60//! The deserializers of data formats implement the [`Deserializer`] trait
61//! which feeds the events of a value into a driver.
62//!
63//! # Layers and Wrapped Sinks
64//!
65//! There are two ways to change how a deserialization is processed without
66//! support by the format or the types:
67//!
68//! * [`Layer`]s sit between the format and the driver and see the events.
69//!   They are useful for everything that can be derived from the events,
70//!   for instance to track the current path, to enforce limits (see
71//!   [`Limits`]) or to rewrite values.
72//! * Wrapped sinks (see [`DeserializeDriver::wrap_sink`]) sit between the
73//!   driver and the sinks of the values.  They are useful for changes that
74//!   depend on the target types.
75//!
76//! Both are set up with [`Deserializer::deserialize_with`].
77//!
78//! # Deserializing Primitives
79//!
80//! To deserialize a primitive you implement a sink for your slot wrapper and
81//! implement the necessary callback.  You can do this as you do not need any
82//! state on the sink so we can use a [`SlotWrapper`].  In this example we
83//! want to accept a `bool` so we just need to implement the
84//! [`atom`](Sink::atom) method as bools are represented as [`Atom`]s.  The
85//! resulting value then must be placed in the slot:
86//!
87//! ```rust
88//! use deser::de::{Sink, Deserialize, SinkHandle};
89//! use deser::State;
90//! use deser::{make_slot_wrapper, Error, Atom};
91//!
92//! make_slot_wrapper!(SlotWrapper);
93//!
94//! struct MyBool(bool);
95//!
96//! impl<'de> Sink<'de> for SlotWrapper<MyBool> {
97//!     fn atom(
98//!         &mut self,
99//!         atom: Atom,
100//!         state: &mut State,
101//!     ) -> Result<(), Error> {
102//!         match atom {
103//!             Atom::Bool(value) => {
104//!                 // note the extra star here to reach through the deref
105//!                 // of the slot wrapper.
106//!                 **self = Some(MyBool(value));
107//!                 Ok(())
108//!             }
109//!             // for any other value we dispatch to the default handling
110//!             // which creates an unexpected type error but might have
111//!             // more elaborate default behavior in the future.
112//!             other => self.unexpected_atom(other, state),
113//!         }
114//!     }
115//! }
116//!
117//! impl<'de> Deserialize<'de> for MyBool {
118//!     fn deserialize_into<'out>(
119//!         out: &'out mut Option<Self>,
120//!         state: &mut State,
121//!     ) -> SinkHandle<'out, 'de> {
122//!         // Since we're using the SlotWrapper abstraction we can directly
123//!         // make a handle here by using the `make_handle` utility.
124//!         SlotWrapper::make_handle(out)
125//!     }
126//! }
127//! ```
128//!
129//! # Struct Deserialization
130//!
131//! If you want to deserialize a struct you need to implement the map methods.
132//! As you need to keep track of state you will need to return a sink that
133//! is owned by the handle (allocated in the arena of the deserialization
134//! with [`SinkHandle::arena`]) and you can't use the slot wrapper.
135//!
136//! ```rust
137//! use deser::de::{Deserialize, Sink, SinkHandle};
138//! use deser::State;
139//! use deser::{Error, ErrorKind};
140//!
141//! struct Flag {
142//!     enabled: bool,
143//!     name: String,
144//! }
145//!
146//! impl<'de> Deserialize<'de> for Flag {
147//!     fn deserialize_into<'out>(
148//!         out: &'out mut Option<Self>,
149//!         state: &mut State,
150//!     ) -> SinkHandle<'out, 'de> {
151//!         let sink = FlagSink {
152//!             out,
153//!             key: None,
154//!             enabled: None,
155//!             name: None,
156//!         };
157//!         SinkHandle::arena(sink, state)
158//!     }
159//! }
160//!
161//! struct FlagSink<'a> {
162//!     out: &'a mut Option<Flag>,
163//!     key: Option<String>,
164//!     enabled: Option<bool>,
165//!     name: Option<String>,
166//! }
167//!
168//! impl<'a, 'de> Sink<'de> for FlagSink<'a> {
169//!     fn map(&mut self, _state: &mut State) -> Result<(), Error> {
170//!         // the default implementation returns an error, so we need to
171//!         // override it to remove this error.
172//!         Ok(())
173//!     }
174//!
175//!     fn next_key(
176//!         &mut self,
177//!         state: &mut State,
178//!     ) -> Result<SinkHandle<'_, 'de>, Error> {
179//!         // directly attach to the key field which can hold any
180//!         // string value.  This means that any string is accepted
181//!         // as key.
182//!         Ok(Deserialize::deserialize_into(&mut self.key, state))
183//!     }
184//!
185//!     fn next_value(
186//!         &mut self,
187//!         state: &mut State,
188//!     ) -> Result<SinkHandle<'_, 'de>, Error> {
189//!         let key = self.key.take().unwrap();
190//!         // since we implement a sink for a struct, move the actual logic
191//!         // for matching into `value_for_key` so that our deserializer can
192//!         // support struct flattening.  If we don't know the key, just
193//!         // return a null handle to ignore it.
194//!         let handle = self.value_for_key(&key, state)?;
195//!         Ok(handle.unwrap_or_else(SinkHandle::null))
196//!     }
197//!
198//!     fn value_for_key(
199//!         &mut self,
200//!         key: &str,
201//!         state: &mut State,
202//!     ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
203//!         Ok(Some(match key {
204//!             "enabled" => bool::deserialize_into(&mut self.enabled, state),
205//!             "name" => String::deserialize_into(&mut self.name, state),
206//!             _ => return Ok(None),
207//!         }))
208//!     }
209//!
210//!     fn finish(&mut self, _state: &mut State) -> Result<(), Error> {
211//!         // when we're done, write the final value into the output slot.
212//!         let enabled = self.enabled.take().ok_or_else(|| {
213//!             Error::new(ErrorKind::MissingField, "field 'enabled' missing")
214//!         })?;
215//!         let name = self.name.take().ok_or_else(|| {
216//!             Error::new(ErrorKind::MissingField, "field 'name' missing")
217//!         })?;
218//!         *self.out = Some(Flag { enabled, name });
219//!         Ok(())
220//!     }
221//! }
222//! ```
223//!
224//! # Owned Sinks and Slots
225//!
226//! From the above model you can see that deserialization requires a mutable reference
227//! to an `Option`.  In certain situations it can become necessary to "make up a slot
228//! on the spot" to temporarily deserialize into.  For more information see
229//! [`OwnedSink`].
230use alloc::borrow::Cow;
231use alloc::vec::Vec;
232
233use crate::error::{Error, ErrorKind};
234use crate::event::Atom;
235
236pub(crate) mod arena;
237pub(crate) mod atoms;
238mod collect;
239pub(crate) mod deserializer;
240mod driver;
241pub(crate) mod duplicates;
242#[cfg(feature = "derive")]
243pub(crate) mod enums;
244#[cfg(feature = "derive")]
245pub(crate) mod fields;
246mod ignore;
247pub(crate) mod impls;
248mod layer;
249pub(crate) mod lexical;
250pub(crate) mod mapped;
251mod owned;
252pub(crate) mod recording;
253mod sinkbox;
254mod stream;
255pub(crate) mod unknown;
256pub(crate) mod update;
257
258pub(crate) use self::atoms::{atom_into_handle, borrowed_atom_into_handle};
259use self::atoms::{
260    default_borrowed_key_atom, default_borrowed_value_atom, default_container, default_key_atom,
261    default_unexpected_atom, default_value_atom,
262};
263pub use self::collect::CollectedErrors;
264pub use self::deserializer::Deserializer;
265pub use self::driver::DeserializeDriver;
266pub use self::duplicates::DuplicateKeys;
267pub use self::layer::{Layer, LayerEvent, Limits, Next};
268pub use self::lexical::{ContentKey, LexicalRules};
269pub use self::owned::{OwnedDriver, OwnedSink};
270pub use self::recording::{RecordBuf, Recording};
271#[cfg(feature = "derive")]
272use self::sinkbox::StructBox;
273use self::sinkbox::{ArenaSink, HeapSink, arena_sink};
274pub use self::stream::{Frame, Progress, StreamDeserializer};
275pub use self::unknown::{IgnoredFields, UnknownFields};
276pub use self::update::checked_update;
277use crate::State;
278
279/// Builds a sequence of atoms in the sink of the sequence it's an element
280/// of.
281///
282/// Sequences of a fixed number of atoms (like `[f32; 2]` or `(u8, u8)`)
283/// are small containers that appear in large numbers.  Instead of creating
284/// a sink for every one of them, the sink of the sequence they are
285/// elements of (see [`Sink::__private_seq`]) builds them in its slot for
286/// the element, the driver passes their events to it.  This has to behave
287/// exactly like the sink of the element.
288#[doc(hidden)]
289pub struct InlineSeq<T> {
290    /// Starts the sequence in the slot.
291    pub start: fn(&mut Option<T>),
292    /// Deserializes the atom at the index.
293    pub atom: fn(&mut Option<T>, usize, Atom, &mut State) -> Result<(), Error>,
294    /// Ends the sequence with the given length.
295    pub end: fn(&mut Option<T>, usize) -> Result<(), Error>,
296    /// Returns the error for a map (`true`) or sequence at the index.
297    pub container: fn(usize, bool, &mut State) -> Error,
298}
299
300/// An event of a sequence that is built inline (see [`InlineSeq`]).
301#[doc(hidden)]
302#[derive(Clone, Copy)]
303pub enum InlineEvent {
304    /// The sequence starts.
305    Start,
306    /// The sequence ends with the given length.
307    End(usize),
308    /// A map (`true`) or sequence starts at the index.
309    Container(usize, bool),
310}
311
312/// Panics as the sink does not build sequences inline.
313#[cold]
314#[inline(never)]
315fn no_inline_seq() -> ! {
316    panic!("the sink does not build sequences inline")
317}
318
319__make_slot_wrapper!((pub), SlotWrapper);
320
321/// A handle to a [`Sink`].
322///
323/// During deserialization the sinks often need to return other sinks
324/// to recurse into structures.  This poses a challenge if the target
325/// sink cannot be directly borrowed.  This is where [`SinkHandle`]
326/// comes in.  In cases where the [`Sink`] cannot be borrowed it's owned
327/// by the handle, either in the arena of the deserialization
328/// ([`arena`](Self::arena), which is what sinks typically use) or on the
329/// heap ([`heap`](Self::heap)).
330///
331/// The handle itself implements [`Sink`] and forwards all calls to the
332/// sink it holds.
333///
334/// The equivalent for serialization is the
335/// [`SerializeHandle`](crate::ser::SerializeHandle).
336pub struct SinkHandle<'a, 'de: 'a>(HandleInner<'a, 'de>);
337
338enum HandleInner<'a, 'de> {
339    Borrowed(&'a mut dyn Sink<'de>),
340    Arena(ArenaSink<'a, 'de>),
341    Heap(HeapSink<'a, 'de>),
342    #[cfg(feature = "derive")]
343    Struct(StructBox<'a, 'de>),
344    Null(ignore::Ignore),
345    // The optional variants are used to implement `Option<T>` without an
346    // extra allocation: a null atom is not forwarded but turns the handle
347    // into a null handle so that `finish` is not forwarded either.
348    OptionalBorrowed(&'a mut dyn Sink<'de>),
349    OptionalArena(ArenaSink<'a, 'de>),
350    OptionalHeap(HeapSink<'a, 'de>),
351    #[cfg(feature = "derive")]
352    OptionalStruct(StructBox<'a, 'de>),
353}
354
355impl<'a, 'de> SinkHandle<'a, 'de> {
356    /// Create a borrowed handle to a [`Sink`].
357    pub fn to(val: &'a mut dyn Sink<'de>) -> SinkHandle<'a, 'de> {
358        SinkHandle(HandleInner::Borrowed(val))
359    }
360
361    /// Creates an owned handle to a sink in the arena of the deserialization.
362    ///
363    /// This is how sinks are typically created: the arena belongs to the
364    /// state of the deserialization and the sinks of the containers that
365    /// are open are on top of each other in it, allocating one is little
366    /// more than bumping a pointer.  Its space is reused once the handle is
367    /// dropped (and the sinks allocated after it are dropped too).
368    ///
369    /// A sink can outlive the deserialization it was created for (the
370    /// state).  The arena then frees its memory except for the chunk the
371    /// sink is in, which is freed when the sink is dropped (and the other
372    /// sinks in it).  A sink that is meant to be kept for longer should
373    /// rather be created with [`heap`](Self::heap).
374    ///
375    /// ```
376    /// use deser::de::{Deserialize, Sink, SinkHandle};
377    /// use deser::{Atom, Error, State};
378    ///
379    /// struct Flag(bool);
380    ///
381    /// struct FlagSink<'a> {
382    ///     out: &'a mut Option<Flag>,
383    /// }
384    ///
385    /// impl<'de> Sink<'de> for FlagSink<'_> {
386    ///     fn atom(
387    ///         &mut self,
388    ///         atom: Atom,
389    ///         state: &mut State,
390    ///     ) -> Result<(), Error> {
391    ///         match atom {
392    ///             Atom::Bool(value) => {
393    ///                 *self.out = Some(Flag(value));
394    ///                 Ok(())
395    ///             }
396    ///             other => self.unexpected_atom(other, state),
397    ///         }
398    ///     }
399    /// }
400    ///
401    /// impl<'de> Deserialize<'de> for Flag {
402    ///     fn deserialize_into<'a>(
403    ///         out: &'a mut Option<Self>,
404    ///         state: &mut State,
405    ///     ) -> SinkHandle<'a, 'de> {
406    ///         SinkHandle::arena(FlagSink { out }, state)
407    ///     }
408    /// }
409    /// ```
410    #[inline(always)]
411    pub fn arena<S: Sink<'de> + 'a>(val: S, state: &mut State) -> SinkHandle<'a, 'de> {
412        SinkHandle(HandleInner::Arena(arena_sink(val, &mut state.arena)))
413    }
414
415    /// Drops the handle, the block of an owned sink is returned to the arena
416    /// of the state right away if it's the top block.
417    ///
418    /// Dropping the handle has the same effect, but the block is only
419    /// reused when the next sink is allocated.  The driver does this with
420    /// the sinks of the containers it closes.
421    #[inline(always)]
422    pub(crate) fn release(self, state: &mut State) {
423        match self.0 {
424            HandleInner::Arena(sink) | HandleInner::OptionalArena(sink) => {
425                arena::ArenaBox::release_in(sink, &mut state.arena)
426            }
427            #[cfg(feature = "derive")]
428            HandleInner::Struct(sink) | HandleInner::OptionalStruct(sink) => {
429                sink.release_in(&mut state.arena)
430            }
431            _ => {}
432        }
433    }
434
435    /// Creates an owned handle to a sink on the heap.
436    ///
437    /// Unlike [`arena`](Self::arena) the sink does not need a state and is
438    /// independent of any deserialization, but every sink is a separate
439    /// allocation.
440    pub fn heap<S: Sink<'de> + 'a>(val: S) -> SinkHandle<'a, 'de> {
441        SinkHandle(HandleInner::Heap(HeapSink::new(val)))
442    }
443
444    /// Creates an owned handle to the sink of a derived struct.
445    #[cfg(feature = "derive")]
446    #[inline]
447    pub(crate) fn from_struct_box(val: StructBox<'a, 'de>) -> SinkHandle<'a, 'de> {
448        SinkHandle(HandleInner::Struct(val))
449    }
450
451    /// Creates a sink handle that drops all values.
452    ///
453    /// This can be used in places where a sink is required but no value
454    /// wants to be collected.  For instance it can be tricky to provide a
455    /// mutable reference to a sink from a function that doesn't have a way
456    /// to put a slot somewhere.
457    pub fn null() -> SinkHandle<'a, 'de> {
458        SinkHandle(HandleInner::Null(ignore::Ignore))
459    }
460
461    /// Shortens the lifetime of the handle.
462    ///
463    /// Handles are invariant over their lifetime, this performs the
464    /// conversion explicitly.
465    pub fn shorten<'b>(self) -> SinkHandle<'b, 'de>
466    where
467        'a: 'b,
468    {
469        SinkHandle(match self.0 {
470            HandleInner::Borrowed(sink) => HandleInner::Borrowed(sink),
471            HandleInner::Arena(sink) => HandleInner::Arena(sink),
472            HandleInner::Heap(sink) => HandleInner::Heap(sink),
473            HandleInner::Null(sink) => HandleInner::Null(sink),
474            HandleInner::OptionalBorrowed(sink) => HandleInner::OptionalBorrowed(sink),
475            HandleInner::OptionalArena(sink) => HandleInner::OptionalArena(sink),
476            HandleInner::OptionalHeap(sink) => HandleInner::OptionalHeap(sink),
477            #[cfg(feature = "derive")]
478            HandleInner::Struct(sink) => HandleInner::Struct(sink),
479            #[cfg(feature = "derive")]
480            HandleInner::OptionalStruct(sink) => HandleInner::OptionalStruct(sink),
481        })
482    }
483
484    /// Returns `true` if this is a null handle.
485    pub fn is_null(&self) -> bool {
486        matches!(self.0, HandleInner::Null(_))
487    }
488
489    /// Converts the handle into one that ignores null atoms.
490    ///
491    /// When a null atom is received the wrapped sink is not invoked (not even
492    /// [`finish`](Sink::finish)) and the handle turns into a null handle.  An
493    /// atom counts as null if it is [`Atom::Null`] or an extension value which
494    /// falls back to null.  An empty [`Atom::Lexical`] (like the value of
495    /// `?limit=` in a query string) is passed to the wrapped sink, if the
496    /// sink rejects it the handle turns into a null handle too.
497    ///
498    /// This is used to implement `Option<T>`: the slot is set to `Some(None)`
499    /// before the handle of the inner value is created and made to ignore
500    /// nulls.
501    ///
502    /// ```
503    /// use deser::State;
504    /// use deser::de::{Deserialize, SinkHandle};
505    ///
506    /// /// Deserializes like an `Option<T>`.
507    /// fn deserialize_optional<'a, 'de, T: Deserialize<'de>>(
508    ///     out: &'a mut Option<Option<T>>,
509    ///     state: &mut State,
510    /// ) -> SinkHandle<'a, 'de> {
511    ///     T::deserialize_into(out.insert(None), state).ignore_null()
512    /// }
513    /// ```
514    pub fn ignore_null(self) -> SinkHandle<'a, 'de> {
515        SinkHandle(match self.0 {
516            HandleInner::Borrowed(sink) => HandleInner::OptionalBorrowed(sink),
517            HandleInner::Arena(sink) => HandleInner::OptionalArena(sink),
518            HandleInner::Heap(sink) => HandleInner::OptionalHeap(sink),
519            #[cfg(feature = "derive")]
520            HandleInner::Struct(sink) => HandleInner::OptionalStruct(sink),
521            other => other,
522        })
523    }
524
525    /// Returns `true` if the handle ignores the atom because it's null.
526    ///
527    /// In that case the handle turned into a null handle.
528    #[inline(always)]
529    fn skip_null(&mut self, atom: &Atom) -> bool {
530        if self.is_optional() && is_null_atom(atom) {
531            *self = SinkHandle::null();
532            return true;
533        }
534        false
535    }
536
537    #[inline(always)]
538    fn sink(&self) -> &(dyn Sink<'de> + 'a) {
539        match self.0 {
540            HandleInner::Borrowed(ref sink) | HandleInner::OptionalBorrowed(ref sink) => &**sink,
541            HandleInner::Arena(ref sink) | HandleInner::OptionalArena(ref sink) => sink.get(),
542            HandleInner::Heap(ref sink) | HandleInner::OptionalHeap(ref sink) => sink.get(),
543            #[cfg(feature = "derive")]
544            HandleInner::Struct(ref sink) | HandleInner::OptionalStruct(ref sink) => sink.get(),
545            HandleInner::Null(ref sink) => sink,
546        }
547    }
548
549    #[inline(always)]
550    fn sink_mut(&mut self) -> &mut (dyn Sink<'de> + 'a) {
551        match self.0 {
552            HandleInner::Borrowed(ref mut sink) | HandleInner::OptionalBorrowed(ref mut sink) => {
553                &mut **sink
554            }
555            HandleInner::Arena(ref mut sink) | HandleInner::OptionalArena(ref mut sink) => {
556                sink.get_mut()
557            }
558            HandleInner::Heap(ref mut sink) | HandleInner::OptionalHeap(ref mut sink) => {
559                sink.get_mut()
560            }
561            #[cfg(feature = "derive")]
562            HandleInner::Struct(ref mut sink) | HandleInner::OptionalStruct(ref mut sink) => {
563                sink.get_mut()
564            }
565            HandleInner::Null(ref mut sink) => sink,
566        }
567    }
568}
569
570#[cold]
571fn is_null_ext(ext: &crate::ext::ExtValue) -> bool {
572    matches!(ext.fallback(), Atom::Null)
573}
574
575/// Checks if an atom is a null for the purpose of optionals.
576#[inline]
577pub(crate) fn is_null_atom(atom: &Atom) -> bool {
578    match atom {
579        Atom::Null => true,
580        // an extension value that falls back to null (for instance a
581        // null with additional information attached) is a null too.
582        Atom::Ext(ext) => is_null_ext(ext),
583        Atom::Implicit(value) => value.value() == crate::ImplicitValue::Null,
584        _ => false,
585    }
586}
587
588/// Checks if an atom is an empty lexical atom that is a missing value.
589///
590/// Optionals are `None` for these if the value rejects them (like the
591/// empty value of a number in a query string), see [`LexicalRules`].
592#[inline]
593pub(crate) fn is_empty_lexical(atom: &Atom, state: &State) -> bool {
594    matches!(atom, Atom::Lexical(value) if lexical::is_empty_null(value, state))
595}
596
597/// Delivers an empty lexical atom to an optional value.
598///
599/// Returns `false` if the value rejects it with [`ErrorKind::Unexpected`],
600/// the optional is `None` then.  As that error is thrown away, it's created
601/// without a message (optional numbers are empty in every other row of
602/// some CSV files).  Other errors are passed on with their message (the
603/// atom is delivered again for this).
604#[inline]
605pub(crate) fn empty_lexical_or_none<'a>(
606    atom: Atom<'a>,
607    state: &mut State,
608    mut deliver: impl FnMut(Atom<'a>, &mut State) -> Result<(), Error>,
609) -> Result<bool, Error> {
610    let retry = atom.clone();
611    match state.discard_errors(|state| deliver(atom, state)) {
612        Ok(()) => Ok(true),
613        Err(err) if err.kind() == ErrorKind::Unexpected => Ok(false),
614        Err(err) if state.discards_errors => Err(err),
615        Err(_) => deliver(retry, state).map(|()| true),
616    }
617}
618
619// The methods on the handle are inherent so that they can be used without
620// having the `Sink` trait in scope.  The `Sink` implementation delegates to
621// them.
622impl<'a, 'de> SinkHandle<'a, 'de> {
623    /// Forwards to [`Sink::atom`].
624    #[inline]
625    pub fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
626        if self.skip_null(&atom) {
627            return Ok(());
628        }
629        if self.is_optional() && is_empty_lexical(&atom, state) {
630            if !empty_lexical_or_none(atom, state, |atom, state| self.sink_mut().atom(atom, state))?
631            {
632                *self = SinkHandle::null();
633            }
634            return Ok(());
635        }
636        self.sink_mut().atom(atom, state)
637    }
638
639    /// Forwards to [`Sink::borrowed_atom`].
640    #[inline]
641    pub fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
642        if self.skip_null(&atom) {
643            return Ok(());
644        }
645        if self.is_optional() && is_empty_lexical(&atom, state) {
646            let delivered = empty_lexical_or_none(atom, state, |atom, state| {
647                self.sink_mut().borrowed_atom(atom, state)
648            })?;
649            if !delivered {
650                *self = SinkHandle::null();
651            }
652            return Ok(());
653        }
654        self.sink_mut().borrowed_atom(atom, state)
655    }
656
657    /// Returns `true` if the handle ignores null atoms (see
658    /// [`ignore_null`](Self::ignore_null)).
659    #[inline(always)]
660    fn is_optional(&self) -> bool {
661        match self.0 {
662            HandleInner::OptionalBorrowed(_)
663            | HandleInner::OptionalArena(_)
664            | HandleInner::OptionalHeap(_) => true,
665            #[cfg(feature = "derive")]
666            HandleInner::OptionalStruct(_) => true,
667            _ => false,
668        }
669    }
670
671    /// Handles an atom the sink does not accept (see
672    /// [`Sink::unexpected_atom`]).
673    pub fn unexpected_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
674        default_unexpected_atom(self.sink_mut(), atom, state)
675    }
676
677    /// Forwards to [`Sink::map`].
678    #[inline]
679    pub fn map(&mut self, state: &mut State) -> Result<(), Error> {
680        self.sink_mut().map(state)
681    }
682
683    /// Forwards to [`Sink::seq`].
684    #[inline]
685    pub fn seq(&mut self, state: &mut State) -> Result<(), Error> {
686        self.sink_mut().seq(state)
687    }
688
689    /// Forwards to [`Sink::next_key`].
690    #[inline]
691    pub fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
692        self.sink_mut().next_key(state)
693    }
694
695    /// Forwards to [`Sink::next_value`].
696    #[inline]
697    pub fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
698        self.sink_mut().next_value(state)
699    }
700
701    /// Forwards to [`Sink::value_for_key`].
702    pub fn value_for_key(
703        &mut self,
704        key: &str,
705        state: &mut State,
706    ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
707        self.sink_mut().value_for_key(key, state)
708    }
709
710    /// Forwards to [`Sink::finish`].
711    #[inline]
712    pub fn finish(&mut self, state: &mut State) -> Result<(), Error> {
713        self.sink_mut().finish(state)
714    }
715
716    /// Forwards to [`Sink::recover`].
717    pub fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
718        self.sink_mut().recover(err, state)
719    }
720
721    /// Forwards to [`Sink::expecting`].
722    pub fn expecting(&self) -> Cow<'_, str> {
723        self.sink().expecting()
724    }
725}
726
727impl<'a, 'de> Sink<'de> for SinkHandle<'a, 'de> {
728    #[inline]
729    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
730        SinkHandle::atom(self, atom, state)
731    }
732
733    #[inline]
734    fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
735        SinkHandle::borrowed_atom(self, atom, state)
736    }
737
738    #[inline]
739    fn map(&mut self, state: &mut State) -> Result<(), Error> {
740        SinkHandle::map(self, state)
741    }
742
743    #[inline]
744    fn seq(&mut self, state: &mut State) -> Result<(), Error> {
745        SinkHandle::seq(self, state)
746    }
747
748    #[inline]
749    fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
750        SinkHandle::next_key(self, state)
751    }
752
753    #[inline]
754    fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
755        SinkHandle::next_value(self, state)
756    }
757
758    #[inline]
759    fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
760        self.sink_mut().__private_key_atom(atom, state)
761    }
762
763    #[inline]
764    fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
765        self.sink_mut().__private_value_atom(atom, state)
766    }
767
768    #[inline]
769    fn __private_borrowed_key_atom(
770        &mut self,
771        atom: Atom<'de>,
772        state: &mut State,
773    ) -> Result<(), Error> {
774        self.sink_mut().__private_borrowed_key_atom(atom, state)
775    }
776
777    #[inline]
778    fn __private_borrowed_value_atom(
779        &mut self,
780        atom: Atom<'de>,
781        state: &mut State,
782    ) -> Result<(), Error> {
783        self.sink_mut().__private_borrowed_value_atom(atom, state)
784    }
785
786    #[inline]
787    fn __private_seq(&mut self, state: &mut State) -> Result<bool, Error> {
788        self.sink_mut().__private_seq(state)
789    }
790
791    #[inline]
792    fn __private_inline_atom(
793        &mut self,
794        index: usize,
795        atom: Atom,
796        state: &mut State,
797    ) -> Result<(), Error> {
798        self.sink_mut().__private_inline_atom(index, atom, state)
799    }
800
801    #[inline]
802    fn __private_inline_event(
803        &mut self,
804        event: InlineEvent,
805        state: &mut State,
806    ) -> Result<(), Error> {
807        self.sink_mut().__private_inline_event(event, state)
808    }
809
810    fn value_for_key(
811        &mut self,
812        key: &str,
813        state: &mut State,
814    ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
815        SinkHandle::value_for_key(self, key, state)
816    }
817
818    #[inline]
819    fn finish(&mut self, state: &mut State) -> Result<(), Error> {
820        SinkHandle::finish(self, state)
821    }
822
823    fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
824        SinkHandle::recover(self, err, state)
825    }
826
827    fn expecting(&self) -> Cow<'_, str> {
828        SinkHandle::expecting(self)
829    }
830}
831
832/// A trait for deserializable types.
833///
834/// A type is deserializable if it can deserialize into a [`Sink`].  The
835/// actual deserialization logic itself is implemented by the returned
836/// [`Sink`].
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/// # Thread Safety
857///
858/// Deserializable values are `Send` and so are the sinks they create.  This
859/// allows an ongoing deserialization (a [`DeserializeDriver`]) to move
860/// between threads, for instance when it is suspended while waiting for more
861/// input.  Types that are not `Send` (such as `Rc`) cannot be deserialized.
862pub trait Deserialize<'de>: Sized + Send {
863    /// Creates a sink that deserializes the value into the given slot.
864    ///
865    /// There are two typical implementations for this method: the common one is
866    /// to return a [`SlotWrapper`].  Custom types will most likely just return
867    /// that.  An alternative method is to "wrap" the deserializable in a custom
868    /// sink.
869    fn deserialize_into<'out>(
870        out: &'out mut Option<Self>,
871        state: &mut State,
872    ) -> SinkHandle<'out, 'de>;
873
874    /// Provides the value of a missing struct field.
875    ///
876    /// When a struct is deserialized the slots of its fields start out with
877    /// this value.  If a field does not appear in the data, the initial value
878    /// is used.  If it is `None` (the default) the field is required.
879    /// `Option<T>` returns `Some(None)` here which makes optional fields
880    /// default to `None` when they are missing.
881    ///
882    /// This only controls missing values.  How null values are handled is up
883    /// to the sink (see [`SinkHandle::ignore_null`]).  The initial value is not
884    /// used for fields with `#[deser(default)]`.
885    fn initial_value() -> Option<Self> {
886        None
887    }
888
889    /// Creates a sink that updates an existing value.
890    ///
891    /// This is used to apply data on top of a value, for instance to layer a
892    /// configuration file over the defaults (see
893    /// [`DeserializeDriver::update`] and [`Deserializer::update`]).  The
894    /// default implementation replaces the value with the deserialized one.
895    /// Derived structs update the fields that are given and keep the others
896    /// (fields are updated the same way, so nested structs are merged).
897    /// `Option` updates the value in it if it's set, null clears it.  `Box`
898    /// updates the value in it.  `HashMap` and `BTreeMap` insert the given
899    /// entries, the values of keys that exist are replaced.
900    ///
901    /// If the update fails, the value might be partially updated.
902    fn deserialize_update<'out>(value: &'out mut Self, state: &mut State) -> SinkHandle<'out, 'de> {
903        update::replace_handle(value, state)
904    }
905
906    /// Deserializes an atom into the slot.
907    ///
908    /// This must behave exactly like invoking [`atom`](Sink::atom) and
909    /// [`finish`](Sink::finish) on the sink returned by
910    /// [`deserialize_into`](Self::deserialize_into), which is what the default
911    /// implementation does.  Types with stateless sinks override this so that
912    /// atoms can be deserialized without dynamic dispatch.
913    #[doc(hidden)]
914    fn __private_atom_into(
915        out: &mut Option<Self>,
916        atom: Atom,
917        state: &mut State,
918    ) -> Result<(), Error> {
919        atom_into_handle(Self::deserialize_into(out, state), atom, state)
920    }
921
922    /// Deserializes a borrowed atom into the slot.
923    ///
924    /// This is like [`__private_atom_into`](Self::__private_atom_into) but
925    /// for [`borrowed_atom`](Sink::borrowed_atom).
926    #[doc(hidden)]
927    fn __private_borrowed_atom_into(
928        out: &mut Option<Self>,
929        atom: Atom<'de>,
930        state: &mut State,
931    ) -> Result<(), Error> {
932        borrowed_atom_into_handle(Self::deserialize_into(out, state), atom, state)
933    }
934
935    /// Returns `true` if this deserialize is `u8`.
936    ///
937    /// This is used to specialize the handling of bytes for vectors and
938    /// arrays of `u8`.
939    #[doc(hidden)]
940    fn __private_is_bytes() -> bool {
941        false
942    }
943
944    /// Converts bytes into a vector of `Self`.
945    ///
946    /// This is only implemented for `u8` and used to specialize the
947    /// deserialization of `Vec<u8>` from bytes.
948    #[doc(hidden)]
949    fn __private_vec_from_bytes(bytes: Vec<u8>) -> Option<Vec<Self>> {
950        let _ = bytes;
951        None
952    }
953
954    /// Converts bytes into an array of `Self`.
955    ///
956    /// This is only implemented for `u8` and used to specialize the
957    /// deserialization of `[u8; N]` from bytes.  Returns `None` if the
958    /// type is not `u8` or the length does not match.
959    #[doc(hidden)]
960    fn __private_array_from_bytes<const N: usize>(bytes: &[u8]) -> Option<[Self; N]> {
961        let _ = bytes;
962        None
963    }
964
965    /// Returns the value of a type that is only deserialized from atoms.
966    ///
967    /// This is implemented for numbers and booleans, sequences of them are
968    /// built inline (see [`InlineSeq`]).  The value is a placeholder, it's
969    /// overwritten.
970    #[doc(hidden)]
971    fn __private_atom_default() -> Option<Self> {
972        None
973    }
974
975    /// Returns how the type is built inline if it's a sequence of atoms.
976    #[doc(hidden)]
977    fn __private_inline_seq() -> Option<InlineSeq<Self>> {
978        None
979    }
980
981    /// Returns `true` if the type collects the values of a repeated key.
982    ///
983    /// This is `true` for collections like `Vec<T>` and sets (and
984    /// `Option`s of them).  In a multimap (see
985    /// [`ContainerShape::with_multimap`](crate::ContainerShape::with_multimap))
986    /// fields and map values of these types receive every value of their
987    /// key through [`__private_collect_into`](Self::__private_collect_into)
988    /// and [`__private_collect_update`](Self::__private_collect_update).
989    #[doc(hidden)]
990    fn __private_collects() -> bool {
991        false
992    }
993
994    /// Returns a sink for a value that is added to the collection in the
995    /// slot.
996    ///
997    /// The collection is created if the slot is empty.  This is only used
998    /// if [`__private_collects`](Self::__private_collects) returns `true`.
999    #[doc(hidden)]
1000    fn __private_collect_into<'out>(
1001        out: &'out mut Option<Self>,
1002        state: &mut State,
1003    ) -> SinkHandle<'out, 'de> {
1004        Self::deserialize_into(out, state)
1005    }
1006
1007    /// Returns a sink for a value that is added to a collection that is
1008    /// updated.
1009    ///
1010    /// The value that is added `first` replaces the collection.  This is
1011    /// only used if [`__private_collects`](Self::__private_collects) returns
1012    /// `true`.
1013    #[doc(hidden)]
1014    fn __private_collect_update<'out>(
1015        value: &'out mut Self,
1016        first: bool,
1017        state: &mut State,
1018    ) -> SinkHandle<'out, 'de> {
1019        let _ = first;
1020        Self::deserialize_update(value, state)
1021    }
1022
1023    /// Returns the value of a collection whose key is missing in a
1024    /// multimap.
1025    ///
1026    /// Collections are empty then.  `None` means that the field is missing
1027    /// (or has its [`initial_value`](Self::initial_value)).
1028    #[doc(hidden)]
1029    fn __private_collect_empty() -> Option<Self> {
1030        None
1031    }
1032}
1033
1034/// A type that can be deserialized without borrowing.
1035///
1036/// This is implemented for all types that implement [`Deserialize`] for all
1037/// lifetimes, which means that they do not borrow from the data they are
1038/// deserialized from.  It's useful as a bound where the data does not
1039/// outlive the deserialization (for instance when reading from a stream).
1040pub trait DeserializeOwned: for<'de> Deserialize<'de> {}
1041
1042impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
1043
1044/// Converts a sink into a trait object.
1045///
1046/// This is implemented for all sinks.  The default methods of [`Sink`] exist
1047/// for every sink type, they use this to forward to code that exists once.
1048#[doc(hidden)]
1049pub trait AsDynSink<'de> {
1050    fn __private_as_dyn(&mut self) -> &mut dyn Sink<'de>;
1051}
1052
1053impl<'de, T: Sink<'de>> AsDynSink<'de> for T {
1054    #[inline(always)]
1055    fn __private_as_dyn(&mut self) -> &mut dyn Sink<'de> {
1056        self
1057    }
1058}
1059
1060/// Trait to place values in a slot.
1061///
1062/// A sink acts as an abstraction to receive a value during deserialization from
1063/// the deserializer.  Sinks in deser are one-shot receivers.  A deserializer must
1064/// invoke one receiver method for a total of zero or one times.
1065///
1066/// The sink then places the received value in the slot connected to the sink.
1067///
1068/// # Borrowed Data
1069///
1070/// Atoms are passed to [`atom`](Self::atom) with a lifetime that only lasts
1071/// for the call.  Formats pass atoms which borrow from the data that is
1072/// deserialized (which lives for `'de`) to [`borrowed_atom`](Self::borrowed_atom)
1073/// instead.  By default this forwards to [`atom`](Self::atom), only sinks of
1074/// types which want to borrow (like `&'de str`) need to implement it.
1075pub trait Sink<'de>: Send + AsDynSink<'de> {
1076    /// Receives an [`Atom`].
1077    ///
1078    /// Any unknown atom variant should be dispatched to [`unexpected_atom`](Self::unexpected_atom).
1079    /// This is particularly important for [`Atom::Ext`] as the default
1080    /// implementation of `unexpected_atom` will retry with the fallback atom
1081    /// of the extension value.
1082    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1083        default_unexpected_atom(self.__private_as_dyn(), atom, state)
1084    }
1085
1086    /// Receives an [`Atom`] that borrows from the data being deserialized.
1087    ///
1088    /// The default implementation forwards to [`atom`](Self::atom).
1089    fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
1090        self.atom(atom, state)
1091    }
1092
1093    /// Implements a default fallback handling for atoms.
1094    ///
1095    /// For [`Atom::Ext`] values the atom is lowered into the core data model
1096    /// with [`fallback`](crate::ext::ExtValue::fallback) and passed to
1097    /// [`atom`](Self::atom) again.  [`Atom::F32`] is widened into an
1098    /// [`Atom::F64`] and passed on the same way, so sinks that accept floats
1099    /// only need to handle `F64`.  [`Atom::Lexical`] is passed on as
1100    /// [`Atom::Str`], so sinks that accept strings accept lexical atoms
1101    /// too.  For all other atoms an error is returned.
1102    ///
1103    /// This is a helper for implementations of [`atom`](Self::atom), it's
1104    /// not invoked by the driver (and not part of the vtable of sinks, so
1105    /// that it does not exist once per sink).
1106    fn unexpected_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error>
1107    where
1108        Self: Sized,
1109    {
1110        default_unexpected_atom(self.__private_as_dyn(), atom, state)
1111    }
1112
1113    /// Begins the deserialization of a map.
1114    ///
1115    /// While the deserialization of a map is ongoing the methods
1116    /// [`next_key`](Self::next_key) and [`next_value`](Self::next_value) are
1117    /// called alternatingly.  The map is ended by [`finish`](Self::finish).
1118    ///
1119    /// The default implementation returns an error.
1120    fn map(&mut self, state: &mut State) -> Result<(), Error> {
1121        default_container(self.__private_as_dyn(), "map", state)
1122    }
1123
1124    /// Begins the receiving process for sequences.
1125    ///
1126    /// While the deserialization of a sequence is ongoing the method
1127    /// [`next_value`](Self::next_value) is called for every new item.
1128    /// The sequence is ended by [`finish`](Self::finish).
1129    ///
1130    /// The default implementation returns an error.
1131    fn seq(&mut self, state: &mut State) -> Result<(), Error> {
1132        default_container(self.__private_as_dyn(), "sequence", state)
1133    }
1134
1135    /// Returns a sink for the next key in a map.
1136    fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1137        let _ = state;
1138        Ok(SinkHandle::null())
1139    }
1140
1141    /// Returns a sink for the next value in a map or sequence.
1142    fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1143        let _ = state;
1144        Ok(SinkHandle::null())
1145    }
1146
1147    /// Receives an atom as the next key in a map.
1148    ///
1149    /// This is a shortcut for invoking [`next_key`](Self::next_key) and then
1150    /// [`atom`](Self::atom) and [`finish`](Self::finish) on the returned sink,
1151    /// which is exactly what the default implementation does.  The driver
1152    /// uses this for keys that are atoms which is the overwhelmingly common
1153    /// case.  Sinks can override this to avoid creating a sink for the key,
1154    /// but the behavior must be the same as with the default implementation.
1155    /// In particular, sinks that override [`next_key`](Self::next_key) must
1156    /// either not override this method or apply the same logic.
1157    #[doc(hidden)]
1158    fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1159        default_key_atom(self.__private_as_dyn(), atom, state)
1160    }
1161
1162    /// Receives an atom as the next value in a map or sequence.
1163    ///
1164    /// This is a shortcut for invoking [`next_value`](Self::next_value) and
1165    /// then [`atom`](Self::atom) and [`finish`](Self::finish) on the returned
1166    /// sink, which is exactly what the default implementation does.  See
1167    /// [`__private_key_atom`](Self::__private_key_atom) for more information.
1168    #[doc(hidden)]
1169    fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1170        default_value_atom(self.__private_as_dyn(), atom, state)
1171    }
1172
1173    /// Receives a borrowed atom as the next key in a map.
1174    ///
1175    /// Like [`__private_key_atom`](Self::__private_key_atom) but the atom is
1176    /// passed to [`borrowed_atom`](Self::borrowed_atom).
1177    #[doc(hidden)]
1178    fn __private_borrowed_key_atom(
1179        &mut self,
1180        atom: Atom<'de>,
1181        state: &mut State,
1182    ) -> Result<(), Error> {
1183        default_borrowed_key_atom(self.__private_as_dyn(), atom, state)
1184    }
1185
1186    /// Receives a borrowed atom as the next value in a map or sequence.
1187    ///
1188    /// Like [`__private_value_atom`](Self::__private_value_atom) but the atom
1189    /// is passed to [`borrowed_atom`](Self::borrowed_atom).
1190    #[doc(hidden)]
1191    fn __private_borrowed_value_atom(
1192        &mut self,
1193        atom: Atom<'de>,
1194        state: &mut State,
1195    ) -> Result<(), Error> {
1196        default_borrowed_value_atom(self.__private_as_dyn(), atom, state)
1197    }
1198
1199    /// Begins a sequence like [`seq`](Self::seq).
1200    ///
1201    /// Returns `true` if the sink builds sequences that are its elements
1202    /// inline (see [`InlineSeq`]): the driver then passes their events to
1203    /// [`__private_inline_atom`](Self::__private_inline_atom) and
1204    /// [`__private_inline_event`](Self::__private_inline_event) instead of
1205    /// asking for a sink for them.  Wrappers that forward this have to
1206    /// forward those as well.
1207    #[doc(hidden)]
1208    fn __private_seq(&mut self, state: &mut State) -> Result<bool, Error> {
1209        self.seq(state)?;
1210        Ok(false)
1211    }
1212
1213    /// Receives the atom at the index of an element that is built inline.
1214    #[doc(hidden)]
1215    fn __private_inline_atom(
1216        &mut self,
1217        index: usize,
1218        atom: Atom,
1219        state: &mut State,
1220    ) -> Result<(), Error> {
1221        let _ = (index, atom, state);
1222        no_inline_seq()
1223    }
1224
1225    /// Receives the other events of an element that is built inline.
1226    #[doc(hidden)]
1227    fn __private_inline_event(
1228        &mut self,
1229        event: InlineEvent,
1230        state: &mut State,
1231    ) -> Result<(), Error> {
1232        let _ = (event, state);
1233        no_inline_seq()
1234    }
1235
1236    /// Returns a value sink for a specific struct field.
1237    ///
1238    /// This is a special method that is supposed to be implemented by structs
1239    /// if they want to support flattening.  A struct that gets flattened into
1240    /// another struct will have this method called to figure out if a key is
1241    /// used by it.  The default implementation always returns `None`.
1242    fn value_for_key(
1243        &mut self,
1244        key: &str,
1245        state: &mut State,
1246    ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
1247        let _ = key;
1248        let _ = state;
1249        Ok(None)
1250    }
1251
1252    /// Called after [`atom`](Self::atom), [`map`](Self::map) or [`seq](Self::seq).
1253    ///
1254    /// The default implementation does nothing.
1255    fn finish(&mut self, state: &mut State) -> Result<(), Error> {
1256        let _ = state;
1257        Ok(())
1258    }
1259
1260    /// Called when an item of this map or sequence failed.
1261    ///
1262    /// This is invoked by the [`DeserializeDriver`] when the key or value
1263    /// that was started last in this container failed with an error, either
1264    /// because its sink (or a sink nested in it) returned the error or
1265    /// because this sink returned it while handling the item (for instance
1266    /// from [`next_value`](Self::next_value) or
1267    /// [`__private_value_atom`](Self::__private_value_atom)).  Errors of
1268    /// this sink's own [`map`](Self::map), [`seq`](Self::seq) and
1269    /// [`finish`](Self::finish) are errors of this sink's value and go to
1270    /// the container this sink is an item of.
1271    ///
1272    /// A sink that returns `Ok` recovers from the error: the driver skips
1273    /// the remaining events of the failed item (and the value of a failed
1274    /// key) and deserialization continues with the next item.  Returning
1275    /// the error (which is what the default implementation does) passes it
1276    /// on to the enclosing container.  All sinks of the failed item are
1277    /// dropped before this is invoked.  The error already has the context of
1278    /// the event that failed attached (see [`Error`]).
1279    ///
1280    /// Only errors of sinks are recoverable: errors of the format and of
1281    /// [`Layer`]s end the deserialization.
1282    ///
1283    /// Sinks that forward [`next_key`](Self::next_key) and
1284    /// [`next_value`](Self::next_value) to another sink should forward this
1285    /// as well.
1286    fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
1287        let _ = state;
1288        Err(err)
1289    }
1290
1291    /// Utility method to return an expectation message that is used in error messages.
1292    ///
1293    /// This is typically the name of the type.  The default implementation
1294    /// returns `"compatible type"`.
1295    fn expecting(&self) -> Cow<'_, str> {
1296        Cow::Borrowed("compatible type")
1297    }
1298}