Skip to main content

deser_core/de/
driver.rs

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