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