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 or to wrap the sink of the value.
18///
19/// ```
20/// use deser::de::{DeserializeDriver, Deserializer, Limits};
21/// use deser::{Error, Event};
22///
23/// /// A format which reads comma separated numbers as a sequence.
24/// struct Numbers<'a>(&'a str);
25///
26/// impl<'de> Deserializer<'de> for Numbers<'de> {
27/// fn drive(
28/// &mut self,
29/// driver: &mut DeserializeDriver<'_, 'de>,
30/// ) -> Result<(), Error> {
31/// driver.emit(Event::seq_start())?;
32/// for item in self.0.split(',') {
33/// let value: u64 = item.trim().parse().map_err(|_| {
34/// Error::new(deser::ErrorKind::Unexpected, "invalid number")
35/// })?;
36/// driver.emit(value)?;
37/// }
38/// driver.emit(Event::SeqEnd)
39/// }
40/// }
41///
42/// let value: Vec<u32> = Numbers("1, 2, 3").deserialize().unwrap();
43/// assert_eq!(value, [1, 2, 3]);
44///
45/// let rv = Numbers("1, 2, 3").deserialize_with::<Vec<u32>, _>(|driver| {
46/// driver.push_layer(Limits::new().max_items(2));
47/// });
48/// assert_eq!(rv.unwrap_err().to_string(), "Unexpected: too many items");
49/// ```
50pub trait Deserializer<'de> {
51 /// Parses the input and feeds the events of a value into the driver.
52 fn drive(&mut self, driver: &mut DeserializeDriver<'_, 'de>) -> Result<(), Error>;
53
54 /// Deserializes a value.
55 fn deserialize<T: Deserialize<'de>>(&mut self) -> Result<T, Error>
56 where
57 Self: Sized,
58 {
59 self.deserialize_with(|_| {})
60 }
61
62 /// Deserializes a value with a configured driver.
63 ///
64 /// The callback is invoked with the driver before the first event is
65 /// emitted.
66 fn deserialize_with<T, F>(&mut self, setup: F) -> Result<T, Error>
67 where
68 T: Deserialize<'de>,
69 F: FnOnce(&mut DeserializeDriver<'_, 'de>),
70 Self: Sized,
71 {
72 // only creating the sink and taking the value depend on the type,
73 // the driver is created and run by a function that exists once.
74 let mut setup = Some(setup);
75 deserialize_value(|make_sink| {
76 drive_new(self, make_sink, &mut |driver| {
77 if let Some(setup) = setup.take() {
78 setup(driver);
79 }
80 })
81 })
82 }
83
84 /// Updates an existing value with the next value.
85 ///
86 /// See [`Deserialize::deserialize_update`]. If this fails, the value
87 /// might be partially updated.
88 fn update<T: Deserialize<'de>>(&mut self, value: &mut T) -> Result<(), Error>
89 where
90 Self: Sized,
91 {
92 self.update_with(value, |_| {})
93 }
94
95 /// Updates an existing value with the next value after setting up the
96 /// driver.
97 ///
98 /// This is like [`update`](Self::update) but the callback is invoked
99 /// with the driver first, like with
100 /// [`deserialize_with`](Self::deserialize_with).
101 fn update_with<T, F>(&mut self, value: &mut T, setup: F) -> Result<(), Error>
102 where
103 T: Deserialize<'de>,
104 F: FnOnce(&mut DeserializeDriver<'_, 'de>),
105 Self: Sized,
106 {
107 let mut driver = DeserializeDriver::update(value);
108 setup(&mut driver);
109 self.drive(&mut driver)
110 }
111}
112
113/// Creates the sink of the value that is deserialized.
114///
115/// See [`deserialize_value`], it's called once.
116pub type MakeSink<'m, 'out, 'de> = dyn FnMut(&mut State) -> SinkHandle<'out, 'de> + 'm;
117
118/// Deserializes a value with a function that drives a deserializer into
119/// its sink.
120///
121/// `drive` receives the function that creates the sink and passes it to
122/// [`drive_value`] (or does what it does). This keeps everything that does
123/// not depend on the type of the value out of the code that exists once per
124/// type: formats implement functions like `from_str` with it and a function
125/// that creates their deserializer and is not generic.
126#[inline]
127pub fn deserialize_value<'de, T: Deserialize<'de>>(
128 drive: impl for<'out> FnOnce(&mut MakeSink<'_, 'out, 'de>) -> Result<(), Error>,
129) -> Result<T, Error> {
130 let mut out = None;
131 {
132 let mut slot = Some(&mut out);
133 drive(&mut |state| match slot.take() {
134 Some(slot) => T::deserialize_into(slot, state),
135 None => panic!("the sink of a value was created twice"),
136 })?;
137 }
138 out.ok_or_else(empty_input)
139}
140
141/// Drives a deserializer into the sink of a value (see
142/// [`deserialize_value`]).
143#[inline(never)]
144pub fn drive_value<'out, 'de>(
145 de: &mut dyn Deserializer<'de>,
146 make_sink: &mut MakeSink<'_, 'out, 'de>,
147) -> Result<(), Error> {
148 drive_new(de, make_sink, &mut |_| {})
149}
150
151/// Creates the state and the sink and drives a deserializer into it.
152#[inline(never)]
153fn drive_new<'out, 'de>(
154 de: &mut dyn Deserializer<'de>,
155 make_sink: &mut MakeSink<'_, 'out, 'de>,
156 setup: &mut dyn FnMut(&mut DeserializeDriver<'_, 'de>),
157) -> Result<(), Error> {
158 let mut state = State::new();
159 let sink = make_sink(&mut state);
160 let mut driver = DeserializeDriver::from_state(state, sink);
161 setup(&mut driver);
162 de.drive(&mut driver)
163}
164
165#[cold]
166fn empty_input() -> Error {
167 Error::new(ErrorKind::EndOfFile, "empty input")
168}