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;
239mod 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 /// Forwards to [`Sink::unexpected_atom`].
672 pub fn unexpected_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
673 self.sink_mut().unexpected_atom(atom, state)
674 }
675
676 /// Forwards to [`Sink::map`].
677 #[inline]
678 pub fn map(&mut self, state: &mut State) -> Result<(), Error> {
679 self.sink_mut().map(state)
680 }
681
682 /// Forwards to [`Sink::seq`].
683 #[inline]
684 pub fn seq(&mut self, state: &mut State) -> Result<(), Error> {
685 self.sink_mut().seq(state)
686 }
687
688 /// Forwards to [`Sink::next_key`].
689 #[inline]
690 pub fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
691 self.sink_mut().next_key(state)
692 }
693
694 /// Forwards to [`Sink::next_value`].
695 #[inline]
696 pub fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
697 self.sink_mut().next_value(state)
698 }
699
700 /// Forwards to [`Sink::value_for_key`].
701 pub fn value_for_key(
702 &mut self,
703 key: &str,
704 state: &mut State,
705 ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
706 self.sink_mut().value_for_key(key, state)
707 }
708
709 /// Forwards to [`Sink::finish`].
710 #[inline]
711 pub fn finish(&mut self, state: &mut State) -> Result<(), Error> {
712 self.sink_mut().finish(state)
713 }
714
715 /// Forwards to [`Sink::recover`].
716 pub fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
717 self.sink_mut().recover(err, state)
718 }
719
720 /// Forwards to [`Sink::expecting`].
721 pub fn expecting(&self) -> Cow<'_, str> {
722 self.sink().expecting()
723 }
724}
725
726impl<'a, 'de> Sink<'de> for SinkHandle<'a, 'de> {
727 #[inline]
728 fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
729 SinkHandle::atom(self, atom, state)
730 }
731
732 #[inline]
733 fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
734 SinkHandle::borrowed_atom(self, atom, state)
735 }
736
737 fn unexpected_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
738 SinkHandle::unexpected_atom(self, atom, state)
739 }
740
741 #[inline]
742 fn map(&mut self, state: &mut State) -> Result<(), Error> {
743 SinkHandle::map(self, state)
744 }
745
746 #[inline]
747 fn seq(&mut self, state: &mut State) -> Result<(), Error> {
748 SinkHandle::seq(self, state)
749 }
750
751 #[inline]
752 fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
753 SinkHandle::next_key(self, state)
754 }
755
756 #[inline]
757 fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
758 SinkHandle::next_value(self, state)
759 }
760
761 #[inline]
762 fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
763 self.sink_mut().__private_key_atom(atom, state)
764 }
765
766 #[inline]
767 fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
768 self.sink_mut().__private_value_atom(atom, state)
769 }
770
771 #[inline]
772 fn __private_borrowed_key_atom(
773 &mut self,
774 atom: Atom<'de>,
775 state: &mut State,
776 ) -> Result<(), Error> {
777 self.sink_mut().__private_borrowed_key_atom(atom, state)
778 }
779
780 #[inline]
781 fn __private_borrowed_value_atom(
782 &mut self,
783 atom: Atom<'de>,
784 state: &mut State,
785 ) -> Result<(), Error> {
786 self.sink_mut().__private_borrowed_value_atom(atom, state)
787 }
788
789 #[inline]
790 fn __private_seq(&mut self, state: &mut State) -> Result<bool, Error> {
791 self.sink_mut().__private_seq(state)
792 }
793
794 #[inline]
795 fn __private_inline_atom(
796 &mut self,
797 index: usize,
798 atom: Atom,
799 state: &mut State,
800 ) -> Result<(), Error> {
801 self.sink_mut().__private_inline_atom(index, atom, state)
802 }
803
804 #[inline]
805 fn __private_inline_event(
806 &mut self,
807 event: InlineEvent,
808 state: &mut State,
809 ) -> Result<(), Error> {
810 self.sink_mut().__private_inline_event(event, state)
811 }
812
813 fn value_for_key(
814 &mut self,
815 key: &str,
816 state: &mut State,
817 ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
818 SinkHandle::value_for_key(self, key, state)
819 }
820
821 #[inline]
822 fn finish(&mut self, state: &mut State) -> Result<(), Error> {
823 SinkHandle::finish(self, state)
824 }
825
826 fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
827 SinkHandle::recover(self, err, state)
828 }
829
830 fn expecting(&self) -> Cow<'_, str> {
831 SinkHandle::expecting(self)
832 }
833}
834
835/// A trait for deserializable types.
836///
837/// A type is deserializable if it can deserialize into a [`Sink`]. The
838/// actual deserialization logic itself is implemented by the returned
839/// [`Sink`].
840///
841/// The lifetime `'de` is the lifetime of the data that is deserialized.
842/// Types that borrow from it (like `&'de str`) only implement
843/// `Deserialize<'de>` for that lifetime, types that do not borrow implement
844/// it for all lifetimes (see [`DeserializeOwned`]):
845///
846/// ```
847/// use deser::Deserialize;
848///
849/// #[derive(Deserialize)]
850/// struct User<'a> {
851/// name: &'a str,
852/// id: u64,
853/// }
854/// ```
855///
856/// Data can only be borrowed if the data format passes it on borrowed (see
857/// [`Sink::borrowed_atom`]).
858///
859/// # Thread Safety
860///
861/// Deserializable values are `Send` and so are the sinks they create. This
862/// allows an ongoing deserialization (a [`DeserializeDriver`]) to move
863/// between threads, for instance when it is suspended while waiting for more
864/// input. Types that are not `Send` (such as `Rc`) cannot be deserialized.
865pub trait Deserialize<'de>: Sized + Send {
866 /// Creates a sink that deserializes the value into the given slot.
867 ///
868 /// There are two typical implementations for this method: the common one is
869 /// to return a [`SlotWrapper`]. Custom types will most likely just return
870 /// that. An alternative method is to "wrap" the deserializable in a custom
871 /// sink.
872 fn deserialize_into<'out>(
873 out: &'out mut Option<Self>,
874 state: &mut State,
875 ) -> SinkHandle<'out, 'de>;
876
877 /// Provides the value of a missing struct field.
878 ///
879 /// When a struct is deserialized the slots of its fields start out with
880 /// this value. If a field does not appear in the data, the initial value
881 /// is used. If it is `None` (the default) the field is required.
882 /// `Option<T>` returns `Some(None)` here which makes optional fields
883 /// default to `None` when they are missing.
884 ///
885 /// This only controls missing values. How null values are handled is up
886 /// to the sink (see [`SinkHandle::ignore_null`]). The initial value is not
887 /// used for fields with `#[deser(default)]`.
888 fn initial_value() -> Option<Self> {
889 None
890 }
891
892 /// Creates a sink that updates an existing value.
893 ///
894 /// This is used to apply data on top of a value, for instance to layer a
895 /// configuration file over the defaults (see
896 /// [`DeserializeDriver::update`] and [`Deserializer::update`]). The
897 /// default implementation replaces the value with the deserialized one.
898 /// Derived structs update the fields that are given and keep the others
899 /// (fields are updated the same way, so nested structs are merged).
900 /// `Option` updates the value in it if it's set, null clears it. `Box`
901 /// updates the value in it. `HashMap` and `BTreeMap` insert the given
902 /// entries, the values of keys that exist are replaced.
903 ///
904 /// If the update fails, the value might be partially updated.
905 fn deserialize_update<'out>(value: &'out mut Self, state: &mut State) -> SinkHandle<'out, 'de> {
906 update::replace_handle(value, state)
907 }
908
909 /// Deserializes an atom into the slot.
910 ///
911 /// This must behave exactly like invoking [`atom`](Sink::atom) and
912 /// [`finish`](Sink::finish) on the sink returned by
913 /// [`deserialize_into`](Self::deserialize_into), which is what the default
914 /// implementation does. Types with stateless sinks override this so that
915 /// atoms can be deserialized without dynamic dispatch.
916 #[doc(hidden)]
917 fn __private_atom_into(
918 out: &mut Option<Self>,
919 atom: Atom,
920 state: &mut State,
921 ) -> Result<(), Error> {
922 atom_into_handle(Self::deserialize_into(out, state), atom, state)
923 }
924
925 /// Deserializes a borrowed atom into the slot.
926 ///
927 /// This is like [`__private_atom_into`](Self::__private_atom_into) but
928 /// for [`borrowed_atom`](Sink::borrowed_atom).
929 #[doc(hidden)]
930 fn __private_borrowed_atom_into(
931 out: &mut Option<Self>,
932 atom: Atom<'de>,
933 state: &mut State,
934 ) -> Result<(), Error> {
935 borrowed_atom_into_handle(Self::deserialize_into(out, state), atom, state)
936 }
937
938 /// Returns `true` if this deserialize is `u8`.
939 ///
940 /// This is used to specialize the handling of bytes for vectors and
941 /// arrays of `u8`.
942 #[doc(hidden)]
943 fn __private_is_bytes() -> bool {
944 false
945 }
946
947 /// Converts bytes into a vector of `Self`.
948 ///
949 /// This is only implemented for `u8` and used to specialize the
950 /// deserialization of `Vec<u8>` from bytes.
951 #[doc(hidden)]
952 fn __private_vec_from_bytes(bytes: Vec<u8>) -> Option<Vec<Self>> {
953 let _ = bytes;
954 None
955 }
956
957 /// Converts bytes into an array of `Self`.
958 ///
959 /// This is only implemented for `u8` and used to specialize the
960 /// deserialization of `[u8; N]` from bytes. Returns `None` if the
961 /// type is not `u8` or the length does not match.
962 #[doc(hidden)]
963 fn __private_array_from_bytes<const N: usize>(bytes: &[u8]) -> Option<[Self; N]> {
964 let _ = bytes;
965 None
966 }
967
968 /// Returns the value of a type that is only deserialized from atoms.
969 ///
970 /// This is implemented for numbers and booleans, sequences of them are
971 /// built inline (see [`InlineSeq`]). The value is a placeholder, it's
972 /// overwritten.
973 #[doc(hidden)]
974 fn __private_atom_default() -> Option<Self> {
975 None
976 }
977
978 /// Returns how the type is built inline if it's a sequence of atoms.
979 #[doc(hidden)]
980 fn __private_inline_seq() -> Option<InlineSeq<Self>> {
981 None
982 }
983
984 /// Returns `true` if the type collects the values of a repeated key.
985 ///
986 /// This is `true` for collections like `Vec<T>` and sets (and
987 /// `Option`s of them). In a multimap (see
988 /// [`ContainerShape::with_multimap`](crate::ContainerShape::with_multimap))
989 /// fields and map values of these types receive every value of their
990 /// key through [`__private_collect_into`](Self::__private_collect_into)
991 /// and [`__private_collect_update`](Self::__private_collect_update).
992 #[doc(hidden)]
993 fn __private_collects() -> bool {
994 false
995 }
996
997 /// Returns a sink for a value that is added to the collection in the
998 /// slot.
999 ///
1000 /// The collection is created if the slot is empty. This is only used
1001 /// if [`__private_collects`](Self::__private_collects) returns `true`.
1002 #[doc(hidden)]
1003 fn __private_collect_into<'out>(
1004 out: &'out mut Option<Self>,
1005 state: &mut State,
1006 ) -> SinkHandle<'out, 'de> {
1007 Self::deserialize_into(out, state)
1008 }
1009
1010 /// Returns a sink for a value that is added to a collection that is
1011 /// updated.
1012 ///
1013 /// The value that is added `first` replaces the collection. This is
1014 /// only used if [`__private_collects`](Self::__private_collects) returns
1015 /// `true`.
1016 #[doc(hidden)]
1017 fn __private_collect_update<'out>(
1018 value: &'out mut Self,
1019 first: bool,
1020 state: &mut State,
1021 ) -> SinkHandle<'out, 'de> {
1022 let _ = first;
1023 Self::deserialize_update(value, state)
1024 }
1025
1026 /// Returns the value of a collection whose key is missing in a
1027 /// multimap.
1028 ///
1029 /// Collections are empty then. `None` means that the field is missing
1030 /// (or has its [`initial_value`](Self::initial_value)).
1031 #[doc(hidden)]
1032 fn __private_collect_empty() -> Option<Self> {
1033 None
1034 }
1035}
1036
1037/// A type that can be deserialized without borrowing.
1038///
1039/// This is implemented for all types that implement [`Deserialize`] for all
1040/// lifetimes, which means that they do not borrow from the data they are
1041/// deserialized from. It's useful as a bound where the data does not
1042/// outlive the deserialization (for instance when reading from a stream).
1043pub trait DeserializeOwned: for<'de> Deserialize<'de> {}
1044
1045impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
1046
1047/// Converts a sink into a trait object.
1048///
1049/// This is implemented for all sinks. The default methods of [`Sink`] exist
1050/// for every sink type, they use this to forward to code that exists once.
1051#[doc(hidden)]
1052pub trait AsDynSink<'de> {
1053 fn __private_as_dyn(&mut self) -> &mut dyn Sink<'de>;
1054}
1055
1056impl<'de, T: Sink<'de>> AsDynSink<'de> for T {
1057 #[inline(always)]
1058 fn __private_as_dyn(&mut self) -> &mut dyn Sink<'de> {
1059 self
1060 }
1061}
1062
1063/// Trait to place values in a slot.
1064///
1065/// A sink acts as an abstraction to receive a value during deserialization from
1066/// the deserializer. Sinks in deser are one-shot receivers. A deserializer must
1067/// invoke one receiver method for a total of zero or one times.
1068///
1069/// The sink then places the received value in the slot connected to the sink.
1070///
1071/// # Borrowed Data
1072///
1073/// Atoms are passed to [`atom`](Self::atom) with a lifetime that only lasts
1074/// for the call. Formats pass atoms which borrow from the data that is
1075/// deserialized (which lives for `'de`) to [`borrowed_atom`](Self::borrowed_atom)
1076/// instead. By default this forwards to [`atom`](Self::atom), only sinks of
1077/// types which want to borrow (like `&'de str`) need to implement it.
1078pub trait Sink<'de>: Send + AsDynSink<'de> {
1079 /// Receives an [`Atom`].
1080 ///
1081 /// Any unknown atom variant should be dispatched to [`unexpected_atom`](Self::unexpected_atom).
1082 /// This is particularly important for [`Atom::Ext`] as the default
1083 /// implementation of `unexpected_atom` will retry with the fallback atom
1084 /// of the extension value.
1085 fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1086 self.unexpected_atom(atom, state)
1087 }
1088
1089 /// Receives an [`Atom`] that borrows from the data being deserialized.
1090 ///
1091 /// The default implementation forwards to [`atom`](Self::atom).
1092 fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
1093 self.atom(atom, state)
1094 }
1095
1096 /// Implements a default fallback handling for atoms.
1097 ///
1098 /// For [`Atom::Ext`] values the atom is lowered into the core data model
1099 /// with [`fallback`](crate::ext::ExtValue::fallback) and passed to
1100 /// [`atom`](Self::atom) again. [`Atom::F32`] is widened into an
1101 /// [`Atom::F64`] and passed on the same way, so sinks that accept floats
1102 /// only need to handle `F64`. [`Atom::Lexical`] is passed on as
1103 /// [`Atom::Str`], so sinks that accept strings accept lexical atoms
1104 /// too. For all other atoms an error is returned.
1105 fn unexpected_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1106 default_unexpected_atom(self.__private_as_dyn(), atom, state)
1107 }
1108
1109 /// Begins the deserialization of a map.
1110 ///
1111 /// While the deserialization of a map is ongoing the methods
1112 /// [`next_key`](Self::next_key) and [`next_value`](Self::next_value) are
1113 /// called alternatingly. The map is ended by [`finish`](Self::finish).
1114 ///
1115 /// The default implementation returns an error.
1116 fn map(&mut self, state: &mut State) -> Result<(), Error> {
1117 default_container(self.__private_as_dyn(), "map", state)
1118 }
1119
1120 /// Begins the receiving process for sequences.
1121 ///
1122 /// While the deserialization of a sequence is ongoing the method
1123 /// [`next_value`](Self::next_value) is called for every new item.
1124 /// The sequence is ended by [`finish`](Self::finish).
1125 ///
1126 /// The default implementation returns an error.
1127 fn seq(&mut self, state: &mut State) -> Result<(), Error> {
1128 default_container(self.__private_as_dyn(), "sequence", state)
1129 }
1130
1131 /// Returns a sink for the next key in a map.
1132 fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1133 let _ = state;
1134 Ok(SinkHandle::null())
1135 }
1136
1137 /// Returns a sink for the next value in a map or sequence.
1138 fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1139 let _ = state;
1140 Ok(SinkHandle::null())
1141 }
1142
1143 /// Receives an atom as the next key in a map.
1144 ///
1145 /// This is a shortcut for invoking [`next_key`](Self::next_key) and then
1146 /// [`atom`](Self::atom) and [`finish`](Self::finish) on the returned sink,
1147 /// which is exactly what the default implementation does. The driver
1148 /// uses this for keys that are atoms which is the overwhelmingly common
1149 /// case. Sinks can override this to avoid creating a sink for the key,
1150 /// but the behavior must be the same as with the default implementation.
1151 /// In particular, sinks that override [`next_key`](Self::next_key) must
1152 /// either not override this method or apply the same logic.
1153 #[doc(hidden)]
1154 fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1155 default_key_atom(self.__private_as_dyn(), atom, state)
1156 }
1157
1158 /// Receives an atom as the next value in a map or sequence.
1159 ///
1160 /// This is a shortcut for invoking [`next_value`](Self::next_value) and
1161 /// then [`atom`](Self::atom) and [`finish`](Self::finish) on the returned
1162 /// sink, which is exactly what the default implementation does. See
1163 /// [`__private_key_atom`](Self::__private_key_atom) for more information.
1164 #[doc(hidden)]
1165 fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1166 default_value_atom(self.__private_as_dyn(), atom, state)
1167 }
1168
1169 /// Receives a borrowed atom as the next key in a map.
1170 ///
1171 /// Like [`__private_key_atom`](Self::__private_key_atom) but the atom is
1172 /// passed to [`borrowed_atom`](Self::borrowed_atom).
1173 #[doc(hidden)]
1174 fn __private_borrowed_key_atom(
1175 &mut self,
1176 atom: Atom<'de>,
1177 state: &mut State,
1178 ) -> Result<(), Error> {
1179 default_borrowed_key_atom(self.__private_as_dyn(), atom, state)
1180 }
1181
1182 /// Receives a borrowed atom as the next value in a map or sequence.
1183 ///
1184 /// Like [`__private_value_atom`](Self::__private_value_atom) but the atom
1185 /// is passed to [`borrowed_atom`](Self::borrowed_atom).
1186 #[doc(hidden)]
1187 fn __private_borrowed_value_atom(
1188 &mut self,
1189 atom: Atom<'de>,
1190 state: &mut State,
1191 ) -> Result<(), Error> {
1192 default_borrowed_value_atom(self.__private_as_dyn(), atom, state)
1193 }
1194
1195 /// Begins a sequence like [`seq`](Self::seq).
1196 ///
1197 /// Returns `true` if the sink builds sequences that are its elements
1198 /// inline (see [`InlineSeq`]): the driver then passes their events to
1199 /// [`__private_inline_atom`](Self::__private_inline_atom) and
1200 /// [`__private_inline_event`](Self::__private_inline_event) instead of
1201 /// asking for a sink for them. Wrappers that forward this have to
1202 /// forward those as well.
1203 #[doc(hidden)]
1204 fn __private_seq(&mut self, state: &mut State) -> Result<bool, Error> {
1205 self.seq(state)?;
1206 Ok(false)
1207 }
1208
1209 /// Receives the atom at the index of an element that is built inline.
1210 #[doc(hidden)]
1211 fn __private_inline_atom(
1212 &mut self,
1213 index: usize,
1214 atom: Atom,
1215 state: &mut State,
1216 ) -> Result<(), Error> {
1217 let _ = (index, atom, state);
1218 no_inline_seq()
1219 }
1220
1221 /// Receives the other events of an element that is built inline.
1222 #[doc(hidden)]
1223 fn __private_inline_event(
1224 &mut self,
1225 event: InlineEvent,
1226 state: &mut State,
1227 ) -> Result<(), Error> {
1228 let _ = (event, state);
1229 no_inline_seq()
1230 }
1231
1232 /// Returns a value sink for a specific struct field.
1233 ///
1234 /// This is a special method that is supposed to be implemented by structs
1235 /// if they want to support flattening. A struct that gets flattened into
1236 /// another struct will have this method called to figure out if a key is
1237 /// used by it. The default implementation always returns `None`.
1238 fn value_for_key(
1239 &mut self,
1240 key: &str,
1241 state: &mut State,
1242 ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
1243 let _ = key;
1244 let _ = state;
1245 Ok(None)
1246 }
1247
1248 /// Called after [`atom`](Self::atom), [`map`](Self::map) or [`seq](Self::seq).
1249 ///
1250 /// The default implementation does nothing.
1251 fn finish(&mut self, state: &mut State) -> Result<(), Error> {
1252 let _ = state;
1253 Ok(())
1254 }
1255
1256 /// Called when an item of this map or sequence failed.
1257 ///
1258 /// This is invoked by the [`DeserializeDriver`] when the key or value
1259 /// that was started last in this container failed with an error, either
1260 /// because its sink (or a sink nested in it) returned the error or
1261 /// because this sink returned it while handling the item (for instance
1262 /// from [`next_value`](Self::next_value) or
1263 /// [`__private_value_atom`](Self::__private_value_atom)). Errors of
1264 /// this sink's own [`map`](Self::map), [`seq`](Self::seq) and
1265 /// [`finish`](Self::finish) are errors of this sink's value and go to
1266 /// the container this sink is an item of.
1267 ///
1268 /// A sink that returns `Ok` recovers from the error: the driver skips
1269 /// the remaining events of the failed item (and the value of a failed
1270 /// key) and deserialization continues with the next item. Returning
1271 /// the error (which is what the default implementation does) passes it
1272 /// on to the enclosing container. All sinks of the failed item are
1273 /// dropped before this is invoked. The error already has the context of
1274 /// the event that failed attached (see [`Error`]).
1275 ///
1276 /// Only errors of sinks are recoverable: errors of the format and of
1277 /// [`Layer`]s end the deserialization.
1278 ///
1279 /// Sinks that forward [`next_key`](Self::next_key) and
1280 /// [`next_value`](Self::next_value) to another sink should forward this
1281 /// as well.
1282 fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
1283 let _ = state;
1284 Err(err)
1285 }
1286
1287 /// Utility method to return an expectation message that is used in error messages.
1288 ///
1289 /// This is typically the name of the type. The default implementation
1290 /// returns `"compatible type"`.
1291 fn expecting(&self) -> Cow<'_, str> {
1292 Cow::Borrowed("compatible type")
1293 }
1294}