1use core::fmt;
2use core::mem::take;
3
4#[cfg(feature = "alloc")]
5use alloc::vec::Vec;
6
7use musli::de::{
8 Decode, DecodeUnsized, Decoder, EntriesDecoder, EntryDecoder, MapDecoder, NumberVisitor,
9 SequenceDecoder, SizeHint, Skip, ValueVisitor, VariantDecoder, Visitor,
10};
11use musli::hint::{MapHint, SequenceHint};
12use musli::Context;
13use musli_storage::de::StorageDecoder;
14use musli_utils::int::continuation as c;
15#[cfg(feature = "musli-value")]
16use musli_utils::options;
17use musli_utils::reader::Limit;
18use musli_utils::{Options, Reader};
19
20use crate::integer_encoding::{decode_typed_signed, decode_typed_unsigned};
21use crate::tag::{Kind, Mark, Tag, F32, F64, I128, I16, I32, I64, I8, U128, U16, U32, U64, U8};
22
23#[cfg(feature = "musli-value")]
24const BUFFER_OPTIONS: Options = options::new().build();
25
26pub struct SelfDecoder<'a, R, const OPT: Options, C: ?Sized> {
28 cx: &'a C,
29 reader: R,
30}
31
32impl<'a, R, const OPT: Options, C: ?Sized> SelfDecoder<'a, R, OPT, C> {
33 #[inline]
35 pub(crate) fn new(cx: &'a C, reader: R) -> Self {
36 Self { cx, reader }
37 }
38}
39
40impl<'a, 'de, R, const OPT: Options, C> SelfDecoder<'a, Limit<R>, OPT, C>
41where
42 R: Reader<'de>,
43 C: ?Sized + Context,
44{
45 #[inline]
46 fn end(mut self) -> Result<(), C::Error> {
47 if self.reader.remaining() > 0 {
48 self.reader.skip(self.cx, self.reader.remaining())?;
49 }
50
51 Ok(())
52 }
53}
54
55impl<'a, 'de, R, const OPT: Options, C> SelfDecoder<'a, R, OPT, C>
56where
57 R: Reader<'de>,
58 C: ?Sized + Context,
59{
60 pub(crate) fn skip_any(mut self) -> Result<(), C::Error> {
62 let mut remaining = 1;
63
64 while remaining > 0 {
65 remaining -= 1;
66
67 let tag = Tag::from_byte(self.reader.read_byte(self.cx)?);
68
69 match tag.kind() {
70 Kind::Number => {
71 _ = c::decode::<_, _, u128>(self.cx, self.reader.borrow_mut())?;
72 }
73 Kind::Mark => match tag.mark() {
74 Mark::Variant => {
75 remaining += 2;
76 }
77 Mark::Char => {
78 _ = c::decode::<_, _, u32>(self.cx, self.reader.borrow_mut())?;
79 }
80 _ => {}
81 },
82 Kind::Bytes | Kind::String => {
83 let len = if let Some(len) = tag.data() {
84 len as usize
85 } else {
86 musli_utils::int::decode_usize::<_, _, OPT>(
87 self.cx,
88 self.reader.borrow_mut(),
89 )?
90 };
91
92 self.reader.skip(self.cx, len)?;
93 }
94 Kind::Sequence => {
95 let len = if let Some(len) = tag.data() {
96 len as usize
97 } else {
98 musli_utils::int::decode_usize::<_, _, OPT>(
99 self.cx,
100 self.reader.borrow_mut(),
101 )?
102 };
103
104 remaining += len;
105 }
106 Kind::Map => {
107 let len = if let Some(len) = tag.data() {
108 len as usize
109 } else {
110 musli_utils::int::decode_usize::<_, _, OPT>(
111 self.cx,
112 self.reader.borrow_mut(),
113 )?
114 };
115
116 remaining += len * 2;
117 }
118 kind => {
119 return Err(self
120 .cx
121 .message(format_args!("Cannot skip over kind {kind:?}")));
122 }
123 }
124 }
125
126 Ok(())
127 }
128
129 #[inline]
131 fn shared_decode_map(mut self) -> Result<RemainingSelfDecoder<'a, R, OPT, C>, C::Error> {
132 let pos = self.cx.mark();
133 let len = self.decode_prefix(Kind::Map, pos)?;
134 Ok(RemainingSelfDecoder::new(self.cx, self.reader, len))
135 }
136
137 #[inline]
139 fn shared_decode_sequence(mut self) -> Result<RemainingSelfDecoder<'a, R, OPT, C>, C::Error> {
140 let pos = self.cx.mark();
141 let len = self.decode_prefix(Kind::Sequence, pos)?;
142 Ok(RemainingSelfDecoder::new(self.cx, self.reader, len))
143 }
144
145 #[inline]
147 fn decode_prefix(&mut self, kind: Kind, mark: C::Mark) -> Result<usize, C::Error> {
148 let tag = Tag::from_byte(self.reader.read_byte(self.cx)?);
149
150 if tag.kind() != kind {
151 return Err(self.cx.marked_message(
152 mark,
153 Expected {
154 expected: kind,
155 actual: tag,
156 },
157 ));
158 }
159
160 Ok(if let Some(len) = tag.data() {
161 len as usize
162 } else {
163 musli_utils::int::decode_usize::<_, _, OPT>(self.cx, self.reader.borrow_mut())?
164 })
165 }
166
167 #[inline]
169 fn decode_pack_length(&mut self, start: C::Mark) -> Result<usize, C::Error> {
170 let tag = Tag::from_byte(self.reader.read_byte(self.cx)?);
171
172 match tag.kind() {
173 Kind::Bytes => Ok(if let Some(len) = tag.data() {
174 len as usize
175 } else {
176 musli_utils::int::decode_usize::<_, _, OPT>(self.cx, self.reader.borrow_mut())?
177 }),
178 _ => Err(self.cx.marked_message(start, "Expected prefix or pack")),
179 }
180 }
181}
182
183#[doc(hidden)]
188pub struct RemainingSelfDecoder<'a, R, const OPT: Options, C: ?Sized> {
189 cx: &'a C,
190 reader: R,
191 remaining: usize,
192}
193
194impl<'a, 'de, R, const OPT: Options, C> RemainingSelfDecoder<'a, R, OPT, C>
195where
196 R: Reader<'de>,
197 C: ?Sized + Context,
198{
199 #[inline]
200 fn new(cx: &'a C, reader: R, remaining: usize) -> Self {
201 Self {
202 cx,
203 reader,
204 remaining,
205 }
206 }
207
208 #[inline]
209 fn skip_sequence_remaining(mut self) -> Result<(), C::Error> {
210 if let Some(item) = self.try_decode_next()? {
211 item.skip()?;
212 }
213
214 Ok(())
215 }
216
217 #[inline]
218 fn skip_map_remaining(mut self) -> Result<(), C::Error> {
219 loop {
220 let Some(key) = self.decode_entry_key()? else {
221 break;
222 };
223
224 key.skip()?;
225 self.decode_entry_value()?.skip()?;
226 }
227
228 Ok(())
229 }
230}
231
232#[musli::decoder]
233impl<'a, 'de, R, const OPT: Options, C> Decoder<'de> for SelfDecoder<'a, R, OPT, C>
234where
235 R: Reader<'de>,
236 C: ?Sized + Context,
237{
238 type Cx = C;
239 type Error = C::Error;
240 type Mode = C::Mode;
241 type WithContext<'this, U> = SelfDecoder<'this, R, OPT, U> where U: 'this + Context;
242 #[cfg(feature = "musli-value")]
243 type DecodeBuffer = musli_value::AsValueDecoder<'a, BUFFER_OPTIONS, C>;
244 type DecodePack = SelfDecoder<'a, Limit<R>, OPT, C>;
245 type DecodeSome = Self;
246 type DecodeSequence = RemainingSelfDecoder<'a, R, OPT, C>;
247 type DecodeSequenceHint = RemainingSelfDecoder<'a, R, OPT, C>;
248 type DecodeMap = RemainingSelfDecoder<'a, R, OPT, C>;
249 type DecodeMapHint = RemainingSelfDecoder<'a, R, OPT, C>;
250 type DecodeMapEntries = RemainingSelfDecoder<'a, R, OPT, C>;
251 type DecodeVariant = Self;
252
253 #[inline]
254 fn cx(&self) -> &C {
255 self.cx
256 }
257
258 #[inline]
259 fn with_context<U>(self, cx: &U) -> Result<Self::WithContext<'_, U>, C::Error>
260 where
261 U: Context,
262 {
263 Ok(SelfDecoder::new(cx, self.reader))
264 }
265
266 #[inline]
267 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 write!(f, "type supported by the descriptive decoder")
269 }
270
271 #[inline]
272 fn decode<T>(self) -> Result<T, Self::Error>
273 where
274 T: Decode<'de, Self::Mode>,
275 {
276 self.cx.decode(self)
277 }
278
279 #[inline]
280 fn decode_unsized<T, F, O>(self, f: F) -> Result<O, Self::Error>
281 where
282 T: ?Sized + DecodeUnsized<'de, Self::Mode>,
283 F: FnOnce(&T) -> Result<O, Self::Error>,
284 {
285 self.cx.decode_unsized(self, f)
286 }
287
288 #[inline]
289 fn skip(self) -> Result<(), C::Error> {
290 self.skip_any()
291 }
292
293 #[inline]
294 fn try_skip(self) -> Result<Skip, C::Error> {
295 self.skip()?;
296 Ok(Skip::Skipped)
297 }
298
299 #[cfg(feature = "musli-value")]
300 #[inline]
301 fn decode_buffer(self) -> Result<Self::DecodeBuffer, C::Error> {
302 let cx = self.cx;
303 let value = self.decode::<musli_value::Value>()?;
304 Ok(value.into_value_decoder(cx))
305 }
306
307 #[inline]
308 fn decode_unit(self) -> Result<(), C::Error> {
309 self.skip()
310 }
311
312 #[inline]
313 fn decode_pack<F, O>(mut self, f: F) -> Result<O, C::Error>
314 where
315 F: FnOnce(&mut Self::DecodePack) -> Result<O, C::Error>,
316 {
317 let pos = self.cx.mark();
318 let len = self.decode_pack_length(pos)?;
319 let mut decoder = SelfDecoder::new(self.cx, self.reader.limit(len));
320 let output = f(&mut decoder)?;
321 decoder.end()?;
322 Ok(output)
323 }
324
325 #[inline]
326 fn decode_array<const N: usize>(mut self) -> Result<[u8; N], C::Error> {
327 let pos = self.cx.mark();
328 let len = self.decode_prefix(Kind::Bytes, pos)?;
329
330 if len != N {
331 return Err(self.cx.marked_message(
332 pos,
333 format_args! {
334 "Bad length, got {len} but expect {N}"
335 },
336 ));
337 }
338
339 self.reader.read_array(self.cx)
340 }
341
342 #[inline]
343 fn decode_bytes<V>(mut self, visitor: V) -> Result<V::Ok, C::Error>
344 where
345 V: ValueVisitor<'de, C, [u8]>,
346 {
347 let pos = self.cx.mark();
348 let len = self.decode_prefix(Kind::Bytes, pos)?;
349 self.reader.read_bytes(self.cx, len, visitor)
350 }
351
352 #[inline]
353 fn decode_string<V>(mut self, visitor: V) -> Result<V::Ok, C::Error>
354 where
355 V: ValueVisitor<'de, C, str>,
356 {
357 struct Visitor<V>(V);
358
359 impl<'de, C, V> ValueVisitor<'de, C, [u8]> for Visitor<V>
360 where
361 C: ?Sized + Context,
362 V: ValueVisitor<'de, C, str>,
363 {
364 type Ok = V::Ok;
365
366 #[inline]
367 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368 self.0.expecting(f)
369 }
370
371 #[cfg(feature = "alloc")]
372 #[inline]
373 fn visit_owned(self, cx: &C, bytes: Vec<u8>) -> Result<Self::Ok, C::Error> {
374 let string = crate::str::from_utf8_owned(bytes).map_err(cx.map())?;
375 self.0.visit_owned(cx, string)
376 }
377
378 #[inline]
379 fn visit_borrowed(self, cx: &C, bytes: &'de [u8]) -> Result<Self::Ok, C::Error> {
380 let string = crate::str::from_utf8(bytes).map_err(cx.map())?;
381 self.0.visit_borrowed(cx, string)
382 }
383
384 #[inline]
385 fn visit_ref(self, cx: &C, bytes: &[u8]) -> Result<Self::Ok, C::Error> {
386 let string = crate::str::from_utf8(bytes).map_err(cx.map())?;
387 self.0.visit_ref(cx, string)
388 }
389 }
390
391 let pos = self.cx.mark();
392 let len = self.decode_prefix(Kind::String, pos)?;
393 self.reader.read_bytes(self.cx, len, Visitor(visitor))
394 }
395
396 #[inline]
397 fn decode_bool(mut self) -> Result<bool, C::Error> {
398 const FALSE: Tag = Tag::from_mark(Mark::False);
399 const TRUE: Tag = Tag::from_mark(Mark::True);
400
401 let pos = self.cx.mark();
402 let tag = Tag::from_byte(self.reader.read_byte(self.cx)?);
403
404 match tag {
405 FALSE => Ok(false),
406 TRUE => Ok(true),
407 tag => Err(self.cx.marked_message(
408 pos,
409 format_args! {
410 "Bad boolean, got {tag:?}"
411 },
412 )),
413 }
414 }
415
416 #[inline]
417 fn decode_char(mut self) -> Result<char, C::Error> {
418 const CHAR: Tag = Tag::from_mark(Mark::Char);
419
420 let pos = self.cx.mark();
421 let tag = Tag::from_byte(self.reader.read_byte(self.cx)?);
422
423 if tag != CHAR {
424 return Err(self
425 .cx
426 .marked_message(pos, format_args!("Expected {CHAR:?}, got {tag:?}")));
427 }
428
429 let num = c::decode(self.cx, self.reader.borrow_mut())?;
430
431 match char::from_u32(num) {
432 Some(d) => Ok(d),
433 None => Err(self.cx.marked_message(pos, format_args!("Bad character"))),
434 }
435 }
436
437 #[inline]
438 fn decode_number<V>(mut self, visitor: V) -> Result<V::Ok, C::Error>
439 where
440 V: NumberVisitor<'de, C>,
441 {
442 let cx = self.cx;
443 let tag = Tag::from_byte(self.reader.read_byte(cx)?);
444
445 match tag.kind() {
446 Kind::Number => match tag.data() {
447 Some(U8) => {
448 let value = self.decode_u8()?;
449 visitor.visit_u8(cx, value)
450 }
451 Some(U16) => {
452 let value = self.decode_u16()?;
453 visitor.visit_u16(cx, value)
454 }
455 Some(U32) => {
456 let value = self.decode_u32()?;
457 visitor.visit_u32(cx, value)
458 }
459 Some(U64) => {
460 let value = self.decode_u64()?;
461 visitor.visit_u64(cx, value)
462 }
463 Some(U128) => {
464 let value = self.decode_u128()?;
465 visitor.visit_u128(cx, value)
466 }
467 Some(I8) => {
468 let value = self.decode_i8()?;
469 visitor.visit_i8(cx, value)
470 }
471 Some(I16) => {
472 let value = self.decode_i16()?;
473 visitor.visit_i16(cx, value)
474 }
475 Some(I32) => {
476 let value = self.decode_i32()?;
477 visitor.visit_i32(cx, value)
478 }
479 Some(I64) => {
480 let value = self.decode_i64()?;
481 visitor.visit_i64(cx, value)
482 }
483 Some(I128) => {
484 let value = self.decode_i128()?;
485 visitor.visit_i128(cx, value)
486 }
487 Some(F32) => {
488 let value = self.decode_f32()?;
489 visitor.visit_f32(cx, value)
490 }
491 Some(F64) => {
492 let value = self.decode_f64()?;
493 visitor.visit_f64(cx, value)
494 }
495 _ => Err(cx.message(format_args!("Unsupported number tag, got {tag:?}"))),
496 },
497 _ => Err(cx.message(format_args!("Expected number, but got {tag:?}"))),
498 }
499 }
500
501 #[inline]
502 fn decode_u8(self) -> Result<u8, C::Error> {
503 decode_typed_unsigned(self.cx, self.reader)
504 }
505
506 #[inline]
507 fn decode_u16(self) -> Result<u16, C::Error> {
508 decode_typed_unsigned(self.cx, self.reader)
509 }
510
511 #[inline]
512 fn decode_u32(self) -> Result<u32, C::Error> {
513 decode_typed_unsigned(self.cx, self.reader)
514 }
515
516 #[inline]
517 fn decode_u64(self) -> Result<u64, C::Error> {
518 decode_typed_unsigned(self.cx, self.reader)
519 }
520
521 #[inline]
522 fn decode_u128(self) -> Result<u128, C::Error> {
523 decode_typed_unsigned(self.cx, self.reader)
524 }
525
526 #[inline]
527 fn decode_i8(self) -> Result<i8, C::Error> {
528 decode_typed_signed(self.cx, self.reader)
529 }
530
531 #[inline]
532 fn decode_i16(self) -> Result<i16, C::Error> {
533 decode_typed_signed(self.cx, self.reader)
534 }
535
536 #[inline]
537 fn decode_i32(self) -> Result<i32, C::Error> {
538 decode_typed_signed(self.cx, self.reader)
539 }
540
541 #[inline]
542 fn decode_i64(self) -> Result<i64, C::Error> {
543 decode_typed_signed(self.cx, self.reader)
544 }
545
546 #[inline]
547 fn decode_i128(self) -> Result<i128, C::Error> {
548 decode_typed_signed(self.cx, self.reader)
549 }
550
551 #[inline]
552 fn decode_usize(mut self) -> Result<usize, C::Error> {
553 decode_typed_unsigned(self.cx, self.reader.borrow_mut())
554 }
555
556 #[inline]
557 fn decode_isize(self) -> Result<isize, C::Error> {
558 decode_typed_signed(self.cx, self.reader)
559 }
560
561 #[inline]
564 fn decode_f32(self) -> Result<f32, C::Error> {
565 let bits = self.decode_u32()?;
566 Ok(f32::from_bits(bits))
567 }
568
569 #[inline]
572 fn decode_f64(self) -> Result<f64, C::Error> {
573 let bits = self.decode_u64()?;
574 Ok(f64::from_bits(bits))
575 }
576
577 #[inline]
578 fn decode_option(mut self) -> Result<Option<Self::DecodeSome>, C::Error> {
579 const NONE: Tag = Tag::from_mark(Mark::None);
581 const SOME: Tag = Tag::from_mark(Mark::Some);
582
583 let pos = self.cx.mark();
584 let tag = Tag::from_byte(self.reader.read_byte(self.cx)?);
585
586 match tag {
587 NONE => Ok(None),
588 SOME => Ok(Some(self)),
589 tag => Err(self.cx.marked_message(
590 pos,
591 format_args! {
592 "Expected option, was {tag:?}"
593 },
594 )),
595 }
596 }
597
598 #[inline]
599 fn decode_sequence<F, O>(self, f: F) -> Result<O, C::Error>
600 where
601 F: FnOnce(&mut Self::DecodeSequence) -> Result<O, C::Error>,
602 {
603 let mut decoder = self.shared_decode_sequence()?;
604 let output = f(&mut decoder)?;
605 decoder.skip_sequence_remaining()?;
606 Ok(output)
607 }
608
609 #[inline]
610 fn decode_sequence_hint<F, O>(self, _: &SequenceHint, f: F) -> Result<O, C::Error>
611 where
612 F: FnOnce(&mut Self::DecodeSequenceHint) -> Result<O, C::Error>,
613 {
614 self.decode_sequence(f)
615 }
616
617 #[inline]
618 fn decode_map<F, O>(self, f: F) -> Result<O, C::Error>
619 where
620 F: FnOnce(&mut Self::DecodeMap) -> Result<O, C::Error>,
621 {
622 let mut decoder = self.shared_decode_map()?;
623 let output = f(&mut decoder)?;
624 decoder.skip_map_remaining()?;
625 Ok(output)
626 }
627
628 #[inline]
629 fn decode_map_hint<F, O>(self, _: &MapHint, f: F) -> Result<O, C::Error>
630 where
631 F: FnOnce(&mut Self::DecodeMapHint) -> Result<O, C::Error>,
632 {
633 self.decode_map(f)
634 }
635
636 #[inline]
637 fn decode_map_entries(self) -> Result<Self::DecodeMapEntries, C::Error> {
638 self.shared_decode_map()
639 }
640
641 #[inline]
642 fn decode_variant<F, O>(mut self, f: F) -> Result<O, C::Error>
643 where
644 F: FnOnce(&mut Self::DecodeVariant) -> Result<O, C::Error>,
645 {
646 const VARIANT: Tag = Tag::from_mark(Mark::Variant);
647
648 let tag = Tag::from_byte(self.reader.read_byte(self.cx)?);
649
650 if tag != VARIANT {
651 return Err(self.cx.message(Expected {
652 expected: Kind::Mark,
653 actual: tag,
654 }));
655 }
656
657 f(&mut self)
658 }
659
660 #[inline]
661 fn decode_any<V>(mut self, visitor: V) -> Result<V::Ok, C::Error>
662 where
663 V: Visitor<'de, C>,
664 {
665 let cx = self.cx;
666
667 let Some(tag) = self.reader.peek(cx)?.map(Tag::from_byte) else {
668 return Err(cx.message("Expected tag in input"));
669 };
670
671 match tag.kind() {
672 Kind::Number => {
673 let Some(data) = tag.data() else {
674 return Err(cx.message("Expected number with data"));
675 };
676
677 match data {
678 U8 => {
679 let value = self.decode_u8()?;
680 visitor.visit_u8(cx, value)
681 }
682 U16 => {
683 let value = self.decode_u16()?;
684 visitor.visit_u16(cx, value)
685 }
686 U32 => {
687 let value = self.decode_u32()?;
688 visitor.visit_u32(cx, value)
689 }
690 U64 => {
691 let value = self.decode_u64()?;
692 visitor.visit_u64(cx, value)
693 }
694 U128 => {
695 let value = self.decode_u128()?;
696 visitor.visit_u128(cx, value)
697 }
698 I8 => {
699 let value = self.decode_i8()?;
700 visitor.visit_i8(cx, value)
701 }
702 I16 => {
703 let value = self.decode_i16()?;
704 visitor.visit_i16(cx, value)
705 }
706 I32 => {
707 let value = self.decode_i32()?;
708 visitor.visit_i32(cx, value)
709 }
710 I64 => {
711 let value = self.decode_i64()?;
712 visitor.visit_i64(cx, value)
713 }
714 I128 => {
715 let value = self.decode_i128()?;
716 visitor.visit_i128(cx, value)
717 }
718 F32 => {
719 let value = self.decode_f32()?;
720 visitor.visit_f32(cx, value)
721 }
722 F64 => {
723 let value = self.decode_f64()?;
724 visitor.visit_f64(cx, value)
725 }
726 data => Err(cx.message(format_args!("Unsupported number data {data:?}"))),
727 }
728 }
729 Kind::Sequence => {
730 let mut sequence = self.shared_decode_sequence()?;
731 let output = visitor.visit_sequence(cx, &mut sequence)?;
732 sequence.skip_sequence_remaining()?;
733 Ok(output)
734 }
735 Kind::Map => {
736 let mut map = self.shared_decode_map()?;
737 let output = visitor.visit_map(cx, &mut map)?;
738 map.skip_map_remaining()?;
739 Ok(output)
740 }
741 Kind::Bytes => {
742 let hint = tag
743 .data()
744 .map(|d| SizeHint::Exact(d as usize))
745 .unwrap_or_default();
746 let visitor = visitor.visit_bytes(cx, hint)?;
747 self.decode_bytes(visitor)
748 }
749 Kind::String => {
750 let hint = tag
751 .data()
752 .map(|d| SizeHint::Exact(d as usize))
753 .unwrap_or_default();
754 let visitor = visitor.visit_string(cx, hint)?;
755 self.decode_string(visitor)
756 }
757 Kind::Mark => match tag.mark() {
758 Mark::True | Mark::False => {
759 let value = self.decode_bool()?;
760 visitor.visit_bool(cx, value)
761 }
762 Mark::Variant => self.decode_variant(|decoder| visitor.visit_variant(cx, decoder)),
763 Mark::Some | Mark::None => {
764 let value = self.decode_option()?;
765 visitor.visit_option(cx, value)
766 }
767 Mark::Char => {
768 let value = self.decode_char()?;
769 visitor.visit_char(cx, value)
770 }
771 Mark::Unit => {
772 self.decode_unit()?;
773 visitor.visit_unit(cx)
774 }
775 mark => Err(cx.message(format_args!("Unsupported mark {mark:?}"))),
776 },
777 kind => Err(cx.message(format_args!("Unsupported kind {kind:?}"))),
778 }
779 }
780}
781
782impl<'a, 'de, R, const OPT: Options, C> SequenceDecoder<'de> for SelfDecoder<'a, Limit<R>, OPT, C>
783where
784 R: Reader<'de>,
785 C: ?Sized + Context,
786{
787 type Cx = C;
788 type DecodeNext<'this> = StorageDecoder<'a, <Limit<R> as Reader<'de>>::Mut<'this>, OPT, C> where Self: 'this;
789
790 #[inline]
791 fn try_decode_next(&mut self) -> Result<Option<Self::DecodeNext<'_>>, C::Error> {
792 Ok(Some(StorageDecoder::new(self.cx, self.reader.borrow_mut())))
793 }
794
795 #[inline]
796 fn decode_next(&mut self) -> Result<Self::DecodeNext<'_>, C::Error> {
797 Ok(StorageDecoder::new(self.cx, self.reader.borrow_mut()))
798 }
799}
800
801impl<'a, 'de, R, const OPT: Options, C> SequenceDecoder<'de> for RemainingSelfDecoder<'a, R, OPT, C>
802where
803 R: Reader<'de>,
804 C: ?Sized + Context,
805{
806 type Cx = C;
807 type DecodeNext<'this> = SelfDecoder<'a, R::Mut<'this>, OPT, C> where Self: 'this;
808
809 #[inline]
810 fn size_hint(&self) -> SizeHint {
811 SizeHint::Exact(self.remaining)
812 }
813
814 #[inline]
815 fn try_decode_next(&mut self) -> Result<Option<Self::DecodeNext<'_>>, C::Error> {
816 if self.remaining == 0 {
817 return Ok(None);
818 }
819
820 self.remaining -= 1;
821 Ok(Some(SelfDecoder::new(self.cx, self.reader.borrow_mut())))
822 }
823
824 #[inline]
825 fn decode_next(&mut self) -> Result<Self::DecodeNext<'_>, <Self::Cx as Context>::Error> {
826 let cx = self.cx;
827
828 let Some(decoder) = self.try_decode_next()? else {
829 return Err(cx.message("No remaining elements"));
830 };
831
832 Ok(decoder)
833 }
834}
835
836impl<'a, 'de, R, const OPT: Options, C> MapDecoder<'de> for RemainingSelfDecoder<'a, R, OPT, C>
837where
838 R: Reader<'de>,
839 C: ?Sized + Context,
840{
841 type Cx = C;
842 type DecodeEntry<'this> = SelfDecoder<'a, R::Mut<'this>, OPT, C>
843 where
844 Self: 'this;
845 type DecodeRemainingEntries<'this> = RemainingSelfDecoder<'a, R::Mut<'this>, OPT, C>
846 where
847 Self: 'this;
848
849 #[inline]
850 fn size_hint(&self) -> SizeHint {
851 SizeHint::Exact(self.remaining)
852 }
853
854 #[inline]
855 fn decode_entry(&mut self) -> Result<Option<Self::DecodeEntry<'_>>, C::Error> {
856 if self.remaining == 0 {
857 return Ok(None);
858 }
859
860 self.remaining -= 1;
861 Ok(Some(SelfDecoder::new(self.cx, self.reader.borrow_mut())))
862 }
863
864 #[inline]
865 fn decode_remaining_entries(&mut self) -> Result<Self::DecodeRemainingEntries<'_>, C::Error> {
866 Ok(RemainingSelfDecoder::new(
867 self.cx,
868 self.reader.borrow_mut(),
869 take(&mut self.remaining),
870 ))
871 }
872}
873
874impl<'a, 'de, R, const OPT: Options, C> EntriesDecoder<'de> for RemainingSelfDecoder<'a, R, OPT, C>
875where
876 R: Reader<'de>,
877 C: ?Sized + Context,
878{
879 type Cx = C;
880 type DecodeEntryKey<'this> = SelfDecoder<'a, R::Mut<'this>, OPT, C>
881 where
882 Self: 'this;
883 type DecodeEntryValue<'this> = SelfDecoder<'a, R::Mut<'this>, OPT, C>
884 where
885 Self: 'this;
886
887 #[inline]
888 fn decode_entry_key(&mut self) -> Result<Option<Self::DecodeEntryKey<'_>>, C::Error> {
889 if self.remaining == 0 {
890 return Ok(None);
891 }
892
893 self.remaining -= 1;
894 Ok(Some(SelfDecoder::new(self.cx, self.reader.borrow_mut())))
895 }
896
897 #[inline]
898 fn decode_entry_value(&mut self) -> Result<Self::DecodeEntryValue<'_>, C::Error> {
899 Ok(SelfDecoder::new(self.cx, self.reader.borrow_mut()))
900 }
901
902 #[inline]
903 fn end_entries(self) -> Result<(), <Self::Cx as Context>::Error> {
904 self.skip_map_remaining()?;
905 Ok(())
906 }
907}
908
909impl<'a, 'de, R, const OPT: Options, C> EntryDecoder<'de> for SelfDecoder<'a, R, OPT, C>
910where
911 R: Reader<'de>,
912 C: ?Sized + Context,
913{
914 type Cx = C;
915 type DecodeKey<'this> = SelfDecoder<'a, R::Mut<'this>, OPT, C> where Self: 'this;
916 type DecodeValue = Self;
917
918 #[inline]
919 fn decode_key(&mut self) -> Result<Self::DecodeKey<'_>, C::Error> {
920 Ok(SelfDecoder::new(self.cx, self.reader.borrow_mut()))
921 }
922
923 #[inline]
924 fn decode_value(self) -> Result<Self::DecodeValue, C::Error> {
925 Ok(self)
926 }
927}
928
929impl<'a, 'de, R, const OPT: Options, C> VariantDecoder<'de> for SelfDecoder<'a, R, OPT, C>
930where
931 R: Reader<'de>,
932 C: ?Sized + Context,
933{
934 type Cx = C;
935 type DecodeTag<'this> = SelfDecoder<'a, R::Mut<'this>, OPT, C> where Self: 'this;
936 type DecodeValue<'this> = SelfDecoder<'a, R::Mut<'this>, OPT, C> where Self: 'this;
937
938 #[inline]
939 fn decode_tag(&mut self) -> Result<Self::DecodeTag<'_>, C::Error> {
940 Ok(SelfDecoder::new(self.cx, self.reader.borrow_mut()))
941 }
942
943 #[inline]
944 fn decode_value(&mut self) -> Result<Self::DecodeValue<'_>, C::Error> {
945 Ok(SelfDecoder::new(self.cx, self.reader.borrow_mut()))
946 }
947}
948
949struct Expected {
950 expected: Kind,
951 actual: Tag,
952}
953
954impl fmt::Display for Expected {
955 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
956 let Self { expected, actual } = *self;
957
958 write!(f, "Expected {expected:?} but was {actual:?}",)
959 }
960}