miniserde/de/
mod.rs

1//! Deserialization traits.
2//!
3//! Deserialization in miniserde works by returning a "place" into which data
4//! may be written through the methods of the `Visitor` trait object.
5//!
6//! Use the `make_place!` macro to acquire a "place" type. A library may use a
7//! single place type across all of its Deserialize impls, or each impl or each
8//! module may use a private place type. There is no difference.
9//!
10//! A place is simply:
11//!
12//! ```rust
13//! struct Place<T> {
14//!     out: Option<T>,
15//! }
16//! ```
17//!
18//! Upon successful deserialization the output object is written as `Some(T)`
19//! into the `out` field of the place.
20//!
21//! ## Deserializing a primitive
22//!
23//! The Visitor trait has a method corresponding to each supported primitive
24//! type.
25//!
26//! ```rust
27//! use miniserde::{make_place, Result};
28//! use miniserde::de::{Deserialize, Visitor};
29//!
30//! make_place!(Place);
31//!
32//! struct MyBoolean(bool);
33//!
34//! // The Visitor trait has a selection of methods corresponding to different
35//! // data types. We override the ones that our Rust type supports
36//! // deserializing from, and write the result into the `out` field of our
37//! // output place.
38//! //
39//! // These methods may perform validation and decide to return an error.
40//! impl Visitor for Place<MyBoolean> {
41//!     fn boolean(&mut self, b: bool) -> Result<()> {
42//!         self.out = Some(MyBoolean(b));
43//!         Ok(())
44//!     }
45//! }
46//!
47//! impl Deserialize for MyBoolean {
48//!     fn begin(out: &mut Option<Self>) -> &mut dyn Visitor {
49//!         // All Deserialize impls will look exactly like this. There is no
50//!         // other correct implementation of Deserialize.
51//!         Place::new(out)
52//!     }
53//! }
54//! ```
55//!
56//! ## Deserializing a sequence
57//!
58//! In the case of a sequence (JSON array), the visitor method returns a builder
59//! that can hand out places to write sequence elements one element at a time.
60//!
61//! ```rust
62//! use miniserde::{make_place, Result};
63//! use miniserde::de::{Deserialize, Seq, Visitor};
64//! use std::mem;
65//!
66//! make_place!(Place);
67//!
68//! struct MyVec<T>(Vec<T>);
69//!
70//! impl<T> Visitor for Place<MyVec<T>>
71//! where
72//!     T: Deserialize,
73//! {
74//!     fn seq(&mut self) -> Result<Box<dyn Seq + '_>> {
75//!         Ok(Box::new(VecBuilder {
76//!             out: &mut self.out,
77//!             vec: Vec::new(),
78//!             element: None,
79//!         }))
80//!     }
81//! }
82//!
83//! struct VecBuilder<'a, T: 'a> {
84//!     // At the end, output will be written here.
85//!     out: &'a mut Option<MyVec<T>>,
86//!     // Previous elements are accumulated here.
87//!     vec: Vec<T>,
88//!     // Next element will be placed here.
89//!     element: Option<T>,
90//! }
91//!
92//! impl<'a, T> Seq for VecBuilder<'a, T>
93//! where
94//!     T: Deserialize,
95//! {
96//!     fn element(&mut self) -> Result<&mut dyn Visitor> {
97//!         // Free up the place by transferring the most recent element
98//!         // into self.vec.
99//!         self.vec.extend(self.element.take());
100//!         // Hand out a place to write the next element.
101//!         Ok(Deserialize::begin(&mut self.element))
102//!     }
103//!
104//!     fn finish(&mut self) -> Result<()> {
105//!         // Transfer the last element.
106//!         self.vec.extend(self.element.take());
107//!         // Move the output object into self.out.
108//!         let vec = mem::replace(&mut self.vec, Vec::new());
109//!         *self.out = Some(MyVec(vec));
110//!         Ok(())
111//!     }
112//! }
113//!
114//! impl<T> Deserialize for MyVec<T>
115//! where
116//!     T: Deserialize,
117//! {
118//!     fn begin(out: &mut Option<Self>) -> &mut dyn Visitor {
119//!         // As mentioned, all Deserialize impls will look like this.
120//!         Place::new(out)
121//!     }
122//! }
123//! ```
124//!
125//! ## Deserializing a map or struct
126//!
127//! This code demonstrates what is generated for structs by
128//! `#[derive(Deserialize)]`.
129//!
130//! ```rust
131//! use miniserde::{make_place, Result};
132//! use miniserde::de::{Deserialize, Map, Visitor};
133//!
134//! make_place!(Place);
135//!
136//! // The struct that we would like to deserialize.
137//! struct Demo {
138//!     code: u32,
139//!     message: String,
140//! }
141//!
142//! impl Visitor for Place<Demo> {
143//!     fn map(&mut self) -> Result<Box<dyn Map + '_>> {
144//!         // Like for sequences, we produce a builder that can hand out places
145//!         // to write one struct field at a time.
146//!         Ok(Box::new(DemoBuilder {
147//!             code: None,
148//!             message: None,
149//!             out: &mut self.out,
150//!         }))
151//!     }
152//! }
153//!
154//! struct DemoBuilder<'a> {
155//!     code: Option<u32>,
156//!     message: Option<String>,
157//!     out: &'a mut Option<Demo>,
158//! }
159//!
160//! impl<'a> Map for DemoBuilder<'a> {
161//!     fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
162//!         // Figure out which field is being deserialized and return a place
163//!         // to write it.
164//!         //
165//!         // The code here ignores unrecognized fields but an implementation
166//!         // would be free to return an error instead. Similarly an
167//!         // implementation may want to check for duplicate fields by
168//!         // returning an error if the current field already has a value.
169//!         match k {
170//!             "code" => Ok(Deserialize::begin(&mut self.code)),
171//!             "message" => Ok(Deserialize::begin(&mut self.message)),
172//!             _ => Ok(<dyn Visitor>::ignore()),
173//!         }
174//!     }
175//!
176//!     fn finish(&mut self) -> Result<()> {
177//!         // Make sure we have every field and then write the output object
178//!         // into self.out.
179//!         let code = self.code.take().ok_or(miniserde::Error)?;
180//!         let message = self.message.take().ok_or(miniserde::Error)?;
181//!         *self.out = Some(Demo { code, message });
182//!         Ok(())
183//!     }
184//! }
185//!
186//! impl Deserialize for Demo {
187//!     fn begin(out: &mut Option<Self>) -> &mut dyn Visitor {
188//!         // All Deserialize impls look like this.
189//!         Place::new(out)
190//!     }
191//! }
192//! ```
193
194mod impls;
195
196use crate::error::{Error, Result};
197use alloc::boxed::Box;
198
199/// Trait for data structures that can be deserialized from a JSON string.
200///
201/// [Refer to the module documentation for examples.][crate::de]
202pub trait Deserialize: Sized {
203    /// The only correct implementation of this method is:
204    ///
205    /// ```rust
206    /// # use miniserde::make_place;
207    /// # use miniserde::de::{Deserialize, Visitor};
208    /// #
209    /// # make_place!(Place);
210    /// # struct S;
211    /// # impl Visitor for Place<S> {}
212    /// #
213    /// # impl Deserialize for S {
214    /// fn begin(out: &mut Option<Self>) -> &mut dyn Visitor {
215    ///     Place::new(out)
216    /// }
217    /// # }
218    /// ```
219    fn begin(out: &mut Option<Self>) -> &mut dyn Visitor;
220
221    // Not public API. This method is only intended for Option<T>, should not
222    // need to be implemented outside of this crate.
223    #[doc(hidden)]
224    #[inline]
225    fn default() -> Option<Self> {
226        None
227    }
228}
229
230/// Trait that can write data into an output place.
231///
232/// [Refer to the module documentation for examples.][crate::de]
233pub trait Visitor {
234    fn null(&mut self) -> Result<()> {
235        Err(Error)
236    }
237
238    fn boolean(&mut self, b: bool) -> Result<()> {
239        let _ = b;
240        Err(Error)
241    }
242
243    fn string(&mut self, s: &str) -> Result<()> {
244        let _ = s;
245        Err(Error)
246    }
247
248    fn negative(&mut self, n: i64) -> Result<()> {
249        let _ = n;
250        Err(Error)
251    }
252
253    fn nonnegative(&mut self, n: u64) -> Result<()> {
254        let _ = n;
255        Err(Error)
256    }
257
258    fn float(&mut self, n: f64) -> Result<()> {
259        let _ = n;
260        Err(Error)
261    }
262
263    fn seq(&mut self) -> Result<Box<dyn Seq + '_>> {
264        Err(Error)
265    }
266
267    fn map(&mut self) -> Result<Box<dyn Map + '_>> {
268        Err(Error)
269    }
270}
271
272/// Trait that can hand out places to write sequence elements.
273///
274/// [Refer to the module documentation for examples.][crate::de]
275pub trait Seq {
276    fn element(&mut self) -> Result<&mut dyn Visitor>;
277    fn finish(&mut self) -> Result<()>;
278}
279
280/// Trait that can hand out places to write values of a map.
281///
282/// [Refer to the module documentation for examples.][crate::de]
283pub trait Map {
284    fn key(&mut self, k: &str) -> Result<&mut dyn Visitor>;
285    fn finish(&mut self) -> Result<()>;
286}