Skip to main content

deser_core/de/
driver.rs

1use alloc::boxed::Box;
2use alloc::vec::Vec;
3use core::marker::PhantomData;
4
5use crate::State;
6use crate::Text;
7use crate::de::arena::Buffer;
8use crate::de::layer::{Layer, LayerEvent, Next};
9use crate::de::lexical::ContentKey;
10use crate::de::{Deserialize, InlineEvent, Sink, SinkHandle};
11use crate::error::{Error, ErrorKind};
12use crate::event::{Atom, ContainerShape, Event};
13
14/// The driver allows emitting deserialization events into a [`Deserialize`].
15///
16/// This is a convenient way to safely drive a [`Sink`](crate::de::Sink) of a [`Deserialize`]
17/// without using the runtime stack.  As rust lifetimes make what this type does
18/// internally impossible with safe code, this is a safe abstractiont that
19/// hides the unsafety internally.
20///
21/// # Events and Their Context
22///
23/// Events are emitted with [`emit`](Self::emit) or, if they borrow from
24/// the data being deserialized, with [`emit_borrowed`](Self::emit_borrowed).
25/// Information about the next event is placed into the [`State`] before it's
26/// emitted: its byte range in the input with
27/// [`State::set_input_range`] and data attached to it with
28/// [`State::event_mut`].  Both are detached after the event was delivered.
29///
30/// ```
31/// use deser::de::DeserializeDriver;
32/// use deser::Event;
33///
34/// let mut out = None::<Vec<u32>>;
35/// let mut driver = DeserializeDriver::new(&mut out);
36/// driver.state_mut().set_input_range(0, 1);
37/// driver.emit(Event::seq_start()).unwrap();
38/// driver.state_mut().set_input_range(1, 3);
39/// driver.emit(42u64).unwrap();
40/// driver.state_mut().set_input_range(3, 4);
41/// driver.emit(Event::SeqEnd).unwrap();
42/// ```
43///
44/// When an event fails, the error gets the context of the event attached
45/// (see [`Error`] and [`State::add_error_context`]).
46///
47/// # Layers
48///
49/// [`Layer`]s sit between the format and the sinks and see every event
50/// before it's delivered.  They are added with
51/// [`push_layer`](Self::push_layer), see [`Layer`] for more information.
52pub struct DeserializeDriver<'a, 'de: 'a> {
53    core: DriverCore<'de>,
54    layers: Vec<Box<dyn Layer>>,
55    // the sinks borrow for 'a
56    _marker: PhantomData<&'a mut ()>,
57}
58
59/// The state and the sinks of a driver.
60pub(crate) struct DriverCore<'de> {
61    pub(crate) state: State,
62    // The sinks borrow from each other: every sink on the stack can borrow
63    // from the sink below it.  The lifetimes of these borrows are erased
64    // (to `'de` as the handles cannot outlive that) and it's the driver's
65    // responsibility to never use a sink while one of the sinks it lent out
66    // is still alive and to drop them in inverse order.
67    //
68    // `root` holds the sink the driver was created with while no container
69    // is open.
70    root: Option<SinkHandle<'de, 'de>>,
71    sink_stack: Vec<(SinkHandle<'de, 'de>, Container)>,
72    // non-zero while the driver is lent out with a shorter lifetime for
73    // the borrowed data (see `DeserializeDriver::transient`): borrowed
74    // atoms are delivered as transient ones.  The value identifies the
75    // call that lent the driver out.
76    transient: usize,
77}
78
79const STACK_CAPACITY: usize = 128;
80
81// an ongoing serialization can move between threads, for instance when it
82// is suspended while waiting for IO.
83const _: () = {
84    const fn assert_send<T: Send>() {}
85    assert_send::<DeserializeDriver<'static, 'static>>();
86};
87
88#[derive(Copy, Clone)]
89enum Container {
90    /// A map, the first flag is `true` if a key is expected next, the
91    /// second if it's a multimap (see [`ContainerShape::with_multimap`]).
92    Map(bool, bool),
93    /// A sequence, the flag is `true` if the sink builds sequences that
94    /// are its elements inline (see [`Sink::__private_seq`]).
95    Seq(bool),
96    /// A sequence whose sink builds an element inline and is within it.
97    /// The number is the index of the next item of the element.
98    Inline(u32),
99    /// A map for a sink that rejected it: the value of the key of the
100    /// content is delivered to the sink, the other entries are skipped (see
101    /// [`ContentKey`]).  The flags are `true` if a key is expected next, if
102    /// the next value is the content and if the content was delivered.
103    Content(bool, bool, bool),
104    /// Takes the next value (an atom or a container) and ignores it.  This
105    /// is placed above a map that recovered from the error of a key (see
106    /// [`Sink::recover`]), the value of the key is skipped.  It holds a null
107    /// sink.
108    SkipValue,
109}
110
111impl Container {
112    /// Returns the state of a container that was just opened.
113    fn new(is_map: bool) -> Container {
114        if is_map {
115            Container::Map(true, false)
116        } else {
117            Container::Seq(false)
118        }
119    }
120
121    /// Returns `true` if the container is a multimap.
122    #[inline(always)]
123    fn is_multimap(&self) -> bool {
124        matches!(self, Container::Map(_, true))
125    }
126}
127
128/// Erases the lifetime of a sink handle.
129///
130/// # Safety
131///
132/// The caller must ensure that the handle is dropped before the data it
133/// borrows from.
134unsafe fn erase_lifetime<'de>(handle: SinkHandle<'_, 'de>) -> SinkHandle<'de, 'de> {
135    unsafe { core::mem::transmute::<SinkHandle<'_, 'de>, SinkHandle<'de, 'de>>(handle) }
136}
137
138/// Restores a driver after it was lent out (see
139/// `DeserializeDriver::transient`).
140struct Lent<'a, 'de> {
141    driver: *mut DeserializeDriver<'a, 'de>,
142    id: usize,
143    outer: usize,
144}
145
146impl Drop for Lent<'_, '_> {
147    fn drop(&mut self) {
148        // SAFETY: the driver outlives this and is not borrowed anymore
149        let driver = unsafe { &mut *self.driver };
150        if driver.core.transient == self.id {
151            driver.core.transient = self.outer;
152            return;
153        }
154        // the callback replaced the driver with one whose sinks can borrow
155        // data that lives shorter than `'de`.  It's dropped while that
156        // data is alive and the driver is left without sinks.
157        let replacement = core::mem::replace(
158            &mut driver.core,
159            DriverCore {
160                state: State::new(),
161                root: None,
162                sink_stack: Vec::new(),
163                transient: 0,
164            },
165        );
166        drop(replacement);
167    }
168}
169
170/// Shortens the lifetimes of a driver (see `DeserializeDriver::transient`).
171///
172/// The lifetime of the sinks becomes the lifetime of the reference, so a
173/// driver that is swapped out cannot outlive the call.
174fn shorten<'r, 'a, 'de, 'f>(
175    driver: &'r mut DeserializeDriver<'a, 'de>,
176) -> &'r mut DeserializeDriver<'r, 'f>
177where
178    'de: 'f,
179    'f: 'r,
180{
181    // SAFETY: the driver has the same layout for all lifetimes.  The
182    // sinks accept data borrowed for `'de` and receive data that lives for
183    // `'f`: the driver delivers borrowed atoms as transient ones while it's
184    // lent out (`DriverCore::transient`), so no data of `'f` is passed to
185    // them as borrowed.  Sinks cannot be wrapped while it's lent out, and
186    // if the driver is replaced the replacement is dropped before `'f`
187    // ends (see `transient`).
188    unsafe { &mut *(driver as *mut DeserializeDriver<'a, 'de>).cast::<DeserializeDriver<'r, 'f>>() }
189}
190
191impl<'a, 'de> DeserializeDriver<'a, 'de> {
192    /// Creates a new deserializer driver.
193    pub fn new<T: Deserialize<'de>>(out: &'a mut Option<T>) -> DeserializeDriver<'a, 'de> {
194        DeserializeDriver::from_fn(|state| T::deserialize_into(out, state))
195    }
196
197    /// Creates a driver that updates an existing value.
198    ///
199    /// See [`Deserialize::deserialize_update`].
200    ///
201    /// ```
202    /// use deser::de::DeserializeDriver;
203    /// use deser::{Deserialize, Event};
204    ///
205    /// #[derive(Deserialize)]
206    /// struct Config {
207    ///     host: String,
208    ///     port: u16,
209    /// }
210    ///
211    /// let mut config = Config { host: "localhost".into(), port: 80 };
212    /// let mut driver = DeserializeDriver::update(&mut config);
213    /// for event in [
214    ///     Event::map_start(),
215    ///     "port".into(),
216    ///     8080u64.into(),
217    ///     Event::MapEnd,
218    /// ] {
219    ///     driver.emit(event).unwrap();
220    /// }
221    /// drop(driver);
222    /// assert_eq!((config.host.as_str(), config.port), ("localhost", 8080));
223    /// ```
224    pub fn update<T: Deserialize<'de>>(value: &'a mut T) -> DeserializeDriver<'a, 'de> {
225        DeserializeDriver::from_fn(|state| T::deserialize_update(value, state))
226    }
227
228    /// Creates a new deserializer driver from a sink.
229    ///
230    /// The sink cannot be allocated in the arena of the driver, see
231    /// [`from_fn`](Self::from_fn) for that.
232    pub fn from_sink(sink: SinkHandle<'a, 'de>) -> DeserializeDriver<'a, 'de> {
233        DeserializeDriver::with_state(State::new(), sink, STACK_CAPACITY)
234    }
235
236    /// Creates a new deserializer driver with a sink that is created with
237    /// the state of the driver.
238    ///
239    /// This allows the sink to be allocated in the arena of the driver
240    /// (see [`SinkHandle::arena`]).
241    ///
242    /// ```
243    /// use deser::de::{DeserializeDriver, Recording};
244    /// use deser::Event;
245    ///
246    /// let mut recording = Recording::new();
247    /// let mut driver =
248    ///     DeserializeDriver::from_fn(|state| recording.recorder(state));
249    /// for event in [Event::seq_start(), 42u64.into(), Event::SeqEnd] {
250    ///     driver.emit(event).unwrap();
251    /// }
252    /// drop(driver);
253    /// assert_eq!(recording.events().count(), 3);
254    /// ```
255    pub fn from_fn(
256        make: impl FnOnce(&mut State) -> SinkHandle<'a, 'de>,
257    ) -> DeserializeDriver<'a, 'de> {
258        // the arena moves into the driver with the state, its chunks (and
259        // the sink in them) do not move
260        let mut state = State::new();
261        let sink = make(&mut state);
262        DeserializeDriver::with_state(state, sink, STACK_CAPACITY)
263    }
264
265    /// Creates a driver from a state and a sink that was created with it.
266    ///
267    /// This is like [`from_fn`](Self::from_fn) for code that creates the
268    /// sink where the type is known and runs the driver in a function that
269    /// is not generic.
270    pub fn from_state(state: State, sink: SinkHandle<'a, 'de>) -> DeserializeDriver<'a, 'de> {
271        DeserializeDriver::with_state(state, sink, STACK_CAPACITY)
272    }
273
274    /// Runs a nested driver within an ongoing deserialization.
275    ///
276    /// The nested driver continues on the state of the ongoing
277    /// deserialization: the extensions are shared and the containers opened
278    /// by the nested driver are placed on top of the ones that are currently
279    /// open.  This is used to replay recorded events so that replayed values
280    /// observe the same state as values that were not buffered.  The nested
281    /// driver has no layers: the replayed events already passed the layers
282    /// when they were recorded.
283    pub(crate) fn nested<R>(
284        state: &mut State,
285        sink: SinkHandle<'_, 'de>,
286        is_map_key: bool,
287        f: impl FnOnce(&mut DeserializeDriver<'_, 'de>) -> R,
288    ) -> R {
289        let depth = state.depth;
290        let outer_is_map_key = state.is_map_key;
291        let outer_is_multimap = state.is_multimap;
292        // replayed values are small and often atoms, the stack is only
293        // allocated once a container is opened
294        let mut driver = DeserializeDriver::with_state(state.take(), sink, 0);
295        driver.core.state.is_map_key = is_map_key;
296        let rv = f(&mut driver);
297        // the sinks and the stack go back to the arena before the state
298        // is returned
299        driver.core.release();
300        *state = driver.core.state.take();
301        drop(driver);
302        // a failed replay can leave containers open
303        state.depth = depth;
304        state.is_map_key = outer_is_map_key;
305        state.is_multimap = outer_is_multimap;
306        rv
307    }
308
309    fn with_state(
310        mut state: State,
311        sink: SinkHandle<'a, 'de>,
312        capacity: usize,
313    ) -> DeserializeDriver<'a, 'de> {
314        // the stack of the last driver is reused
315        let sink_stack = state
316            .arena
317            .take_vec(Buffer::SinkStack)
318            .unwrap_or_else(|| Vec::with_capacity(capacity));
319        DeserializeDriver {
320            core: DriverCore {
321                state,
322                sink_stack,
323                // SAFETY: the driver cannot outlive 'a
324                root: Some(unsafe { erase_lifetime(sink) }),
325                transient: 0,
326            },
327            layers: Vec::new(),
328            _marker: PhantomData,
329        }
330    }
331
332    /// Returns a borrowed reference to the current deserializer state.
333    pub fn state(&self) -> &State {
334        &self.core.state
335    }
336
337    /// Returns a mutable reference to the current deserializer state.
338    ///
339    /// Formats use this to publish information for the event they emit
340    /// next into the state.
341    pub fn state_mut(&mut self) -> &mut State {
342        &mut self.core.state
343    }
344
345    /// Adds a layer.
346    ///
347    /// Layers see the events in the order they were added: the layer that
348    /// was added first sees the events emitted into the driver, the last
349    /// one passes them on to the sinks.  See [`Layer`] for more
350    /// information.
351    pub fn push_layer<L: Layer + 'static>(&mut self, layer: L) {
352        self.layers.push(Box::new(layer));
353    }
354
355    /// Wraps the sink the driver deserializes into.
356    ///
357    /// This allows placing a sink between the driver and the sink of a
358    /// value, for instance to change how certain values are deserialized.
359    /// Unlike [`Layer`]s such sinks see the sinks of the values and not just
360    /// the events.  Sinks created by a wrapped sink are not wrapped
361    /// automatically, the wrapper needs to wrap them in
362    /// [`next_key`](crate::de::Sink::next_key) and
363    /// [`next_value`](crate::de::Sink::next_value) if it wants to see
364    /// them.
365    ///
366    /// # Panics
367    ///
368    /// Panics if events were already emitted.
369    pub fn wrap_sink<F>(&mut self, f: F)
370    where
371        F: for<'x> FnOnce(SinkHandle<'x, 'de>, &mut State) -> SinkHandle<'x, 'de>,
372    {
373        assert!(
374            self.core.sink_stack.is_empty(),
375            "sinks can only be wrapped before events are emitted"
376        );
377        // a wrapper could keep data of the shorter lifetime
378        assert!(
379            self.core.transient == 0,
380            "sinks cannot be wrapped in a transient driver"
381        );
382        let root = self.core.root.take().expect("no active sink");
383        self.core.root = Some(f(root, &mut self.core.state));
384    }
385
386    /// Emits an event into the driver.
387    ///
388    /// The data of the event is only valid for the call.  To emit data that
389    /// can be borrowed use [`emit_borrowed`](Self::emit_borrowed).
390    ///
391    /// # Panics
392    ///
393    /// The driver keeps an internal state and emitting events when they are
394    /// not expected will cause the driver to panic.
395    #[inline]
396    pub fn emit<'e, E: Into<Event<'e>>>(&mut self, event: E) -> Result<(), Error> {
397        match event.into() {
398            Event::Atom(atom) => self.atom_event(atom),
399            Event::MapStart(shape) => self.start_event(true, shape),
400            Event::SeqStart(shape) => self.start_event(false, shape),
401            Event::MapEnd => self.end_event(true),
402            Event::SeqEnd => self.end_event(false),
403        }
404    }
405
406    /// Emits an event that borrows from the data being deserialized.
407    ///
408    /// This is like [`emit`](Self::emit) but atoms are passed to
409    /// [`Sink::borrowed_atom`](crate::de::Sink::borrowed_atom) which means
410    /// that types like `&str` can borrow them:
411    ///
412    /// ```
413    /// use deser::de::DeserializeDriver;
414    ///
415    /// let input = String::from("hello");
416    /// let mut out = None::<&str>;
417    /// {
418    ///     let mut driver = DeserializeDriver::new(&mut out);
419    ///     driver.emit_borrowed(input.as_str()).unwrap();
420    /// }
421    /// assert_eq!(out, Some("hello"));
422    /// ```
423    #[inline]
424    pub fn emit_borrowed<E: Into<Event<'de>>>(&mut self, event: E) -> Result<(), Error> {
425        match event.into() {
426            Event::Atom(atom) => self.borrowed_atom_event(atom),
427            Event::MapStart(shape) => self.start_event(true, shape),
428            Event::SeqStart(shape) => self.start_event(false, shape),
429            Event::MapEnd => self.end_event(true),
430            Event::SeqEnd => self.end_event(false),
431        }
432    }
433
434    /// Lends the driver out for data that lives shorter than `'de`.
435    ///
436    /// The callback receives the driver with the lifetime `'f` for borrowed
437    /// data.  Events emitted with [`emit_borrowed`](Self::emit_borrowed)
438    /// within it are delivered like the ones emitted with
439    /// [`emit`](Self::emit): types that keep the data copy it and types
440    /// which can only borrow (like `&str`) fail.  This allows data that
441    /// only lives for a call (like the frame of a value in a stream buffer)
442    /// to be deserialized with code that borrows from its input into a
443    /// driver for any lifetime:
444    ///
445    /// ```
446    /// use deser::de::DeserializeDriver;
447    ///
448    /// /// Emits the words of the input, borrowing from it.
449    /// fn words<'de>(input: &'de str, driver: &mut DeserializeDriver<'_, 'de>) {
450    ///     driver.emit(deser::Event::seq_start()).unwrap();
451    ///     for word in input.split(' ') {
452    ///         driver.emit_borrowed(word).unwrap();
453    ///     }
454    ///     driver.emit(deser::Event::SeqEnd).unwrap();
455    /// }
456    ///
457    /// let mut out = None::<Vec<String>>;
458    /// {
459    ///     let mut driver = DeserializeDriver::new(&mut out);
460    ///     let input = String::from("hello world");
461    ///     driver.transient(|driver| words(&input, driver));
462    /// }
463    /// assert_eq!(out.unwrap(), ["hello", "world"]);
464    /// ```
465    ///
466    /// # Panics
467    ///
468    /// Panics if the callback replaces the driver (for instance with
469    /// [`mem::swap`](core::mem::swap)), the driver cannot be used after
470    /// that.  Wrapping the sink ([`wrap_sink`](Self::wrap_sink)) in the
471    /// callback panics as well.
472    pub fn transient<'f, R>(&mut self, f: impl FnOnce(&mut DeserializeDriver<'_, 'f>) -> R) -> R
473    where
474        'de: 'f,
475    {
476        // identifies this call, the address is unique while it runs
477        let marker = 0u8;
478        let id = &marker as *const u8 as usize;
479        let outer = core::mem::replace(&mut self.core.transient, id);
480        let driver: *mut DeserializeDriver<'a, 'de> = self;
481        // restores the driver, also if the callback panics
482        let lent = Lent { driver, id, outer };
483        // SAFETY: the pointer comes from `self`, which is not used until
484        // the callback returned
485        let rv = f(shorten(unsafe { &mut *driver }));
486        // SAFETY: the callback returned, nothing borrows the driver
487        let replaced = unsafe { (*driver).core.transient != id };
488        drop(lent);
489        assert!(!replaced, "the driver was replaced while it was lent out");
490        rv
491    }
492
493    // The following functions deliver an event emitted into the driver and
494    // detach its context afterwards.  They are not inlined so that the code
495    // emitting events stays small.
496
497    #[inline(never)]
498    fn atom_event(&mut self, atom: Atom) -> Result<(), Error> {
499        if !self.layers.is_empty() {
500            return self.emit_layered(LayerEvent::new(Event::Atom(atom)));
501        }
502        let rv = self.core.deliver_atom(atom);
503        self.core.finish_event(rv)
504    }
505
506    #[inline(never)]
507    fn borrowed_atom_event(&mut self, atom: Atom<'de>) -> Result<(), Error> {
508        if !self.layers.is_empty() {
509            return self.emit_layered(LayerEvent::borrowed(Event::Atom(atom)));
510        }
511        let rv = self.core.deliver_borrowed_atom(atom);
512        self.core.finish_event(rv)
513    }
514
515    #[inline(never)]
516    fn start_event(&mut self, is_map: bool, shape: ContainerShape) -> Result<(), Error> {
517        if !self.layers.is_empty() {
518            let event = if is_map {
519                Event::MapStart(shape)
520            } else {
521                Event::SeqStart(shape)
522            };
523            return self.emit_layered(LayerEvent::new(event));
524        }
525        let rv = self.core.deliver_start(is_map, shape);
526        self.core.finish_event(rv)
527    }
528
529    #[inline(never)]
530    fn end_event(&mut self, is_map: bool) -> Result<(), Error> {
531        if !self.layers.is_empty() {
532            let event = if is_map { Event::MapEnd } else { Event::SeqEnd };
533            return self.emit_layered(LayerEvent::new(event));
534        }
535        let rv = self.core.deliver_end(is_map);
536        self.core.finish_event(rv)
537    }
538
539    /// Passes an event through the layers.
540    ///
541    /// This is marked as cold so that it does not affect the code emitting
542    /// events when there are no layers.
543    #[cold]
544    #[inline(never)]
545    fn emit_layered(&mut self, event: LayerEvent<'_, 'de>) -> Result<(), Error> {
546        let rv = Next::new(&mut self.layers, &mut self.core).emit(event);
547        self.core.finish_event(rv)
548    }
549}
550
551impl<'de> DriverCore<'de> {
552    /// Detaches the context of the event that was delivered.
553    ///
554    /// If the event failed, the context is attached to the error.
555    #[inline(always)]
556    fn finish_event(&mut self, rv: Result<(), Error>) -> Result<(), Error> {
557        let rv = match rv {
558            Ok(()) => Ok(()),
559            // the error is thrown away (see `State::discard_errors`)
560            Err(err) if self.state.discards_errors => Err(err),
561            Err(err) => Err(self.state.attach_error_context(err)),
562        };
563        self.state.clear_event();
564        rv
565    }
566
567    /// Sets the position of the next event in the state.
568    #[inline]
569    pub(crate) fn update_position(&mut self, event: &Event<'_>) {
570        self.state.is_map_key = match event {
571            Event::MapEnd | Event::SeqEnd => false,
572            // the keys of maps whose content is delivered are not
573            // delivered to sinks
574            _ => matches!(self.sink_stack.last(), Some((_, Container::Map(true, _)))),
575        };
576    }
577
578    /// Delivers an event to the sinks.
579    #[inline(always)]
580    pub(crate) fn dispatch(&mut self, event: Event<'_>) -> Result<(), Error> {
581        match event {
582            Event::Atom(atom) => self.deliver_atom(atom),
583            Event::MapStart(shape) => self.deliver_start(true, shape),
584            Event::SeqStart(shape) => self.deliver_start(false, shape),
585            Event::MapEnd => self.deliver_end(true),
586            Event::SeqEnd => self.deliver_end(false),
587        }
588    }
589
590    /// Delivers an event that borrows from the data to the sinks.
591    #[inline(always)]
592    pub(crate) fn dispatch_borrowed(&mut self, event: Event<'de>) -> Result<(), Error> {
593        match event {
594            Event::Atom(atom) => self.deliver_borrowed_atom(atom),
595            Event::MapStart(shape) => self.deliver_start(true, shape),
596            Event::SeqStart(shape) => self.deliver_start(false, shape),
597            Event::MapEnd => self.deliver_end(true),
598            Event::SeqEnd => self.deliver_end(false),
599        }
600    }
601
602    // The `deliver_*` functions deliver an event to the sinks.  If the event
603    // fails, the sinks get a chance to recover from the error (see
604    // `recover`).
605
606    #[inline(always)]
607    fn deliver_atom(&mut self, atom: Atom) -> Result<(), Error> {
608        match self.emit_atom(atom) {
609            Ok(()) => Ok(()),
610            Err(err) => self.recover(err, None),
611        }
612    }
613
614    #[inline(always)]
615    fn deliver_borrowed_atom(&mut self, atom: Atom<'de>) -> Result<(), Error> {
616        // the data does not live for the lifetime of the sinks (see
617        // `DeserializeDriver::transient`)
618        if self.transient != 0 {
619            return self.deliver_atom(atom);
620        }
621        match self.emit_borrowed_atom(atom) {
622            Ok(()) => Ok(()),
623            Err(err) => self.recover(err, None),
624        }
625    }
626
627    #[inline(always)]
628    fn deliver_start(&mut self, is_map: bool, shape: ContainerShape) -> Result<(), Error> {
629        match self.emit_start(is_map, shape) {
630            Ok(()) => Ok(()),
631            Err(err) => self.recover(err, Some(is_map)),
632        }
633    }
634
635    #[inline(always)]
636    fn deliver_end(&mut self, is_map: bool) -> Result<(), Error> {
637        match self.emit_end(is_map) {
638            Ok(()) => Ok(()),
639            Err(err) => self.recover(err, None),
640        }
641    }
642
643    /// Recovers from the error of an item.
644    ///
645    /// The error belongs to the item that was started last in the container
646    /// on top of the stack.  The containers are asked to recover (see
647    /// [`Sink::recover`]) from the innermost to the outermost.  The sinks of
648    /// the ones that do not recover are replaced with null sinks, as the
649    /// error passes through them.  Once a sink recovers, the null sinks
650    /// above it take the remaining events of the failed item: skipping them
651    /// needs no support from the dispatch of the events.  `opened` is set if
652    /// the event that failed was the start of a map (`true`) or sequence,
653    /// the container is open in the input and gets a null sink too.
654    #[cold]
655    #[inline(never)]
656    fn recover(&mut self, err: Error, opened: Option<bool>) -> Result<(), Error> {
657        let mut err = if self.state.discards_errors {
658            // the error is thrown away (see `State::discard_errors`)
659            err
660        } else {
661            self.state.attach_error_context(err)
662        };
663        // an element that is built inline failed, it gets a null sink for
664        // its remaining events like the sink of an element
665        if let Some((_, container @ Container::Inline(_))) = self.sink_stack.last_mut() {
666            *container = Container::Seq(true);
667            self.sink_stack
668                .push((SinkHandle::null(), Container::Seq(false)));
669        }
670        for idx in (0..self.sink_stack.len()).rev() {
671            // the sinks above were replaced, nothing borrows from this one
672            let (sink, container) = &mut self.sink_stack[idx];
673            err = match sink.recover(err, &mut self.state) {
674                Ok(()) => {
675                    // after a key failed its value is skipped as well
676                    if let Container::Map(is_key @ false, _) = container {
677                        *is_key = true;
678                        self.sink_stack
679                            .insert(idx + 1, (SinkHandle::null(), Container::SkipValue));
680                    }
681                    if let Some(is_map) = opened {
682                        self.state.depth += 1;
683                        self.sink_stack
684                            .push((SinkHandle::null(), Container::new(is_map)));
685                    }
686                    return Ok(());
687                }
688                Err(err) => err,
689            };
690            *sink = SinkHandle::null();
691            *container = match *container {
692                Container::Seq(_) => Container::Seq(false),
693                other => other,
694            };
695        }
696        // nothing recovered, the deserialization failed
697        self.sink_stack.clear();
698        Err(err)
699    }
700
701    /// Skips an atom which is the value of a key that failed.
702    #[cold]
703    #[inline(never)]
704    fn skip_value(&mut self) {
705        self.state.is_map_key = false;
706        self.sink_stack.pop();
707    }
708
709    #[inline(always)]
710    fn emit_borrowed_atom(&mut self, atom: Atom<'de>) -> Result<(), Error> {
711        match self.sink_stack.last_mut() {
712            Some((sink, Container::Map(is_key, _))) => {
713                let key = *is_key;
714                *is_key = !key;
715                self.state.is_map_key = key;
716                if key {
717                    sink.__private_borrowed_key_atom(atom, &mut self.state)
718                } else {
719                    sink.__private_borrowed_value_atom(atom, &mut self.state)
720                }
721            }
722            Some((sink, Container::Seq(_))) => {
723                self.state.is_map_key = false;
724                sink.__private_borrowed_value_atom(atom, &mut self.state)
725            }
726            Some((sink, Container::Inline(index))) => {
727                let item = *index;
728                *index = item.saturating_add(1);
729                self.state.is_map_key = false;
730                sink.__private_inline_atom(item as usize, atom, &mut self.state)
731            }
732            Some((sink, Container::Content(is_key, take, found))) => {
733                match content_atom(&self.state, is_key, take, found, &atom)? {
734                    true => sink.borrowed_atom(atom, &mut self.state),
735                    false => Ok(()),
736                }
737            }
738            Some((_, Container::SkipValue)) => {
739                self.skip_value();
740                Ok(())
741            }
742            None => {
743                let sink = self.root.as_mut().expect("no active sink");
744                sink.borrowed_atom(atom, &mut self.state)?;
745                sink.finish(&mut self.state)
746            }
747        }
748    }
749
750    #[inline(always)]
751    fn emit_atom(&mut self, atom: Atom) -> Result<(), Error> {
752        match self.sink_stack.last_mut() {
753            Some((sink, Container::Map(is_key, _))) => {
754                let key = *is_key;
755                *is_key = !key;
756                self.state.is_map_key = key;
757                if key {
758                    sink.__private_key_atom(atom, &mut self.state)
759                } else {
760                    sink.__private_value_atom(atom, &mut self.state)
761                }
762            }
763            Some((sink, Container::Seq(_))) => {
764                self.state.is_map_key = false;
765                sink.__private_value_atom(atom, &mut self.state)
766            }
767            Some((sink, Container::Inline(index))) => {
768                let item = *index;
769                *index = item.saturating_add(1);
770                self.state.is_map_key = false;
771                sink.__private_inline_atom(item as usize, atom, &mut self.state)
772            }
773            Some((sink, Container::Content(is_key, take, found))) => {
774                match content_atom(&self.state, is_key, take, found, &atom)? {
775                    true => sink.atom(atom, &mut self.state),
776                    false => Ok(()),
777                }
778            }
779            Some((_, Container::SkipValue)) => {
780                self.skip_value();
781                Ok(())
782            }
783            None => {
784                let sink = self.root.as_mut().expect("no active sink");
785                sink.atom(atom, &mut self.state)?;
786                sink.finish(&mut self.state)
787            }
788        }
789    }
790
791    #[inline(always)]
792    fn emit_start(&mut self, is_map: bool, shape: ContainerShape) -> Result<(), Error> {
793        let mut sink = match self.sink_stack.last_mut() {
794            Some((parent, Container::Map(is_key, _))) => {
795                let key = *is_key;
796                *is_key = !key;
797                self.state.is_map_key = key;
798                let sink = if key {
799                    parent.next_key(&mut self.state)?
800                } else {
801                    parent.next_value(&mut self.state)?
802                };
803                // SAFETY: the sink borrows from the sink on the top of the
804                // stack.  It's placed above it on the stack and dropped
805                // before it.
806                unsafe { erase_lifetime(sink) }
807            }
808            Some((parent, container @ Container::Seq(_))) => {
809                self.state.is_map_key = false;
810                if let (Container::Seq(true), false) = (*container, is_map) {
811                    // the element is built inline by the parent
812                    self.state.container_shape = shape;
813                    parent.__private_inline_event(InlineEvent::Start, &mut self.state)?;
814                    *container = Container::Inline(0);
815                    self.state.is_multimap = false;
816                    self.state.depth += 1;
817                    return Ok(());
818                }
819                let sink = parent.next_value(&mut self.state)?;
820                // SAFETY: see above
821                unsafe { erase_lifetime(sink) }
822            }
823            // a container in an element that is built inline, its items
824            // are atoms and this fails
825            Some((parent, Container::Inline(index))) => {
826                let item = *index;
827                *index = item.saturating_add(1);
828                self.state.is_map_key = false;
829                self.state.container_shape = shape;
830                let event = InlineEvent::Container(item as usize, is_map);
831                return parent.__private_inline_event(event, &mut self.state);
832            }
833            // entries of a map that is not the content are skipped
834            Some((_, Container::Content(is_key, take, _))) => {
835                if *is_key || *take {
836                    return Err(content_container_error(*is_key));
837                }
838                *is_key = true;
839                self.state.is_map_key = false;
840                self.state.depth += 1;
841                self.sink_stack
842                    .push((SinkHandle::null(), Container::new(is_map)));
843                return Ok(());
844            }
845            // the skipped value is a container, the null sink takes it
846            Some((_, container @ Container::SkipValue)) => {
847                self.state.is_map_key = false;
848                *container = Container::new(is_map);
849                self.state.depth += 1;
850                return Ok(());
851            }
852            None => self.root.take().expect("no active sink"),
853        };
854        self.state.container_shape = shape;
855        let container = if is_map {
856            match sink.map(&mut self.state) {
857                Ok(()) => Container::Map(true, shape.is_multimap()),
858                // a map for a sink that wants its content
859                Err(err)
860                    if err.kind() == ErrorKind::Unexpected
861                        && ContentKey::of(&self.state).is_some() =>
862                {
863                    Container::Content(true, false, false)
864                }
865                Err(err) => return Err(err),
866            }
867        } else {
868            Container::Seq(sink.__private_seq(&mut self.state)?)
869        };
870        self.state.is_multimap = container.is_multimap();
871        self.state.depth += 1;
872        self.sink_stack.push((sink, container));
873        Ok(())
874    }
875
876    #[inline(always)]
877    fn emit_end(&mut self, is_map: bool) -> Result<(), Error> {
878        match self.sink_stack.last() {
879            Some((_, Container::Map(..) | Container::Content(..))) if is_map => {}
880            Some((_, Container::Seq(_))) if !is_map => {}
881            Some((_, Container::Inline(_))) if !is_map => return self.end_inline(),
882            _ => panic!("not inside a {}", if is_map { "map" } else { "sequence" }),
883        }
884        let (mut sink, container) = self.sink_stack.pop().unwrap();
885        // the container remains the current one while it's finished as sinks
886        // can still produce values within it (for instance by replaying
887        // recorded values).
888        self.state.is_multimap = container.is_multimap();
889        let mut rv = Ok(());
890        // a map without content is empty text
891        if let Container::Content(_, _, false) = container {
892            self.state.is_map_key = false;
893            rv = sink
894                .atom(Atom::Lexical(Text::borrowed("")), &mut self.state)
895                .map_err(|err| match err.kind() {
896                    // it's rejected as the map it is
897                    ErrorKind::Unexpected => {
898                        super::default_container(&mut sink, "map", &self.state).unwrap_err()
899                    }
900                    _ => err,
901                });
902        }
903        let rv = rv.and_then(|()| sink.finish(&mut self.state));
904        self.state.depth -= 1;
905        self.state.is_multimap = self
906            .sink_stack
907            .last()
908            .is_some_and(|(_, container)| container.is_multimap());
909        if self.sink_stack.is_empty() {
910            // the root sink is retained until the driver is dropped
911            self.root = Some(sink);
912        } else {
913            sink.release(&mut self.state);
914        }
915        rv
916    }
917
918    /// Ends an element that is built inline by the sink on top of the
919    /// stack.
920    ///
921    /// This behaves like ending the container of an element.
922    #[inline(always)]
923    fn end_inline(&mut self) -> Result<(), Error> {
924        let (sink, container) = self.sink_stack.last_mut().unwrap();
925        let Container::Inline(len) = *container else {
926            unreachable!()
927        };
928        *container = Container::Seq(true);
929        self.state.is_multimap = false;
930        let rv = sink.__private_inline_event(InlineEvent::End(len as usize), &mut self.state);
931        self.state.depth -= 1;
932        rv
933    }
934}
935
936/// Handles an atom of a map whose content is delivered (see
937/// [`Container::Content`]).
938///
939/// Returns `true` if the atom is the content.
940#[cold]
941#[inline(never)]
942fn content_atom(
943    state: &State,
944    is_key: &mut bool,
945    take: &mut bool,
946    found: &mut bool,
947    atom: &Atom<'_>,
948) -> Result<bool, Error> {
949    let was_key = *is_key;
950    *is_key = !was_key;
951    if was_key {
952        *take = match atom {
953            Atom::Str(key) | Atom::Lexical(key) => ContentKey::of(state) == Some(&**key),
954            _ => false,
955        };
956        return Ok(false);
957    }
958    if !core::mem::take(take) {
959        return Ok(false);
960    }
961    if core::mem::replace(found, true) {
962        return Err(Error::new(
963            ErrorKind::Unexpected,
964            "unexpected map with more than one content, expected a single value",
965        ));
966    }
967    Ok(true)
968}
969
970#[cold]
971fn content_container_error(is_key: bool) -> Error {
972    Error::new(
973        ErrorKind::Unexpected,
974        if is_key {
975            "unexpected map with a key that is not a single value, expected a single value"
976        } else {
977            "unexpected map whose content is not a single value, expected a single value"
978        },
979    )
980}
981
982impl<'de> DriverCore<'de> {
983    /// Drops the sinks and keeps the stack for the next driver.
984    fn release(&mut self) {
985        // sinks borrow from the sinks below them, drop them in inverse order
986        while let Some((sink, _)) = self.sink_stack.pop() {
987            sink.release(&mut self.state);
988        }
989        // the sinks are dropped before the state, the arena they are in is
990        // only freed if they were dropped
991        if let Some(root) = self.root.take() {
992            root.release(&mut self.state);
993        }
994        let stack = core::mem::take(&mut self.sink_stack);
995        self.state.arena.put_vec(Buffer::SinkStack, stack);
996    }
997}
998
999impl<'de> Drop for DriverCore<'de> {
1000    fn drop(&mut self) {
1001        self.release();
1002    }
1003}
1004
1005#[test]
1006fn test_arena_is_not_orphaned() {
1007    use crate::de::Recording;
1008    use crate::de::arena::ORPHANED;
1009    use alloc::collections::BTreeMap;
1010    use alloc::string::String;
1011
1012    let orphaned = ORPHANED.with(|x| x.get());
1013    // nested containers
1014    let mut out = None::<Vec<BTreeMap<String, Vec<u32>>>>;
1015    let mut driver = DeserializeDriver::new(&mut out);
1016    for event in [
1017        Event::seq_start(),
1018        Event::map_start(),
1019        "a".into(),
1020        Event::seq_start(),
1021        1u64.into(),
1022        Event::SeqEnd,
1023        Event::MapEnd,
1024        Event::SeqEnd,
1025    ] {
1026        driver.emit(event).unwrap();
1027    }
1028    drop(driver);
1029    assert_eq!(out.unwrap()[0]["a"], [1]);
1030
1031    // replayed (nested drivers)
1032    let mut recording = Recording::new();
1033    let mut driver = DeserializeDriver::from_fn(|state| recording.recorder(state));
1034    for event in [Event::seq_start(), 1u64.into(), 2u64.into(), Event::SeqEnd] {
1035        driver.emit(event).unwrap();
1036    }
1037    drop(driver);
1038    let mut driver_out = None::<()>;
1039    let mut driver = DeserializeDriver::new(&mut driver_out);
1040    let mut out = None::<Vec<u32>>;
1041    let state = driver.state_mut();
1042    recording
1043        .replay(Vec::<u32>::deserialize_into(&mut out, state), state)
1044        .unwrap();
1045    drop(driver);
1046    assert_eq!(out.unwrap(), [1, 2]);
1047
1048    // an error and an incomplete value
1049    let mut out = None::<Vec<Vec<u32>>>;
1050    let mut driver = DeserializeDriver::new(&mut out);
1051    driver.emit(Event::seq_start()).unwrap();
1052    driver.emit(Event::seq_start()).unwrap();
1053    assert!(driver.emit("not a number").is_err());
1054    drop(driver);
1055
1056    assert_eq!(ORPHANED.with(|x| x.get()), orphaned);
1057}
1058
1059#[test]
1060fn test_sink_outlives_state() {
1061    use crate::de::OwnedSink;
1062    use crate::de::arena::ORPHANED;
1063    use alloc::collections::BTreeMap;
1064    use alloc::string::String;
1065
1066    // the sink is in the arena of a temporary state, the arena is orphaned
1067    // and freed with the sink (miri checks that nothing leaks)
1068    let orphaned = ORPHANED.with(|x| x.get());
1069    let mut out = None::<Vec<BTreeMap<String, u32>>>;
1070    let mut driver = DeserializeDriver::from_sink(Vec::<BTreeMap<String, u32>>::deserialize_into(
1071        &mut out,
1072        &mut State::new(),
1073    ));
1074    assert_eq!(ORPHANED.with(|x| x.get()), orphaned + 1);
1075    for event in [
1076        Event::seq_start(),
1077        Event::map_start(),
1078        "a".into(),
1079        1u64.into(),
1080        Event::MapEnd,
1081        Event::SeqEnd,
1082    ] {
1083        driver.emit(event).unwrap();
1084    }
1085    drop(driver);
1086    assert_eq!(out.unwrap()[0]["a"], 1);
1087
1088    // an owned sink that is kept after its driver
1089    let mut driver_out = None::<()>;
1090    let mut driver = DeserializeDriver::new(&mut driver_out);
1091    let mut owned = OwnedSink::<Vec<u32>>::deserialize(driver.state_mut());
1092    drop(driver);
1093    assert_eq!(ORPHANED.with(|x| x.get()), orphaned + 2);
1094    let mut driver = DeserializeDriver::from_sink(SinkHandle::to(owned.borrow_mut()));
1095    for event in [Event::seq_start(), 1u64.into(), 2u64.into(), Event::SeqEnd] {
1096        driver.emit(event).unwrap();
1097    }
1098    drop(driver);
1099    assert_eq!(owned.take().unwrap(), [1, 2]);
1100    // dropped on another thread
1101    std::thread::spawn(move || drop(owned)).join().unwrap();
1102}
1103
1104#[test]
1105fn test_driver() {
1106    let mut out: Option<alloc::collections::BTreeMap<u32, String>> = None;
1107    {
1108        let mut driver = DeserializeDriver::new(&mut out);
1109        driver.emit(Event::map_start()).unwrap();
1110        driver.emit(1u64).unwrap();
1111        driver.emit("Hello").unwrap();
1112        driver.emit(2u64).unwrap();
1113        driver.emit("World").unwrap();
1114        driver.emit(Event::MapEnd).unwrap();
1115    }
1116
1117    let map = out.unwrap();
1118    assert_eq!(map[&1], "Hello");
1119    assert_eq!(map[&2], "World");
1120}