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