deser/ser/
chunk.rs

1use std::borrow::Cow;
2
3use crate::event::Atom;
4use crate::ser::{MapEmitter, SeqEmitter, StructEmitter};
5
6/// A chunk represents the minimum state necessary to serialize a value.
7///
8/// Chunks are of two types: atomic primitives and stateful emitters.
9/// For instance `Chunk::Bool(true)` is an atomic primitive.  It can be emitted
10/// to a serializer directly.  On the other hand a `Chunk::Map` contains a
11/// stateful emitter that keeps yielding values until it's done walking over
12/// the map.
13pub enum Chunk<'a> {
14    Atom(Atom<'a>),
15    Struct(Box<dyn StructEmitter + 'a>),
16    Map(Box<dyn MapEmitter + 'a>),
17    Seq(Box<dyn SeqEmitter + 'a>),
18}
19
20impl<'a> From<Atom<'a>> for Chunk<'a> {
21    fn from(atom: Atom<'a>) -> Self {
22        Chunk::Atom(atom)
23    }
24}
25
26macro_rules! impl_from {
27    ($ty:ty, $atom:ident) => {
28        impl From<$ty> for Chunk<'static> {
29            fn from(value: $ty) -> Self {
30                Chunk::Atom(Atom::$atom(value as _))
31            }
32        }
33    };
34}
35
36impl_from!(u64, U64);
37impl_from!(i64, I64);
38impl_from!(f64, F64);
39impl_from!(usize, U64);
40impl_from!(isize, I64);
41impl_from!(bool, Bool);
42impl_from!(char, Char);
43
44impl From<()> for Chunk<'static> {
45    fn from(_: ()) -> Chunk<'static> {
46        Chunk::Atom(Atom::Null)
47    }
48}
49
50impl<'a> From<&'a str> for Chunk<'a> {
51    fn from(value: &'a str) -> Chunk<'a> {
52        Chunk::Atom(Atom::Str(Cow::Borrowed(value)))
53    }
54}
55
56impl<'a> From<&'a [u8]> for Chunk<'a> {
57    fn from(value: &'a [u8]) -> Chunk<'a> {
58        Chunk::Atom(Atom::Bytes(Cow::Borrowed(value)))
59    }
60}
61
62impl From<String> for Chunk<'static> {
63    fn from(value: String) -> Chunk<'static> {
64        Chunk::Atom(Atom::Str(Cow::Owned(value)))
65    }
66}