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 out = None;
75 let mut setup = Some(setup);
76 let mut state = State::new();
77 let sink = T::deserialize_into(&mut out, &mut state);
78 drive_sink(self, state, sink, &mut |driver| {
79 if let Some(setup) = setup.take() {
80 setup(driver);
81 }
82 })?;
83 out.ok_or_else(empty_input)
84 }
85
86 /// Updates an existing value with the next value.
87 ///
88 /// See [`Deserialize::deserialize_update`]. If this fails, the value
89 /// might be partially updated.
90 fn update<T: Deserialize<'de>>(&mut self, value: &mut T) -> Result<(), Error>
91 where
92 Self: Sized,
93 {
94 self.update_with(value, |_| {})
95 }
96
97 /// Updates an existing value with the next value after setting up the
98 /// driver.
99 ///
100 /// This is like [`update`](Self::update) but the callback is invoked
101 /// with the driver first, like with
102 /// [`deserialize_with`](Self::deserialize_with).
103 fn update_with<T, F>(&mut self, value: &mut T, setup: F) -> Result<(), Error>
104 where
105 T: Deserialize<'de>,
106 F: FnOnce(&mut DeserializeDriver<'_, 'de>),
107 Self: Sized,
108 {
109 let mut driver = DeserializeDriver::update(value);
110 setup(&mut driver);
111 self.drive(&mut driver)
112 }
113}
114
115/// Drives a deserializer into a sink.
116#[inline(never)]
117fn drive_sink<'de>(
118 de: &mut dyn Deserializer<'de>,
119 state: State,
120 sink: SinkHandle<'_, 'de>,
121 setup: &mut dyn FnMut(&mut DeserializeDriver<'_, 'de>),
122) -> Result<(), Error> {
123 let mut driver = DeserializeDriver::from_state(state, sink);
124 setup(&mut driver);
125 de.drive(&mut driver)
126}
127
128#[cold]
129fn empty_input() -> Error {
130 Error::new(ErrorKind::EndOfFile, "empty input")
131}