Skip to main content

deser_core/ser/
layer.rs

1use crate::State;
2use crate::error::Error;
3use crate::event::Event;
4use crate::ser::SerializeRef;
5use alloc::boxed::Box;
6
7/// The function that receives the events of a [`SerializeDriver`](crate::ser::SerializeDriver).
8pub(crate) type EventFn<'f> =
9    dyn FnMut(Event<'_>, SerializeRef<'_>, &mut State) -> Result<(), Error> + 'f;
10
11/// A layer between the serialization and a format.
12///
13/// Layers are added to a [`SerializeDriver`](crate::ser::SerializeDriver)
14/// with [`push_layer`](crate::ser::SerializeDriver::push_layer) and see
15/// every event produced by the serialized values before the format receives
16/// it.  A layer receives the event together with a [`Next`] which passes
17/// events on to the next layer (or the format).  This way a layer can
18/// observe events and track information in the [`State`] (which the
19/// [`Serialize`](crate::ser::Serialize) implementations of the values that
20/// follow can access), reject, change or drop events or emit additional
21/// events.
22///
23/// Layers are only applied by [`drive`](crate::ser::SerializeDriver::drive).
24///
25/// ```
26/// use deser::ser::{Layer, Next, SerializeDriver};
27/// use deser::{Atom, Error, Event};
28///
29/// /// Upper cases all map keys.
30/// struct UppercaseKeys;
31///
32/// impl Layer for UppercaseKeys {
33///     fn event(
34///         &mut self,
35///         event: Event<'_>,
36///         next: &mut Next<'_>,
37///     ) -> Result<(), Error> {
38///         match event {
39///             Event::Atom(Atom::Str(key)) if next.state().is_map_key() => {
40///                 next.emit(Event::from(key.to_uppercase()))
41///             }
42///             event => next.emit(event),
43///         }
44///     }
45/// }
46///
47/// let mut map = std::collections::BTreeMap::new();
48/// map.insert("key", "value");
49/// let mut events = Vec::new();
50/// let mut driver = SerializeDriver::new(&map);
51/// driver.push_layer(UppercaseKeys);
52/// driver.drive(|event, _| {
53///     events.push(event.to_static());
54///     Ok(())
55/// }).unwrap();
56/// assert_eq!(events.len(), 4);
57/// assert_eq!(events[1], "KEY".into());
58/// ```
59///
60/// # Changing the Events
61///
62/// Layers that emit events other than the one they received should take
63/// care of the [`State`]: the next layers and the format see the state as
64/// it is when the event is emitted.  For instance a layer which delays an
65/// event emits it with the [event data](State::event) of the event that is
66/// current when it's emitted.  Map keys that are emitted at another time
67/// have to be emitted with [`Next::emit_key`] so that they are recognized
68/// as map keys (see [`State::is_map_key`]).
69///
70/// All events a layer emits are passed on with the value of the event the
71/// layer received (see [`Next::value`]), so that formats that
72/// [describe](crate::ser::Describe) values see the description of the
73/// original value.
74pub trait Layer: Send {
75    /// Processes an event.
76    ///
77    /// To pass the event on, invoke [`Next::emit`].
78    fn event(&mut self, event: Event<'_>, next: &mut Next<'_>) -> Result<(), Error>;
79}
80
81/// Passes events on to the next [`Layer`].
82///
83/// The last layer passes the events on to the format.
84pub struct Next<'n> {
85    layers: &'n mut [Box<dyn Layer>],
86    state: &'n mut State,
87    f: &'n mut EventFn<'n>,
88    value: SerializeRef<'n>,
89}
90
91impl<'n> Next<'n> {
92    #[inline(always)]
93    pub(crate) fn new(
94        layers: &'n mut [Box<dyn Layer>],
95        state: &'n mut State,
96        f: &'n mut EventFn<'n>,
97        value: SerializeRef<'n>,
98    ) -> Next<'n> {
99        Next {
100            layers,
101            state,
102            f,
103            value,
104        }
105    }
106
107    /// Returns the value of the current event.
108    ///
109    /// This is only useful to [describe](crate::ser::Describe) the value.
110    /// If the driver does not pass on values (see
111    /// [`EventSink::DESCRIBED`](crate::ser::EventSink::DESCRIBED)), this is
112    /// a value that describes nothing.
113    pub fn value(&self) -> SerializeRef<'_> {
114        self.value
115    }
116
117    /// Returns the state.
118    pub fn state(&self) -> &State {
119        self.state
120    }
121
122    /// Returns the state mutably.
123    pub fn state_mut(&mut self) -> &mut State {
124        self.state
125    }
126
127    /// Passes an event on as map key.
128    ///
129    /// This is like [`emit`](Self::emit) but the event is passed on with
130    /// [`State::is_map_key`] set.  This is useful for layers which hold back
131    /// map keys and emit them later, when the state already describes the
132    /// value.
133    pub fn emit_key(&mut self, event: Event<'_>) -> Result<(), Error> {
134        let was_key = core::mem::replace(&mut self.state.is_map_key, true);
135        let rv = self.emit(event);
136        self.state.is_map_key = was_key;
137        rv
138    }
139
140    /// Passes an event on.
141    ///
142    /// This can be invoked any number of times per event.
143    pub fn emit(&mut self, event: Event<'_>) -> Result<(), Error> {
144        match self.layers.split_first_mut() {
145            Some((layer, rest)) => layer.event(
146                event,
147                &mut Next {
148                    layers: rest,
149                    state: self.state,
150                    f: self.f,
151                    value: self.value,
152                },
153            ),
154            None => (self.f)(event, self.value, self.state),
155        }
156    }
157}