musli/storage/
de.rs

1use core::fmt;
2
3#[cfg(feature = "alloc")]
4use rust_alloc::vec::Vec;
5
6use crate::de::{
7    DecodeUnsized, Decoder, EntriesDecoder, EntryDecoder, MapDecoder, SequenceDecoder, SizeHint,
8    UnsizedVisitor, VariantDecoder,
9};
10use crate::{Context, Decode, Options, Reader};
11
12/// A very simple decoder suitable for storage decoding.
13pub struct StorageDecoder<'a, R, const OPT: Options, C: ?Sized> {
14    cx: &'a C,
15    reader: R,
16}
17
18impl<'a, R, const OPT: Options, C: ?Sized> StorageDecoder<'a, R, OPT, C> {
19    /// Construct a new fixed width message encoder.
20    #[inline]
21    pub fn new(cx: &'a C, reader: R) -> Self {
22        Self { cx, reader }
23    }
24}
25
26/// A length-prefixed decode wrapper.
27///
28/// This simplifies implementing decoders that do not have any special handling
29/// for length-prefixed types.
30#[doc(hidden)]
31pub struct LimitedStorageDecoder<'a, R, const OPT: Options, C: ?Sized> {
32    remaining: usize,
33    cx: &'a C,
34    reader: R,
35}
36
37#[crate::decoder(crate)]
38impl<'a, 'de, R, const OPT: Options, C: ?Sized + Context> Decoder<'de>
39    for StorageDecoder<'a, R, OPT, C>
40where
41    R: Reader<'de>,
42{
43    type Cx = C;
44    type Error = C::Error;
45    type Mode = C::Mode;
46    type WithContext<'this, U> = StorageDecoder<'this, R, OPT, U> where U: 'this + Context;
47    type DecodePack = Self;
48    type DecodeSome = Self;
49    type DecodeSequence = LimitedStorageDecoder<'a, R, OPT, C>;
50    type DecodeMap = LimitedStorageDecoder<'a, R, OPT, C>;
51    type DecodeMapEntries = LimitedStorageDecoder<'a, R, OPT, C>;
52    type DecodeVariant = Self;
53
54    fn cx(&self) -> &C {
55        self.cx
56    }
57
58    #[inline]
59    fn with_context<U>(self, cx: &U) -> Result<Self::WithContext<'_, U>, C::Error>
60    where
61        U: Context,
62    {
63        Ok(StorageDecoder::new(cx, self.reader))
64    }
65
66    #[inline]
67    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        write!(f, "type supported by the storage decoder")
69    }
70
71    #[inline]
72    fn decode<T>(self) -> Result<T, Self::Error>
73    where
74        T: Decode<'de, Self::Mode>,
75    {
76        self.cx.decode(self)
77    }
78
79    #[inline]
80    fn decode_unsized<T, F, O>(self, f: F) -> Result<O, Self::Error>
81    where
82        T: ?Sized + DecodeUnsized<'de, Self::Mode>,
83        F: FnOnce(&T) -> Result<O, Self::Error>,
84    {
85        self.cx.decode_unsized(self, f)
86    }
87
88    #[inline]
89    fn decode_empty(mut self) -> Result<(), C::Error> {
90        let mark = self.cx.mark();
91        let count = crate::int::decode_usize::<_, _, OPT>(self.cx, self.reader.borrow_mut())?;
92
93        if count != 0 {
94            return Err(self
95                .cx
96                .marked_message(mark, ExpectedEmptySequence { actual: count }));
97        }
98
99        Ok(())
100    }
101
102    #[inline]
103    fn decode_pack<F, O>(mut self, f: F) -> Result<O, C::Error>
104    where
105        F: FnOnce(&mut Self::DecodePack) -> Result<O, C::Error>,
106    {
107        f(&mut self)
108    }
109
110    #[inline]
111    fn decode_array<const N: usize>(mut self) -> Result<[u8; N], C::Error> {
112        self.reader.read_array(self.cx)
113    }
114
115    #[inline]
116    fn decode_bytes<V>(mut self, visitor: V) -> Result<V::Ok, C::Error>
117    where
118        V: UnsizedVisitor<'de, C, [u8]>,
119    {
120        let len = crate::int::decode_usize::<_, _, OPT>(self.cx, self.reader.borrow_mut())?;
121        self.reader.read_bytes(self.cx, len, visitor)
122    }
123
124    #[inline]
125    fn decode_string<V>(self, visitor: V) -> Result<V::Ok, C::Error>
126    where
127        V: UnsizedVisitor<'de, C, str>,
128    {
129        struct Visitor<V>(V);
130
131        impl<'de, C, V> UnsizedVisitor<'de, C, [u8]> for Visitor<V>
132        where
133            C: ?Sized + Context,
134            V: UnsizedVisitor<'de, C, str>,
135        {
136            type Ok = V::Ok;
137
138            #[inline]
139            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140                self.0.expecting(f)
141            }
142
143            #[cfg(feature = "alloc")]
144            #[inline]
145            fn visit_owned(self, cx: &C, bytes: Vec<u8>) -> Result<Self::Ok, C::Error> {
146                let string = crate::str::from_utf8_owned(bytes).map_err(cx.map())?;
147                self.0.visit_owned(cx, string)
148            }
149
150            #[inline]
151            fn visit_borrowed(self, cx: &C, bytes: &'de [u8]) -> Result<Self::Ok, C::Error> {
152                let string = crate::str::from_utf8(bytes).map_err(cx.map())?;
153                self.0.visit_borrowed(cx, string)
154            }
155
156            #[inline]
157            fn visit_ref(self, cx: &C, bytes: &[u8]) -> Result<Self::Ok, C::Error> {
158                let string = crate::str::from_utf8(bytes).map_err(cx.map())?;
159                self.0.visit_ref(cx, string)
160            }
161        }
162
163        self.decode_bytes(Visitor(visitor))
164    }
165
166    #[inline]
167    fn decode_bool(mut self) -> Result<bool, C::Error> {
168        let mark = self.cx.mark();
169        let byte = self.reader.read_byte(self.cx)?;
170
171        match byte {
172            0 => Ok(false),
173            1 => Ok(true),
174            b => Err(self.cx.marked_message(mark, BadBoolean { actual: b })),
175        }
176    }
177
178    #[inline]
179    fn decode_char(self) -> Result<char, C::Error> {
180        let cx = self.cx;
181        let mark = self.cx.mark();
182        let num = self.decode_u32()?;
183
184        match char::from_u32(num) {
185            Some(d) => Ok(d),
186            None => Err(cx.marked_message(mark, BadCharacter { actual: num })),
187        }
188    }
189
190    #[inline]
191    fn decode_u8(mut self) -> Result<u8, C::Error> {
192        self.reader.read_byte(self.cx)
193    }
194
195    #[inline]
196    fn decode_u16(self) -> Result<u16, C::Error> {
197        crate::int::decode_unsigned::<_, _, _, OPT>(self.cx, self.reader)
198    }
199
200    #[inline]
201    fn decode_u32(self) -> Result<u32, C::Error> {
202        crate::int::decode_unsigned::<_, _, _, OPT>(self.cx, self.reader)
203    }
204
205    #[inline]
206    fn decode_u64(self) -> Result<u64, C::Error> {
207        crate::int::decode_unsigned::<_, _, _, OPT>(self.cx, self.reader)
208    }
209
210    #[inline]
211    fn decode_u128(self) -> Result<u128, C::Error> {
212        crate::int::decode_unsigned::<_, _, _, OPT>(self.cx, self.reader)
213    }
214
215    #[inline]
216    fn decode_i8(self) -> Result<i8, C::Error> {
217        Ok(self.decode_u8()? as i8)
218    }
219
220    #[inline]
221    fn decode_i16(self) -> Result<i16, C::Error> {
222        crate::int::decode_signed::<_, _, _, OPT>(self.cx, self.reader)
223    }
224
225    #[inline]
226    fn decode_i32(self) -> Result<i32, C::Error> {
227        crate::int::decode_signed::<_, _, _, OPT>(self.cx, self.reader)
228    }
229
230    #[inline]
231    fn decode_i64(self) -> Result<i64, C::Error> {
232        crate::int::decode_signed::<_, _, _, OPT>(self.cx, self.reader)
233    }
234
235    #[inline]
236    fn decode_i128(self) -> Result<i128, C::Error> {
237        crate::int::decode_signed::<_, _, _, OPT>(self.cx, self.reader)
238    }
239
240    #[inline]
241    fn decode_usize(self) -> Result<usize, C::Error> {
242        crate::int::decode_usize::<_, _, OPT>(self.cx, self.reader)
243    }
244
245    #[inline]
246    fn decode_isize(self) -> Result<isize, C::Error> {
247        Ok(self.decode_usize()? as isize)
248    }
249
250    /// Decode a 32-bit floating point value by reading the 32-bit in-memory
251    /// IEEE 754 encoding byte-by-byte.
252    #[inline]
253    fn decode_f32(self) -> Result<f32, C::Error> {
254        Ok(f32::from_bits(self.decode_u32()?))
255    }
256
257    /// Decode a 64-bit floating point value by reading the 64-bit in-memory
258    /// IEEE 754 encoding byte-by-byte.
259    #[inline]
260    fn decode_f64(self) -> Result<f64, C::Error> {
261        let bits = self.decode_u64()?;
262        Ok(f64::from_bits(bits))
263    }
264
265    #[inline]
266    fn decode_option(mut self) -> Result<Option<Self::DecodeSome>, C::Error> {
267        let b = self.reader.read_byte(self.cx)?;
268        Ok(if b == 1 { Some(self) } else { None })
269    }
270
271    #[inline]
272    fn decode_sequence<F, O>(self, f: F) -> Result<O, C::Error>
273    where
274        F: FnOnce(&mut Self::DecodeSequence) -> Result<O, C::Error>,
275    {
276        let cx = self.cx;
277        let mut decoder = LimitedStorageDecoder::new(self.cx, self.reader)?;
278        let output = f(&mut decoder)?;
279
280        if decoder.remaining != 0 {
281            return Err(cx.message("Caller did not decode all available map entries"));
282        }
283
284        Ok(output)
285    }
286
287    #[inline]
288    fn decode_map<F, O>(self, f: F) -> Result<O, C::Error>
289    where
290        F: FnOnce(&mut Self::DecodeMap) -> Result<O, C::Error>,
291    {
292        let cx = self.cx;
293        let mut decoder = LimitedStorageDecoder::new(self.cx, self.reader)?;
294        let output = f(&mut decoder)?;
295
296        if decoder.remaining != 0 {
297            return Err(cx.message("Caller did not decode all available map entries"));
298        }
299
300        Ok(output)
301    }
302
303    #[inline]
304    fn decode_map_entries<F, O>(self, f: F) -> Result<O, C::Error>
305    where
306        F: FnOnce(&mut Self::DecodeMapEntries) -> Result<O, C::Error>,
307    {
308        self.decode_map(f)
309    }
310
311    #[inline]
312    fn decode_variant<F, O>(mut self, f: F) -> Result<O, C::Error>
313    where
314        F: FnOnce(&mut Self::DecodeVariant) -> Result<O, C::Error>,
315    {
316        f(&mut self)
317    }
318}
319
320impl<'a, 'de, R, const OPT: Options, C: ?Sized + Context> SequenceDecoder<'de>
321    for StorageDecoder<'a, R, OPT, C>
322where
323    R: Reader<'de>,
324{
325    type Cx = C;
326    type DecodeNext<'this> = StorageDecoder<'a, R::Mut<'this>, OPT, C> where Self: 'this;
327
328    #[inline]
329    fn try_decode_next(
330        &mut self,
331    ) -> Result<Option<Self::DecodeNext<'_>>, <Self::Cx as Context>::Error> {
332        Ok(Some(self.decode_next()?))
333    }
334
335    #[inline]
336    fn decode_next(&mut self) -> Result<Self::DecodeNext<'_>, C::Error> {
337        Ok(StorageDecoder::new(self.cx, self.reader.borrow_mut()))
338    }
339}
340
341impl<'a, 'de, R, const OPT: Options, C> LimitedStorageDecoder<'a, R, OPT, C>
342where
343    C: ?Sized + Context,
344    R: Reader<'de>,
345{
346    #[inline]
347    fn new(cx: &'a C, mut reader: R) -> Result<Self, C::Error> {
348        let remaining = crate::int::decode_usize::<_, _, OPT>(cx, reader.borrow_mut())?;
349
350        Ok(Self {
351            cx,
352            reader,
353            remaining,
354        })
355    }
356
357    #[inline]
358    fn with_remaining(cx: &'a C, reader: R, remaining: usize) -> Self {
359        Self {
360            cx,
361            reader,
362            remaining,
363        }
364    }
365}
366
367impl<'a, 'de, R, const OPT: Options, C: ?Sized + Context> SequenceDecoder<'de>
368    for LimitedStorageDecoder<'a, R, OPT, C>
369where
370    R: Reader<'de>,
371{
372    type Cx = C;
373    type DecodeNext<'this> = StorageDecoder<'a, R::Mut<'this>, OPT, C> where Self: 'this;
374
375    #[inline]
376    fn size_hint(&self) -> SizeHint {
377        SizeHint::exact(self.remaining)
378    }
379
380    #[inline]
381    fn try_decode_next(&mut self) -> Result<Option<Self::DecodeNext<'_>>, C::Error> {
382        if self.remaining == 0 {
383            return Ok(None);
384        }
385
386        self.remaining -= 1;
387        Ok(Some(StorageDecoder::new(self.cx, self.reader.borrow_mut())))
388    }
389
390    #[inline]
391    fn decode_next(&mut self) -> Result<Self::DecodeNext<'_>, <Self::Cx as Context>::Error> {
392        let cx = self.cx;
393
394        let Some(decoder) = self.try_decode_next()? else {
395            return Err(cx.message("No remaining elements"));
396        };
397
398        Ok(decoder)
399    }
400}
401
402impl<'a, 'de, R, const OPT: Options, C: ?Sized + Context> MapDecoder<'de>
403    for LimitedStorageDecoder<'a, R, OPT, C>
404where
405    R: Reader<'de>,
406{
407    type Cx = C;
408    type DecodeEntry<'this> = StorageDecoder<'a, R::Mut<'this>, OPT, C>
409    where
410        Self: 'this;
411    type DecodeRemainingEntries<'this> = LimitedStorageDecoder<'a, R::Mut<'this>, OPT, C> where Self: 'this;
412
413    #[inline]
414    fn size_hint(&self) -> SizeHint {
415        SizeHint::exact(self.remaining)
416    }
417
418    #[inline]
419    fn decode_entry(&mut self) -> Result<Option<Self::DecodeEntry<'_>>, C::Error> {
420        if self.remaining == 0 {
421            return Ok(None);
422        }
423
424        self.remaining -= 1;
425        Ok(Some(StorageDecoder::new(self.cx, self.reader.borrow_mut())))
426    }
427
428    #[inline]
429    fn decode_remaining_entries(
430        &mut self,
431    ) -> Result<Self::DecodeRemainingEntries<'_>, <Self::Cx as Context>::Error> {
432        Ok(LimitedStorageDecoder::with_remaining(
433            self.cx,
434            self.reader.borrow_mut(),
435            self.remaining,
436        ))
437    }
438}
439
440impl<'a, 'de, R, const OPT: Options, C: ?Sized + Context> EntryDecoder<'de>
441    for StorageDecoder<'a, R, OPT, C>
442where
443    R: Reader<'de>,
444{
445    type Cx = C;
446    type DecodeKey<'this> = StorageDecoder<'a, R::Mut<'this>, OPT, C> where Self: 'this;
447    type DecodeValue = Self;
448
449    #[inline]
450    fn decode_key(&mut self) -> Result<Self::DecodeKey<'_>, C::Error> {
451        Ok(StorageDecoder::new(self.cx, self.reader.borrow_mut()))
452    }
453
454    #[inline]
455    fn decode_value(self) -> Result<Self::DecodeValue, C::Error> {
456        Ok(self)
457    }
458}
459
460impl<'a, 'de, R, const OPT: Options, C: ?Sized + Context> EntriesDecoder<'de>
461    for LimitedStorageDecoder<'a, R, OPT, C>
462where
463    R: Reader<'de>,
464{
465    type Cx = C;
466    type DecodeEntryKey<'this> = StorageDecoder<'a, R::Mut<'this>, OPT, C> where Self: 'this;
467    type DecodeEntryValue<'this> = StorageDecoder<'a, R::Mut<'this>, OPT, C> where Self: 'this;
468
469    #[inline]
470    fn decode_entry_key(&mut self) -> Result<Option<Self::DecodeEntryKey<'_>>, C::Error> {
471        if self.remaining == 0 {
472            return Ok(None);
473        }
474
475        self.remaining -= 1;
476        Ok(Some(StorageDecoder::new(self.cx, self.reader.borrow_mut())))
477    }
478
479    #[inline]
480    fn decode_entry_value(&mut self) -> Result<Self::DecodeEntryValue<'_>, C::Error> {
481        Ok(StorageDecoder::new(self.cx, self.reader.borrow_mut()))
482    }
483
484    #[inline]
485    fn end_entries(self) -> Result<(), C::Error> {
486        if self.remaining != 0 {
487            return Err(self
488                .cx
489                .message("Caller did not decode all available map entries"));
490        }
491
492        Ok(())
493    }
494}
495
496impl<'a, 'de, R, const OPT: Options, C: ?Sized + Context> VariantDecoder<'de>
497    for StorageDecoder<'a, R, OPT, C>
498where
499    R: Reader<'de>,
500{
501    type Cx = C;
502    type DecodeTag<'this> = StorageDecoder<'a, R::Mut<'this>, OPT, C> where Self: 'this;
503    type DecodeValue<'this> = StorageDecoder<'a, R::Mut<'this>, OPT, C> where Self: 'this;
504
505    #[inline]
506    fn decode_tag(&mut self) -> Result<Self::DecodeTag<'_>, C::Error> {
507        Ok(StorageDecoder::new(self.cx, self.reader.borrow_mut()))
508    }
509
510    #[inline]
511    fn decode_value(&mut self) -> Result<Self::DecodeValue<'_>, C::Error> {
512        Ok(StorageDecoder::new(self.cx, self.reader.borrow_mut()))
513    }
514}
515
516struct ExpectedEmptySequence {
517    actual: usize,
518}
519
520impl fmt::Display for ExpectedEmptySequence {
521    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522        let Self { actual } = *self;
523        write!(f, "Expected empty sequence, but was {actual}",)
524    }
525}
526
527struct BadBoolean {
528    actual: u8,
529}
530
531impl fmt::Display for BadBoolean {
532    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
533        let Self { actual } = *self;
534        write!(f, "Bad boolean byte 0x{actual:02x}")
535    }
536}
537
538struct BadCharacter {
539    actual: u32,
540}
541
542impl fmt::Display for BadCharacter {
543    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544        let Self { actual } = *self;
545        write!(f, "Bad character number {actual}")
546    }
547}