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