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