Skip to main content

deser_core/ser/
mod.rs

1//! Generic data structure serialization framework.
2//!
3//! Serialization in deser is based on the [`Serialize`] trait which produces
4//! [`Chunk`] objects.  A serializable object walks an object and produces either
5//! an atomic chunk or a chunk containing an emitter which yields further values.
6//!
7//! # Streaming Serialization
8//!
9//! For convenient serialization, Deser provides a [`SerializeDriver`] that allows
10//! streaming serialization of values.  A driver can be created by passing a reference
11//! to a [`Serialize`] value to the constructor.  Then [`next`](SerializeDriver::next)
12//! is called repeatedly until no more events are produced.
13//!
14//! ```
15//! # use deser::ser::SerializeDriver;
16//! # fn do_it() -> Result<(), deser::Error> {
17//! let serializable = vec!["foo", "bar", "baz"];
18//! let mut driver = SerializeDriver::new(&serializable);
19//! while let Some((_event, _value, _state)) = driver.next()? {
20//!     // serialize each event for the target format such as JSON
21//! }
22//! # Ok(()) } do_it().unwrap();
23//! ```
24//!
25//! This type of interface also permits the serialization of almost unlimited depth.
26//!
27//! # Serializing Primitives
28//!
29//! Primitive values such as integers are trivial to serialize as you just
30//! directly return the right type of [`Chunk`] from the serialization method.
31//!
32//! ```rust
33//! use deser::ser::{Serialize, Chunk};
34//! use deser::State;
35//! use deser::{Atom, Error};
36//!
37//! struct MyInt(u32);
38//!
39//! impl Serialize for MyInt {
40//!     fn serialize(&self, _state: &mut State) -> Result<Chunk<'_>, Error> {
41//!         // one can also just do `self.0.serialize(state)`
42//!         Ok(Chunk::Atom(Atom::U64(self.0 as u64)))
43//!     }
44//! }
45//! ```
46//!
47//! # Serializing Structs
48//!
49//! To serialize compounds like structs you return a chunk containing an emitter.
50//! Note that the emitter returns a [`SerializeHandle`].  If want you want to
51//! serialize is not already available the handle can hold a boxed [`Serialize`].
52//!
53//! ```rust
54//! use std::borrow::Cow;
55//! use deser::ser::{Serialize, Chunk, StructEmitter, SerializeHandle};
56//! use deser::State;
57//! use deser::Error;
58//!
59//! struct User {
60//!     id: u32,
61//!     username: String,
62//! }
63//!
64//! impl Serialize for User {
65//!     fn serialize(&self, state: &mut State) -> Result<Chunk<'_>, Error> {
66//!         // the emitter is allocated in the arena of the serialization
67//!         Ok(Chunk::structure(UserEmitter { user: self, index: 0 }, state))
68//!     }
69//! }
70//!
71//! struct UserEmitter<'a> {
72//!     user: &'a User,
73//!     index: usize,
74//! }
75//!
76//! impl<'a> StructEmitter for UserEmitter<'a> {
77//!     fn next(
78//!         &mut self,
79//!         _state: &mut State,
80//!     ) -> Result<Option<(Cow<'_, str>, SerializeHandle<'_>)>, Error>
81//!     {
82//!         let index = self.index;
83//!         self.index += 1;
84//!         Ok(match index {
85//!             0 => Some(("id".into(), SerializeHandle::to(&self.user.id))),
86//!             1 => Some((
87//!                 "username".into(),
88//!                 SerializeHandle::to(&self.user.username),
89//!             )),
90//!             _ => None,
91//!         })
92//!     }
93//! }
94//! ```
95use alloc::borrow::Cow;
96use alloc::boxed::Box;
97use core::ops::Deref;
98
99use crate::State;
100use crate::error::Error;
101use crate::event::ContainerShape;
102
103pub(crate) mod begin;
104mod boxed;
105mod chunk;
106mod describe;
107mod driver;
108#[cfg(feature = "derive")]
109pub(crate) mod enums;
110#[cfg(feature = "derive")]
111pub(crate) mod flatten;
112pub(crate) mod impls;
113mod layer;
114mod serializer;
115mod stream;
116
117pub use self::boxed::Boxed;
118pub use self::chunk::Chunk;
119pub use self::describe::{Describe, Variant, VariantKind, VariantRepr};
120pub use self::layer::{Layer, Next};
121pub use self::serializer::Serializer;
122pub use self::stream::{StreamSerializer, Written};
123
124pub use driver::{EventSink, PausableSink, SerializeDriver};
125
126pub(crate) use self::begin::{
127    Begin, BeginKind, FIELDS_END, IndexedSeq, IndexedSeqEmitter, IndexedStruct, PLAIN_BUDGET,
128    PlainSink, StructField, atom_cost, plain_atom,
129};
130
131/// A handle to a [`Serialize`] type.
132///
133/// During serialization it common to be in a situation where one needs to
134/// return locally constructed [`Serialize`].  This is where
135/// [`SerializeHandle`] comes in.  In cases where the [`Serialize`] cannot
136/// be borrowed it can be boxed up inside the handle.
137///
138/// The equivalent for deserialization is the
139/// [`SinkHandle`](crate::de::SinkHandle).
140pub enum SerializeHandle<'a> {
141    /// A borrowed reference to a [`Serialize`].
142    Borrowed(&'a dyn Serialize),
143    /// A [`Serialize`] owned by the handle (see [`Boxed`]).
144    ///
145    /// Owned values must be `Send` so that the serialization can move
146    /// between threads.
147    Owned(Boxed<dyn Serialize + Send + 'a>),
148}
149
150impl<'a> Deref for SerializeHandle<'a> {
151    type Target = dyn Serialize + 'a;
152
153    fn deref(&self) -> &Self::Target {
154        match self {
155            SerializeHandle::Borrowed(val) => *val,
156            SerializeHandle::Owned(val) => &**val,
157        }
158    }
159}
160
161impl<'a> SerializeHandle<'a> {
162    /// Create a borrowed handle to a [`Serialize`].
163    pub fn to<S: Serialize + 'a>(val: &'a S) -> SerializeHandle<'a> {
164        SerializeHandle::Borrowed(val as &dyn Serialize)
165    }
166
167    /// Creates an owned handle to a value in the arena of the serialization.
168    ///
169    /// This is how owned values are typically created (for instance for
170    /// [`Chunk::Forward`]), see [`Boxed`].
171    #[inline(always)]
172    pub fn arena<S: Serialize + Send + 'a>(val: S, state: &mut State) -> SerializeHandle<'a> {
173        SerializeHandle::Owned(boxed::unsize(Boxed::arena(val, state), |x| {
174            x as *mut (dyn Serialize + Send + 'a)
175        }))
176    }
177
178    /// Creates an owned handle to a value on the heap.
179    ///
180    /// Unlike [`arena`](Self::arena) the value does not need a state and is
181    /// independent of any serialization.
182    pub fn heap<S: Serialize + Send + 'a>(val: S) -> SerializeHandle<'a> {
183        SerializeHandle::Owned(Boxed::from(Box::new(val) as Box<dyn Serialize + Send + 'a>))
184    }
185}
186
187/// A struct emitter.
188///
189/// A struct emitter is a simplified version of a [`MapEmitter`] which produces struct
190/// field and value in one go.  The object model itself however does not know structs,
191/// it only knows about maps.
192pub trait StructEmitter: Send {
193    /// Produces the next field and value in the struct.
194    fn next(
195        &mut self,
196        state: &mut State,
197    ) -> Result<Option<(Cow<'_, str>, SerializeHandle<'_>)>, Error>;
198}
199
200/// A map emitter.
201pub trait MapEmitter: Send {
202    /// Produces the next key in the map.
203    ///
204    /// If this reached the end of the map `None` shall be returned.  The expectation
205    /// is that this method changes an internal state in the emitter and the next
206    /// call to [`next_value`](Self::next_value) returns the corresponding value.
207    fn next_key(&mut self, state: &mut State) -> Result<Option<SerializeHandle<'_>>, Error>;
208
209    /// Produces the next value in the map.
210    ///
211    /// # Panics
212    ///
213    /// This method shall panic if the emitter is not able to produce a value because
214    /// the emitter is in the wrong state.
215    fn next_value(&mut self, state: &mut State) -> Result<SerializeHandle<'_>, Error>;
216}
217
218/// A sequence emitter.
219pub trait SeqEmitter: Send {
220    /// Produces the next item in the sequence.
221    fn next(&mut self, state: &mut State) -> Result<Option<SerializeHandle<'_>>, Error>;
222}
223
224/// A data structure that can be serialized into any data format supported by Deser.
225///
226/// [`serialize`](Self::serialize) serializes the value into a [`Chunk`].  For
227/// compound values like lists or similar, the piece contains a boxed emitter
228/// which can be further processed to walk the embedded compound value.  The
229/// [`container_shape`](Self::container_shape) of such values is passed on
230/// with the start event of the container.
231///
232/// # Thread Safety
233///
234/// Serializables are `Sync` and the emitters they create are `Send`.  This
235/// allows an ongoing serialization (a [`SerializeDriver`]) to move between
236/// threads, for instance when it is suspended while the output is written
237/// asynchronously.  Types with shared ownership or interior mutability that
238/// is not thread safe (such as `Rc` or `RefCell`) cannot be serialized.
239/// `Mutex` and `RwLock` cannot be serialized either as the lock guard would
240/// have to be held while the serialization moves between threads.
241pub trait Serialize: Sync {
242    /// Serializes this serializable.
243    fn serialize(&self, state: &mut State) -> Result<Chunk<'_>, Error>;
244
245    /// Invoked after the serialization finished.
246    ///
247    /// This is primarily useful to undo some state change in the serializer
248    /// state at the end of the processing.
249    fn finish(&self, _state: &mut State) -> Result<(), Error> {
250        Ok(())
251    }
252
253    /// Checks if the current value that would be serialized represents an
254    /// optional value.
255    ///
256    /// This can be used by an emitter to skip over values that are currently
257    /// in the optional state.  For instance `Option<T>` returns `true` here if
258    /// the value is `None` and the struct emitter created by the `derive` feature
259    /// will skip over these if `#[deser(skip_serializing_optionals)]` is set on
260    /// the struct.
261    fn is_optional(&self) -> bool {
262        false
263    }
264
265    /// Describes the Rust shape of this value.
266    ///
267    /// This is only invoked by formats which want to reflect the Rust shape
268    /// of values, see [`Describe`].  The default implementation describes
269    /// nothing.  Wrappers which serialize as the value they wrap should
270    /// describe themselves and then delegate to the wrapped value.
271    fn describe(&self, d: &mut dyn Describe) {
272        let _ = d;
273    }
274
275    /// Returns the shape of this value if it's a map or sequence.
276    ///
277    /// The shape is passed on with the [`MapStart`](crate::Event::MapStart)
278    /// or [`SeqStart`](crate::Event::SeqStart) event, it's ignored for other
279    /// values.  The default is [`ContainerShape::new`].
280    fn container_shape(&self) -> ContainerShape {
281        ContainerShape::new()
282    }
283
284    /// Begins the serialization of this value.
285    ///
286    /// Returns the [`container_shape`](Self::container_shape), the result of
287    /// [`serialize`](Self::serialize) and a flag that indicates if
288    /// [`finish`](Self::finish) needs to be invoked.  The default
289    /// implementation calls both methods (in this order) and always requests
290    /// `finish` to be invoked.  Types which do not override `finish` can
291    /// implement this so that the driver needs a single call per value.
292    #[doc(hidden)]
293    #[inline]
294    fn __private_begin(&self, state: &mut State) -> Result<Begin<'_>, Error> {
295        let shape = self.container_shape();
296        Ok(Begin::chunk(self.serialize(state)?, shape, true))
297    }
298
299    /// Returns `true` if the values of this type are plain.
300    ///
301    /// Plain values serialize as an atom or a sequence of plain values,
302    /// independent of the state and without `finish`.  The driver emits
303    /// sequences of plain values without driving every value on its own
304    /// (see [`PlainSink`]).  Types which are plain implement
305    /// [`__private_emit_plain`](Self::__private_emit_plain) which has to
306    /// produce the same events as serializing the value.
307    #[doc(hidden)]
308    #[inline]
309    fn __private_is_plain() -> bool
310    where
311        Self: Sized,
312    {
313        false
314    }
315
316    /// Returns `true` if this value is plain.
317    ///
318    /// This is `true` for all values of plain types and for some values
319    /// of other types, like empty sequences and maps or `None`.
320    #[doc(hidden)]
321    #[inline]
322    fn __private_is_plain_value(&self) -> bool
323    where
324        Self: Sized,
325    {
326        Self::__private_is_plain()
327    }
328
329    /// Emits the events of a plain value.
330    ///
331    /// This is only invoked if
332    /// [`__private_is_plain_value`](Self::__private_is_plain_value) returns
333    /// `true`.
334    #[doc(hidden)]
335    fn __private_emit_plain(&self, sink: &mut dyn PlainSink) -> Result<(), Error> {
336        let _ = sink;
337        unreachable!("not a plain value")
338    }
339
340    /// Returns the budget that is left after emitting this plain value at
341    /// once, `None` if it does not fit.
342    ///
343    /// Atoms cost one (long text and bytes more, see `atom_cost`),
344    /// containers one plus the costs of their values.  Values that are not
345    /// plain are not emitted at once, they cost one.  See `PLAIN_BUDGET`.
346    #[doc(hidden)]
347    #[inline]
348    fn __private_plain_cost(&self, budget: usize) -> Option<usize> {
349        budget.checked_sub(1)
350    }
351
352    /// Hidden internal trait method to allow specializations of bytes.
353    ///
354    /// This method is used by `u8` and `Vec<T>` / `&[T]` to achieve special
355    /// casing of bytes for the serialization system.  It allows a vector of
356    /// bytes to be emitted as `Chunk::Bytes` rather than a `Seq`.
357    #[doc(hidden)]
358    fn __private_slice_as_bytes(_val: &[Self]) -> Option<Cow<'_, [u8]>>
359    where
360        Self: Sized,
361    {
362        None
363    }
364}
365
366#[test]
367fn test_serialize() {
368    let mut v = Vec::new();
369    let mut m = alloc::collections::BTreeMap::new();
370    m.insert(true, vec![vec![&b"x"[..], b"yyy"], vec![b"zzzz"]]);
371    m.insert(false, vec![]);
372
373    let mut driver = SerializeDriver::new(&m);
374    while let Some((event, _, _)) = driver.next().unwrap() {
375        v.push(format!(
376            "{:?}",
377            crate::event::without_len(event.to_static())
378        ));
379    }
380
381    assert_eq!(
382        &v[..],
383        [
384            "MapStart(ContainerShape { len: None, order: Sorted })",
385            "Atom(Bool(false))",
386            "SeqStart",
387            "SeqEnd",
388            "Atom(Bool(true))",
389            "SeqStart",
390            "SeqStart",
391            "Atom(Bytes([120]))",
392            "Atom(Bytes([121, 121, 121]))",
393            "SeqEnd",
394            "SeqStart",
395            "Atom(Bytes([122, 122, 122, 122]))",
396            "SeqEnd",
397            "SeqEnd",
398            "MapEnd",
399        ]
400    );
401}