musli_core/en/encoder.rs
1use core::fmt;
2
3use crate::expecting::{self, Expecting};
4use crate::hint::{MapHint, SequenceHint};
5use crate::Context;
6
7use super::{utils, Encode, EntriesEncoder, MapEncoder, SequenceEncoder, VariantEncoder};
8
9/// An outcome of a fast encode attempt.
10#[non_exhaustive]
11pub enum TryFastEncode<T, E>
12where
13 E: Encoder,
14{
15 /// The encode attempt was successful.
16 Ok,
17 /// The encode was unsupported.
18 Unsupported(T, E),
19}
20
21/// Trait governing how the encoder works.
22#[must_use = "Encoders must be consumed through one of its encode_* methods"]
23#[allow(unused_variables)]
24pub trait Encoder: Sized {
25 /// Context associated with the encoder.
26 type Cx: Context<Error = Self::Error>;
27 /// Error associated with encoding.
28 type Error;
29 /// Mode associated with encoding.
30 type Mode: 'static;
31 /// A simple pack that packs a sequence of elements.
32 type EncodePack: SequenceEncoder<Cx = Self::Cx, Error = Self::Error, Mode = Self::Mode>;
33 /// Encoder returned when encoding an optional value which is present.
34 type EncodeSome: Encoder<Cx = Self::Cx, Error = Self::Error, Mode = Self::Mode>;
35 /// The type of a sequence encoder.
36 type EncodeSequence: SequenceEncoder<Cx = Self::Cx, Error = Self::Error, Mode = Self::Mode>;
37 /// The type of a map encoder.
38 type EncodeMap: MapEncoder<Cx = Self::Cx, Error = Self::Error, Mode = Self::Mode>;
39 /// Streaming encoder for map pairs.
40 type EncodeMapEntries: EntriesEncoder<Cx = Self::Cx, Error = Self::Error, Mode = Self::Mode>;
41 /// Encoder for a variant.
42 type EncodeVariant: VariantEncoder<Cx = Self::Cx, Error = Self::Error, Mode = Self::Mode>;
43 /// Encoder for a sequence variant.
44 type EncodeSequenceVariant: SequenceEncoder<
45 Cx = Self::Cx,
46 Error = Self::Error,
47 Mode = Self::Mode,
48 >;
49 /// Encoder for a map variant.
50 type EncodeMapVariant: MapEncoder<Cx = Self::Cx, Error = Self::Error, Mode = Self::Mode>;
51
52 /// This is a type argument used to hint to any future implementor that they
53 /// should be using the [`#[musli::encoder]`][musli::encoder]
54 /// attribute macro when implementing [`Encoder`].
55 #[doc(hidden)]
56 type __UseMusliEncoderAttributeMacro;
57
58 /// Access the context associated with the encoder.
59 fn cx(&self) -> Self::Cx;
60
61 /// An expectation error. Every other implementation defers to this to
62 /// report that something unexpected happened.
63 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
64
65 /// Try to quickly encode the specified value.
66 ///
67 /// The default implementation simply returns the current encoder as
68 /// `Err(Self)`.
69 ///
70 /// This is intended to be a fast path when encoding a value when an
71 /// encoding permits it.
72 #[inline]
73 fn try_fast_encode<T>(self, value: T) -> Result<TryFastEncode<T, Self>, Self::Error>
74 where
75 T: Encode<Self::Mode>,
76 {
77 Ok(TryFastEncode::Unsupported(value, self))
78 }
79
80 /// Encode the value `T` into the current encoder.
81 ///
82 /// This calls the appropriate [`Encode`] implementation for the given type.
83 #[inline]
84 fn encode<T>(self, value: T) -> Result<(), Self::Error>
85 where
86 T: Encode<Self::Mode>,
87 {
88 match self.try_fast_encode(value)? {
89 TryFastEncode::Ok => Ok(()),
90 TryFastEncode::Unsupported(value, this) => value.encode(this),
91 }
92 }
93
94 /// Encode a unit or something that is completely empty.
95 ///
96 /// # Examples
97 ///
98 /// Deriving an implementation:
99 ///
100 /// ```
101 /// use musli::Encode;
102 ///
103 /// #[derive(Encode)]
104 /// struct UnitStruct;
105 /// ```
106 ///
107 /// Implementing manually:
108 ///
109 /// ```
110 /// use musli::{Encode, Encoder};
111 /// # struct UnitStruct;
112 ///
113 /// impl<M> Encode<M> for UnitStruct {
114 /// type Encode = Self;
115 ///
116 /// #[inline]
117 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
118 /// where
119 /// E: Encoder,
120 /// {
121 /// encoder.encode_empty()
122 /// }
123 ///
124 /// #[inline]
125 /// fn as_encode(&self) -> &Self::Encode {
126 /// self
127 /// }
128 /// }
129 /// ```
130 #[inline]
131 fn encode_empty(self) -> Result<(), Self::Error> {
132 Err(self.cx().message(expecting::unsupported_type(
133 &expecting::Empty,
134 ExpectingWrapper::new(&self),
135 )))
136 }
137
138 /// Encode a boolean value.
139 ///
140 /// # Examples
141 ///
142 /// Deriving an implementation:
143 ///
144 /// ```
145 /// use musli::Encode;
146 ///
147 /// #[derive(Encode)]
148 /// #[musli(packed)]
149 /// struct MyType {
150 /// data: bool
151 /// }
152 /// ```
153 ///
154 /// Implementing manually:
155 ///
156 /// ```
157 /// use musli::{Encode, Encoder};
158 /// # struct MyType { data: bool }
159 ///
160 /// impl<M> Encode<M> for MyType {
161 /// type Encode = Self;
162 ///
163 /// #[inline]
164 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
165 /// where
166 /// E: Encoder,
167 /// {
168 /// encoder.encode_bool(self.data)
169 /// }
170 ///
171 /// #[inline]
172 /// fn as_encode(&self) -> &Self::Encode {
173 /// self
174 /// }
175 /// }
176 /// ```
177 #[inline]
178 fn encode_bool(self, v: bool) -> Result<(), Self::Error> {
179 Err(self.cx().message(expecting::unsupported_type(
180 &expecting::Bool,
181 ExpectingWrapper::new(&self),
182 )))
183 }
184
185 /// Encode a character.
186 ///
187 /// # Examples
188 ///
189 /// Deriving an implementation:
190 ///
191 /// ```
192 /// use musli::Encode;
193 ///
194 /// #[derive(Encode)]
195 /// #[musli(packed)]
196 /// struct MyType {
197 /// data: char
198 /// }
199 /// ```
200 ///
201 /// Implementing manually:
202 ///
203 /// ```
204 /// use musli::{Encode, Encoder};
205 /// # struct MyType { data: char }
206 ///
207 /// impl<M> Encode<M> for MyType {
208 /// type Encode = Self;
209 ///
210 /// #[inline]
211 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
212 /// where
213 /// E: Encoder,
214 /// {
215 /// encoder.encode_char(self.data)
216 /// }
217 ///
218 /// #[inline]
219 /// fn as_encode(&self) -> &Self::Encode {
220 /// self
221 /// }
222 /// }
223 /// ```
224 #[inline]
225 fn encode_char(self, v: char) -> Result<(), Self::Error> {
226 Err(self.cx().message(expecting::unsupported_type(
227 &expecting::Char,
228 ExpectingWrapper::new(&self),
229 )))
230 }
231
232 /// Encode a 8-bit unsigned integer.
233 ///
234 /// # Examples
235 ///
236 /// Deriving an implementation:
237 ///
238 /// ```
239 /// use musli::Encode;
240 ///
241 /// #[derive(Encode)]
242 /// #[musli(packed)]
243 /// struct MyType {
244 /// data: u8
245 /// }
246 /// ```
247 ///
248 /// Implementing manually:
249 ///
250 /// ```
251 /// use musli::{Encode, Encoder};
252 /// # struct MyType { data: u8 }
253 ///
254 /// impl<M> Encode<M> for MyType {
255 /// type Encode = Self;
256 ///
257 /// #[inline]
258 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
259 /// where
260 /// E: Encoder,
261 /// {
262 /// encoder.encode_u8(self.data)
263 /// }
264 ///
265 /// #[inline]
266 /// fn as_encode(&self) -> &Self::Encode {
267 /// self
268 /// }
269 /// }
270 /// ```
271 #[inline]
272 fn encode_u8(self, v: u8) -> Result<(), Self::Error> {
273 Err(self.cx().message(expecting::unsupported_type(
274 &expecting::Unsigned8,
275 ExpectingWrapper::new(&self),
276 )))
277 }
278
279 /// Encode a 16-bit unsigned integer.
280 ///
281 /// # Examples
282 ///
283 /// Deriving an implementation:
284 ///
285 /// ```
286 /// use musli::Encode;
287 ///
288 /// #[derive(Encode)]
289 /// #[musli(packed)]
290 /// struct MyType {
291 /// data: u16
292 /// }
293 /// ```
294 ///
295 /// Implementing manually:
296 ///
297 /// ```
298 /// use musli::{Encode, Encoder};
299 /// # struct MyType { data: u16 }
300 ///
301 /// impl<M> Encode<M> for MyType {
302 /// type Encode = Self;
303 ///
304 /// #[inline]
305 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
306 /// where
307 /// E: Encoder,
308 /// {
309 /// encoder.encode_u16(self.data)
310 /// }
311 ///
312 /// #[inline]
313 /// fn as_encode(&self) -> &Self::Encode {
314 /// self
315 /// }
316 /// }
317 /// ```
318 #[inline]
319 fn encode_u16(self, v: u16) -> Result<(), Self::Error> {
320 Err(self.cx().message(expecting::unsupported_type(
321 &expecting::Unsigned16,
322 ExpectingWrapper::new(&self),
323 )))
324 }
325
326 /// Encode a 32-bit unsigned integer.
327 ///
328 /// # Examples
329 ///
330 /// Deriving an implementation:
331 ///
332 /// ```
333 /// use musli::Encode;
334 ///
335 /// #[derive(Encode)]
336 /// #[musli(packed)]
337 /// struct MyType {
338 /// data: u32
339 /// }
340 /// ```
341 ///
342 /// Implementing manually:
343 ///
344 /// ```
345 /// use musli::{Encode, Encoder};
346 /// # struct MyType { data: u32 }
347 ///
348 /// impl<M> Encode<M> for MyType {
349 /// type Encode = Self;
350 ///
351 /// #[inline]
352 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
353 /// where
354 /// E: Encoder,
355 /// {
356 /// encoder.encode_u32(self.data)
357 /// }
358 ///
359 /// #[inline]
360 /// fn as_encode(&self) -> &Self::Encode {
361 /// self
362 /// }
363 /// }
364 /// ```
365 #[inline]
366 fn encode_u32(self, v: u32) -> Result<(), Self::Error> {
367 Err(self.cx().message(expecting::unsupported_type(
368 &expecting::Unsigned32,
369 ExpectingWrapper::new(&self),
370 )))
371 }
372
373 /// Encode a 64-bit unsigned integer.
374 ///
375 /// # Examples
376 ///
377 /// Deriving an implementation:
378 ///
379 /// ```
380 /// use musli::Encode;
381 ///
382 /// #[derive(Encode)]
383 /// #[musli(packed)]
384 /// struct MyType {
385 /// data: u64
386 /// }
387 /// ```
388 ///
389 /// Implementing manually:
390 ///
391 /// ```
392 /// use musli::{Encode, Encoder};
393 /// # struct MyType { data: u64 }
394 ///
395 /// impl<M> Encode<M> for MyType {
396 /// type Encode = Self;
397 ///
398 /// #[inline]
399 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
400 /// where
401 /// E: Encoder,
402 /// {
403 /// encoder.encode_u64(self.data)
404 /// }
405 ///
406 /// #[inline]
407 /// fn as_encode(&self) -> &Self::Encode {
408 /// self
409 /// }
410 /// }
411 /// ```
412 #[inline]
413 fn encode_u64(self, v: u64) -> Result<(), Self::Error> {
414 Err(self.cx().message(expecting::unsupported_type(
415 &expecting::Unsigned64,
416 ExpectingWrapper::new(&self),
417 )))
418 }
419
420 /// Encode a 128-bit unsigned integer.
421 ///
422 /// # Examples
423 ///
424 /// Deriving an implementation:
425 ///
426 /// ```
427 /// use musli::Encode;
428 ///
429 /// #[derive(Encode)]
430 /// #[musli(packed)]
431 /// struct MyType {
432 /// data: u128
433 /// }
434 /// ```
435 ///
436 /// Implementing manually:
437 ///
438 /// ```
439 /// use musli::{Encode, Encoder};
440 /// # struct MyType { data: u128 }
441 ///
442 /// impl<M> Encode<M> for MyType {
443 /// type Encode = Self;
444 ///
445 /// #[inline]
446 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
447 /// where
448 /// E: Encoder,
449 /// {
450 /// encoder.encode_u128(self.data)
451 /// }
452 ///
453 /// #[inline]
454 /// fn as_encode(&self) -> &Self::Encode {
455 /// self
456 /// }
457 /// }
458 /// ```
459 #[inline]
460 fn encode_u128(self, v: u128) -> Result<(), Self::Error> {
461 Err(self.cx().message(expecting::unsupported_type(
462 &expecting::Unsigned128,
463 ExpectingWrapper::new(&self),
464 )))
465 }
466
467 /// Encode a 8-bit signed integer.
468 ///
469 /// # Examples
470 ///
471 /// Deriving an implementation:
472 ///
473 /// ```
474 /// use musli::Encode;
475 ///
476 /// #[derive(Encode)]
477 /// #[musli(packed)]
478 /// struct MyType {
479 /// data: i8
480 /// }
481 /// ```
482 ///
483 /// Implementing manually:
484 ///
485 /// ```
486 /// use musli::{Encode, Encoder};
487 /// # struct MyType { data: i8 }
488 ///
489 /// impl<M> Encode<M> for MyType {
490 /// type Encode = Self;
491 ///
492 /// #[inline]
493 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
494 /// where
495 /// E: Encoder,
496 /// {
497 /// encoder.encode_i8(self.data)
498 /// }
499 ///
500 /// #[inline]
501 /// fn as_encode(&self) -> &Self::Encode {
502 /// self
503 /// }
504 /// }
505 /// ```
506 #[inline]
507 fn encode_i8(self, v: i8) -> Result<(), Self::Error> {
508 Err(self.cx().message(expecting::unsupported_type(
509 &expecting::Signed8,
510 ExpectingWrapper::new(&self),
511 )))
512 }
513
514 /// Encode a 16-bit signed integer.
515 ///
516 /// # Examples
517 ///
518 /// Deriving an implementation:
519 ///
520 /// ```
521 /// use musli::Encode;
522 ///
523 /// #[derive(Encode)]
524 /// #[musli(packed)]
525 /// struct MyType {
526 /// data: i16
527 /// }
528 /// ```
529 ///
530 /// Implementing manually:
531 ///
532 /// ```
533 /// use musli::{Encode, Encoder};
534 /// # struct MyType { data: i16 }
535 ///
536 /// impl<M> Encode<M> for MyType {
537 /// type Encode = Self;
538 ///
539 /// #[inline]
540 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
541 /// where
542 /// E: Encoder,
543 /// {
544 /// encoder.encode_i16(self.data)
545 /// }
546 ///
547 /// #[inline]
548 /// fn as_encode(&self) -> &Self::Encode {
549 /// self
550 /// }
551 /// }
552 /// ```
553 #[inline]
554 fn encode_i16(self, v: i16) -> Result<(), Self::Error> {
555 Err(self.cx().message(expecting::unsupported_type(
556 &expecting::Signed16,
557 ExpectingWrapper::new(&self),
558 )))
559 }
560
561 /// Encode a 32-bit signed integer.
562 ///
563 /// # Examples
564 ///
565 /// Deriving an implementation:
566 ///
567 /// ```
568 /// use musli::Encode;
569 ///
570 /// #[derive(Encode)]
571 /// #[musli(packed)]
572 /// struct MyType {
573 /// data: i32
574 /// }
575 /// ```
576 ///
577 /// Implementing manually:
578 ///
579 /// ```
580 /// use musli::{Encode, Encoder};
581 /// # struct MyType { data: i32 }
582 ///
583 /// impl<M> Encode<M> for MyType {
584 /// type Encode = Self;
585 ///
586 /// #[inline]
587 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
588 /// where
589 /// E: Encoder,
590 /// {
591 /// encoder.encode_i32(self.data)
592 /// }
593 ///
594 /// #[inline]
595 /// fn as_encode(&self) -> &Self::Encode {
596 /// self
597 /// }
598 /// }
599 /// ```
600 #[inline]
601 fn encode_i32(self, v: i32) -> Result<(), Self::Error> {
602 Err(self.cx().message(expecting::unsupported_type(
603 &expecting::Signed32,
604 ExpectingWrapper::new(&self),
605 )))
606 }
607
608 /// Encode a 64-bit signed integer.
609 ///
610 /// # Examples
611 ///
612 /// Deriving an implementation:
613 ///
614 /// ```
615 /// use musli::Encode;
616 ///
617 /// #[derive(Encode)]
618 /// #[musli(packed)]
619 /// struct MyType {
620 /// data: i64
621 /// }
622 /// ```
623 ///
624 /// Implementing manually:
625 ///
626 /// ```
627 /// use musli::{Encode, Encoder};
628 /// # struct MyType { data: i64 }
629 ///
630 /// impl<M> Encode<M> for MyType {
631 /// type Encode = Self;
632 ///
633 /// #[inline]
634 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
635 /// where
636 /// E: Encoder,
637 /// {
638 /// encoder.encode_i64(self.data)
639 /// }
640 ///
641 /// #[inline]
642 /// fn as_encode(&self) -> &Self::Encode {
643 /// self
644 /// }
645 /// }
646 /// ```
647 #[inline]
648 fn encode_i64(self, v: i64) -> Result<(), Self::Error> {
649 Err(self.cx().message(expecting::unsupported_type(
650 &expecting::Signed64,
651 ExpectingWrapper::new(&self),
652 )))
653 }
654
655 /// Encode a 128-bit signed integer.
656 ///
657 /// # Examples
658 ///
659 /// Deriving an implementation:
660 ///
661 /// ```
662 /// use musli::Encode;
663 ///
664 /// #[derive(Encode)]
665 /// #[musli(packed)]
666 /// struct MyType {
667 /// data: i128
668 /// }
669 /// ```
670 ///
671 /// Implementing manually:
672 ///
673 /// ```
674 /// use musli::{Encode, Encoder};
675 /// # struct MyType { data: i128 }
676 ///
677 /// impl<M> Encode<M> for MyType {
678 /// type Encode = Self;
679 ///
680 /// #[inline]
681 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
682 /// where
683 /// E: Encoder,
684 /// {
685 /// encoder.encode_i128(self.data)
686 /// }
687 ///
688 /// #[inline]
689 /// fn as_encode(&self) -> &Self::Encode {
690 /// self
691 /// }
692 /// }
693 /// ```
694 #[inline]
695 fn encode_i128(self, v: i128) -> Result<(), Self::Error> {
696 Err(self.cx().message(expecting::unsupported_type(
697 &expecting::Signed128,
698 ExpectingWrapper::new(&self),
699 )))
700 }
701
702 /// Encode a [`usize`].
703 ///
704 /// # Examples
705 ///
706 /// Deriving an implementation:
707 ///
708 /// ```
709 /// use musli::Encode;
710 ///
711 /// #[derive(Encode)]
712 /// #[musli(packed)]
713 /// struct MyType {
714 /// data: usize
715 /// }
716 /// ```
717 ///
718 /// Implementing manually:
719 ///
720 /// ```
721 /// use musli::{Encode, Encoder};
722 /// # struct MyType { data: usize }
723 ///
724 /// impl<M> Encode<M> for MyType {
725 /// type Encode = Self;
726 ///
727 /// #[inline]
728 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
729 /// where
730 /// E: Encoder,
731 /// {
732 /// encoder.encode_usize(self.data)
733 /// }
734 ///
735 /// #[inline]
736 /// fn as_encode(&self) -> &Self::Encode {
737 /// self
738 /// }
739 /// }
740 /// ```
741 #[inline]
742 fn encode_usize(self, v: usize) -> Result<(), Self::Error> {
743 Err(self.cx().message(expecting::unsupported_type(
744 &expecting::Usize,
745 ExpectingWrapper::new(&self),
746 )))
747 }
748
749 /// Encode a [`isize`].
750 ///
751 /// # Examples
752 ///
753 /// Deriving an implementation:
754 ///
755 /// ```
756 /// use musli::Encode;
757 ///
758 /// #[derive(Encode)]
759 /// #[musli(packed)]
760 /// struct MyType {
761 /// data: isize
762 /// }
763 /// ```
764 ///
765 /// Implementing manually:
766 ///
767 /// ```
768 /// use musli::{Encode, Encoder};
769 /// # struct MyType { data: isize }
770 ///
771 /// impl<M> Encode<M> for MyType {
772 /// type Encode = Self;
773 ///
774 /// #[inline]
775 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
776 /// where
777 /// E: Encoder,
778 /// {
779 /// encoder.encode_isize(self.data)
780 /// }
781 ///
782 /// #[inline]
783 /// fn as_encode(&self) -> &Self::Encode {
784 /// self
785 /// }
786 /// }
787 /// ```
788 #[inline]
789 fn encode_isize(self, v: isize) -> Result<(), Self::Error> {
790 Err(self.cx().message(expecting::unsupported_type(
791 &expecting::Isize,
792 ExpectingWrapper::new(&self),
793 )))
794 }
795
796 /// Encode a 32-bit floating point value.
797 ///
798 /// # Examples
799 ///
800 /// Deriving an implementation:
801 ///
802 /// ```
803 /// use musli::Encode;
804 ///
805 /// #[derive(Encode)]
806 /// #[musli(packed)]
807 /// struct MyType {
808 /// data: f32
809 /// }
810 /// ```
811 ///
812 /// Implementing manually:
813 ///
814 /// ```
815 /// use musli::{Encode, Encoder};
816 /// # struct MyType { data: f32 }
817 ///
818 /// impl<M> Encode<M> for MyType {
819 /// type Encode = Self;
820 ///
821 /// #[inline]
822 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
823 /// where
824 /// E: Encoder,
825 /// {
826 /// encoder.encode_f32(self.data)
827 /// }
828 ///
829 /// #[inline]
830 /// fn as_encode(&self) -> &Self::Encode {
831 /// self
832 /// }
833 /// }
834 /// ```
835 #[inline]
836 fn encode_f32(self, v: f32) -> Result<(), Self::Error> {
837 Err(self.cx().message(expecting::unsupported_type(
838 &expecting::Float32,
839 ExpectingWrapper::new(&self),
840 )))
841 }
842
843 /// Encode a 64-bit floating point value.
844 ///
845 /// # Examples
846 ///
847 /// Deriving an implementation:
848 ///
849 /// ```
850 /// use musli::Encode;
851 ///
852 /// #[derive(Encode)]
853 /// #[musli(packed)]
854 /// struct MyType {
855 /// data: f64
856 /// }
857 /// ```
858 ///
859 /// Implementing manually:
860 ///
861 /// ```
862 /// use musli::{Encode, Encoder};
863 /// # struct MyType { data: f64 }
864 ///
865 /// impl<M> Encode<M> for MyType {
866 /// type Encode = Self;
867 ///
868 /// #[inline]
869 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
870 /// where
871 /// E: Encoder,
872 /// {
873 /// encoder.encode_f64(self.data)
874 /// }
875 ///
876 /// #[inline]
877 /// fn as_encode(&self) -> &Self::Encode {
878 /// self
879 /// }
880 /// }
881 /// ```
882 #[inline]
883 fn encode_f64(self, v: f64) -> Result<(), Self::Error> {
884 Err(self.cx().message(expecting::unsupported_type(
885 &expecting::Float64,
886 ExpectingWrapper::new(&self),
887 )))
888 }
889
890 /// Encode fixed-length array.
891 ///
892 /// # Examples
893 ///
894 /// Deriving an implementation:
895 ///
896 /// ```
897 /// use musli::Encode;
898 ///
899 /// #[derive(Encode)]
900 /// #[musli(packed)]
901 /// struct MyType {
902 /// data: [u8; 128]
903 /// }
904 /// ```
905 ///
906 /// Implementing manually:
907 ///
908 /// ```
909 /// use musli::{Encode, Encoder};
910 /// # struct MyType { data: [u8; 128] }
911 ///
912 /// impl<M> Encode<M> for MyType {
913 /// type Encode = Self;
914 ///
915 /// #[inline]
916 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
917 /// where
918 /// E: Encoder,
919 /// {
920 /// encoder.encode_array(&self.data)
921 /// }
922 ///
923 /// #[inline]
924 /// fn as_encode(&self) -> &Self::Encode {
925 /// self
926 /// }
927 /// }
928 /// ```
929 #[inline]
930 fn encode_array<const N: usize>(self, array: &[u8; N]) -> Result<(), Self::Error> {
931 Err(self.cx().message(expecting::unsupported_type(
932 &expecting::Array,
933 ExpectingWrapper::new(&self),
934 )))
935 }
936
937 /// Encode a sequence of bytes.
938 ///
939 /// # Examples
940 ///
941 /// Deriving an implementation:
942 ///
943 /// ```
944 /// use musli::Encode;
945 ///
946 /// #[derive(Encode)]
947 /// #[musli(packed)]
948 /// struct MyType {
949 /// #[musli(bytes)]
950 /// data: Vec<u8>
951 /// }
952 /// ```
953 ///
954 /// Implementing manually:
955 ///
956 /// ```
957 /// use musli::{Encode, Encoder};
958 /// # struct MyType { data: Vec<u8> }
959 ///
960 /// impl<M> Encode<M> for MyType {
961 /// type Encode = Self;
962 ///
963 /// #[inline]
964 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
965 /// where
966 /// E: Encoder,
967 /// {
968 /// encoder.encode_bytes(self.data.as_slice())
969 /// }
970 ///
971 /// #[inline]
972 /// fn as_encode(&self) -> &Self::Encode {
973 /// self
974 /// }
975 /// }
976 /// ```
977 #[inline]
978 fn encode_bytes(self, bytes: &[u8]) -> Result<(), Self::Error> {
979 Err(self.cx().message(expecting::unsupported_type(
980 &expecting::Bytes,
981 ExpectingWrapper::new(&self),
982 )))
983 }
984
985 /// Encode the given slices of bytes in sequence, with one following another
986 /// as a single contiguous byte array.
987 ///
988 /// The provided `len` is trusted, but providing the wrong length must never
989 /// result in any memory unsafety. It might just cause the payload to be
990 /// corrupted.
991 ///
992 /// This can be useful to avoid allocations when a caller doesn't have
993 /// access to a single byte sequence like in
994 /// [`VecDeque`][std::collections::VecDeque].
995 ///
996 /// # Examples
997 ///
998 /// Deriving an implementation:
999 ///
1000 /// ```
1001 /// use std::collections::VecDeque;
1002 /// use musli::Encode;
1003 ///
1004 /// #[derive(Encode)]
1005 /// #[musli(packed)]
1006 /// struct MyType {
1007 /// data: VecDeque<u8>
1008 /// }
1009 /// ```
1010 ///
1011 /// Implementing manually:
1012 ///
1013 /// ```
1014 /// use musli::{Encode, Encoder};
1015 /// # use std::collections::VecDeque;
1016 /// # struct MyType { data: VecDeque<u8> }
1017 ///
1018 /// impl<M> Encode<M> for MyType {
1019 /// type Encode = Self;
1020 ///
1021 /// #[inline]
1022 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1023 /// where
1024 /// E: Encoder,
1025 /// {
1026 /// let (first, second) = self.data.as_slices();
1027 /// encoder.encode_bytes_vectored(self.data.len(), [first, second])
1028 /// }
1029 ///
1030 /// #[inline]
1031 /// fn as_encode(&self) -> &Self::Encode {
1032 /// self
1033 /// }
1034 /// }
1035 /// ```
1036 #[inline]
1037 fn encode_bytes_vectored<I>(self, len: usize, vectors: I) -> Result<(), Self::Error>
1038 where
1039 I: IntoIterator<Item: AsRef<[u8]>>,
1040 {
1041 Err(self.cx().message(expecting::unsupported_type(
1042 &expecting::Bytes,
1043 ExpectingWrapper::new(&self),
1044 )))
1045 }
1046
1047 /// Encode a string.
1048 ///
1049 /// # Examples
1050 ///
1051 /// Deriving an implementation:
1052 ///
1053 /// ```
1054 /// use musli::Encode;
1055 ///
1056 /// #[derive(Encode)]
1057 /// #[musli(packed)]
1058 /// struct MyType {
1059 /// data: String
1060 /// }
1061 /// ```
1062 ///
1063 /// Implementing manually:
1064 ///
1065 /// ```
1066 /// use musli::{Encode, Encoder};
1067 /// # struct MyType { data: String }
1068 ///
1069 /// impl<M> Encode<M> for MyType {
1070 /// type Encode = Self;
1071 ///
1072 /// #[inline]
1073 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1074 /// where
1075 /// E: Encoder,
1076 /// {
1077 /// encoder.encode_string(self.data.as_str())
1078 /// }
1079 ///
1080 /// #[inline]
1081 /// fn as_encode(&self) -> &Self::Encode {
1082 /// self
1083 /// }
1084 /// }
1085 /// ```
1086 #[inline]
1087 fn encode_string(self, string: &str) -> Result<(), Self::Error> {
1088 Err(self.cx().message(expecting::unsupported_type(
1089 &expecting::String,
1090 ExpectingWrapper::new(&self),
1091 )))
1092 }
1093
1094 /// Encode a value that implements [`Display`] as a string.
1095 ///
1096 /// [`Display`]: fmt::Display
1097 ///
1098 /// # Examples
1099 ///
1100 /// ```
1101 /// use musli::{Encode, Encoder};
1102 ///
1103 /// struct MyType {
1104 /// data: String,
1105 /// }
1106 ///
1107 /// impl<M> Encode<M> for MyType {
1108 /// type Encode = Self;
1109 ///
1110 /// #[inline]
1111 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1112 /// where
1113 /// E: Encoder,
1114 /// {
1115 /// encoder.collect_string(self.data.as_str())
1116 /// }
1117 ///
1118 /// #[inline]
1119 /// fn as_encode(&self) -> &Self::Encode {
1120 /// self
1121 /// }
1122 /// }
1123 /// ```
1124 #[inline]
1125 fn collect_string<T>(self, value: &T) -> Result<(), Self::Error>
1126 where
1127 T: ?Sized + fmt::Display,
1128 {
1129 let cx = self.cx();
1130 let buf = crate::alloc::collect_string(cx.alloc(), value).map_err(cx.map())?;
1131 self.encode_string(buf.as_ref())
1132 }
1133
1134 /// Encode an optional value that is present.
1135 ///
1136 /// # Examples
1137 ///
1138 /// Deriving an implementation:
1139 ///
1140 /// ```
1141 /// use musli::Encode;
1142 ///
1143 /// #[derive(Encode)]
1144 /// #[musli(packed)]
1145 /// struct MyType {
1146 /// data: Option<String>
1147 /// }
1148 /// ```
1149 ///
1150 /// Implementing manually:
1151 ///
1152 /// ```
1153 /// use musli::{Encode, Encoder};
1154 /// # struct MyType { data: Option<String> }
1155 ///
1156 /// impl<M> Encode<M> for MyType {
1157 /// type Encode = Self;
1158 ///
1159 /// #[inline]
1160 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1161 /// where
1162 /// E: Encoder,
1163 /// {
1164 /// match &self.data {
1165 /// Some(data) => {
1166 /// encoder.encode_some()?.encode(data)
1167 /// }
1168 /// None => {
1169 /// encoder.encode_none()
1170 /// }
1171 /// }
1172 /// }
1173 ///
1174 /// #[inline]
1175 /// fn as_encode(&self) -> &Self::Encode {
1176 /// self
1177 /// }
1178 /// }
1179 /// ```
1180 #[inline]
1181 fn encode_some(self) -> Result<Self::EncodeSome, Self::Error> {
1182 Err(self.cx().message(expecting::unsupported_type(
1183 &expecting::Option,
1184 ExpectingWrapper::new(&self),
1185 )))
1186 }
1187
1188 /// Encode an optional value that is absent.
1189 ///
1190 /// # Examples
1191 ///
1192 /// Deriving an implementation:
1193 ///
1194 /// ```
1195 /// use musli::Encode;
1196 ///
1197 /// #[derive(Encode)]
1198 /// #[musli(packed)]
1199 /// struct MyType {
1200 /// data: Option<String>
1201 /// }
1202 /// ```
1203 ///
1204 /// Implementing manually:
1205 ///
1206 /// ```
1207 /// use musli::{Encode, Encoder};
1208 /// # struct MyType { data: Option<String> }
1209 ///
1210 /// impl<M> Encode<M> for MyType {
1211 /// type Encode = Self;
1212 ///
1213 /// #[inline]
1214 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1215 /// where
1216 /// E: Encoder,
1217 /// {
1218 /// match &self.data {
1219 /// Some(data) => {
1220 /// encoder.encode_some()?.encode(data)
1221 /// }
1222 /// None => {
1223 /// encoder.encode_none()
1224 /// }
1225 /// }
1226 /// }
1227 ///
1228 /// #[inline]
1229 /// fn as_encode(&self) -> &Self::Encode {
1230 /// self
1231 /// }
1232 /// }
1233 /// ```
1234 #[inline]
1235 fn encode_none(self) -> Result<(), Self::Error> {
1236 Err(self.cx().message(expecting::unsupported_type(
1237 &expecting::Option,
1238 ExpectingWrapper::new(&self),
1239 )))
1240 }
1241
1242 /// Construct a pack that can encode more than one element at a time.
1243 ///
1244 /// This hints to the format that it should attempt to encode all of the
1245 /// elements in the packed sequence as compact as possible and that
1246 /// subsequent unpackers will know the exact length of the element being
1247 /// unpacked.
1248 ///
1249 /// # Examples
1250 ///
1251 /// ```
1252 /// use musli::{Encode, Encoder};
1253 /// use musli::en::SequenceEncoder;
1254 ///
1255 /// struct PackedStruct {
1256 /// field: u32,
1257 /// data: [u8; 128],
1258 /// }
1259 ///
1260 /// impl<M> Encode<M> for PackedStruct {
1261 /// type Encode = Self;
1262 ///
1263 /// #[inline]
1264 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1265 /// where
1266 /// E: Encoder,
1267 /// {
1268 /// let mut pack = encoder.encode_pack()?;
1269 /// pack.encode_next()?.encode(self.field)?;
1270 /// pack.encode_next()?.encode(self.data)?;
1271 /// pack.finish_sequence()
1272 /// }
1273 ///
1274 /// #[inline]
1275 /// fn as_encode(&self) -> &Self::Encode {
1276 /// self
1277 /// }
1278 /// }
1279 /// ```
1280 #[inline]
1281 fn encode_pack(self) -> Result<Self::EncodePack, Self::Error> {
1282 Err(self.cx().message(expecting::unsupported_type(
1283 &expecting::Pack,
1284 ExpectingWrapper::new(&self),
1285 )))
1286 }
1287
1288 /// Encodes a pack using a closure.
1289 ///
1290 /// # Examples
1291 ///
1292 /// ```
1293 /// use musli::{Encode, Encoder};
1294 /// use musli::en::SequenceEncoder;
1295 ///
1296 /// struct PackedStruct {
1297 /// field: u32,
1298 /// data: [u8; 128],
1299 /// }
1300 ///
1301 /// impl<M> Encode<M> for PackedStruct {
1302 /// type Encode = Self;
1303 ///
1304 /// #[inline]
1305 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1306 /// where
1307 /// E: Encoder,
1308 /// {
1309 /// encoder.encode_pack_fn(|pack| {
1310 /// pack.encode_next()?.encode(self.field)?;
1311 /// pack.encode_next()?.encode(&self.data)?;
1312 /// Ok(())
1313 /// })
1314 /// }
1315 ///
1316 /// #[inline]
1317 /// fn as_encode(&self) -> &Self::Encode {
1318 /// self
1319 /// }
1320 /// }
1321 /// ```
1322 #[inline]
1323 fn encode_pack_fn<F>(self, f: F) -> Result<(), Self::Error>
1324 where
1325 F: FnOnce(&mut Self::EncodePack) -> Result<(), Self::Error>,
1326 {
1327 let mut pack = self.encode_pack()?;
1328 f(&mut pack)?;
1329 pack.finish_sequence()
1330 }
1331
1332 /// Encode a slice as a sequence.
1333 ///
1334 /// This defaults to using [`Encoder::encode_sequence`] and if specialized
1335 /// must implement the same format as would calling that method.
1336 ///
1337 /// # Examples
1338 ///
1339 /// Deriving an implementation:
1340 ///
1341 /// ```
1342 /// use musli::Encode;
1343 ///
1344 /// #[derive(Encode)]
1345 /// #[musli(packed)]
1346 /// struct MyType {
1347 /// data: Vec<String>
1348 /// }
1349 /// ```
1350 ///
1351 /// Implementing manually:
1352 ///
1353 /// ```
1354 /// use musli::{Encode, Encoder};
1355 /// # struct MyType { data: Vec<String> }
1356 ///
1357 /// impl<M> Encode<M> for MyType {
1358 /// type Encode = Self;
1359 ///
1360 /// #[inline]
1361 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1362 /// where
1363 /// E: Encoder,
1364 /// {
1365 /// encoder.encode_slice(&self.data)
1366 /// }
1367 ///
1368 /// #[inline]
1369 /// fn as_encode(&self) -> &Self::Encode {
1370 /// self
1371 /// }
1372 /// }
1373 /// ```
1374 #[inline]
1375 fn encode_slice<T>(self, slice: impl AsRef<[T]>) -> Result<(), Self::Error>
1376 where
1377 T: Encode<Self::Mode>,
1378 {
1379 utils::default_encode_slice(self, slice)
1380 }
1381
1382 /// Encode a sequence extracted from an iterator of slices with a trusted
1383 /// length.
1384 ///
1385 /// This defaults to using [`Encoder::encode_sequence`] and if specialized
1386 /// must implement the same format as would calling that method.
1387 ///
1388 /// # Examples
1389 ///
1390 /// Deriving an implementation:
1391 ///
1392 /// ```
1393 /// use std::collections::VecDeque;
1394 /// use musli::Encode;
1395 ///
1396 /// #[derive(Encode)]
1397 /// #[musli(packed)]
1398 /// struct MyType {
1399 /// data: VecDeque<String>,
1400 /// }
1401 /// ```
1402 ///
1403 /// Implementing manually:
1404 ///
1405 /// ```
1406 /// # use musli::Encode;
1407 /// # use std::collections::VecDeque;
1408 /// # struct MyType { data: VecDeque<String> }
1409 /// use musli::Encoder;
1410 ///
1411 /// impl<M> Encode<M> for MyType {
1412 /// type Encode = Self;
1413 ///
1414 /// #[inline]
1415 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1416 /// where
1417 /// E: Encoder,
1418 /// {
1419 /// let (a, b) = self.data.as_slices();
1420 /// encoder.encode_slices(self.data.len(), [a, b])
1421 /// }
1422 ///
1423 /// #[inline]
1424 /// fn as_encode(&self) -> &Self::Encode {
1425 /// self
1426 /// }
1427 /// }
1428 /// ```
1429 #[inline]
1430 fn encode_slices<T>(
1431 self,
1432 len: usize,
1433 slices: impl IntoIterator<Item: AsRef<[T]>>,
1434 ) -> Result<(), Self::Error>
1435 where
1436 T: Encode<Self::Mode>,
1437 {
1438 utils::default_encode_slices(self, len, slices)
1439 }
1440
1441 /// Encode a sequence with a known length `len`.
1442 ///
1443 /// A sequence encodes one element following another and must in some way
1444 /// encode the length of the sequence in the underlying format. It is
1445 /// decoded with [`Decoder::decode_sequence`].
1446 ///
1447 /// [`Decoder::decode_sequence`]: crate::de::Decoder::decode_sequence
1448 ///
1449 /// # Examples
1450 ///
1451 /// Deriving an implementation:
1452 ///
1453 /// ```
1454 /// use musli::Encode;
1455 ///
1456 /// #[derive(Encode)]
1457 /// #[musli(packed)]
1458 /// struct MyType {
1459 /// data: Vec<String>
1460 /// }
1461 /// ```
1462 ///
1463 /// Implementing manually:
1464 ///
1465 /// ```
1466 /// use musli::{Encode, Encoder};
1467 /// use musli::en::SequenceEncoder;
1468 /// # struct MyType { data: Vec<String> }
1469 ///
1470 /// impl<M> Encode<M> for MyType {
1471 /// type Encode = Self;
1472 ///
1473 /// #[inline]
1474 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1475 /// where
1476 /// E: Encoder,
1477 /// {
1478 /// let mut seq = encoder.encode_sequence(self.data.len())?;
1479 ///
1480 /// for element in &self.data {
1481 /// seq.push(element)?;
1482 /// }
1483 ///
1484 /// seq.finish_sequence()
1485 /// }
1486 ///
1487 /// #[inline]
1488 /// fn as_encode(&self) -> &Self::Encode {
1489 /// self
1490 /// }
1491 /// }
1492 /// ```
1493 ///
1494 /// Encoding a tuple:
1495 ///
1496 /// ```
1497 /// use musli::{Encode, Encoder};
1498 /// use musli::en::SequenceEncoder;
1499 ///
1500 /// struct PackedTuple(u32, [u8; 128]);
1501 ///
1502 /// impl<M> Encode<M> for PackedTuple {
1503 /// type Encode = Self;
1504 ///
1505 /// #[inline]
1506 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1507 /// where
1508 /// E: Encoder,
1509 /// {
1510 /// let mut tuple = encoder.encode_sequence(2)?;
1511 /// tuple.encode_next()?.encode(self.0)?;
1512 /// tuple.encode_next()?.encode(&self.1)?;
1513 /// tuple.finish_sequence()
1514 /// }
1515 ///
1516 /// #[inline]
1517 /// fn as_encode(&self) -> &Self::Encode {
1518 /// self
1519 /// }
1520 /// }
1521 /// ```
1522 #[inline]
1523 fn encode_sequence(self, hint: impl SequenceHint) -> Result<Self::EncodeSequence, Self::Error> {
1524 Err(self.cx().message(expecting::unsupported_type(
1525 &expecting::SequenceWith(hint.size_hint()),
1526 ExpectingWrapper::new(&self),
1527 )))
1528 }
1529
1530 /// Encode a sequence using a closure.
1531 ///
1532 /// # Examples
1533 ///
1534 /// ```
1535 /// use musli::{Encode, Encoder};
1536 /// use musli::en::SequenceEncoder;
1537 /// # struct MyType { data: Vec<String> }
1538 ///
1539 /// impl<M> Encode<M> for MyType {
1540 /// type Encode = Self;
1541 ///
1542 /// #[inline]
1543 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1544 /// where
1545 /// E: Encoder,
1546 /// {
1547 /// encoder.encode_sequence_fn(self.data.len(), |seq| {
1548 /// for element in &self.data {
1549 /// seq.push(element)?;
1550 /// }
1551 ///
1552 /// Ok(())
1553 /// })
1554 /// }
1555 ///
1556 /// #[inline]
1557 /// fn as_encode(&self) -> &Self::Encode {
1558 /// self
1559 /// }
1560 /// }
1561 /// ```
1562 ///
1563 /// Encoding a tuple:
1564 ///
1565 /// ```
1566 /// use musli::{Encode, Encoder};
1567 /// use musli::en::SequenceEncoder;
1568 ///
1569 /// struct PackedTuple(u32, [u8; 128]);
1570 ///
1571 /// impl<M> Encode<M> for PackedTuple {
1572 /// type Encode = Self;
1573 ///
1574 /// #[inline]
1575 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1576 /// where
1577 /// E: Encoder,
1578 /// {
1579 /// encoder.encode_sequence_fn(2, |tuple| {
1580 /// tuple.encode_next()?.encode(self.0)?;
1581 /// tuple.encode_next()?.encode(&self.1)?;
1582 /// Ok(())
1583 /// })
1584 /// }
1585 ///
1586 /// #[inline]
1587 /// fn as_encode(&self) -> &Self::Encode {
1588 /// self
1589 /// }
1590 /// }
1591 /// ```
1592 #[inline]
1593 fn encode_sequence_fn<F>(self, hint: impl SequenceHint, f: F) -> Result<(), Self::Error>
1594 where
1595 F: FnOnce(&mut Self::EncodeSequence) -> Result<(), Self::Error>,
1596 {
1597 let mut seq = self.encode_sequence(hint)?;
1598 f(&mut seq)?;
1599 seq.finish_sequence()
1600 }
1601
1602 /// Encode a map with a known length `len`.
1603 ///
1604 /// # Examples
1605 ///
1606 /// Deriving an implementation:
1607 ///
1608 /// ```
1609 /// use musli::Encode;
1610 ///
1611 /// #[derive(Encode)]
1612 /// struct Struct {
1613 /// name: String,
1614 /// age: u32,
1615 /// }
1616 /// ```
1617 ///
1618 /// Implementing manually:
1619 ///
1620 /// ```
1621 /// use musli::{Encode, Encoder};
1622 /// use musli::en::MapEncoder;
1623 /// # struct Struct { name: String, age: u32 }
1624 ///
1625 /// impl<M> Encode<M> for Struct {
1626 /// type Encode = Self;
1627 ///
1628 /// #[inline]
1629 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1630 /// where
1631 /// E: Encoder,
1632 /// {
1633 /// let mut map = encoder.encode_map(2)?;
1634 /// map.insert_entry("name", &self.name)?;
1635 /// map.insert_entry("age", self.age)?;
1636 /// map.finish_map()
1637 /// }
1638 ///
1639 /// #[inline]
1640 /// fn as_encode(&self) -> &Self::Encode {
1641 /// self
1642 /// }
1643 /// }
1644 /// ```
1645 #[inline]
1646 #[must_use = "Map encoders must be consumed"]
1647 fn encode_map(self, hint: impl MapHint) -> Result<Self::EncodeMap, Self::Error> {
1648 Err(self.cx().message(expecting::unsupported_type(
1649 &expecting::Map,
1650 ExpectingWrapper::new(&self),
1651 )))
1652 }
1653
1654 /// Encode a map using a closure.
1655 ///
1656 /// # Examples
1657 ///
1658 /// ```
1659 /// use musli::{Encode, Encoder};
1660 /// use musli::en::MapEncoder;
1661 ///
1662 /// struct Struct {
1663 /// name: String,
1664 /// age: u32
1665 /// }
1666 ///
1667 /// impl<M> Encode<M> for Struct {
1668 /// type Encode = Self;
1669 ///
1670 /// #[inline]
1671 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1672 /// where
1673 /// E: Encoder,
1674 /// {
1675 /// encoder.encode_map_fn(2, |map| {
1676 /// map.insert_entry("name", &self.name)?;
1677 /// map.insert_entry("age", self.age)?;
1678 /// Ok(())
1679 /// })
1680 /// }
1681 ///
1682 /// #[inline]
1683 /// fn as_encode(&self) -> &Self::Encode {
1684 /// self
1685 /// }
1686 /// }
1687 /// ```
1688 #[inline]
1689 fn encode_map_fn<F>(self, hint: impl MapHint, f: F) -> Result<(), Self::Error>
1690 where
1691 F: FnOnce(&mut Self::EncodeMap) -> Result<(), Self::Error>,
1692 {
1693 let mut map = self.encode_map(hint)?;
1694 f(&mut map)?;
1695 map.finish_map()
1696 }
1697
1698 /// Encode a map through pairs with a known length `len`.
1699 ///
1700 /// # Examples
1701 ///
1702 /// ```
1703 /// use musli::{Encode, Encoder};
1704 /// use musli::en::EntriesEncoder;
1705 ///
1706 /// struct Struct {
1707 /// name: String,
1708 /// age: u32,
1709 /// }
1710 ///
1711 /// impl<M> Encode<M> for Struct {
1712 /// type Encode = Self;
1713 ///
1714 /// #[inline]
1715 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1716 /// where
1717 /// E: Encoder,
1718 /// {
1719 /// let mut m = encoder.encode_map_entries(2)?;
1720 ///
1721 /// // Simplified encoding.
1722 /// m.insert_entry("name", &self.name)?;
1723 ///
1724 /// // Key and value encoding as a stream.
1725 /// m.encode_entry_key()?.encode("age")?;
1726 /// m.encode_entry_value()?.encode(self.age)?;
1727 /// m.finish_entries()
1728 /// }
1729 ///
1730 /// #[inline]
1731 /// fn as_encode(&self) -> &Self::Encode {
1732 /// self
1733 /// }
1734 /// }
1735 /// ```
1736 #[inline]
1737 fn encode_map_entries(self, hint: impl MapHint) -> Result<Self::EncodeMapEntries, Self::Error> {
1738 Err(self.cx().message(expecting::unsupported_type(
1739 &expecting::MapWith(hint.size_hint()),
1740 ExpectingWrapper::new(&self),
1741 )))
1742 }
1743
1744 /// Encode a variant.
1745 ///
1746 /// # Examples
1747 ///
1748 /// ```
1749 /// use musli::Encode;
1750 ///
1751 /// #[derive(Encode)]
1752 /// enum Enum {
1753 /// UnitVariant,
1754 /// TupleVariant(String),
1755 /// StructVariant {
1756 /// data: String,
1757 /// age: u32,
1758 /// }
1759 /// }
1760 /// ```
1761 ///
1762 /// Implementing manually:
1763 ///
1764 /// ```
1765 /// use musli::{Encode, Encoder};
1766 /// use musli::en::{VariantEncoder, SequenceEncoder, MapEncoder};
1767 /// # enum Enum { UnitVariant, TupleVariant(String), StructVariant { data: String, age: u32 } }
1768 ///
1769 /// impl<M> Encode<M> for Enum {
1770 /// type Encode = Self;
1771 ///
1772 /// #[inline]
1773 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1774 /// where
1775 /// E: Encoder,
1776 /// {
1777 /// let mut variant = encoder.encode_variant()?;
1778 ///
1779 /// match self {
1780 /// Enum::UnitVariant => {
1781 /// variant.insert_variant("UnitVariant", ())
1782 /// }
1783 /// Enum::TupleVariant(data) => {
1784 /// variant.encode_tag()?.encode_string("TupleVariant")?;
1785 ///
1786 /// let mut tuple = variant.encode_data()?.encode_sequence(1)?;
1787 /// tuple.push(data)?;
1788 /// tuple.finish_sequence()?;
1789 ///
1790 /// variant.finish_variant()
1791 /// }
1792 /// Enum::StructVariant { data, age } => {
1793 /// variant.encode_tag()?.encode_string("StructVariant")?;
1794 ///
1795 /// let mut st = variant.encode_data()?.encode_map(2)?;
1796 /// st.insert_entry("data", data)?;
1797 /// st.insert_entry("age", age)?;
1798 /// st.finish_map()?;
1799 ///
1800 /// variant.finish_variant()
1801 /// }
1802 /// }
1803 /// }
1804 ///
1805 /// #[inline]
1806 /// fn as_encode(&self) -> &Self::Encode {
1807 /// self
1808 /// }
1809 /// }
1810 /// ```
1811 #[inline]
1812 fn encode_variant(self) -> Result<Self::EncodeVariant, Self::Error> {
1813 Err(self.cx().message(expecting::unsupported_type(
1814 &expecting::Variant,
1815 ExpectingWrapper::new(&self),
1816 )))
1817 }
1818
1819 /// Encode a variant using a closure.
1820 ///
1821 /// # Examples
1822 ///
1823 /// ```
1824 /// use musli::{Encode, Encoder};
1825 /// use musli::en::{VariantEncoder, SequenceEncoder, MapEncoder};
1826 ///
1827 /// enum Enum {
1828 /// UnitVariant,
1829 /// TupleVariant(String),
1830 /// StructVariant {
1831 /// data: String,
1832 /// age: u32,
1833 /// }
1834 /// }
1835 ///
1836 /// impl<M> Encode<M> for Enum {
1837 /// type Encode = Self;
1838 ///
1839 /// #[inline]
1840 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1841 /// where
1842 /// E: Encoder,
1843 /// {
1844 /// match self {
1845 /// Enum::UnitVariant => {
1846 /// encoder.encode_variant()?.insert_variant("variant1", ())
1847 /// }
1848 /// Enum::TupleVariant(data) => {
1849 /// encoder.encode_variant_fn(|variant| {
1850 /// variant.encode_tag()?.encode("TupleVariant")?;
1851 ///
1852 /// variant.encode_data()?.encode_sequence_fn(2, |tuple| {
1853 /// tuple.push(data)?;
1854 /// Ok(())
1855 /// })?;
1856 ///
1857 /// Ok(())
1858 /// })
1859 /// }
1860 /// Enum::StructVariant { data, age } => {
1861 /// encoder.encode_variant_fn(|variant| {
1862 /// variant.encode_tag()?.encode("variant3")?;
1863 ///
1864 /// variant.encode_data()?.encode_map_fn(2, |st| {
1865 /// st.insert_entry("data", data)?;
1866 /// st.insert_entry("age", age)?;
1867 /// Ok(())
1868 /// })?;
1869 ///
1870 /// Ok(())
1871 /// })
1872 /// }
1873 /// }
1874 /// }
1875 ///
1876 /// #[inline]
1877 /// fn as_encode(&self) -> &Self::Encode {
1878 /// self
1879 /// }
1880 /// }
1881 /// ```
1882 #[inline]
1883 fn encode_variant_fn<F>(self, f: F) -> Result<(), Self::Error>
1884 where
1885 F: FnOnce(&mut Self::EncodeVariant) -> Result<(), Self::Error>,
1886 {
1887 let mut variant = self.encode_variant()?;
1888 f(&mut variant)?;
1889 variant.finish_variant()
1890 }
1891
1892 /// Simplified encoding for a unit variant.
1893 ///
1894 /// # Examples
1895 ///
1896 /// Deriving an implementation:
1897 ///
1898 /// ```
1899 /// use musli::Encode;
1900 ///
1901 /// #[derive(Encode)]
1902 /// enum Enum {
1903 /// UnitVariant,
1904 /// }
1905 /// ```
1906 ///
1907 /// Implementing manually:
1908 ///
1909 /// ```
1910 /// use musli::{Encode, Encoder};
1911 /// use musli::en::{VariantEncoder, MapEncoder, SequenceEncoder};
1912 /// # enum Enum { UnitVariant }
1913 ///
1914 /// impl<M> Encode<M> for Enum {
1915 /// type Encode = Self;
1916 ///
1917 /// #[inline]
1918 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1919 /// where
1920 /// E: Encoder,
1921 /// {
1922 /// match self {
1923 /// Enum::UnitVariant => {
1924 /// encoder.encode_unit_variant("variant1")
1925 /// }
1926 /// }
1927 /// }
1928 ///
1929 /// #[inline]
1930 /// fn as_encode(&self) -> &Self::Encode {
1931 /// self
1932 /// }
1933 /// }
1934 /// ```
1935 #[inline]
1936 fn encode_unit_variant<T>(self, tag: &T) -> Result<(), Self::Error>
1937 where
1938 T: ?Sized + Encode<Self::Mode>,
1939 {
1940 self.encode_variant_fn(|variant| {
1941 variant.encode_tag()?.encode(tag)?;
1942 variant.encode_data()?.encode_empty()?;
1943 Ok(())
1944 })
1945 }
1946
1947 /// Simplified encoding for a tuple variant.
1948 ///
1949 /// # Examples
1950 ///
1951 /// Deriving an implementation:
1952 ///
1953 /// ```
1954 /// use musli::Encode;
1955 ///
1956 /// #[derive(Encode)]
1957 /// enum Enum {
1958 /// TupleVariant(String),
1959 /// }
1960 /// ```
1961 ///
1962 /// Implementing manually:
1963 ///
1964 /// ```
1965 /// use musli::{Encode, Encoder};
1966 /// use musli::en::SequenceEncoder;
1967 /// # enum Enum { TupleVariant(String) }
1968 ///
1969 /// impl<M> Encode<M> for Enum {
1970 /// type Encode = Self;
1971 ///
1972 /// #[inline]
1973 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1974 /// where
1975 /// E: Encoder,
1976 /// {
1977 /// match self {
1978 /// Enum::TupleVariant(data) => {
1979 /// let mut variant = encoder.encode_sequence_variant("variant2", 1)?;
1980 /// variant.push(data)?;
1981 /// variant.finish_sequence()
1982 /// }
1983 /// }
1984 /// }
1985 ///
1986 /// #[inline]
1987 /// fn as_encode(&self) -> &Self::Encode {
1988 /// self
1989 /// }
1990 /// }
1991 /// ```
1992 #[inline]
1993 fn encode_sequence_variant<T>(
1994 self,
1995 tag: &T,
1996 hint: impl SequenceHint,
1997 ) -> Result<Self::EncodeSequenceVariant, Self::Error>
1998 where
1999 T: ?Sized + Encode<Self::Mode>,
2000 {
2001 Err(self.cx().message(expecting::unsupported_type(
2002 &expecting::SequenceVariant,
2003 ExpectingWrapper::new(&self),
2004 )))
2005 }
2006
2007 /// Simplified encoding for a struct variant.
2008 ///
2009 /// # Examples
2010 ///
2011 /// Deriving an implementation:
2012 ///
2013 /// ```
2014 /// use musli::Encode;
2015 ///
2016 /// #[derive(Encode)]
2017 /// enum Enum {
2018 /// StructVariant {
2019 /// data: String,
2020 /// age: u32,
2021 /// }
2022 /// }
2023 /// ```
2024 ///
2025 /// Implementing manually:
2026 ///
2027 /// ```
2028 /// use musli::{Encode, Encoder};
2029 /// use musli::en::MapEncoder;
2030 /// # enum Enum { StructVariant { data: String, age: u32 } }
2031 ///
2032 /// impl<M> Encode<M> for Enum {
2033 /// type Encode = Self;
2034 ///
2035 /// #[inline]
2036 /// fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
2037 /// where
2038 /// E: Encoder,
2039 /// {
2040 /// match self {
2041 /// Enum::StructVariant { data, age } => {
2042 /// let mut variant = encoder.encode_map_variant("variant3", 2)?;
2043 /// variant.insert_entry("data", data)?;
2044 /// variant.insert_entry("age", age)?;
2045 /// variant.finish_map()
2046 /// }
2047 /// }
2048 /// }
2049 ///
2050 /// #[inline]
2051 /// fn as_encode(&self) -> &Self::Encode {
2052 /// self
2053 /// }
2054 /// }
2055 /// ```
2056 #[inline]
2057 fn encode_map_variant<T>(
2058 self,
2059 tag: &T,
2060 hint: impl MapHint,
2061 ) -> Result<Self::EncodeMapVariant, Self::Error>
2062 where
2063 T: ?Sized + Encode<Self::Mode>,
2064 {
2065 Err(self.cx().message(expecting::unsupported_type(
2066 &expecting::MapVariant,
2067 ExpectingWrapper::new(&self),
2068 )))
2069 }
2070}
2071
2072#[repr(transparent)]
2073struct ExpectingWrapper<T> {
2074 inner: T,
2075}
2076
2077impl<T> ExpectingWrapper<T> {
2078 #[inline]
2079 const fn new(value: &T) -> &Self {
2080 // SAFETY: `ExpectingWrapper` is repr(transparent) over `T`.
2081 unsafe { &*(value as *const T as *const Self) }
2082 }
2083}
2084
2085impl<T> Expecting for ExpectingWrapper<T>
2086where
2087 T: Encoder,
2088{
2089 #[inline]
2090 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2091 self.inner.expecting(f)
2092 }
2093}