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