Skip to main content

deser_core/de/
deserializer.rs

1use crate::State;
2use crate::de::{Deserialize, DeserializeDriver, SinkHandle};
3use crate::error::{Error, ErrorKind};
4
5/// Deserializes values from an input.
6///
7/// This is implemented by the deserializers of the data formats (for
8/// instance `deser_json::Deserializer`) and by other sources of values
9/// (like the value type of `deser-value`).  A deserializer holds its input,
10/// every call deserializes the next value.  Deserializers implement
11/// [`drive`](Self::drive) which parses the input and feeds the events of a
12/// value into a driver.  The provided methods create the driver:
13///
14/// * [`deserialize`](Self::deserialize) deserializes a value.
15/// * [`deserialize_with`](Self::deserialize_with) deserializes a value and
16///   allows configuring the driver first, for instance to add
17///   [`Layer`](crate::de::Layer)s, to wrap the sink of the value or to
18///   give it a [`Context`](crate::Context).
19///
20/// ```
21/// use deser::de::{DeserializeDriver, Deserializer, Limits};
22/// use deser::{Context, Error, Event};
23///
24/// /// A format which reads comma separated numbers as a sequence.
25/// struct Numbers<'a>(&'a str);
26///
27/// impl<'de> Deserializer<'de> for Numbers<'de> {
28///     fn drive(
29///         &mut self,
30///         driver: &mut DeserializeDriver<'_, 'de>,
31///     ) -> Result<(), Error> {
32///         driver.emit(Event::seq_start())?;
33///         for item in self.0.split(',') {
34///             let value: u64 = item.trim().parse().map_err(|_| {
35///                 Error::new(deser::ErrorKind::Syntax, "invalid number")
36///             })?;
37///             driver.emit(value)?;
38///         }
39///         driver.emit(Event::SeqEnd)
40///     }
41/// }
42///
43/// let value: Vec<u32> = Numbers("1, 2, 3").deserialize().unwrap();
44/// assert_eq!(value, [1, 2, 3]);
45///
46/// let limits = Context::with(Limits::builder().max_items(2).build());
47/// let rv = Numbers("1, 2, 3")
48///     .deserialize_with::<Vec<u32>, _>(|driver| driver.set_context(limits.clone()));
49/// assert_eq!(rv.unwrap_err().to_string(), "LimitExceeded: too many items");
50/// ```
51pub trait Deserializer<'de> {
52    /// Parses the input and feeds the events of a value into the driver.
53    fn drive(&mut self, driver: &mut DeserializeDriver<'_, 'de>) -> Result<(), Error>;
54
55    /// Deserializes a value.
56    fn deserialize<T: Deserialize<'de>>(&mut self) -> Result<T, Error>
57    where
58        Self: Sized,
59    {
60        self.deserialize_with(|_| {})
61    }
62
63    /// Deserializes a value with a configured driver.
64    ///
65    /// The callback is invoked with the driver before the first event is
66    /// emitted.
67    fn deserialize_with<T, F>(&mut self, setup: F) -> Result<T, Error>
68    where
69        T: Deserialize<'de>,
70        F: FnOnce(&mut DeserializeDriver<'_, 'de>),
71        Self: Sized,
72    {
73        deserialize_value(|driver| {
74            setup(driver);
75            self.drive(driver)
76        })
77    }
78
79    /// Updates an existing value with the next value.
80    ///
81    /// See [`Deserialize::deserialize_update`].  If this fails, the value
82    /// might be partially updated.
83    fn update<T: Deserialize<'de>>(&mut self, value: &mut T) -> Result<(), Error>
84    where
85        Self: Sized,
86    {
87        self.update_with(value, |_| {})
88    }
89
90    /// Updates an existing value with the next value after setting up the
91    /// driver.
92    ///
93    /// This is like [`update`](Self::update) but the callback is invoked
94    /// with the driver first, like with
95    /// [`deserialize_with`](Self::deserialize_with).
96    fn update_with<T, F>(&mut self, value: &mut T, setup: F) -> Result<(), Error>
97    where
98        T: Deserialize<'de>,
99        F: FnOnce(&mut DeserializeDriver<'_, 'de>),
100        Self: Sized,
101    {
102        let mut driver = DeserializeDriver::update(value);
103        setup(&mut driver);
104        self.drive(&mut driver)
105    }
106}
107
108/// Deserializes a value with a function that drives a deserializer.
109///
110/// This creates a [`DeserializeDriver`] for the value, invokes `drive`
111/// with it and returns the value.  It does the same as
112/// [`Deserializer::deserialize`] and is how formats implement functions
113/// like `from_str`: if `drive` calls a function that is not generic over
114/// the value (which creates the format's deserializer and drives it), the
115/// code of the format exists once rather than once per type.
116///
117/// If no value was deserialized, an [`EndOfFile`](ErrorKind::EndOfFile)
118/// error is returned.
119///
120/// ```
121/// use deser::de::{Deserialize, DeserializeDriver, Deserializer, deserialize_value};
122/// use deser::{Error, ErrorKind, Event};
123///
124/// /// A format which reads comma separated numbers as a sequence.
125/// struct Numbers<'a>(&'a str);
126///
127/// impl<'de> Deserializer<'de> for Numbers<'de> {
128///     fn drive(&mut self, driver: &mut DeserializeDriver<'_, 'de>) -> Result<(), Error> {
129///         driver.emit(Event::seq_start())?;
130///         for item in self.0.split(',') {
131///             let value: u64 = item
132///                 .trim()
133///                 .parse()
134///                 .map_err(|_| Error::new(ErrorKind::Syntax, "invalid number"))?;
135///             driver.emit(value)?;
136///         }
137///         driver.emit(Event::SeqEnd)
138///     }
139/// }
140///
141/// /// Deserializes a value from comma separated numbers.
142/// pub fn from_str<'de, T: Deserialize<'de>>(s: &'de str) -> Result<T, Error> {
143///     deserialize_value(|driver| drive_str(s, driver))
144/// }
145///
146/// /// The part of `from_str` that does not depend on the type of the value.
147/// fn drive_str<'de>(s: &'de str, driver: &mut DeserializeDriver<'_, 'de>) -> Result<(), Error> {
148///     Numbers(s).drive(driver)
149/// }
150///
151/// let value: Vec<u32> = from_str("1, 2, 3").unwrap();
152/// assert_eq!(value, [1, 2, 3]);
153/// ```
154#[inline]
155pub fn deserialize_value<'de, T: Deserialize<'de>>(
156    drive: impl FnOnce(&mut DeserializeDriver<'_, 'de>) -> Result<(), Error>,
157) -> Result<T, Error> {
158    // only creating the sink and taking the value depend on the type, the
159    // driver is created, run and dropped by a function that exists once.
160    let mut out = None;
161    let mut slot = Some(&mut out);
162    let mut drive = Some(drive);
163    drive_new(
164        &mut |state| match slot.take() {
165            Some(slot) => {
166                // the top-level value is requested before it starts
167                state.raw_requested = T::__private_raw();
168                T::deserialize_into(slot, state)
169            }
170            None => called_twice(),
171        },
172        &mut |driver| match drive.take() {
173            Some(drive) => drive(driver),
174            None => called_twice(),
175        },
176    )?;
177    out.ok_or_else(empty_input)
178}
179
180/// Creates a driver with the sink `make` creates and runs `drive` with it.
181#[inline(never)]
182fn drive_new<'out, 'de>(
183    make: &mut dyn FnMut(&mut State) -> SinkHandle<'out, 'de>,
184    drive: &mut dyn FnMut(&mut DeserializeDriver<'_, 'de>) -> Result<(), Error>,
185) -> Result<(), Error> {
186    let mut state = State::new();
187    let sink = make(&mut state);
188    drive(&mut DeserializeDriver::from_state(state, sink))
189}
190
191#[cold]
192#[inline(never)]
193fn called_twice() -> ! {
194    panic!("deserialize_value called a function twice")
195}
196
197#[cold]
198fn empty_input() -> Error {
199    Error::new(ErrorKind::EndOfFile, "empty input")
200}