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