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