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