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