Skip to main content

deser_core/de/
layer.rs

1use crate::State;
2use crate::de::driver::DriverCore;
3use crate::error::Error;
4use crate::event::Event;
5use alloc::boxed::Box;
6
7/// A layer between a format and the sinks.
8///
9/// Layers are added to a [`DeserializeDriver`](crate::de::DeserializeDriver)
10/// with [`push_layer`](crate::de::DeserializeDriver::push_layer), usually in
11/// the setup callback of
12/// [`Deserializer::deserialize_with`](crate::de::Deserializer::deserialize_with).  Every
13/// event that is emitted into the driver passes through the layers before
14/// it's delivered to the sinks.  A layer receives the event together with
15/// a [`Next`] which passes events on to the next layer (or the sinks).  This
16/// way a layer can:
17///
18/// * observe events and track information in the [`State`] (for instance
19///   the current path),
20/// * reject events by returning an error (for instance to enforce limits),
21/// * change events, drop them or emit additional events,
22/// * act on the result of the events that it passed on.
23///
24/// The position of the event is known when a layer is invoked:
25/// [`State::is_map_key`] tells if the event is (the start of) a map key
26/// and [`State::depth`] is the number of open containers.
27///
28/// ```
29/// use deser::de::{Deserializer, Layer, LayerEvent, Next};
30/// use deser::{Atom, Error, Event};
31///
32/// /// Upper cases all strings that are not map keys.
33/// struct Uppercase;
34///
35/// impl Layer for Uppercase {
36///     fn event<'de>(
37///         &mut self,
38///         event: LayerEvent<'_, 'de>,
39///         next: &mut Next<'_, 'de>,
40///     ) -> Result<(), Error> {
41///         match event.event() {
42///             Event::Atom(Atom::Str(s)) if !next.state().is_map_key() => {
43///                 next.emit(LayerEvent::new(Event::from(s.to_uppercase())))
44///             }
45///             _ => next.emit(event),
46///         }
47///     }
48/// }
49///
50/// let words: Vec<String> = deser_json::Deserializer::from_str(r#"["hello", "world"]"#)
51///     .deserialize_with(|driver| driver.push_layer(Uppercase))
52///     .unwrap();
53/// assert_eq!(words, ["HELLO", "WORLD"]);
54/// ```
55///
56/// # Buffered Values
57///
58/// Some types buffer values and replay them later (see
59/// [`Recording`](crate::de::Recording)).  Replayed events do not pass
60/// through the layers again as they already did when they were recorded,
61/// this means that changes made by layers are retained and not applied
62/// twice.  Information that layers keep in the state and that is needed
63/// for replayed values should be kept in replayable extensions (see
64/// [`State::set_replayable`]) which are captured with the events.
65pub trait Layer: Send {
66    /// Processes an event.
67    ///
68    /// To pass the event on, invoke [`Next::emit`].
69    fn event<'de>(
70        &mut self,
71        event: LayerEvent<'_, 'de>,
72        next: &mut Next<'_, 'de>,
73    ) -> Result<(), Error>;
74}
75
76/// An event that passes through the [`Layer`]s.
77///
78/// Events emitted with
79/// [`emit_borrowed`](crate::de::DeserializeDriver::emit_borrowed) borrow
80/// from the data that is deserialized for `'de`, other events are only
81/// valid for `'e`.  Layers that pass on the event they received retain
82/// this.
83pub struct LayerEvent<'e, 'de>(Repr<'e, 'de>);
84
85enum Repr<'e, 'de> {
86    Borrowed(Event<'de>),
87    Transient(Event<'e>),
88}
89
90impl<'e, 'de> LayerEvent<'e, 'de> {
91    /// Creates an event that is only valid for `'e`.
92    #[inline(always)]
93    pub fn new(event: Event<'e>) -> LayerEvent<'e, 'de> {
94        LayerEvent(Repr::Transient(event))
95    }
96
97    /// Creates an event that borrows from the data being deserialized.
98    #[inline(always)]
99    pub fn borrowed(event: Event<'de>) -> LayerEvent<'e, 'de> {
100        LayerEvent(Repr::Borrowed(event))
101    }
102
103    /// Returns the event.
104    #[inline(always)]
105    pub fn event(&self) -> &Event<'_> {
106        match self.0 {
107            Repr::Borrowed(ref event) => event,
108            Repr::Transient(ref event) => event,
109        }
110    }
111
112    /// Returns `true` if the event borrows from the data being deserialized.
113    pub fn is_borrowed(&self) -> bool {
114        matches!(self.0, Repr::Borrowed(_))
115    }
116}
117
118/// Passes events on to the next [`Layer`].
119///
120/// The last layer passes the events on to the sinks.
121pub struct Next<'n, 'de> {
122    layers: &'n mut [Box<dyn Layer>],
123    core: &'n mut DriverCore<'de>,
124}
125
126impl<'n, 'de> Next<'n, 'de> {
127    #[inline(always)]
128    pub(crate) fn new(layers: &'n mut [Box<dyn Layer>], core: &'n mut DriverCore<'de>) -> Self {
129        Next { layers, core }
130    }
131
132    /// Returns the state.
133    pub fn state(&self) -> &State {
134        &self.core.state
135    }
136
137    /// Returns the state mutably.
138    pub fn state_mut(&mut self) -> &mut State {
139        &mut self.core.state
140    }
141
142    /// Passes an event on.
143    ///
144    /// This can be invoked any number of times per event.  Events that were
145    /// passed on get the same input range (see
146    /// [`State::input_range`]) and event data (see [`State::event`]),
147    /// unless the layer changes them in the state.
148    pub fn emit(&mut self, event: LayerEvent<'_, 'de>) -> Result<(), Error> {
149        self.core.update_position(event.event());
150        match self.layers.split_first_mut() {
151            Some((layer, rest)) => layer.event(event, &mut Next::new(rest, self.core)),
152            None => match event.0 {
153                Repr::Borrowed(event) => self.core.dispatch_borrowed(event),
154                Repr::Transient(event) => self.core.dispatch(event),
155            },
156        }
157    }
158}