Skip to main content

destream/de/
mod.rs

1//! Stream deserialization framework with an interface based on `serde::de`.
2//!
3//! The two most important traits in this module are [`FromStream`] and [`Decoder`].
4//!
5//! - **A type that implements [`FromStream`] is a data structure** that can be decoded from any
6//!   stream encoding supported by `destream`, and conversely
7//! - **A type that implements `Decoder` is a data format** that can decode any supported stream.
8//!
9//! # The FromStream trait
10//!
11//! `destream` implements [`FromStream`] for many Rust primitive and standard library types.
12//! The complete list is below.
13//!
14//! # Implementations of FromStream provided by destream
15//!
16//!  - **Primitive types**:
17//!    - ()
18//!    - bool
19//!    - i8, i16, i32, i64
20//!    - u8, u16, u32, u64, usize
21//!    - f32, f64
22//!  - **Compound types**:
23//!    - \[T; 0\] through \[T; 32\]
24//!    - tuples up to size 16
25//!  - **Common standard library types**:
26//!    - String
27//!    - Option\<T\>
28//!    - PhantomData\<T\>
29//!  - **Other common types**:
30//!    - Bytes
31//!    - Uuid
32//!  - **Collection types**:
33//!    - BTreeMap\<K, V\>
34//!    - BTreeSet\<T\>
35//!    - BinaryHeap\<T\>
36//!    - HashMap\<K, V, H\>
37//!    - HashSet\<T, H\>
38//!    - LinkedList\<T\>
39//!    - VecDeque\<T\>
40//!    - Vec\<T\>
41//!
42//! Enable support for `SmallVec` using the `smallvec` feature flag.
43
44use std::fmt;
45
46mod impls;
47
48mod size_hint {
49    use std::cmp;
50
51    #[inline]
52    pub fn cautious(hint: Option<usize>) -> usize {
53        cmp::min(hint.unwrap_or(0), 4096)
54    }
55}
56
57/// The `Error` trait allows [`FromStream`] implementations to create descriptive
58/// error messages belonging to their [`Decoder`] context.
59///
60/// Most implementors should only need to provide the `Error::custom` method
61/// and inherit the default behavior for the other methods.
62///
63/// Based on `serde::de::Error`.
64pub trait Error: Send + Sized + std::error::Error {
65    /// Raised when there is general error when decoding a type.
66    /// The message should not be capitalized and should not end with a period.
67    fn custom<T: fmt::Display>(msg: T) -> Self;
68
69    /// Raised when [`FromStream`] receives a type different from what it was expecting.
70    fn invalid_type<U: fmt::Display, E: fmt::Display>(unexp: U, exp: E) -> Self {
71        Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp))
72    }
73
74    /// Raised when [`FromStream`] receives a value of the right type but that
75    /// is wrong for some other reason.
76    fn invalid_value<U: fmt::Display, E: fmt::Display>(unexp: U, exp: E) -> Self {
77        Error::custom(format_args!("invalid value: {}, expected {}", unexp, exp))
78    }
79
80    /// Raised when decoding a sequence or map and the input data contains too many
81    /// or too few elements.
82    fn invalid_length<E: fmt::Display>(len: usize, exp: E) -> Self {
83        Error::custom(format_args!("invalid length: {}, expected {}", len, exp))
84    }
85}
86
87/// A data format that can decode a given well-formatted stream using one or more [`Visitor`]s.
88///
89/// Based on `serde::de::Deserializer`.
90#[trait_variant::make(Send)]
91pub trait Decoder: Send {
92    /// Type to return in case of a decoding error.
93    type Error: Error;
94
95    /// Require the `Decoder` to figure out how to drive the visitor based
96    /// on what data type is in the input.
97    ///
98    /// When implementing [`FromStream`], you should avoid relying on
99    /// `Decoder::decode_any` unless you need to be told by the
100    /// Decoder what type is in the input. Know that relying on
101    /// `Decoder::decode_any` means your data type will be able to
102    /// decode self-describing formats only.
103    async fn decode_any<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
104
105    /// Hint that the [`FromStream`] type is expecting a `bool` value.
106    async fn decode_bool<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
107
108    /// Hint that the [`FromStream`] type is expecting a binary value.
109    async fn decode_bytes<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
110
111    /// Hint that the [`FromStream`] type is expecting an `i8` value.
112    async fn decode_i8<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
113
114    /// Hint that the [`FromStream`] type is expecting an `i16` value.
115    async fn decode_i16<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
116
117    /// Hint that the [`FromStream`] type is expecting an `i32` value.
118    async fn decode_i32<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
119
120    /// Hint that the [`FromStream`] type is expecting an `i64` value.
121    async fn decode_i64<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
122
123    /// Hint that the [`FromStream`] type is expecting a `u8` value.
124    async fn decode_u8<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
125
126    /// Hint that the [`FromStream`] type is expecting a `u16` value.
127    async fn decode_u16<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
128
129    /// Hint that the [`FromStream`] type is expecting a `u32` value.
130    async fn decode_u32<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
131
132    /// Hint that the [`FromStream`] type is expecting a `u64` value.
133    async fn decode_u64<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
134
135    /// Hint that the [`FromStream`] type is expecting a `f32` value.
136    async fn decode_f32<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
137
138    /// Hint that the [`FromStream`] type is expecting a `f64` value.
139    async fn decode_f64<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
140
141    /// Hint that the [`FromStream`] type is expecting an array of `bool`s.
142    async fn decode_array_bool<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
143
144    /// Hint that the [`FromStream`] type is expecting an array of `i8`s.
145    async fn decode_array_i8<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
146
147    /// Hint that the [`FromStream`] type is expecting an array of `i16`s.
148    async fn decode_array_i16<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
149
150    /// Hint that the [`FromStream`] type is expecting an array of `i32`s.
151    async fn decode_array_i32<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
152
153    /// Hint that the [`FromStream`] type is expecting an array of `i64`s.
154    async fn decode_array_i64<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
155
156    /// Hint that the [`FromStream`] type is expecting an array of `u8`s.
157    async fn decode_array_u8<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
158
159    /// Hint that the [`FromStream`] type is expecting an array of `u16`s.
160    async fn decode_array_u16<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
161
162    /// Hint that the [`FromStream`] type is expecting an array of `u32`s.
163    async fn decode_array_u32<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
164
165    /// Hint that the [`FromStream`] type is expecting an array of `u64`s.
166    async fn decode_array_u64<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
167
168    /// Hint that the [`FromStream`] type is expecting an array of `f32`s.
169    async fn decode_array_f32<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
170
171    /// Hint that the [`FromStream`] type is expecting an array of `f64`s.
172    async fn decode_array_f64<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
173
174    /// Hint that the [`FromStream`] type is expecting a map of key-value pairs.
175    async fn decode_map<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
176
177    /// Hint that the [`FromStream`] type is expecting an optional value.
178    ///
179    /// This allows decoders that encode an optional value as a nullable
180    /// value to convert the null value into `None` and a regular value into
181    /// `Some(value)`.
182    async fn decode_option<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
183
184    /// Hint that the [`FromStream`] type is expecting a sequence of values.
185    async fn decode_seq<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
186
187    /// Hint that the [`FromStream`] type is expecting a string value.
188    async fn decode_string<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
189
190    /// Hint that the [`FromStream`] type is expecting a sequence of values and
191    /// knows how many values there are without looking at the encoded data.
192    async fn decode_tuple<V: Visitor>(
193        &mut self,
194        len: usize,
195        visitor: V,
196    ) -> Result<V::Value, Self::Error>;
197
198    /// Hint that the [`FromStream`] type is expecting a unit value (i.e. `()`).
199    async fn decode_unit<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
200
201    /// Hint that the [`FromStream`] type is expecting a [`uuid::Uuid`].
202    async fn decode_uuid<V: Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error>;
203
204    /// Hint that the [`FromStream`] type needs to decode a value whose type
205    /// doesn't matter because it is ignored.
206    ///
207    /// Decoders for non-self-describing formats may not support this mode.
208    async fn decode_ignored_any<V: Visitor>(&mut self, visitor: V)
209        -> Result<V::Value, Self::Error>;
210}
211
212/// This trait describes a value which can be decoded from a stream.
213///
214/// Based on `serde::de::Deserialize`.
215#[trait_variant::make(Send)]
216pub trait FromStream: Send + Sized {
217    /// The decoding context of this type, useful in situations where the stream to be decoded
218    /// may be too large to hold in main memory.
219    ///
220    /// Types intended to be stored entirely in main memory should use the unit context `()`.
221    type Context: Send;
222
223    /// Parse this value using the given `Decoder`.
224    async fn from_stream<D: Decoder>(
225        context: Self::Context,
226        decoder: &mut D,
227    ) -> Result<Self, D::Error>;
228}
229
230/// Provides a [`Visitor`] with access to an array of type `T`.
231///
232/// This is a trait that a [`Decoder`] passes to a `Visitor` implementation.
233#[trait_variant::make(Send)]
234pub trait ArrayAccess<T>: Send {
235    type Error: Error;
236
237    /// Write array values from the stream being decoded into the given `buffer`.
238    ///
239    /// Returns the number of values written (this will be in the range `0..buffer.len()`).
240    async fn buffer(&mut self, buffer: &mut [T]) -> Result<usize, Self::Error>;
241}
242
243/// Provides a [`Visitor`] with access to each entry of a map in the input.
244///
245/// This is a trait that a [`Decoder`] passes to a `Visitor` implementation.
246///
247/// Based on `serde::de::MapAccess`.
248#[trait_variant::make(Send)]
249pub trait MapAccess: Send {
250    /// Type to return in case of a decoding error.
251    type Error: Error;
252
253    /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
254    /// if there are no more remaining entries.
255    ///
256    /// `context` is the decoder context used by `K`'s [`FromStream`] impl.
257    /// If `K` is small enough to fit in main memory, pass the unit context `()`.
258    async fn next_key<K: FromStream>(
259        &mut self,
260        context: K::Context,
261    ) -> Result<Option<K>, Self::Error>;
262
263    /// This returns `Ok(value)` for the next value in the map.
264    ///
265    /// `context` is the decoder context used by `V`'s [`FromStream`] impl.
266    /// If `V` is small enough to fit in main memory, pass the unit context `()`.
267    ///
268    /// # Panics
269    ///
270    /// Calling `next_value` before `next_key` is incorrect and is allowed to
271    /// panic or return bogus results.
272    async fn next_value<V: FromStream>(&mut self, context: V::Context) -> Result<V, Self::Error>;
273
274    /// Returns the number of entries remaining in the map, if known.
275    #[inline]
276    fn size_hint(&self) -> Option<usize> {
277        None
278    }
279}
280
281/// Provides a [`Visitor`] access to each element of a sequence in the input.
282///
283/// This is a trait that a [`Decoder`] passes to a `Visitor` implementation,
284/// which decodes each item in a sequence.
285///
286/// Based on `serde::de::SeqAccess`.
287#[trait_variant::make(Send)]
288pub trait SeqAccess: Send {
289    /// The type to return if decoding encounters an error.
290    type Error: Error;
291
292    /// Returns `Ok(Some(value))` for the next value in the sequence,
293    /// or `Ok(None)` if there is no next item of type `T`.
294    ///
295    /// `context` is the decoder context used by `T`'s [`FromStream`] impl.
296    /// If `T` is small enough to fit in main memory, pass the unit context `()`.
297    async fn next_element<T: FromStream>(
298        &mut self,
299        context: T::Context,
300    ) -> Result<Option<T>, Self::Error>;
301
302    /// Returns `Ok(Some(value))` for the next value in the sequence,
303    /// or an error if there is no next item or it's not the required type.
304    ///
305    /// `context` is the decoder context used by `T`'s [`FromStream`] impl.
306    /// If `T` is small enough to fit in main memory, pass the unit context `()`.
307    async fn expect_next<T: FromStream>(&mut self, context: T::Context) -> Result<T, Self::Error> {
308        async {
309            if let Some(element) = self.next_element(context).await? {
310                Ok(element)
311            } else {
312                Err(Error::custom("expected sequence element is missing"))
313            }
314        }
315    }
316
317    /// Returns the number of elements remaining in the sequence, if known.
318    #[inline]
319    fn size_hint(&self) -> Option<usize> {
320        None
321    }
322}
323
324/// This trait describes a visitor responsible for decoding a stream.
325///
326/// Based on `serde::de::Visitor`.
327#[trait_variant::make(Send)]
328pub trait Visitor: Send + Sized {
329    /// The type which this [`Visitor`] is responsible for decoding.
330    type Value;
331
332    /// Format a message stating what data this [`Visitor`] expects to receive.
333    ///
334    /// This is used in error messages. The message should complete the sentence
335    /// "This Visitor expects to receive ...", for example the message could be
336    /// "an integer between 0 and 64". The message should not be capitalized and
337    /// should not end with a period.
338    fn expecting() -> &'static str;
339
340    /// The input contains a boolean.
341    ///
342    /// The default implementation fails with a type error.
343    fn visit_bool<E: Error>(self, v: bool) -> Result<Self::Value, E> {
344        Err(Error::invalid_type(v, Self::expecting()))
345    }
346
347    /// The input contains an `i8`.
348    ///
349    /// The default implementation forwards to [`visit_i64`].
350    ///
351    /// [`visit_i64`]: #method.visit_i64
352    #[inline]
353    fn visit_i8<E: Error>(self, v: i8) -> Result<Self::Value, E> {
354        self.visit_i64(v as i64)
355    }
356
357    /// The input contains an `i16`.
358    ///
359    /// The default implementation forwards to [`visit_i64`].
360    ///
361    /// [`visit_i64`]: #method.visit_i64
362    #[inline]
363    fn visit_i16<E: Error>(self, v: i16) -> Result<Self::Value, E> {
364        self.visit_i64(v as i64)
365    }
366
367    /// The input contains an `i32`.
368    ///
369    /// The default implementation forwards to [`visit_i64`].
370    ///
371    /// [`visit_i64`]: #method.visit_i64
372    #[inline]
373    fn visit_i32<E: Error>(self, v: i32) -> Result<Self::Value, E> {
374        self.visit_i64(v as i64)
375    }
376
377    /// The input contains an `i64`.
378    ///
379    /// The default implementation fails with a type error.
380    fn visit_i64<E: Error>(self, v: i64) -> Result<Self::Value, E> {
381        Err(Error::invalid_type(v, Self::expecting()))
382    }
383
384    /// The input contains a `u8`.
385    ///
386    /// The default implementation forwards to [`visit_u64`].
387    ///
388    /// [`visit_u64`]: #method.visit_u64
389    #[inline]
390    fn visit_u8<E: Error>(self, v: u8) -> Result<Self::Value, E> {
391        self.visit_u64(v as u64)
392    }
393
394    /// The input contains a `u16`.
395    ///
396    /// The default implementation forwards to [`visit_u64`].
397    ///
398    /// [`visit_u64`]: #method.visit_u64
399    #[inline]
400    fn visit_u16<E: Error>(self, v: u16) -> Result<Self::Value, E> {
401        self.visit_u64(v as u64)
402    }
403
404    /// The input contains a `u32`.
405    ///
406    /// The default implementation forwards to [`visit_u64`].
407    ///
408    /// [`visit_u64`]: #method.visit_u64
409    #[inline]
410    fn visit_u32<E: Error>(self, v: u32) -> Result<Self::Value, E> {
411        self.visit_u64(v as u64)
412    }
413
414    /// The input contains a `u64`.
415    ///
416    /// The default implementation fails with a type error.
417    fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> {
418        Err(Error::invalid_type(v, Self::expecting()))
419    }
420
421    /// The input contains an `f32`.
422    ///
423    /// The default implementation forwards to [`visit_f64`].
424    ///
425    /// [`visit_f64`]: #method.visit_f64
426    #[inline]
427    fn visit_f32<E: Error>(self, v: f32) -> Result<Self::Value, E> {
428        self.visit_f64(v as f64)
429    }
430
431    /// The input contains an `f64`.
432    ///
433    /// The default implementation fails with a type error.
434    fn visit_f64<E: Error>(self, v: f64) -> Result<Self::Value, E> {
435        Err(Error::invalid_type(v, Self::expecting()))
436    }
437
438    /// The input contains an array of `bool`s.
439    ///
440    /// The default implementation fails with a type error.
441    #[allow(unused_variables)]
442    async fn visit_array_bool<A: ArrayAccess<bool>>(
443        self,
444        array: A,
445    ) -> Result<Self::Value, A::Error> {
446        async { Err(Error::invalid_type("boolean array", Self::expecting())) }
447    }
448
449    /// The input contains an array of `i8`s.
450    ///
451    /// The default implementation fails with a type error.
452    #[allow(unused_variables)]
453    async fn visit_array_i8<A: ArrayAccess<i8>>(self, array: A) -> Result<Self::Value, A::Error> {
454        async { Err(Error::invalid_type("i8 array", Self::expecting())) }
455    }
456
457    /// The input contains an array of `i16`s.
458    ///
459    /// The default implementation fails with a type error.
460    #[allow(unused_variables)]
461    async fn visit_array_i16<A: ArrayAccess<i16>>(self, array: A) -> Result<Self::Value, A::Error> {
462        async { Err(Error::invalid_type("i16 array", Self::expecting())) }
463    }
464
465    /// The input contains an array of `i32`s.
466    ///
467    /// The default implementation fails with a type error.
468    #[allow(unused_variables)]
469    async fn visit_array_i32<A: ArrayAccess<i32>>(self, array: A) -> Result<Self::Value, A::Error> {
470        async { Err(Error::invalid_type("i32 array", Self::expecting())) }
471    }
472
473    /// The input contains an array of `i64`s.
474    ///
475    /// The default implementation fails with a type error.
476    #[allow(unused_variables)]
477    async fn visit_array_i64<A: ArrayAccess<i64>>(self, array: A) -> Result<Self::Value, A::Error> {
478        async { Err(Error::invalid_type("i64 array", Self::expecting())) }
479    }
480
481    /// The input contains an array of `u8`s.
482    ///
483    /// The default implementation fails with a type error.
484    #[allow(unused_variables)]
485    async fn visit_array_u8<A: ArrayAccess<u8>>(self, array: A) -> Result<Self::Value, A::Error> {
486        async { Err(Error::invalid_type("u8 array", Self::expecting())) }
487    }
488
489    /// The input contains an array of `u16`s.
490    ///
491    /// The default implementation fails with a type error.
492    #[allow(unused_variables)]
493    async fn visit_array_u16<A: ArrayAccess<u16>>(self, array: A) -> Result<Self::Value, A::Error> {
494        async { Err(Error::invalid_type("u16 array", Self::expecting())) }
495    }
496
497    /// The input contains an array of `u32`s.
498    ///
499    /// The default implementation fails with a type error.
500    #[allow(unused_variables)]
501    async fn visit_array_u32<A: ArrayAccess<u32>>(self, array: A) -> Result<Self::Value, A::Error> {
502        async { Err(Error::invalid_type("u32 array", Self::expecting())) }
503    }
504
505    /// The input contains an array of `u64`s.
506    ///
507    /// The default implementation fails with a type error.
508    #[allow(unused_variables)]
509    async fn visit_array_u64<A: ArrayAccess<u64>>(self, array: A) -> Result<Self::Value, A::Error> {
510        async { Err(Error::invalid_type("u64 array", Self::expecting())) }
511    }
512
513    /// The input contains an array of `f32`s.
514    ///
515    /// The default implementation fails with a type error.
516    #[allow(unused_variables)]
517    async fn visit_array_f32<A: ArrayAccess<f32>>(self, array: A) -> Result<Self::Value, A::Error> {
518        async { Err(Error::invalid_type("f32 array", Self::expecting())) }
519    }
520
521    /// The input contains an array of `f64`s.
522    ///
523    /// The default implementation fails with a type error.
524    #[allow(unused_variables)]
525    async fn visit_array_f64<A: ArrayAccess<f64>>(self, array: A) -> Result<Self::Value, A::Error> {
526        async { Err(Error::invalid_type("f64 array", Self::expecting())) }
527    }
528
529    /// The input contains a string and ownership of the string is being given
530    /// to the [`Visitor`].
531    ///
532    /// The default implementation fails with a type error.
533    fn visit_string<E: Error>(self, v: String) -> Result<Self::Value, E> {
534        Err(Error::invalid_type(v, Self::expecting()))
535    }
536
537    /// The input contains a unit `()`.
538    ///
539    /// The default implementation fails with a type error.
540    fn visit_unit<E: Error>(self) -> Result<Self::Value, E> {
541        Err(Error::invalid_type("unit", Self::expecting()))
542    }
543
544    /// The input contains an optional that is absent.
545    /// The default implementation fails with a type error.
546    fn visit_none<E: Error>(self) -> Result<Self::Value, E> {
547        Err(Error::invalid_type("Option::None", Self::expecting()))
548    }
549
550    /// The input contains an optional that is present.
551    /// The default implementation fails with a type error.
552    #[allow(unused_variables)]
553    async fn visit_some<D: Decoder>(self, decoder: &mut D) -> Result<Self::Value, D::Error> {
554        async { Err(Error::invalid_type("Option::Some", Self::expecting())) }
555    }
556
557    /// The input contains a key-value map.
558    /// The default implementation fails with a type error.
559    #[allow(unused_variables)]
560    async fn visit_map<A: MapAccess>(self, map: A) -> Result<Self::Value, A::Error> {
561        async { Err(Error::invalid_type("map", Self::expecting())) }
562    }
563
564    /// The input contains a sequence of elements.
565    /// The default implementation fails with a type error.
566    #[allow(unused_variables)]
567    async fn visit_seq<A: SeqAccess>(self, seq: A) -> Result<Self::Value, A::Error> {
568        async { Err(Error::invalid_type("sequence", Self::expecting())) }
569    }
570}
571
572#[derive(Copy, Clone, Debug, Default, PartialEq)]
573pub struct IgnoredAny;