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