musli_core/de/decoder.rs
1use core::fmt;
2
3use crate::expecting::{self, Expecting};
4use crate::hint::{MapHint, SequenceHint};
5use crate::{Allocator, Context};
6
7use super::{
8 utils, AsDecoder, Decode, DecodeSliceBuilder, DecodeUnsized, DecodeUnsizedBytes,
9 EntriesDecoder, MapDecoder, SequenceDecoder, Skip, UnsizedVisitor, VariantDecoder, Visitor,
10};
11
12/// An outcome of a fast decode attempt.
13#[non_exhaustive]
14pub enum TryFastDecode<T, D> {
15 /// The decode attempt was successful.
16 Ok(T),
17 /// The decode was unsupported.
18 Unsupported(D),
19}
20
21/// Trait governing the implementation of a decoder.
22#[must_use = "Decoders must be consumed through one of its decode_* methods"]
23#[allow(unused_variables)]
24pub trait Decoder<'de>: Sized {
25 /// Context associated with the decoder.
26 type Cx: Context<Error = Self::Error, Allocator = Self::Allocator>;
27 /// Error associated with decoding.
28 type Error;
29 /// The allocator associated with the decoder.
30 type Allocator: Allocator;
31 /// Mode associated with decoding.
32 type Mode: 'static;
33 /// A clone of the current decoder.
34 type TryClone: Decoder<
35 'de,
36 Cx = Self::Cx,
37 Error = Self::Error,
38 Allocator = Self::Allocator,
39 Mode = Self::Mode,
40 >;
41 /// Decoder returned by [`Decoder::decode_buffer`].
42 type DecodeBuffer: AsDecoder<
43 Cx = Self::Cx,
44 Error = Self::Error,
45 Allocator = Self::Allocator,
46 Mode = Self::Mode,
47 >;
48 /// Decoder returned by [`Decoder::decode_option`].
49 type DecodeSome: Decoder<
50 'de,
51 Cx = Self::Cx,
52 Error = Self::Error,
53 Allocator = Self::Allocator,
54 Mode = Self::Mode,
55 >;
56 /// Decoder used by [`Decoder::decode_pack`].
57 type DecodePack: SequenceDecoder<
58 'de,
59 Cx = Self::Cx,
60 Error = Self::Error,
61 Allocator = Self::Allocator,
62 Mode = Self::Mode,
63 >;
64 /// Decoder returned by [`Decoder::decode_sequence`].
65 type DecodeSequence: SequenceDecoder<
66 'de,
67 Cx = Self::Cx,
68 Error = Self::Error,
69 Allocator = Self::Allocator,
70 Mode = Self::Mode,
71 >;
72 /// Decoder returned by [`Decoder::decode_map`].
73 type DecodeMap: MapDecoder<
74 'de,
75 Cx = Self::Cx,
76 Error = Self::Error,
77 Allocator = Self::Allocator,
78 Mode = Self::Mode,
79 >;
80 /// Decoder returned by [`Decoder::decode_map_entries`].
81 type DecodeMapEntries: EntriesDecoder<
82 'de,
83 Cx = Self::Cx,
84 Error = Self::Error,
85 Allocator = Self::Allocator,
86 Mode = Self::Mode,
87 >;
88 /// Decoder used by [`Decoder::decode_variant`].
89 type DecodeVariant: VariantDecoder<
90 'de,
91 Cx = Self::Cx,
92 Error = Self::Error,
93 Allocator = Self::Allocator,
94 Mode = Self::Mode,
95 >;
96
97 /// This is a type argument used to hint to any future implementor that they
98 /// should be using the [`#[musli::decoder]`][musli::decoder] attribute
99 /// macro when implementing [`Decoder`].
100 #[doc(hidden)]
101 type __UseMusliDecoderAttributeMacro;
102
103 /// Access the context associated with the decoder.
104 fn cx(&self) -> Self::Cx;
105
106 /// Format the human-readable message that should occur if the decoder was
107 /// expecting to decode some specific kind of value.
108 ///
109 /// # Examples
110 ///
111 /// ```
112 /// use std::fmt;
113 /// use std::convert::Infallible;
114 /// use std::marker::PhantomData;
115 ///
116 /// use musli::Context;
117 /// use musli::de::{self, Decoder, Decode};
118 ///
119 /// struct MyDecoder<C, M> {
120 /// cx: C,
121 /// _marker: PhantomData<M>,
122 /// }
123 ///
124 /// #[musli::decoder]
125 /// impl<'de, C, M> Decoder<'de> for MyDecoder<C, M>
126 /// where
127 /// C: Context,
128 /// M: 'static,
129 /// {
130 /// type Cx = C;
131 ///
132 /// #[inline]
133 /// fn cx(&self) -> Self::Cx {
134 /// self.cx
135 /// }
136 ///
137 /// #[inline]
138 /// fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 /// write!(f, "32-bit unsigned integers")
140 /// }
141 ///
142 /// #[inline]
143 /// fn decode_u32(self) -> Result<u32, Self::Error> {
144 /// Ok(42)
145 /// }
146 /// }
147 /// ```
148 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
149
150 /// Attempt to clone the decoder so that it can be used multiple times.
151 #[inline]
152 fn try_clone(&self) -> Option<Self::TryClone> {
153 None
154 }
155
156 /// Try to quickly decode the specified value.
157 ///
158 /// The default implementation simply returns the current decoder as
159 /// `Err(Self)`.
160 ///
161 /// This is intended to be a fast path when decoding a value when an
162 /// encoding permits it.
163 #[inline]
164 fn try_fast_decode<T>(self) -> Result<TryFastDecode<T, Self>, Self::Error>
165 where
166 T: Decode<'de, Self::Mode, Self::Allocator>,
167 {
168 Ok(TryFastDecode::Unsupported(self))
169 }
170
171 /// Decode the current decoder into the value `T`.
172 ///
173 /// This calls the appropriate [`Decode`] implementation for the given type.
174 #[inline]
175 fn decode<T>(self) -> Result<T, Self::Error>
176 where
177 T: Decode<'de, Self::Mode, Self::Allocator>,
178 {
179 match self.try_fast_decode::<T>()? {
180 TryFastDecode::Ok(value) => Ok(value),
181 TryFastDecode::Unsupported(decoder) => T::decode(decoder),
182 }
183 }
184
185 /// Decode an unsized value by reference through the specified closure.
186 #[inline]
187 fn decode_unsized<T, F, O>(self, f: F) -> Result<O, Self::Error>
188 where
189 T: ?Sized + DecodeUnsized<'de, Self::Mode>,
190 F: FnOnce(&T) -> Result<O, Self::Error>,
191 {
192 T::decode_unsized(self, f)
193 }
194
195 /// Decode an unsized value as bytes by reference through the specified
196 /// closure.
197 #[inline]
198 fn decode_unsized_bytes<T, F, O>(self, f: F) -> Result<O, Self::Error>
199 where
200 T: ?Sized + DecodeUnsizedBytes<'de, Self::Mode>,
201 F: FnOnce(&T) -> Result<O, Self::Error>,
202 {
203 T::decode_unsized_bytes(self, f)
204 }
205
206 /// Skip over the current next value.
207 #[inline]
208 fn skip(self) -> Result<(), Self::Error> {
209 Err(self.cx().message(format_args!(
210 "Skipping is not supported, expected {}",
211 ExpectingWrapper::new(&self).format()
212 )))
213 }
214
215 /// This is a variant of [`Decoder::skip`], but instead of erroring in case
216 /// skipping is not supported it must return [`Skip::Unsupported`].
217 #[inline(always)]
218 fn try_skip(self) -> Result<Skip, Self::Error> {
219 Ok(Skip::Unsupported)
220 }
221
222 /// Buffer the current decoder into a buffer that can be used multiple times.
223 ///
224 /// Buffering a decoder is necessary when additional introspection is needed
225 /// to decode a type, but it also means that:
226 ///
227 /// * The entire contents of the decoder needs to be dynamically buffered in
228 /// memory.
229 /// * The in-memory representation might be lossy in some trivial ways. Such
230 /// as arbitrary precision numbers being punted into a 64-bit float.
231 ///
232 /// # Examples
233 ///
234 /// ```
235 /// use musli::{Allocator, Context, Decode, Decoder};
236 /// use musli::de::{AsDecoder, MapDecoder, EntryDecoder};
237 /// use musli::mode::Binary;
238 ///
239 /// #[derive(Decode)]
240 /// struct Person {
241 /// name: String,
242 /// age: u32,
243 /// }
244 ///
245 /// enum Enum {
246 /// Empty,
247 /// Person(Person),
248 /// }
249 ///
250 /// impl<'de, A> Decode<'de, Binary, A> for Enum
251 /// where
252 /// A: Allocator,
253 /// {
254 /// #[inline]
255 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
256 /// where
257 /// D: Decoder<'de, Mode = Binary>,
258 /// {
259 /// let cx = decoder.cx();
260 ///
261 /// let mut buffer = decoder.decode_buffer()?;
262 ///
263 /// let discriminant = buffer.as_decoder()?.decode_map(|st| {
264 /// loop {
265 /// let Some(mut e) = st.decode_entry()? else {
266 /// return Err(cx.message("Missing variant tag"));
267 /// };
268 ///
269 /// let found = e.decode_key()?.decode_unsized(|string: &str| {
270 /// Ok(string == "type")
271 /// })?;
272 ///
273 /// if found {
274 /// break Ok(e.decode_value()?.decode()?);
275 /// }
276 /// }
277 /// })?;
278 ///
279 /// match discriminant {
280 /// 0 => Ok(Enum::Empty),
281 /// 1 => Ok(Enum::Person(buffer.as_decoder()?.decode()?)),
282 /// other => Err(cx.message(format_args!("Invalid variant tag {other:?}"))),
283 /// }
284 /// }
285 /// }
286 /// ```
287 #[inline]
288 fn decode_buffer(self) -> Result<Self::DecodeBuffer, Self::Error> {
289 Err(self.cx().message(format_args!(
290 "Decode buffering not supported, expected {}",
291 ExpectingWrapper::new(&self).format()
292 )))
293 }
294
295 /// Decode a unit.
296 ///
297 /// # Examples
298 ///
299 /// Deriving an implementation:
300 ///
301 /// ```
302 /// use musli::Decode;
303 ///
304 /// #[derive(Decode)]
305 /// struct UnitStruct;
306 /// ```
307 ///
308 /// Implementing manually:
309 ///
310 /// ```
311 /// use musli::{Allocator, Decode, Decoder};
312 /// # struct UnitType;
313 ///
314 /// impl<'de, M, A> Decode<'de, M, A> for UnitType
315 /// where
316 /// A: Allocator,
317 /// {
318 /// #[inline]
319 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
320 /// where
321 /// D: Decoder<'de>,
322 /// {
323 /// decoder.decode_empty()?;
324 /// Ok(UnitType)
325 /// }
326 /// }
327 /// ```
328 #[inline]
329 fn decode_empty(self) -> Result<(), Self::Error> {
330 Err(self.cx().message(expecting::unsupported_type(
331 &expecting::Empty,
332 ExpectingWrapper::new(&self),
333 )))
334 }
335
336 /// Decode a boolean.
337 ///
338 /// # Examples
339 ///
340 /// Deriving an implementation:
341 ///
342 /// ```
343 /// use musli::Decode;
344 ///
345 /// #[derive(Decode)]
346 /// #[musli(packed)]
347 /// struct BooleanField {
348 /// field: bool,
349 /// }
350 /// ```
351 ///
352 /// Implementing manually:
353 ///
354 /// ```
355 /// use musli::{Allocator, Decode, Decoder};
356 /// # struct BooleanField { field: bool }
357 ///
358 /// impl<'de, M, A> Decode<'de, M, A> for BooleanField
359 /// where
360 /// A: Allocator,
361 /// {
362 /// #[inline]
363 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
364 /// where
365 /// D: Decoder<'de>,
366 /// {
367 /// Ok(Self {
368 /// field: decoder.decode_bool()?,
369 /// })
370 /// }
371 /// }
372 /// ```
373 #[inline]
374 fn decode_bool(self) -> Result<bool, Self::Error> {
375 Err(self.cx().message(expecting::unsupported_type(
376 &expecting::Bool,
377 ExpectingWrapper::new(&self),
378 )))
379 }
380
381 /// Decode a character.
382 ///
383 /// # Examples
384 ///
385 /// Deriving an implementation:
386 ///
387 /// ```
388 /// use musli::Decode;
389 ///
390 /// #[derive(Decode)]
391 /// #[musli(packed)]
392 /// struct MyType {
393 /// data: char,
394 /// }
395 /// ```
396 ///
397 /// Implementing manually:
398 ///
399 /// ```
400 /// use musli::{Allocator, Decode, Decoder};
401 /// # struct MyType { data: char }
402 ///
403 /// impl<'de, M, A> Decode<'de, M, A> for MyType
404 /// where
405 /// A: Allocator,
406 /// {
407 /// #[inline]
408 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
409 /// where
410 /// D: Decoder<'de>,
411 /// {
412 /// Ok(Self {
413 /// data: decoder.decode_char()?,
414 /// })
415 /// }
416 /// }
417 /// ```
418 #[inline]
419 fn decode_char(self) -> Result<char, Self::Error> {
420 Err(self.cx().message(expecting::unsupported_type(
421 &expecting::Char,
422 ExpectingWrapper::new(&self),
423 )))
424 }
425
426 /// Decode a 8-bit unsigned integer (a.k.a. a byte).
427 ///
428 /// # Examples
429 ///
430 /// Deriving an implementation:
431 ///
432 /// ```
433 /// use musli::Decode;
434 ///
435 /// #[derive(Decode)]
436 /// #[musli(packed)]
437 /// struct MyType {
438 /// data: u8,
439 /// }
440 /// ```
441 ///
442 /// Implementing manually:
443 ///
444 /// ```
445 /// use musli::{Allocator, Decode, Decoder};
446 /// # struct MyType { data: u8 }
447 ///
448 /// impl<'de, M, A> Decode<'de, M, A> for MyType
449 /// where
450 /// A: Allocator,
451 /// {
452 /// #[inline]
453 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
454 /// where
455 /// D: Decoder<'de>,
456 /// {
457 /// Ok(Self {
458 /// data: decoder.decode_u8()?,
459 /// })
460 /// }
461 /// }
462 /// ```
463 #[inline]
464 fn decode_u8(self) -> Result<u8, Self::Error> {
465 Err(self.cx().message(expecting::unsupported_type(
466 &expecting::Unsigned8,
467 ExpectingWrapper::new(&self),
468 )))
469 }
470
471 /// Decode a 16-bit unsigned integer.
472 ///
473 /// # Examples
474 ///
475 /// Deriving an implementation:
476 ///
477 /// ```
478 /// use musli::Decode;
479 ///
480 /// #[derive(Decode)]
481 /// #[musli(packed)]
482 /// struct MyType {
483 /// data: u16,
484 /// }
485 /// ```
486 ///
487 /// Implementing manually:
488 ///
489 /// ```
490 /// use musli::{Allocator, Decode, Decoder};
491 /// # struct MyType { data: u16 }
492 ///
493 /// impl<'de, M, A> Decode<'de, M, A> for MyType
494 /// where
495 /// A: Allocator,
496 /// {
497 /// #[inline]
498 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
499 /// where
500 /// D: Decoder<'de>,
501 /// {
502 /// Ok(Self {
503 /// data: decoder.decode_u16()?,
504 /// })
505 /// }
506 /// }
507 /// ```
508 #[inline]
509 fn decode_u16(self) -> Result<u16, Self::Error> {
510 Err(self.cx().message(expecting::unsupported_type(
511 &expecting::Unsigned16,
512 ExpectingWrapper::new(&self),
513 )))
514 }
515
516 /// Decode a 32-bit unsigned integer.
517 ///
518 /// # Examples
519 ///
520 /// Deriving an implementation:
521 ///
522 /// ```
523 /// use musli::Decode;
524 ///
525 /// #[derive(Decode)]
526 /// #[musli(packed)]
527 /// struct MyType {
528 /// data: u32,
529 /// }
530 /// ```
531 ///
532 /// Implementing manually:
533 ///
534 /// ```
535 /// use musli::{Allocator, Decode, Decoder};
536 /// # struct MyType { data: u32 }
537 ///
538 /// impl<'de, M, A> Decode<'de, M, A> for MyType
539 /// where
540 /// A: Allocator,
541 /// {
542 /// #[inline]
543 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
544 /// where
545 /// D: Decoder<'de>,
546 /// {
547 /// Ok(Self {
548 /// data: decoder.decode_u32()?,
549 /// })
550 /// }
551 /// }
552 /// ```
553 #[inline]
554 fn decode_u32(self) -> Result<u32, Self::Error> {
555 Err(self.cx().message(expecting::unsupported_type(
556 &expecting::Unsigned32,
557 ExpectingWrapper::new(&self),
558 )))
559 }
560
561 /// Decode a 64-bit unsigned integer.
562 ///
563 /// # Examples
564 ///
565 /// Deriving an implementation:
566 ///
567 /// ```
568 /// use musli::Decode;
569 ///
570 /// #[derive(Decode)]
571 /// #[musli(packed)]
572 /// struct MyType {
573 /// data: u64,
574 /// }
575 /// ```
576 ///
577 /// Implementing manually:
578 ///
579 /// ```
580 /// use musli::{Allocator, Decode, Decoder};
581 /// # struct MyType { data: u64 }
582 ///
583 /// impl<'de, M, A> Decode<'de, M, A> for MyType
584 /// where
585 /// A: Allocator,
586 /// {
587 /// #[inline]
588 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
589 /// where
590 /// D: Decoder<'de>,
591 /// {
592 /// Ok(Self {
593 /// data: decoder.decode_u64()?,
594 /// })
595 /// }
596 /// }
597 /// ```
598 #[inline]
599 fn decode_u64(self) -> Result<u64, Self::Error> {
600 Err(self.cx().message(expecting::unsupported_type(
601 &expecting::Unsigned64,
602 ExpectingWrapper::new(&self),
603 )))
604 }
605
606 /// Decode a 128-bit unsigned integer.
607 ///
608 /// # Examples
609 ///
610 /// Deriving an implementation:
611 ///
612 /// ```
613 /// use musli::Decode;
614 ///
615 /// #[derive(Decode)]
616 /// #[musli(packed)]
617 /// struct MyType {
618 /// data: u128,
619 /// }
620 /// ```
621 ///
622 /// Implementing manually:
623 ///
624 /// ```
625 /// use musli::{Allocator, Decode, Decoder};
626 /// # struct MyType { data: u128 }
627 ///
628 /// impl<'de, M, A> Decode<'de, M, A> for MyType
629 /// where
630 /// A: Allocator,
631 /// {
632 /// #[inline]
633 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
634 /// where
635 /// D: Decoder<'de>,
636 /// {
637 /// Ok(Self {
638 /// data: decoder.decode_u128()?,
639 /// })
640 /// }
641 /// }
642 /// ```
643 #[inline]
644 fn decode_u128(self) -> Result<u128, Self::Error> {
645 Err(self.cx().message(expecting::unsupported_type(
646 &expecting::Unsigned128,
647 ExpectingWrapper::new(&self),
648 )))
649 }
650
651 /// Decode a 8-bit signed integer.
652 ///
653 /// # Examples
654 ///
655 /// Deriving an implementation:
656 ///
657 /// ```
658 /// use musli::Decode;
659 ///
660 /// #[derive(Decode)]
661 /// #[musli(packed)]
662 /// struct MyType {
663 /// data: i8,
664 /// }
665 /// ```
666 ///
667 /// Implementing manually:
668 ///
669 /// ```
670 /// use musli::{Allocator, Decode, Decoder};
671 /// # struct MyType { data: i8 }
672 ///
673 /// impl<'de, M, A> Decode<'de, M, A> for MyType
674 /// where
675 /// A: Allocator,
676 /// {
677 /// #[inline]
678 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
679 /// where
680 /// D: Decoder<'de>,
681 /// {
682 /// Ok(Self {
683 /// data: decoder.decode_i8()?,
684 /// })
685 /// }
686 /// }
687 /// ```
688 #[inline]
689 fn decode_i8(self) -> Result<i8, Self::Error> {
690 Err(self.cx().message(expecting::unsupported_type(
691 &expecting::Signed8,
692 ExpectingWrapper::new(&self),
693 )))
694 }
695
696 /// Decode a 16-bit signed integer.
697 ///
698 /// # Examples
699 ///
700 /// Deriving an implementation:
701 ///
702 /// ```
703 /// use musli::Decode;
704 ///
705 /// #[derive(Decode)]
706 /// #[musli(packed)]
707 /// struct MyType {
708 /// data: i16,
709 /// }
710 /// ```
711 ///
712 /// Implementing manually:
713 ///
714 /// ```
715 /// use musli::{Allocator, Decode, Decoder};
716 /// # struct MyType { data: i16 }
717 ///
718 /// impl<'de, M, A> Decode<'de, M, A> for MyType
719 /// where
720 /// A: Allocator,
721 /// {
722 /// #[inline]
723 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
724 /// where
725 /// D: Decoder<'de>,
726 /// {
727 /// Ok(Self {
728 /// data: decoder.decode_i16()?,
729 /// })
730 /// }
731 /// }
732 /// ```
733 #[inline]
734 fn decode_i16(self) -> Result<i16, Self::Error> {
735 Err(self.cx().message(expecting::unsupported_type(
736 &expecting::Signed16,
737 ExpectingWrapper::new(&self),
738 )))
739 }
740
741 /// Decode a 32-bit signed integer.
742 ///
743 /// # Examples
744 ///
745 /// Deriving an implementation:
746 ///
747 /// ```
748 /// use musli::Decode;
749 ///
750 /// #[derive(Decode)]
751 /// #[musli(packed)]
752 /// struct MyType {
753 /// data: i32,
754 /// }
755 /// ```
756 ///
757 /// Implementing manually:
758 ///
759 /// ```
760 /// use musli::{Allocator, Decode, Decoder};
761 /// # struct MyType { data: i32 }
762 ///
763 /// impl<'de, M, A> Decode<'de, M, A> for MyType
764 /// where
765 /// A: Allocator,
766 /// {
767 /// #[inline]
768 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
769 /// where
770 /// D: Decoder<'de>,
771 /// {
772 /// Ok(Self {
773 /// data: decoder.decode_i32()?,
774 /// })
775 /// }
776 /// }
777 /// ```
778 #[inline]
779 fn decode_i32(self) -> Result<i32, Self::Error> {
780 Err(self.cx().message(expecting::unsupported_type(
781 &expecting::Signed32,
782 ExpectingWrapper::new(&self),
783 )))
784 }
785
786 /// Decode a 64-bit signed integer.
787 ///
788 /// # Examples
789 ///
790 /// Deriving an implementation:
791 ///
792 /// ```
793 /// use musli::Decode;
794 ///
795 /// #[derive(Decode)]
796 /// #[musli(packed)]
797 /// struct MyType {
798 /// data: i64,
799 /// }
800 /// ```
801 ///
802 /// Implementing manually:
803 ///
804 /// ```
805 /// use musli::{Allocator, Decode, Decoder};
806 /// # struct MyType { data: i64 }
807 ///
808 /// impl<'de, M, A> Decode<'de, M, A> for MyType
809 /// where
810 /// A: Allocator,
811 /// {
812 /// #[inline]
813 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
814 /// where
815 /// D: Decoder<'de>,
816 /// {
817 /// Ok(Self {
818 /// data: decoder.decode_i64()?,
819 /// })
820 /// }
821 /// }
822 /// ```
823 #[inline]
824 fn decode_i64(self) -> Result<i64, Self::Error> {
825 Err(self.cx().message(expecting::unsupported_type(
826 &expecting::Signed64,
827 ExpectingWrapper::new(&self),
828 )))
829 }
830
831 /// Decode a 128-bit signed integer.
832 ///
833 /// # Examples
834 ///
835 /// Deriving an implementation:
836 ///
837 /// ```
838 /// use musli::Decode;
839 ///
840 /// #[derive(Decode)]
841 /// #[musli(packed)]
842 /// struct MyType {
843 /// data: i128,
844 /// }
845 /// ```
846 ///
847 /// Implementing manually:
848 ///
849 /// ```
850 /// use musli::{Allocator, Decode, Decoder};
851 /// # struct MyType { data: i128 }
852 ///
853 /// impl<'de, M, A> Decode<'de, M, A> for MyType
854 /// where
855 /// A: Allocator,
856 /// {
857 /// #[inline]
858 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
859 /// where
860 /// D: Decoder<'de>,
861 /// {
862 /// Ok(Self {
863 /// data: decoder.decode_i128()?,
864 /// })
865 /// }
866 /// }
867 /// ```
868 #[inline]
869 fn decode_i128(self) -> Result<i128, Self::Error> {
870 Err(self.cx().message(expecting::unsupported_type(
871 &expecting::Signed128,
872 ExpectingWrapper::new(&self),
873 )))
874 }
875
876 /// Decode a [`usize`].
877 ///
878 /// # Examples
879 ///
880 /// Deriving an implementation:
881 ///
882 /// ```
883 /// use musli::Decode;
884 ///
885 /// #[derive(Decode)]
886 /// #[musli(packed)]
887 /// struct MyType {
888 /// data: usize,
889 /// }
890 /// ```
891 ///
892 /// Implementing manually:
893 ///
894 /// ```
895 /// use musli::{Allocator, Decode, Decoder};
896 /// # struct MyType { data: usize }
897 ///
898 /// impl<'de, M, A> Decode<'de, M, A> for MyType
899 /// where
900 /// A: Allocator,
901 /// {
902 /// #[inline]
903 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
904 /// where
905 /// D: Decoder<'de>,
906 /// {
907 /// Ok(Self {
908 /// data: decoder.decode_usize()?,
909 /// })
910 /// }
911 /// }
912 /// ```
913 #[inline]
914 fn decode_usize(self) -> Result<usize, Self::Error> {
915 Err(self.cx().message(expecting::unsupported_type(
916 &expecting::Usize,
917 ExpectingWrapper::new(&self),
918 )))
919 }
920
921 /// Decode a [`isize`].
922 ///
923 /// # Examples
924 ///
925 /// Deriving an implementation:
926 ///
927 /// ```
928 /// use musli::Decode;
929 ///
930 /// #[derive(Decode)]
931 /// #[musli(packed)]
932 /// struct MyType {
933 /// data: isize,
934 /// }
935 /// ```
936 ///
937 /// Implementing manually:
938 ///
939 /// ```
940 /// use musli::{Allocator, Decode, Decoder};
941 /// # struct MyType { data: isize }
942 ///
943 /// impl<'de, M, A> Decode<'de, M, A> for MyType
944 /// where
945 /// A: Allocator,
946 /// {
947 /// #[inline]
948 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
949 /// where
950 /// D: Decoder<'de>,
951 /// {
952 /// Ok(Self {
953 /// data: decoder.decode_isize()?,
954 /// })
955 /// }
956 /// }
957 /// ```
958 #[inline]
959 fn decode_isize(self) -> Result<isize, Self::Error> {
960 Err(self.cx().message(expecting::unsupported_type(
961 &expecting::Isize,
962 ExpectingWrapper::new(&self),
963 )))
964 }
965
966 /// Decode a 32-bit floating point value.
967 ///
968 /// # Examples
969 ///
970 /// Deriving an implementation:
971 ///
972 /// ```
973 /// use musli::Decode;
974 ///
975 /// #[derive(Decode)]
976 /// #[musli(packed)]
977 /// struct MyType {
978 /// data: f32,
979 /// }
980 /// ```
981 ///
982 /// Implementing manually:
983 ///
984 /// ```
985 /// use musli::{Allocator, Decode, Decoder};
986 /// # struct MyType { data: f32 }
987 ///
988 /// impl<'de, M, A> Decode<'de, M, A> for MyType
989 /// where
990 /// A: Allocator,
991 /// {
992 /// #[inline]
993 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
994 /// where
995 /// D: Decoder<'de>,
996 /// {
997 /// Ok(Self {
998 /// data: decoder.decode_f32()?,
999 /// })
1000 /// }
1001 /// }
1002 /// ```
1003 #[inline]
1004 fn decode_f32(self) -> Result<f32, Self::Error> {
1005 Err(self.cx().message(expecting::unsupported_type(
1006 &expecting::Float32,
1007 ExpectingWrapper::new(&self),
1008 )))
1009 }
1010
1011 /// Decode a 64-bit floating point value.
1012 ///
1013 /// # Examples
1014 ///
1015 /// Deriving an implementation:
1016 ///
1017 /// ```
1018 /// use musli::Decode;
1019 ///
1020 /// #[derive(Decode)]
1021 /// #[musli(packed)]
1022 /// struct MyType {
1023 /// data: f64,
1024 /// }
1025 /// ```
1026 ///
1027 /// Implementing manually:
1028 ///
1029 /// ```
1030 /// use musli::{Allocator, Decode, Decoder};
1031 /// # struct MyType { data: f64 }
1032 ///
1033 /// impl<'de, M, A> Decode<'de, M, A> for MyType
1034 /// where
1035 /// A: Allocator,
1036 /// {
1037 /// #[inline]
1038 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
1039 /// where
1040 /// D: Decoder<'de>,
1041 /// {
1042 /// Ok(Self {
1043 /// data: decoder.decode_f64()?,
1044 /// })
1045 /// }
1046 /// }
1047 /// ```
1048 #[inline]
1049 fn decode_f64(self) -> Result<f64, Self::Error> {
1050 Err(self.cx().message(expecting::unsupported_type(
1051 &expecting::Float64,
1052 ExpectingWrapper::new(&self),
1053 )))
1054 }
1055
1056 /// Decode a fixed-length array.
1057 ///
1058 /// # Examples
1059 ///
1060 /// Deriving an implementation:
1061 ///
1062 /// ```
1063 /// use musli::Decode;
1064 ///
1065 /// #[derive(Decode)]
1066 /// #[musli(packed)]
1067 /// struct MyType {
1068 /// data: [u8; 128],
1069 /// }
1070 /// ```
1071 ///
1072 /// Implementing manually:
1073 ///
1074 /// ```
1075 /// use musli::{Allocator, Decode, Decoder};
1076 /// # struct MyType { data: [u8; 128] }
1077 ///
1078 /// impl<'de, M, A> Decode<'de, M, A> for MyType
1079 /// where
1080 /// A: Allocator,
1081 /// {
1082 /// #[inline]
1083 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
1084 /// where
1085 /// D: Decoder<'de>,
1086 /// {
1087 /// Ok(Self {
1088 /// data: decoder.decode_array()?,
1089 /// })
1090 /// }
1091 /// }
1092 /// ```
1093 #[inline]
1094 fn decode_array<const N: usize>(self) -> Result<[u8; N], Self::Error> {
1095 Err(self.cx().message(expecting::unsupported_type(
1096 &expecting::Array,
1097 ExpectingWrapper::new(&self),
1098 )))
1099 }
1100
1101 /// Decode a sequence of bytes whos length is encoded in the payload.
1102 ///
1103 /// # Examples
1104 ///
1105 /// Deriving an implementation:
1106 ///
1107 /// ```
1108 /// use musli::Decode;
1109 ///
1110 /// #[derive(Decode)]
1111 /// #[musli(packed)]
1112 /// struct BytesReference<'de> {
1113 /// data: &'de [u8],
1114 /// }
1115 /// ```
1116 ///
1117 /// Implementing manually:
1118 ///
1119 /// ```
1120 /// use std::fmt;
1121 ///
1122 /// use musli::{Allocator, Context, Decode, Decoder};
1123 /// use musli::de::UnsizedVisitor;
1124 /// # struct BytesReference<'de> { data: &'de [u8] }
1125 ///
1126 /// impl<'de, M, A> Decode<'de, M, A> for BytesReference<'de>
1127 /// where
1128 /// A: Allocator,
1129 /// {
1130 /// #[inline]
1131 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
1132 /// where
1133 /// D: Decoder<'de>,
1134 /// {
1135 /// struct Visitor;
1136 ///
1137 /// #[musli::de::unsized_visitor]
1138 /// impl<'de, C> UnsizedVisitor<'de, C, [u8]> for Visitor
1139 /// where
1140 /// C: Context
1141 /// {
1142 /// type Ok = &'de [u8];
1143 ///
1144 /// #[inline]
1145 /// fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1146 /// write!(f, "a literal byte reference")
1147 /// }
1148 ///
1149 /// #[inline]
1150 /// fn visit_borrowed(self, cx: C, bytes: &'de [u8]) -> Result<Self::Ok, C::Error> {
1151 /// Ok(bytes)
1152 /// }
1153 /// }
1154 ///
1155 /// Ok(Self {
1156 /// data: decoder.decode_bytes(Visitor)?,
1157 /// })
1158 /// }
1159 /// }
1160 /// ```
1161 #[inline]
1162 fn decode_bytes<V>(self, visitor: V) -> Result<V::Ok, V::Error>
1163 where
1164 V: UnsizedVisitor<'de, Self::Cx, [u8], Error = Self::Error, Allocator = Self::Allocator>,
1165 {
1166 Err(self.cx().message(expecting::unsupported_type(
1167 &expecting::Bytes,
1168 ExpectingWrapper::new(&self),
1169 )))
1170 }
1171
1172 /// Decode a string slice from the current decoder.
1173 ///
1174 /// # Examples
1175 ///
1176 /// Deriving an implementation:
1177 ///
1178 /// ```
1179 /// use musli::Decode;
1180 ///
1181 /// #[derive(Decode)]
1182 /// #[musli(packed)]
1183 /// struct StringReference<'de> {
1184 /// data: &'de str,
1185 /// }
1186 /// ```
1187 ///
1188 /// Implementing manually:
1189 ///
1190 /// ```
1191 /// use std::fmt;
1192 ///
1193 /// use musli::{Allocator, Context, Decode, Decoder};
1194 /// use musli::de::UnsizedVisitor;
1195 /// # struct StringReference<'de> { data: &'de str }
1196 ///
1197 /// impl<'de, M, A> Decode<'de, M, A> for StringReference<'de>
1198 /// where
1199 /// A: Allocator,
1200 /// {
1201 /// #[inline]
1202 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
1203 /// where
1204 /// D: Decoder<'de>,
1205 /// {
1206 /// struct Visitor;
1207 ///
1208 /// #[musli::de::unsized_visitor]
1209 /// impl<'de, C> UnsizedVisitor<'de, C, str> for Visitor
1210 /// where
1211 /// C: Context,
1212 /// {
1213 /// type Ok = &'de str;
1214 ///
1215 /// #[inline]
1216 /// fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1217 /// write!(f, "exact bytes reference")
1218 /// }
1219 ///
1220 /// #[inline]
1221 /// fn visit_borrowed(self, _: C, bytes: &'de str) -> Result<Self::Ok, C::Error> {
1222 /// Ok(bytes)
1223 /// }
1224 /// }
1225 ///
1226 /// Ok(Self {
1227 /// data: decoder.decode_string(Visitor)?,
1228 /// })
1229 /// }
1230 /// }
1231 /// ```
1232 #[inline]
1233 fn decode_string<V>(self, visitor: V) -> Result<V::Ok, V::Error>
1234 where
1235 V: UnsizedVisitor<'de, Self::Cx, str, Error = Self::Error, Allocator = Self::Allocator>,
1236 {
1237 Err(self.cx().message(expecting::unsupported_type(
1238 &expecting::String,
1239 ExpectingWrapper::new(&self),
1240 )))
1241 }
1242
1243 /// Decode an optional value.
1244 ///
1245 /// # Examples
1246 ///
1247 /// Deriving an implementation:
1248 ///
1249 /// ```
1250 /// use musli::{Context, Decode};
1251 ///
1252 /// #[derive(Decode)]
1253 /// struct OptionalField {
1254 /// data: Option<String>,
1255 /// }
1256 /// ```
1257 ///
1258 /// Implementing manually:
1259 ///
1260 /// ```
1261 /// use musli::{Allocator, Context, Decode, Decoder};
1262 /// # struct OptionalField { data: Option<String>}
1263 ///
1264 /// impl<'de, M, A> Decode<'de, M, A> for OptionalField
1265 /// where
1266 /// A: Allocator,
1267 /// {
1268 /// #[inline]
1269 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
1270 /// where
1271 /// D: Decoder<'de>,
1272 /// {
1273 /// let data = if let Some(decoder) = decoder.decode_option()? {
1274 /// Some(decoder.decode()?)
1275 /// } else {
1276 /// None
1277 /// };
1278 ///
1279 /// Ok(Self { data })
1280 /// }
1281 /// }
1282 /// ```
1283 #[inline]
1284 #[must_use = "Decoders must be consumed"]
1285 fn decode_option(self) -> Result<Option<Self::DecodeSome>, Self::Error> {
1286 Err(self.cx().message(expecting::unsupported_type(
1287 &expecting::Option,
1288 ExpectingWrapper::new(&self),
1289 )))
1290 }
1291
1292 /// Construct an unpack that can decode more than one element at a time.
1293 ///
1294 /// This hints to the format that it should attempt to decode all of the
1295 /// elements in the packed sequence from an as compact format as possible
1296 /// compatible with what's being returned by
1297 /// [Encoder::pack][crate::Encoder::encode_pack].
1298 ///
1299 /// # Examples
1300 ///
1301 /// Deriving an implementation:
1302 ///
1303 /// ```
1304 /// use musli::Decode;
1305 ///
1306 /// #[derive(Decode)]
1307 /// #[musli(packed)]
1308 /// struct PackedStruct {
1309 /// field: u32,
1310 /// data: [u8; 128],
1311 /// }
1312 /// ```
1313 ///
1314 /// Implementing manually:
1315 ///
1316 /// ```
1317 /// use musli::{Allocator, Context, Decode, Decoder};
1318 /// use musli::de::SequenceDecoder;
1319 /// # struct PackedStruct { field: u32, data: [u8; 128] }
1320 ///
1321 /// impl<'de, M, A> Decode<'de, M, A> for PackedStruct
1322 /// where
1323 /// A: Allocator,
1324 /// {
1325 /// #[inline]
1326 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
1327 /// where
1328 /// D: Decoder<'de>,
1329 /// {
1330 /// decoder.decode_pack(|pack| Ok(Self {
1331 /// field: pack.next()?,
1332 /// data: pack.next()?,
1333 /// }))
1334 /// }
1335 /// }
1336 /// ```
1337 #[inline]
1338 fn decode_pack<F, O>(self, f: F) -> Result<O, Self::Error>
1339 where
1340 F: FnOnce(&mut Self::DecodePack) -> Result<O, Self::Error>,
1341 {
1342 Err(self.cx().message(expecting::unsupported_type(
1343 &expecting::Pack,
1344 ExpectingWrapper::new(&self),
1345 )))
1346 }
1347
1348 /// Decode a sequence of values.
1349 #[inline]
1350 fn decode_slice<V, T>(self) -> Result<V, Self::Error>
1351 where
1352 V: DecodeSliceBuilder<T, Self::Allocator>,
1353 T: Decode<'de, Self::Mode, Self::Allocator>,
1354 {
1355 utils::default_decode_slice(self)
1356 }
1357
1358 /// Decode a sequence.
1359 ///
1360 /// # Examples
1361 ///
1362 /// Deriving an implementation:
1363 ///
1364 /// ```
1365 /// use musli::Decode;
1366 ///
1367 /// #[derive(Decode)]
1368 /// struct VectorField {
1369 /// data: Vec<String>,
1370 /// }
1371 /// ```
1372 ///
1373 /// Implementing manually:
1374 ///
1375 /// ```
1376 /// use musli::{Allocator, Context, Decode, Decoder};
1377 /// use musli::de::SequenceDecoder;
1378 ///
1379 /// struct VectorField {
1380 /// data: Vec<String>,
1381 /// }
1382 ///
1383 /// impl<'de, M, A> Decode<'de, M, A> for VectorField
1384 /// where
1385 /// A: Allocator,
1386 /// {
1387 /// #[inline]
1388 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
1389 /// where
1390 /// D: Decoder<'de>,
1391 /// {
1392 /// decoder.decode_sequence(|seq| {
1393 /// let mut data = Vec::new();
1394 ///
1395 /// while let Some(decoder) = seq.try_decode_next()? {
1396 /// data.push(decoder.decode()?);
1397 /// }
1398 ///
1399 /// Ok(Self { data })
1400 /// })
1401 /// }
1402 /// }
1403 /// ```
1404 ///
1405 /// Deriving an implementation for a tuple:
1406 ///
1407 /// ```
1408 /// use musli::Decode;
1409 ///
1410 /// #[derive(Decode)]
1411 /// struct TupleStruct(String, u32);
1412 /// ```
1413 ///
1414 /// Implementing manually:
1415 ///
1416 /// ```
1417 /// use musli::{Allocator, Context, Decode, Decoder};
1418 /// use musli::de::SequenceDecoder;
1419 /// # struct TupleStruct(String, u32);
1420 ///
1421 /// impl<'de, M, A> Decode<'de, M, A> for TupleStruct
1422 /// where
1423 /// A: Allocator,
1424 /// {
1425 /// #[inline]
1426 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
1427 /// where
1428 /// D: Decoder<'de>,
1429 /// {
1430 /// decoder.decode_sequence_hint(2, |tuple| {
1431 /// Ok(Self(tuple.next()?, tuple.next()?))
1432 /// })
1433 /// }
1434 /// }
1435 /// ```
1436 #[inline]
1437 fn decode_sequence<F, O>(self, f: F) -> Result<O, Self::Error>
1438 where
1439 F: FnOnce(&mut Self::DecodeSequence) -> Result<O, Self::Error>,
1440 {
1441 Err(self.cx().message(expecting::unsupported_type(
1442 &expecting::UnsizedSequence,
1443 ExpectingWrapper::new(&self),
1444 )))
1445 }
1446
1447 /// Decode a sequence with a `hint` indicating its expected characteristics.
1448 ///
1449 /// # Examples
1450 ///
1451 /// ```
1452 /// use musli::{Allocator, Context, Decode, Decoder};
1453 /// use musli::de::SequenceDecoder;
1454 /// # struct TupleStruct(String, u32);
1455 ///
1456 /// impl<'de, M, A> Decode<'de, M, A> for TupleStruct
1457 /// where
1458 /// A: Allocator,
1459 /// {
1460 /// #[inline]
1461 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
1462 /// where
1463 /// D: Decoder<'de>,
1464 /// {
1465 /// decoder.decode_sequence_hint(2, |tuple| {
1466 /// Ok(Self(tuple.next()?, tuple.next()?))
1467 /// })
1468 /// }
1469 /// }
1470 /// ```
1471 #[inline]
1472 fn decode_sequence_hint<F, O>(self, hint: impl SequenceHint, f: F) -> Result<O, Self::Error>
1473 where
1474 F: FnOnce(&mut Self::DecodeSequence) -> Result<O, Self::Error>,
1475 {
1476 self.decode_sequence(f)
1477 }
1478
1479 /// Decode a map who's size is not known at compile time.
1480 ///
1481 /// # Examples
1482 ///
1483 /// ```
1484 /// use std::collections::HashMap;
1485 ///
1486 /// use musli::{Allocator, Decode, Decoder};
1487 /// use musli::de::{MapDecoder, EntryDecoder};
1488 /// # struct MapStruct { data: HashMap<String, u32> }
1489 ///
1490 /// impl<'de, M, A> Decode<'de, M, A> for MapStruct
1491 /// where
1492 /// A: Allocator,
1493 /// {
1494 /// #[inline]
1495 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
1496 /// where
1497 /// D: Decoder<'de>,
1498 /// {
1499 /// decoder.decode_map(|map| {
1500 /// let mut data = HashMap::with_capacity(map.size_hint().or_default());
1501 ///
1502 /// while let Some((key, value)) = map.entry()? {
1503 /// data.insert(key, value);
1504 /// }
1505 ///
1506 /// Ok(Self { data })
1507 /// })
1508 /// }
1509 /// }
1510 /// ```
1511 fn decode_map<F, O>(self, f: F) -> Result<O, Self::Error>
1512 where
1513 F: FnOnce(&mut Self::DecodeMap) -> Result<O, Self::Error>,
1514 {
1515 Err(self.cx().message(expecting::unsupported_type(
1516 &expecting::UnsizedMap,
1517 ExpectingWrapper::new(&self),
1518 )))
1519 }
1520
1521 /// Decode a map using a simplified function.
1522 ///
1523 /// The length of the map must somehow be determined from the underlying
1524 /// format.
1525 ///
1526 /// # Examples
1527 ///
1528 /// Deriving an implementation from a struct:
1529 ///
1530 /// ```
1531 /// use std::collections::HashMap;
1532 ///
1533 /// use musli::Decode;
1534 ///
1535 /// #[derive(Decode)]
1536 /// struct Struct {
1537 /// string: String,
1538 /// integer: u32,
1539 /// }
1540 /// ```
1541 ///
1542 /// Implementing manually:
1543 ///
1544 /// ```
1545 /// use musli::{Allocator, Context, Decode, Decoder};
1546 /// use musli::de::{MapDecoder, EntryDecoder};
1547 ///
1548 /// struct Struct {
1549 /// string: String,
1550 /// integer: u32,
1551 /// }
1552 ///
1553 /// impl<'de, M, A> Decode<'de, M, A> for Struct
1554 /// where
1555 /// A: Allocator,
1556 /// {
1557 /// #[inline]
1558 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
1559 /// where
1560 /// D: Decoder<'de>,
1561 /// {
1562 /// static HINT: usize = 2;
1563 ///
1564 /// let cx = decoder.cx();
1565 ///
1566 /// decoder.decode_map_hint(HINT, |st| {
1567 /// let mut string = None;
1568 /// let mut integer = None;
1569 ///
1570 /// while let Some(mut field) = st.decode_entry()? {
1571 /// // Note: to avoid allocating `decode_string` needs to be used with a visitor.
1572 /// let tag = field.decode_key()?.decode::<String>()?;
1573 ///
1574 /// match tag.as_str() {
1575 /// "string" => {
1576 /// string = Some(field.decode_value()?.decode()?);
1577 /// }
1578 /// "integer" => {
1579 /// integer = Some(field.decode_value()?.decode()?);
1580 /// }
1581 /// tag => {
1582 /// return Err(cx.message(format_args!("Invalid field tag {tag:?}")));
1583 /// }
1584 /// }
1585 /// }
1586 ///
1587 /// Ok(Self {
1588 /// string: string.ok_or_else(|| cx.message("Expected tag `string`"))?,
1589 /// integer: integer.ok_or_else(|| cx.message("Expected tag `integer`"))?,
1590 /// })
1591 /// })
1592 /// }
1593 /// }
1594 /// ```
1595 #[inline]
1596 fn decode_map_hint<F, O>(self, _: impl MapHint, f: F) -> Result<O, Self::Error>
1597 where
1598 F: FnOnce(&mut Self::DecodeMap) -> Result<O, Self::Error>,
1599 {
1600 self.decode_map(f)
1601 }
1602
1603 /// Simplified decoding a map of unknown length.
1604 ///
1605 /// The length of the map must somehow be determined from the underlying
1606 /// format.
1607 #[inline]
1608 fn decode_map_entries<F, O>(self, f: F) -> Result<O, Self::Error>
1609 where
1610 F: FnOnce(&mut Self::DecodeMapEntries) -> Result<O, Self::Error>,
1611 {
1612 Err(self.cx().message(expecting::unsupported_type(
1613 &expecting::MapEntries,
1614 ExpectingWrapper::new(&self),
1615 )))
1616 }
1617
1618 /// Decode a variant using a closure.
1619 ///
1620 /// # Examples
1621 ///
1622 /// ```
1623 /// use musli::{Allocator, Context, Decode};
1624 /// use musli::de::{Decoder, VariantDecoder};
1625 ///
1626 /// enum Enum {
1627 /// Number(u32),
1628 /// String(String),
1629 /// }
1630 ///
1631 /// impl<'de, M, A> Decode<'de, M, A> for Enum
1632 /// where
1633 /// A: Allocator,
1634 /// {
1635 /// #[inline]
1636 /// fn decode<D>(decoder: D) -> Result<Self, D::Error>
1637 /// where
1638 /// D: Decoder<'de>,
1639 /// {
1640 /// let cx = decoder.cx();
1641 ///
1642 /// decoder.decode_variant(|variant| {
1643 /// let tag = variant.decode_tag()?.decode()?;
1644 /// let value = variant.decode_value()?;
1645 ///
1646 /// match tag {
1647 /// 0 => Ok(Self::Number(value.decode()?)),
1648 /// 1 => Ok(Self::String(value.decode()?)),
1649 /// tag => Err(cx.message(format_args!("Invalid variant tag {tag:?}"))),
1650 /// }
1651 /// })
1652 /// }
1653 /// }
1654 /// ```
1655 #[inline]
1656 fn decode_variant<F, O>(self, f: F) -> Result<O, Self::Error>
1657 where
1658 F: FnOnce(&mut Self::DecodeVariant) -> Result<O, Self::Error>,
1659 {
1660 Err(self.cx().message(expecting::unsupported_type(
1661 &expecting::Variant,
1662 ExpectingWrapper::new(&self),
1663 )))
1664 }
1665
1666 /// Decode an unknown number using a visitor.
1667 #[inline]
1668 fn decode_number<V>(self, visitor: V) -> Result<V::Ok, Self::Error>
1669 where
1670 V: Visitor<'de, Self::Cx, Error = Self::Error, Allocator = Self::Allocator>,
1671 {
1672 Err(self.cx().message(expecting::unsupported_type(
1673 &expecting::Number,
1674 ExpectingWrapper::new(&self),
1675 )))
1676 }
1677
1678 /// Decode dynamically through a [`Visitor`].
1679 #[inline]
1680 fn decode_any<V>(self, visitor: V) -> Result<V::Ok, V::Error>
1681 where
1682 V: Visitor<'de, Self::Cx, Error = Self::Error, Allocator = Self::Allocator>,
1683 {
1684 Err(self.cx().message(format_args!(
1685 "Any type not supported, expected {}",
1686 ExpectingWrapper::new(&self).format()
1687 )))
1688 }
1689}
1690
1691#[repr(transparent)]
1692struct ExpectingWrapper<T> {
1693 inner: T,
1694}
1695
1696impl<T> ExpectingWrapper<T> {
1697 fn new(inner: &T) -> &Self {
1698 // Safety: `ExpectingWrapper` is repr(transparent) over `T`.
1699 unsafe { &*(inner as *const T as *const Self) }
1700 }
1701}
1702
1703impl<'de, T> Expecting for ExpectingWrapper<T>
1704where
1705 T: Decoder<'de>,
1706{
1707 #[inline]
1708 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1709 self.inner.expecting(f)
1710 }
1711}