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