Skip to main content

deser_core/ser/
driver.rs

1use alloc::borrow::Cow;
2use alloc::boxed::Box;
3use alloc::vec::Vec;
4use core::marker::PhantomData;
5use core::ptr::NonNull;
6
7use crate::arena::{Alloc, Buffer};
8use crate::error::Error;
9use crate::ser::layer::{EventFn, Layer, Next};
10use crate::ser::{
11    Begin, BeginKind, Boxed, ContainerShape, Emit, Erased, FIELDS_END, HandleInner, IndexedSeq,
12    IndexedStruct, PLAIN_BUDGET, PlainSink, Serialize, SerializeRef, StructField,
13};
14use crate::unwind::DropInReverse;
15use crate::{Atom, Event, State};
16use crate::{Context, Text};
17
18use super::{MapEmitter, SeqEmitter, SerializeHandle, StructEmitter};
19
20/// The driver allows serializing a [`Serialize`] iteratively.
21///
22/// This is the only way to convert from a [`Serialize`] into an event
23/// stream.  There are several ways to receive the events:
24///
25/// * [`drive`](Self::drive) invokes a callback for every event and
26///   [`drive_sink`](Self::drive_sink) delivers them to an [`EventSink`].
27///   Both serialize the value at once.
28/// * [`drive_until`](Self::drive_until) delivers the events to an
29///   [`EventSink`] which can pause the driver, for instance to write the
30///   output of large values in pieces.
31/// * [`next`](Self::next) returns one event at a time.
32///
33/// Event sinks can also receive the values of the events to
34/// [describe](crate::ser::Describe) them (see [`EventSink::DESCRIBED`]).
35///
36/// When the serialization fails, the error gets the context of the
37/// current value attached (see [`State::add_error_context`]).
38///
39/// # Layers
40///
41/// [`Layer`]s sit between the serialized values and the format and see
42/// every event before the format receives it.  They are added with
43/// [`push_layer`](Self::push_layer) and are not supported by
44/// [`next`](Self::next).
45pub struct SerializeDriver<'a> {
46    state: State,
47    layers: Vec<Box<dyn Layer>>,
48    // Values and frames refer to data borrowed from the serializables and
49    // emitters of the frames below them, which is why the lifetimes are
50    // erased.  `next_value` and `needs_finish` borrow from the top frame.
51    //
52    // A value that was produced by an emitter (or the root value) that still
53    // needs to be serialized.
54    next_value: Option<Held>,
55    // A value that was fully emitted.  It's held until the next call as the
56    // last event can borrow from it.  If the flag is set, `finish` needs to
57    // be called on it.
58    needs_finish: Option<(Held, bool)>,
59    stack: Vec<Frame>,
60    // `true` if `next` returned an event.  Its event data is detached on the
61    // next call.
62    delivered: bool,
63    _marker: PhantomData<SerializeRef<'a>>,
64}
65
66/// A compound value that is currently being serialized.
67struct Frame {
68    // `emitter` must be declared (and thus dropped) before `serializable` as
69    // the emitters borrow from the serializable.
70    emitter: Emitter,
71    serializable: Held,
72    needs_finish: bool,
73}
74
75enum Emitter {
76    Seq(Boxed<dyn SeqEmitter>),
77    /// A map emitter, the flag is `true` if a value is expected next.
78    Map(Boxed<dyn MapEmitter>, bool),
79    Struct(Boxed<dyn StructEmitter>),
80    /// A sequence with the index of the next element.
81    IndexedSeq(&'static dyn IndexedSeq, usize),
82    /// A struct with the index of the next field.
83    IndexedStruct(&'static dyn IndexedStruct, usize),
84    /// A value that forwarded to another value (see [`Emit::Forward`]).
85    ///
86    /// The frame holds the value while the forwarded value (which can
87    /// borrow from it) is serialized.  It does not emit events and it's
88    /// removed once it's on the top of the stack again.
89    Forward,
90}
91
92impl Emitter {
93    /// Drops the emitter, it's popped from the arena right away if it's on
94    /// the top.
95    #[inline(always)]
96    fn release(self, state: &mut State) {
97        match self {
98            Emitter::Seq(emitter) => Boxed::release(emitter, state),
99            Emitter::Map(emitter, _) => Boxed::release(emitter, state),
100            Emitter::Struct(emitter) => Boxed::release(emitter, state),
101            _ => {}
102        }
103    }
104}
105
106/// A serializable held by the driver.
107///
108/// This is like a [`SerializeHandle`] with an erased lifetime, but owned
109/// values are held by raw pointer so that the handle can be moved while
110/// events or emitters borrow from the value.
111pub(crate) struct Held {
112    ptr: NonNull<dyn Erased>,
113    /// Where the value is allocated if it's owned, `None` if it's borrowed.
114    owned: Option<Alloc>,
115}
116
117// SAFETY: a held value is either a borrowed `SerializeRef` (which is
118// `Send` as serializables are `Sync`) or an owned
119// `Boxed<dyn Erased + Send>`.
120unsafe impl Send for Held {}
121
122impl Held {
123    /// Creates a held value from a handle.
124    ///
125    /// # Safety
126    ///
127    /// The held value must be dropped before the data the handle borrows.
128    #[inline]
129    pub(crate) unsafe fn new(handle: SerializeHandle<'_>) -> Held {
130        unsafe {
131            let (ptr, owned) = match handle.0 {
132                HandleInner::Borrowed(value) => (NonNull::from(value.as_dyn()), None),
133                HandleInner::Owned(value) => {
134                    let (ptr, alloc) = Boxed::into_raw(value);
135                    let ptr: NonNull<dyn Erased + '_> = ptr;
136                    (ptr, Some(alloc))
137                }
138            };
139            Held {
140                ptr: core::mem::transmute::<NonNull<dyn Erased + '_>, NonNull<dyn Erased>>(ptr),
141                owned,
142            }
143        }
144    }
145
146    /// Returns the value with an unbounded lifetime.
147    ///
148    /// # Safety
149    ///
150    /// The returned reference must not be used after the held value was
151    /// dropped.
152    #[inline(always)]
153    pub(crate) unsafe fn get<'x>(&self) -> SerializeRef<'x> {
154        SerializeRef::from_dyn(unsafe { &*self.ptr.as_ptr() })
155    }
156}
157
158impl Drop for Held {
159    #[inline(always)]
160    fn drop(&mut self) {
161        #[cold]
162        #[inline(never)]
163        unsafe fn drop_owned(ptr: NonNull<dyn Erased>, alloc: Alloc) {
164            unsafe {
165                drop(Boxed::from_raw(ptr, alloc));
166            }
167        }
168
169        if let Some(alloc) = self.owned {
170            // SAFETY: owned values were created from a box of the allocation
171            unsafe { drop_owned(self.ptr, alloc) };
172        }
173    }
174}
175
176impl<'a> Drop for SerializeDriver<'a> {
177    fn drop(&mut self) {
178        // the pending values borrow from the top frame and inner frames can
179        // borrow from outer frames, drop in inverse order.  This order is
180        // kept if a drop panics: the guard drops the remaining frames in
181        // inverse order and as locals are dropped in inverse order (also
182        // when unwinding), the pending values are dropped before it.
183        let frames = DropInReverse(&mut self.stack);
184        let needs_finish = self.needs_finish.take();
185        let next_value = self.next_value.take();
186        drop(next_value);
187        drop(needs_finish);
188        while let Some(frame) = frames.0.pop() {
189            // the emitter borrows from the serializable, drop it first
190            frame.emitter.release(&mut self.state);
191        }
192        drop(frames);
193        let stack = core::mem::take(&mut self.stack);
194        self.state.arena.put_vec(Buffer::SerializeStack, stack);
195    }
196}
197
198const STACK_CAPACITY: usize = 128;
199
200// an ongoing serialization can move between threads, for instance when it
201// is suspended while waiting for IO.
202const _: () = {
203    const fn assert_send<T: Send>() {}
204    assert_send::<SerializeDriver<'static>>();
205};
206
207type NextEvent<'a> = Option<(Event<'a>, SerializeRef<'a>)>;
208
209/// The callback of [`SerializeDriver::drive`] and
210/// [`SerializeDriver::drive_until`].
211trait Callback {
212    /// `true` if the callback receives the values of the events.
213    const DESCRIBED: bool;
214
215    /// `true` if the callback can pause the driver (see
216    /// [`SerializeDriver::drive_until`]).
217    ///
218    /// Plain values are only emitted at once if they fit into the budget
219    /// (see `PLAIN_BUDGET`), large plain sequences are emitted in pieces
220    /// so that the driver can pause in between.
221    const PAUSABLE: bool = false;
222
223    /// `true` if the fast paths for plain values are used.
224    ///
225    /// Callbacks that describe values need to see every value.
226    const FAST: bool = !Self::DESCRIBED;
227
228    /// `true` if large plain sequences are emitted at once.
229    const UNBOUNDED: bool = Self::FAST && !Self::PAUSABLE;
230
231    fn call(
232        &mut self,
233        event: Event<'_>,
234        value: SerializeRef<'_>,
235        state: &mut State,
236    ) -> Result<(), Error>;
237
238    /// Returns `true` if the driver should pause before the next value.
239    #[inline(always)]
240    fn pause(&mut self) -> bool {
241        false
242    }
243}
244
245/// A callback that does not receive values.
246struct Plain<F>(F);
247
248impl<F: FnMut(Event<'_>, &mut State) -> Result<(), Error>> Callback for Plain<F> {
249    const DESCRIBED: bool = false;
250
251    #[inline(always)]
252    fn call(
253        &mut self,
254        event: Event<'_>,
255        _value: SerializeRef<'_>,
256        state: &mut State,
257    ) -> Result<(), Error> {
258        (self.0)(event, state)
259    }
260}
261
262/// Receives the events of [`SerializeDriver::drive_sink`] and
263/// [`SerializeDriver::drive_until`].
264///
265/// Unlike the callback of [`drive`](SerializeDriver::drive) an event
266/// sink can:
267///
268/// * pause the driver (with [`drive_until`](SerializeDriver::drive_until)):
269///   before the next value is serialized the driver asks the sink with
270///   [`pause`](Self::pause) if it should stop.  This is used to write the
271///   output of large values in pieces, for instance to wait until the
272///   output that was produced so far was written to a socket.
273/// * receive the values of the events (see [`DESCRIBED`](Self::DESCRIBED))
274///   to [describe](crate::ser::Describe) them, which formats that reflect
275///   the Rust shape of values need.
276///
277/// ```
278/// # use deser::ser::{Describe, EventSink, SerializeDriver, SerializeRef};
279/// # use deser::{Error, Event, State};
280/// /// Records if the values are `Some`.
281/// struct IsSome(Vec<bool>);
282///
283/// struct Describer(bool);
284///
285/// impl Describe for Describer {
286///     fn some(&mut self) {
287///         self.0 = true;
288///     }
289/// }
290///
291/// impl EventSink for IsSome {
292///     const DESCRIBED: bool = true;
293///
294///     fn event(
295///         &mut self,
296///         _event: Event<'_>,
297///         value: SerializeRef<'_>,
298///         _state: &mut State,
299///     ) -> Result<(), Error> {
300///         let mut describer = Describer(false);
301///         value.describe(&mut describer);
302///         self.0.push(describer.0);
303///         Ok(())
304///     }
305/// }
306///
307/// # fn do_it() -> Result<(), deser::Error> {
308/// let mut sink = IsSome(Vec::new());
309/// let value = vec![Some(1), None];
310/// SerializeDriver::new(&value).drive_sink(&mut sink)?;
311/// assert_eq!(sink.0, [false, true, false, false]);
312/// # Ok(()) } do_it().unwrap();
313/// ```
314pub trait EventSink {
315    /// `true` if the sink receives the values of the events.
316    ///
317    /// Otherwise the value passed to [`event`](Self::event) describes
318    /// nothing.  Values are only passed on if they are wanted as the
319    /// driver serializes values faster if it does not need to hand out
320    /// every one of them.
321    const DESCRIBED: bool = false;
322
323    /// Receives an event.
324    ///
325    /// Formats can mark the implementation as `#[inline(always)]` which
326    /// makes the compiler specialize it for every kind of event the driver
327    /// delivers (which is not possible with the callback of
328    /// [`drive`](SerializeDriver::drive)).
329    fn event(
330        &mut self,
331        event: Event<'_>,
332        value: SerializeRef<'_>,
333        state: &mut State,
334    ) -> Result<(), Error>;
335
336    /// Returns `true` if the driver should pause.
337    ///
338    /// This is invoked between values: before the values in maps and
339    /// sequences (not the keys of structs) and between the pieces of large
340    /// values that only hold atoms.  After the first value of a call to
341    /// [`drive_until`](SerializeDriver::drive_until) returns `true`, the
342    /// call returns.  The default implementation never pauses.
343    ///
344    /// [`drive_sink`](SerializeDriver::drive_sink) does not invoke this.
345    fn pause(&mut self) -> bool {
346        false
347    }
348}
349
350/// A callback that delivers to an event sink and does not pause.
351struct Sink<'s, S>(&'s mut S);
352
353impl<S: EventSink> Callback for Sink<'_, S> {
354    const DESCRIBED: bool = S::DESCRIBED;
355
356    #[inline(always)]
357    fn call(
358        &mut self,
359        event: Event<'_>,
360        value: SerializeRef<'_>,
361        state: &mut State,
362    ) -> Result<(), Error> {
363        self.0.event(event, value, state)
364    }
365}
366
367/// A callback that delivers to an event sink which can pause.
368struct Pausable<'s, S>(&'s mut S);
369
370impl<S: EventSink> Callback for Pausable<'_, S> {
371    const DESCRIBED: bool = S::DESCRIBED;
372    const PAUSABLE: bool = true;
373
374    #[inline(always)]
375    fn call(
376        &mut self,
377        event: Event<'_>,
378        value: SerializeRef<'_>,
379        state: &mut State,
380    ) -> Result<(), Error> {
381        self.0.event(event, value, state)
382    }
383
384    #[inline(always)]
385    fn pause(&mut self) -> bool {
386        self.0.pause()
387    }
388}
389
390/// The value of the keys of structs, it describes nothing.
391static FIELD_KEY: () = ();
392
393/// Returns the value of the keys of structs.
394#[inline(always)]
395fn field_key() -> SerializeRef<'static> {
396    SerializeRef::new(&FIELD_KEY)
397}
398
399/// Serializes a plain value into an `Emit`, for when every value is driven
400/// on its own.
401#[inline(never)]
402fn serialize_plain<'x>(plain: SerializeRef<'x>, state: &mut State) -> Result<BeginKind<'x>, Error> {
403    Ok(BeginKind::Emit(plain.serialize(state)?))
404}
405
406/// Delivers the events of plain values (see [`PlainSink`]).
407///
408/// The first event of a value is a key if `is_map_key` is set in the
409/// state, it's reset after every such event.
410struct PlainDelivery<'d, 'a, C> {
411    driver: &'d mut SerializeDriver<'a>,
412    f: &'d mut C,
413}
414
415impl<C: Callback> PlainDelivery<'_, '_, C> {
416    /// Delivers the first event of a value.
417    #[inline(always)]
418    fn begin(&mut self, event: Event<'_>) -> Result<(), Error> {
419        self.driver.deliver(self.f, event, field_key())?;
420        self.driver.state.is_map_key = false;
421        Ok(())
422    }
423}
424
425impl<C: Callback> PlainSink for PlainDelivery<'_, '_, C> {
426    #[inline]
427    fn atom(&mut self, atom: Atom<'_>) -> Result<(), Error> {
428        self.begin(Event::Atom(atom))
429    }
430
431    #[inline]
432    fn seq_start(&mut self, shape: ContainerShape) -> Result<(), Error> {
433        self.driver.state.depth += 1;
434        self.begin(Event::SeqStart(shape))
435    }
436
437    #[inline]
438    fn seq_end(&mut self) -> Result<(), Error> {
439        self.driver.state.depth -= 1;
440        self.driver.deliver(self.f, Event::SeqEnd, field_key())
441    }
442
443    #[inline]
444    fn map_start(&mut self, shape: ContainerShape) -> Result<(), Error> {
445        self.driver.state.depth += 1;
446        self.begin(Event::MapStart(shape))
447    }
448
449    #[inline]
450    fn map_end(&mut self) -> Result<(), Error> {
451        self.driver.state.depth -= 1;
452        self.driver.deliver(self.f, Event::MapEnd, field_key())
453    }
454
455    #[inline]
456    fn key(&mut self) {
457        self.driver.state.is_map_key = true;
458    }
459
460    #[inline]
461    fn field(&mut self, name: &str) -> Result<(), Error> {
462        self.driver.state.is_map_key = true;
463        self.begin(Event::Atom(Atom::Str(Text::borrowed(name))))
464    }
465}
466
467impl<'a> SerializeDriver<'a> {
468    /// Creates a new driver which serializes the given value implementing [`Serialize`].
469    #[inline]
470    pub fn new<T: Serialize>(value: &'a T) -> SerializeDriver<'a> {
471        SerializeDriver::from_ref(SerializeRef::new(value))
472    }
473
474    /// Creates a new driver which serializes the value of a reference.
475    ///
476    /// Unlike [`new`](Self::new) this is not generic, the reference can be
477    /// to a value with an adapter (see [`SerializeRef::serialize_as`]).
478    pub fn from_ref(serializable: SerializeRef<'a>) -> SerializeDriver<'a> {
479        let mut state = State::new();
480        // the stack of the last driver is reused
481        let stack = state
482            .arena
483            .take_vec(Buffer::SerializeStack)
484            .unwrap_or_else(|| Vec::with_capacity(STACK_CAPACITY));
485        SerializeDriver {
486            state,
487            layers: Vec::new(),
488            // SAFETY: the driver cannot outlive 'a
489            next_value: Some(unsafe { Held::new(SerializeHandle::from(serializable)) }),
490            needs_finish: None,
491            stack,
492            delivered: false,
493            _marker: PhantomData,
494        }
495    }
496
497    /// Returns a borrowed reference to the current serializer state.
498    pub fn state(&self) -> &State {
499        &self.state
500    }
501
502    /// Returns a mutable reference to the current serializer state.
503    ///
504    /// This can be used to place extension values into the state which the
505    /// serializable values can then pick up.
506    pub fn state_mut(&mut self) -> &mut State {
507        &mut self.state
508    }
509
510    /// Sets the context of the serialization.
511    ///
512    /// The values of the context are the defaults of the extension values
513    /// of the state (see [`Context`]).  This replaces the context of the
514    /// driver.  Formats add the values of their own context for the types
515    /// it has no value for (see
516    /// [`set_default_context`](Self::set_default_context)).
517    pub fn set_context(&mut self, context: Context) {
518        self.state.set_context(context);
519    }
520
521    /// Adds the values of a context that the context of the driver has no
522    /// value for.
523    ///
524    /// Formats use this for the context they were given (for instance the
525    /// one of their configuration).  A context that was set on the driver
526    /// before (for instance in the setup callback of `serialize_with`)
527    /// takes precedence: its values are kept and the values of the given
528    /// context are only added for the types it has no value for.
529    #[inline(never)]
530    pub fn set_default_context(&mut self, context: Context) {
531        let mut merged = self.state.context().clone();
532        if merged.fill_from(&context) {
533            self.set_context(merged);
534        }
535    }
536
537    /// Returns the context of the serialization.
538    pub fn context(&self) -> &Context {
539        self.state.context()
540    }
541
542    /// Adds a layer.
543    ///
544    /// Layers see the events in the order they were added: the layer that
545    /// was added first sees the events produced by the values, the last one
546    /// passes them on to the format.  See [`Layer`] for more information.
547    pub fn push_layer<L: Layer + 'static>(&mut self, layer: L) {
548        self.layers.push(Box::new(layer));
549    }
550
551    /// Produces the next serialization event.
552    ///
553    /// # Panics
554    ///
555    /// The driver will panic if the data fed from the serializer is
556    /// malformed.  As layers can change the number of events, this method
557    /// panics if layers were added.
558    #[allow(clippy::should_implement_trait)]
559    #[inline]
560    pub fn next(&mut self) -> Result<Option<(Event<'_>, SerializeRef<'_>, &mut State)>, Error> {
561        assert!(
562            self.layers.is_empty(),
563            "layers are only supported by SerializeDriver::drive"
564        );
565        let rv = match self.advance() {
566            Ok(rv) => rv,
567            Err(err) => return Err(self.state.error_in_context(err)),
568        };
569        self.delivered = rv.is_some();
570        // The event and the value borrow from the values held by the driver
571        // but never from the state (serializables cannot return `Emit`s
572        // borrowing from it), which is why the state can be handed out
573        // mutably.
574        Ok(rv.map(|(event, value)| (event, value, &mut self.state)))
575    }
576
577    /// Detaches the event data of an event returned by `next`.
578    #[inline(always)]
579    fn detach_delivered_event_data(&mut self) {
580        if self.delivered {
581            self.delivered = false;
582            self.state.clear_event_data();
583        }
584    }
585
586    /// Drives the serialization to the end and invokes a callback for every
587    /// event.
588    ///
589    /// This produces the same events as calling [`next`](Self::next) until
590    /// it returns `None` but it's faster.  The first error (either produced
591    /// by a serializable or returned by the callback) aborts the
592    /// serialization.  To receive the values of the events or to pause the
593    /// serialization, use an [`EventSink`].
594    ///
595    /// ```
596    /// # use deser::ser::SerializeDriver;
597    /// # fn do_it() -> Result<(), deser::Error> {
598    /// let serializable = vec!["foo", "bar", "baz"];
599    /// let mut events = Vec::new();
600    /// SerializeDriver::new(&serializable).drive(|event, _state| {
601    ///     events.push(event.to_static());
602    ///     Ok(())
603    /// })?;
604    /// assert_eq!(events.len(), 5);
605    /// # Ok(()) } do_it().unwrap();
606    /// ```
607    #[inline]
608    pub fn drive<F>(&mut self, f: F) -> Result<(), Error>
609    where
610        F: FnMut(Event<'_>, &mut State) -> Result<(), Error>,
611    {
612        match self.drive_impl(Plain(f)) {
613            Ok(_) => Ok(()),
614            Err(err) => Err(self.state.error_in_context(err)),
615        }
616    }
617
618    /// Like [`drive`](Self::drive) but delivers the events to an
619    /// [`EventSink`].
620    ///
621    /// The sink is not asked to pause (see [`drive_until`](Self::drive_until)),
622    /// the value is serialized at once.
623    #[inline]
624    pub fn drive_sink<S: EventSink>(&mut self, sink: &mut S) -> Result<(), Error> {
625        match self.drive_impl(Sink(sink)) {
626            Ok(_) => Ok(()),
627            Err(err) => Err(self.state.error_in_context(err)),
628        }
629    }
630
631    /// Drives the serialization until it's complete or the sink pauses it.
632    ///
633    /// Returns `true` once the serialization is complete.  If the sink
634    /// paused the driver (see [`EventSink::pause`]), `false` is returned
635    /// and the next call continues where this one stopped.  At least one
636    /// value is serialized per call.
637    ///
638    /// Unlike [`drive`](Self::drive), which emits values that only hold
639    /// atoms (like a `Vec<u64>`) at once, the driver emits such values in
640    /// pieces of a few hundred atoms and can pause in between.  The amount
641    /// of events between two pauses only depends on the size of the atoms,
642    /// not on the size of the value.
643    ///
644    /// ```
645    /// # use deser::ser::{EventSink, SerializeDriver, SerializeRef};
646    /// # use deser::{Error, Event, State};
647    /// /// Collects events and pauses once it holds 100.
648    /// struct Collect(Vec<Event<'static>>);
649    ///
650    /// impl EventSink for Collect {
651    ///     fn event(
652    ///         &mut self,
653    ///         event: Event<'_>,
654    ///         _value: SerializeRef<'_>,
655    ///         _state: &mut State,
656    ///     ) -> Result<(), Error> {
657    ///         self.0.push(event.to_static());
658    ///         Ok(())
659    ///     }
660    ///
661    ///     fn pause(&mut self) -> bool {
662    ///         self.0.len() >= 100
663    ///     }
664    /// }
665    ///
666    /// # fn do_it() -> Result<(), deser::Error> {
667    /// let value: Vec<u64> = (0..10_000).collect();
668    /// let mut driver = SerializeDriver::new(&value);
669    /// let mut sink = Collect(Vec::new());
670    /// let mut events = 0;
671    /// loop {
672    ///     let done = driver.drive_until(&mut sink)?;
673    ///     // the events so far are processed while the driver is paused
674    ///     assert!(sink.0.len() < 1000);
675    ///     events += sink.0.len();
676    ///     sink.0.clear();
677    ///     if done {
678    ///         break;
679    ///     }
680    /// }
681    /// assert_eq!(events, 10_002);
682    /// # Ok(()) } do_it().unwrap();
683    /// ```
684    #[inline]
685    pub fn drive_until<S: EventSink>(&mut self, sink: &mut S) -> Result<bool, Error> {
686        match self.drive_impl(Pausable(sink)) {
687            Ok(done) => Ok(done),
688            Err(err) => Err(self.state.error_in_context(err)),
689        }
690    }
691
692    /// Delivers an event to the layers and the callback of
693    /// [`drive`](Self::drive).
694    #[inline(always)]
695    fn deliver<C: Callback>(
696        &mut self,
697        f: &mut C,
698        event: Event<'_>,
699        value: SerializeRef<'_>,
700    ) -> Result<(), Error> {
701        // the value is only passed on if the callback wants it
702        let value = if C::DESCRIBED { value } else { field_key() };
703        if self.layers.is_empty() {
704            f.call(event, value, &mut self.state)?;
705        } else {
706            self.deliver_layered(
707                &mut |event, value, state| f.call(event, value, state),
708                event,
709                value,
710            )?;
711        }
712        self.state.clear_event_data();
713        Ok(())
714    }
715
716    /// Passes an event through the layers.
717    #[inline(never)]
718    fn deliver_layered(
719        &mut self,
720        f: &mut EventFn<'_>,
721        event: Event<'_>,
722        value: SerializeRef<'_>,
723    ) -> Result<(), Error> {
724        Next::new(&mut self.layers, &mut self.state, f, value).emit(event)
725    }
726
727    /// Drives the serialization, returns `false` if the callback paused it.
728    #[inline(always)]
729    fn drive_impl<C: Callback>(&mut self, mut f: C) -> Result<bool, Error> {
730        // `next` might have been used before.
731        self.detach_delivered_event_data();
732        if let Some((held, true)) = self.needs_finish.take() {
733            // SAFETY: the value is alive until the end of this block
734            unsafe { held.get() }.finish(&mut self.state)?;
735        }
736        if let Some(value) = self.next_value.take() {
737            self.drive_value(value, false, &mut f)?;
738        }
739
740        // at least one value is serialized per call
741        let mut first = true;
742        while let Some(frame) = self.stack.last_mut() {
743            // the state is complete between the iterations, the driver can
744            // continue from here in the next call
745            if C::PAUSABLE {
746                if !first && f.pause() {
747                    return Ok(false);
748                }
749                first = false;
750            }
751            // SAFETY: values produced by the emitter borrow from it.  The
752            // frame stays on the stack until all of them are dropped.
753            let emitter = unsafe { &mut *(&mut frame.emitter as *mut Emitter) };
754            let value = match emitter {
755                Emitter::Forward => {
756                    self.finish_forward()?;
757                    continue;
758                }
759                Emitter::IndexedStruct(fields, index) => {
760                    if C::FAST {
761                        *index = fields.emit_plain_fields(
762                            *index,
763                            C::PAUSABLE,
764                            &mut PlainDelivery {
765                                driver: self,
766                                f: &mut f,
767                            },
768                        )?;
769                        if *index == FIELDS_END {
770                            self.drive_end(&mut f)?;
771                            continue;
772                        }
773                    }
774                    let field = fields.field(*index);
775                    *index += 1;
776                    match field {
777                        StructField::Field(key, value) => {
778                            self.state.is_map_key = true;
779                            self.deliver(
780                                &mut f,
781                                Event::Atom(Atom::Str(Text::borrowed(key))),
782                                field_key(),
783                            )?;
784                            (value, false)
785                        }
786                        StructField::Skip => continue,
787                        StructField::End => {
788                            self.drive_end(&mut f)?;
789                            continue;
790                        }
791                    }
792                }
793                Emitter::IndexedSeq(seq, index) => {
794                    // large plain sequences are emitted in pieces
795                    if C::FAST && C::PAUSABLE {
796                        // the sequence might be a key, its values are not
797                        self.state.is_map_key = false;
798                        let next = seq.emit_plain_chunk(
799                            *index,
800                            PLAIN_BUDGET,
801                            &mut PlainDelivery {
802                                driver: self,
803                                f: &mut f,
804                            },
805                        )?;
806                        if next != *index {
807                            *index = next;
808                            continue;
809                        }
810                    }
811                    let element = seq.element(*index, &mut self.state)?;
812                    *index += 1;
813                    match element {
814                        Some(value) => (value, false),
815                        None => {
816                            self.drive_end(&mut f)?;
817                            continue;
818                        }
819                    }
820                }
821                Emitter::Struct(emitter) => match emitter.next(&mut self.state)? {
822                    Some((key, value)) => {
823                        self.state.is_map_key = true;
824                        self.deliver(&mut f, Event::Atom(Atom::Str(key.into())), field_key())?;
825                        (value, false)
826                    }
827                    None => {
828                        self.drive_end(&mut f)?;
829                        continue;
830                    }
831                },
832                Emitter::Seq(emitter) => match emitter.next(&mut self.state)? {
833                    Some(value) => (value, false),
834                    None => {
835                        self.drive_end(&mut f)?;
836                        continue;
837                    }
838                },
839                Emitter::Map(emitter, is_value) => {
840                    if *is_value {
841                        *is_value = false;
842                        (emitter.next_value(&mut self.state)?, false)
843                    } else {
844                        match emitter.next_key(&mut self.state)? {
845                            Some(key) => {
846                                *is_value = true;
847                                (key, true)
848                            }
849                            None => {
850                                self.drive_end(&mut f)?;
851                                continue;
852                            }
853                        }
854                    }
855                }
856            };
857            // SAFETY: the value borrows from the emitter on the top of the
858            // stack.
859            self.drive_value(unsafe { Held::new(value.0) }, value.1, &mut f)?;
860        }
861
862        Ok(true)
863    }
864
865    /// Removes a forwarding frame from the top of the stack.
866    ///
867    /// This is invoked once the forwarded value was serialized.
868    #[cold]
869    fn finish_forward(&mut self) -> Result<(), Error> {
870        let Frame {
871            emitter,
872            serializable,
873            needs_finish,
874        } = self.stack.pop().unwrap();
875        debug_assert!(matches!(emitter, Emitter::Forward));
876        if needs_finish {
877            // SAFETY: the value is alive until the end of this block
878            unsafe { serializable.get() }.finish(&mut self.state)?;
879        }
880        Ok(())
881    }
882
883    /// Places a value that forwarded to another value on the stack.
884    ///
885    /// Returns the forwarded value.
886    #[cold]
887    fn push_forward(
888        &mut self,
889        value: Held,
890        needs_finish: bool,
891        forwarded: SerializeHandle<'_>,
892    ) -> Held {
893        self.stack.push(Frame {
894            emitter: Emitter::Forward,
895            serializable: value,
896            needs_finish,
897        });
898        // SAFETY: the forwarded value can borrow from the value which is
899        // held by the frame.  It's dropped before the frame.
900        unsafe { Held::new(forwarded) }
901    }
902
903    /// Serializes a forwarded value and emits its first event.
904    #[inline(never)]
905    fn drive_forwarded<C: Callback>(
906        &mut self,
907        value: Held,
908        is_key: bool,
909        f: &mut C,
910    ) -> Result<(), Error> {
911        self.drive_value(value, is_key, f)
912    }
913
914    /// Serializes a value and emits its first event.
915    #[inline(always)]
916    fn drive_value<C: Callback>(
917        &mut self,
918        value: Held,
919        is_key: bool,
920        f: &mut C,
921    ) -> Result<(), Error> {
922        // SAFETY: the value is held until the event and the emitters derived
923        // from it are dropped.
924        let serializable = unsafe { value.get() };
925        self.state.is_map_key = is_key;
926        let Begin {
927            kind,
928            shape,
929            needs_finish,
930        } = serializable.begin(&mut self.state)?;
931        let kind = match kind {
932            // callbacks that describe values need to see every value,
933            // large plain values are driven on their own for callbacks that
934            // pause
935            BeginKind::Plain(plain)
936                if C::UNBOUNDED || (C::FAST && plain.plain_cost(PLAIN_BUDGET).is_some()) =>
937            {
938                return plain.emit_plain(&mut PlainDelivery { driver: self, f });
939            }
940            BeginKind::Plain(plain) => serialize_plain(plain, &mut self.state)?,
941            kind => kind,
942        };
943        let (emitter, event) = match kind {
944            BeginKind::Emit(Emit::Atom(atom)) => {
945                self.deliver(f, Event::Atom(atom), serializable)?;
946                if needs_finish {
947                    serializable.finish(&mut self.state)?;
948                }
949                return Ok(());
950            }
951            BeginKind::Emit(Emit::Struct(emitter)) => {
952                (Emitter::Struct(emitter), Event::MapStart(shape))
953            }
954            BeginKind::Emit(Emit::Map(emitter)) => {
955                (Emitter::Map(emitter, false), Event::MapStart(shape))
956            }
957            BeginKind::Emit(Emit::Seq(emitter)) => (Emitter::Seq(emitter), Event::SeqStart(shape)),
958            // callbacks that describe values need to see every value
959            BeginKind::Struct(fields) if C::FAST => {
960                // an owned value is dropped here, not in the callee where
961                // `fields` (which borrows from it) is an argument.
962                let mut value = Some(value);
963                let rv = self.drive_indexed_struct(&mut value, fields, shape, f);
964                drop(value);
965                return rv;
966            }
967            BeginKind::Struct(fields) => {
968                (Emitter::IndexedStruct(fields, 0), Event::MapStart(shape))
969            }
970            // large sequences are emitted in pieces for callbacks that pause
971            BeginKind::Seq(seq)
972                if C::UNBOUNDED || (C::FAST && serializable.plain_cost(PLAIN_BUDGET).is_some()) =>
973            {
974                // see above
975                let mut value = Some(value);
976                let rv = self.drive_indexed_seq(&mut value, seq, shape, f);
977                drop(value);
978                return rv;
979            }
980            BeginKind::Seq(seq) => (Emitter::IndexedSeq(seq, 0), Event::SeqStart(shape)),
981            BeginKind::Emit(Emit::Forward(forwarded)) => {
982                let forwarded = self.push_forward(value, needs_finish, forwarded);
983                return self.drive_forwarded(forwarded, is_key, f);
984            }
985            BeginKind::Plain(_) => unreachable!(),
986        };
987        self.stack.push(Frame {
988            emitter,
989            serializable: value,
990            needs_finish,
991        });
992        self.state.depth += 1;
993        self.deliver(f, event, serializable)
994    }
995
996    /// Starts an indexed struct.
997    ///
998    /// Its leading plain fields are emitted right away.  If all fields are
999    /// plain the struct is ended, otherwise it's placed on the stack.
1000    ///
1001    /// The value is taken if it's placed on the stack, otherwise the caller
1002    /// drops it.  An owned value must not be dropped in here as `fields`
1003    /// borrows from it (it's an argument, which must stay valid for the
1004    /// whole call).
1005    #[inline(always)]
1006    fn drive_indexed_struct<C: Callback>(
1007        &mut self,
1008        value: &mut Option<Held>,
1009        fields: &'static dyn IndexedStruct,
1010        shape: ContainerShape,
1011        f: &mut C,
1012    ) -> Result<(), Error> {
1013        // SAFETY: the value is held by the caller or by the frame
1014        let serializable = unsafe { value.as_ref().unwrap().get() };
1015        self.state.depth += 1;
1016        self.deliver(f, Event::MapStart(shape), serializable)?;
1017        self.state.is_map_key = false;
1018        let index =
1019            fields.emit_plain_fields(0, C::PAUSABLE, &mut PlainDelivery { driver: self, f })?;
1020        if index == FIELDS_END {
1021            self.state.depth -= 1;
1022            self.deliver(f, Event::MapEnd, serializable)
1023        } else {
1024            self.stack.push(Frame {
1025                emitter: Emitter::IndexedStruct(fields, index),
1026                serializable: value.take().unwrap(),
1027                // indexed structs do not need `finish`
1028                needs_finish: false,
1029            });
1030            Ok(())
1031        }
1032    }
1033
1034    /// Starts an indexed sequence.
1035    ///
1036    /// If its elements are plain, they are emitted right away and the
1037    /// sequence is ended.  Otherwise it's placed on the stack.
1038    ///
1039    /// The value is taken if it's placed on the stack, otherwise the caller
1040    /// drops it.  An owned value must not be dropped in here as `seq`
1041    /// borrows from it (it's an argument, which must stay valid for the
1042    /// whole call).
1043    #[inline(always)]
1044    fn drive_indexed_seq<C: Callback>(
1045        &mut self,
1046        value: &mut Option<Held>,
1047        seq: &'static dyn IndexedSeq,
1048        shape: ContainerShape,
1049        f: &mut C,
1050    ) -> Result<(), Error> {
1051        // SAFETY: the value is held by the caller or by the frame
1052        let serializable = unsafe { value.as_ref().unwrap().get() };
1053        self.state.depth += 1;
1054        self.deliver(f, Event::SeqStart(shape), serializable)?;
1055        self.state.is_map_key = false;
1056        let emitted = seq.emit_plain(&mut PlainDelivery { driver: self, f })?;
1057        if emitted {
1058            self.state.depth -= 1;
1059            self.deliver(f, Event::SeqEnd, serializable)
1060        } else {
1061            self.stack.push(Frame {
1062                emitter: Emitter::IndexedSeq(seq, 0),
1063                serializable: value.take().unwrap(),
1064                // indexed sequences do not need `finish`
1065                needs_finish: false,
1066            });
1067            Ok(())
1068        }
1069    }
1070
1071    /// Ends the container on the top of the stack and emits the end event.
1072    ///
1073    /// Unlike with `next` the value does not need to outlive this call.
1074    #[inline]
1075    fn drive_end<C: Callback>(&mut self, f: &mut C) -> Result<(), Error> {
1076        let Frame {
1077            emitter,
1078            serializable,
1079            needs_finish,
1080        } = self.stack.pop().unwrap();
1081        let event = match emitter {
1082            Emitter::Seq(_) | Emitter::IndexedSeq(..) => Event::SeqEnd,
1083            _ => Event::MapEnd,
1084        };
1085        // the emitter borrows from the serializable, drop it first.
1086        emitter.release(&mut self.state);
1087        self.state.depth -= 1;
1088        // SAFETY: the value is held until the end of this function
1089        let value = unsafe { serializable.get() };
1090        self.deliver(f, event, value)?;
1091        if needs_finish {
1092            value.finish(&mut self.state)?;
1093        }
1094        Ok(())
1095    }
1096
1097    /// Advances the driver.
1098    ///
1099    /// The returned event is bound to `'static` but it actually borrows from
1100    /// the values and frames held by the driver.  It's only valid until the
1101    /// next call.
1102    fn advance(&mut self) -> Result<NextEvent<'static>, Error> {
1103        self.detach_delivered_event_data();
1104        if let Some((held, true)) = self.needs_finish.take() {
1105            // SAFETY: the value is alive until the end of this block
1106            unsafe { held.get() }.finish(&mut self.state)?;
1107        }
1108
1109        let mut is_key = false;
1110        let value = match self.next_value.take() {
1111            Some(value) => value,
1112            None => loop {
1113                let frame = match self.stack.last_mut() {
1114                    Some(frame) => frame,
1115                    None => return Ok(None),
1116                };
1117                // SAFETY: values produced by the emitter borrow from it.  The
1118                // frame stays on the stack until all of them are dropped.
1119                let emitter = unsafe { &mut *(&mut frame.emitter as *mut Emitter) };
1120                let next = match emitter {
1121                    Emitter::Forward => {
1122                        self.finish_forward()?;
1123                        continue;
1124                    }
1125                    Emitter::Seq(emitter) => emitter.next(&mut self.state)?,
1126                    Emitter::Map(emitter, is_value) => {
1127                        if *is_value {
1128                            *is_value = false;
1129                            Some(emitter.next_value(&mut self.state)?)
1130                        } else {
1131                            let key = emitter.next_key(&mut self.state)?;
1132                            *is_value = key.is_some();
1133                            is_key = true;
1134                            key
1135                        }
1136                    }
1137                    Emitter::Struct(emitter) => match emitter.next(&mut self.state)? {
1138                        Some((key, value)) => {
1139                            // the key is emitted directly as event, the value
1140                            // is serialized on the next call.
1141                            // SAFETY: the value and key borrow from the emitter
1142                            // which stays alive until the next call.
1143                            self.next_value = Some(unsafe { Held::new(value) });
1144                            let key = unsafe {
1145                                core::mem::transmute::<Cow<'_, str>, Cow<'static, str>>(key)
1146                            };
1147                            self.state.is_map_key = true;
1148                            return Ok(Some((Event::Atom(Atom::Str(key.into())), field_key())));
1149                        }
1150                        None => None,
1151                    },
1152                    Emitter::IndexedSeq(seq, index) => {
1153                        let rv = seq.element(*index, &mut self.state)?;
1154                        *index += 1;
1155                        rv
1156                    }
1157                    Emitter::IndexedStruct(fields, index) => loop {
1158                        let field = fields.field(*index);
1159                        *index += 1;
1160                        match field {
1161                            StructField::Field(key, value) => {
1162                                // SAFETY: the value and key borrow from the
1163                                // serializable of the frame.
1164                                self.next_value = Some(unsafe { Held::new(value) });
1165                                self.state.is_map_key = true;
1166                                return Ok(Some((
1167                                    Event::Atom(Atom::Str(Text::borrowed(key))),
1168                                    field_key(),
1169                                )));
1170                            }
1171                            StructField::Skip => continue,
1172                            StructField::End => break None,
1173                        }
1174                    },
1175                };
1176                match next {
1177                    // SAFETY: the value borrows from the emitter on the top
1178                    // of the stack.
1179                    Some(value) => break unsafe { Held::new(value) },
1180                    None => {
1181                        let event = self.end_container();
1182                        // SAFETY: the value is held until the next call
1183                        return Ok(Some((event, unsafe { self.finished_value() })));
1184                    }
1185                }
1186            },
1187        };
1188
1189        self.serialize_value(value, is_key)
1190    }
1191
1192    /// Ends the container on the top of the stack.
1193    fn end_container(&mut self) -> Event<'static> {
1194        let Frame {
1195            emitter,
1196            serializable,
1197            needs_finish,
1198        } = self.stack.pop().unwrap();
1199        let event = match emitter {
1200            Emitter::Seq(_) | Emitter::IndexedSeq(..) => Event::SeqEnd,
1201            _ => Event::MapEnd,
1202        };
1203        // the emitter borrows from the serializable, drop it first.
1204        emitter.release(&mut self.state);
1205        self.needs_finish = Some((serializable, needs_finish));
1206        self.state.depth -= 1;
1207        event
1208    }
1209
1210    /// Returns the value of the container that was ended last.
1211    ///
1212    /// # Safety
1213    ///
1214    /// The value must not be used after the next event.
1215    #[inline(always)]
1216    unsafe fn finished_value(&self) -> SerializeRef<'static> {
1217        match self.needs_finish {
1218            // SAFETY: the caller guarantees the value is not used for longer
1219            Some((ref held, _)) => unsafe { held.get() },
1220            None => field_key(),
1221        }
1222    }
1223
1224    /// Serializes a value and returns its first event.
1225    #[inline]
1226    fn serialize_value(&mut self, value: Held, is_key: bool) -> Result<NextEvent<'static>, Error> {
1227        // SAFETY: the value is held by the driver until the event and the
1228        // emitters derived from it are dropped.  Moving `value` only moves a
1229        // pointer to it.
1230        let serializable = unsafe { value.get() };
1231        self.state.is_map_key = is_key;
1232        let Begin {
1233            kind,
1234            shape,
1235            needs_finish,
1236        } = serializable.begin(&mut self.state)?;
1237        let kind = match kind {
1238            BeginKind::Plain(plain) => serialize_plain(plain, &mut self.state)?,
1239            kind => kind,
1240        };
1241        let (emitter, event) = match kind {
1242            BeginKind::Emit(Emit::Atom(atom)) => {
1243                self.needs_finish = Some((value, needs_finish));
1244                return Ok(Some((Event::Atom(atom), serializable)));
1245            }
1246            BeginKind::Emit(Emit::Struct(emitter)) => {
1247                (Emitter::Struct(emitter), Event::MapStart(shape))
1248            }
1249            BeginKind::Emit(Emit::Map(emitter)) => {
1250                (Emitter::Map(emitter, false), Event::MapStart(shape))
1251            }
1252            BeginKind::Emit(Emit::Seq(emitter)) => (Emitter::Seq(emitter), Event::SeqStart(shape)),
1253            BeginKind::Struct(fields) => {
1254                (Emitter::IndexedStruct(fields, 0), Event::MapStart(shape))
1255            }
1256            BeginKind::Seq(seq) => (Emitter::IndexedSeq(seq, 0), Event::SeqStart(shape)),
1257            BeginKind::Emit(Emit::Forward(forwarded)) => {
1258                let forwarded = self.push_forward(value, needs_finish, forwarded);
1259                return self.serialize_forwarded(forwarded, is_key);
1260            }
1261            BeginKind::Plain(_) => unreachable!(),
1262        };
1263        self.stack.push(Frame {
1264            emitter,
1265            serializable: value,
1266            needs_finish,
1267        });
1268        self.state.depth += 1;
1269        Ok(Some((event, serializable)))
1270    }
1271
1272    /// Serializes a forwarded value and returns its first event.
1273    #[inline(never)]
1274    fn serialize_forwarded(
1275        &mut self,
1276        value: Held,
1277        is_key: bool,
1278    ) -> Result<NextEvent<'static>, Error> {
1279        self.serialize_value(value, is_key)
1280    }
1281}
1282
1283#[test]
1284fn test_seq_emitting() {
1285    let vec = vec![vec![1u64, 2], vec![3, 4]];
1286
1287    let mut driver = SerializeDriver::new(&vec);
1288    let mut events = Vec::new();
1289    while let Some((event, _, _)) = driver.next().unwrap() {
1290        events.push(crate::event::without_len(event.to_static()));
1291    }
1292
1293    assert_eq!(
1294        events,
1295        vec![
1296            Event::seq_start(),
1297            Event::seq_start(),
1298            1u64.into(),
1299            2u64.into(),
1300            Event::SeqEnd,
1301            Event::seq_start(),
1302            3u64.into(),
1303            4u64.into(),
1304            Event::SeqEnd,
1305            Event::SeqEnd,
1306        ],
1307    );
1308}
1309
1310#[test]
1311fn test_map_emitting() {
1312    let mut map = alloc::collections::BTreeMap::new();
1313    map.insert((1u32, 2u32), "first");
1314    map.insert((2, 3), "second");
1315
1316    let mut driver = SerializeDriver::new(&map);
1317    let mut events = Vec::new();
1318    while let Some((event, _, _)) = driver.next().unwrap() {
1319        events.push(crate::event::without_len(event.to_static()));
1320    }
1321
1322    assert_eq!(
1323        events,
1324        vec![
1325            Event::MapStart(crate::ContainerShape::with_order(crate::Order::Sorted)),
1326            Event::seq_start(),
1327            1u64.into(),
1328            2u64.into(),
1329            Event::SeqEnd,
1330            "first".into(),
1331            Event::seq_start(),
1332            2u64.into(),
1333            3u64.into(),
1334            Event::SeqEnd,
1335            "second".into(),
1336            Event::MapEnd
1337        ]
1338    );
1339}
1340
1341#[test]
1342fn test_state_mut() {
1343    #[derive(Debug, Default)]
1344    struct Uppercase(bool);
1345
1346    struct Name(&'static str);
1347
1348    impl Serialize for Name {
1349        fn serialize<'a>(value: &'a Self, state: &mut State) -> Result<Emit<'a>, Error> {
1350            Ok(Emit::Atom(Atom::Str(
1351                if state.get::<Uppercase>().is_some_and(|x| x.0) {
1352                    value.0.to_uppercase().into()
1353                } else {
1354                    value.0.into()
1355                },
1356            )))
1357        }
1358    }
1359
1360    let names = vec![Name("foo"), Name("bar")];
1361    let mut driver = SerializeDriver::new(&names);
1362    driver.state_mut().get_mut::<Uppercase>().0 = true;
1363    let mut events = Vec::new();
1364    while let Some((event, _, _)) = driver.next().unwrap() {
1365        events.push(crate::event::without_len(event.to_static()));
1366    }
1367
1368    assert_eq!(
1369        events,
1370        vec![
1371            Event::seq_start(),
1372            "FOO".into(),
1373            "BAR".into(),
1374            Event::SeqEnd
1375        ],
1376    );
1377}