1use crate::error::{Error, Result};
2use crate::ser::flavors::{Cobs, Flavor, Slice};
3use serde::Serialize;
4
5#[cfg(feature = "heapless")]
6use crate::ser::flavors::HVec;
7
8#[cfg(feature = "heapless")]
9use heapless::Vec;
10
11#[cfg(feature = "alloc")]
12use crate::ser::flavors::AllocVec;
13
14#[cfg(feature = "alloc")]
15extern crate alloc;
16
17use crate::ser::serializer::Serializer;
18
19pub mod flavors;
20pub(crate) mod serializer;
21
22pub fn to_slice_cobs<'a, 'b, T>(value: &'b T, buf: &'a mut [u8]) -> Result<&'a mut [u8]>
49where
50 T: Serialize + ?Sized,
51{
52 serialize_with_flavor::<T, Cobs<Slice<'a>>, &'a mut [u8]>(
53 value,
54 Cobs::try_new(Slice::new(buf))?,
55 )
56}
57
58pub fn to_slice<'a, 'b, T>(value: &'b T, buf: &'a mut [u8]) -> Result<&'a mut [u8]>
86where
87 T: Serialize + ?Sized,
88{
89 serialize_with_flavor::<T, Slice<'a>, &'a mut [u8]>(value, Slice::new(buf))
90}
91
92#[cfg(feature = "heapless")]
135#[cfg_attr(docsrs, doc(cfg(feature = "heapless")))]
136pub fn to_vec_cobs<T, const B: usize>(value: &T) -> Result<Vec<u8, B>>
137where
138 T: Serialize + ?Sized,
139{
140 serialize_with_flavor::<T, Cobs<HVec<B>>, Vec<u8, B>>(value, Cobs::try_new(HVec::default())?)
141}
142
143#[cfg(feature = "heapless")]
184#[cfg_attr(docsrs, doc(cfg(feature = "heapless")))]
185pub fn to_vec<T, const B: usize>(value: &T) -> Result<Vec<u8, B>>
186where
187 T: Serialize + ?Sized,
188{
189 serialize_with_flavor::<T, HVec<B>, Vec<u8, B>>(value, HVec::default())
190}
191
192#[cfg(feature = "use-std")]
206#[cfg_attr(docsrs, doc(cfg(feature = "use-std")))]
207#[inline]
208pub fn to_stdvec<T>(value: &T) -> Result<std::vec::Vec<u8>>
209where
210 T: Serialize + ?Sized,
211{
212 to_allocvec(value)
213}
214
215#[cfg(feature = "use-std")]
231#[cfg_attr(docsrs, doc(cfg(feature = "use-std")))]
232#[inline]
233pub fn to_stdvec_cobs<T>(value: &T) -> Result<std::vec::Vec<u8>>
234where
235 T: Serialize + ?Sized,
236{
237 to_allocvec_cobs(value)
238}
239
240#[cfg(feature = "alloc")]
254#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
255pub fn to_allocvec<T>(value: &T) -> Result<alloc::vec::Vec<u8>>
256where
257 T: Serialize + ?Sized,
258{
259 serialize_with_flavor::<T, AllocVec, alloc::vec::Vec<u8>>(value, AllocVec::new())
260}
261
262#[cfg(feature = "alloc")]
278#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
279pub fn to_allocvec_cobs<T>(value: &T) -> Result<alloc::vec::Vec<u8>>
280where
281 T: Serialize + ?Sized,
282{
283 serialize_with_flavor::<T, Cobs<AllocVec>, alloc::vec::Vec<u8>>(
284 value,
285 Cobs::try_new(AllocVec::new())?,
286 )
287}
288
289pub fn to_extend<T, W>(value: &T, writer: W) -> Result<W>
301where
302 T: Serialize + ?Sized,
303 W: core::iter::Extend<u8>,
304{
305 serialize_with_flavor::<T, _, _>(value, flavors::ExtendFlavor::new(writer))
306}
307
308#[cfg(any(feature = "embedded-io-04", feature = "embedded-io-06"))]
321pub fn to_eio<T, W>(value: &T, writer: W) -> Result<W>
322where
323 T: Serialize + ?Sized,
324 W: crate::eio::Write,
325{
326 serialize_with_flavor::<T, _, _>(value, flavors::eio::WriteFlavor::new(writer))
327}
328
329#[cfg(feature = "use-std")]
342pub fn to_io<T, W>(value: &T, writer: W) -> Result<W>
343where
344 T: Serialize + ?Sized,
345 W: std::io::Write,
346{
347 serialize_with_flavor::<T, _, _>(value, flavors::io::WriteFlavor::new(writer))
348}
349
350#[cfg(feature = "use-crc")]
371#[cfg_attr(docsrs, doc(cfg(feature = "use-crc")))]
372#[inline]
373pub fn to_slice_crc32<'a, T>(
374 value: &T,
375 buf: &'a mut [u8],
376 digest: crc::Digest<'_, u32>,
377) -> Result<&'a mut [u8]>
378where
379 T: Serialize + ?Sized,
380{
381 flavors::crc::to_slice_u32(value, buf, digest)
382}
383
384#[cfg(all(feature = "use-crc", feature = "heapless"))]
426#[cfg_attr(docsrs, doc(cfg(all(feature = "use-crc", feature = "heapless"))))]
427#[inline]
428pub fn to_vec_crc32<T, const B: usize>(
429 value: &T,
430 digest: crc::Digest<'_, u32>,
431) -> Result<heapless::Vec<u8, B>>
432where
433 T: Serialize + ?Sized,
434{
435 flavors::crc::to_vec_u32(value, digest)
436}
437
438#[cfg(all(feature = "use-crc", feature = "use-std"))]
460#[cfg_attr(docsrs, doc(cfg(all(feature = "use-crc", feature = "use-std"))))]
461#[inline]
462pub fn to_stdvec_crc32<T>(value: &T, digest: crc::Digest<'_, u32>) -> Result<std::vec::Vec<u8>>
463where
464 T: Serialize + ?Sized,
465{
466 flavors::crc::to_allocvec_u32(value, digest)
467}
468
469#[cfg(all(feature = "use-crc", feature = "alloc"))]
491#[cfg_attr(docsrs, doc(cfg(all(feature = "use-crc", feature = "alloc"))))]
492#[inline]
493pub fn to_allocvec_crc32<T>(value: &T, digest: crc::Digest<'_, u32>) -> Result<alloc::vec::Vec<u8>>
494where
495 T: Serialize + ?Sized,
496{
497 flavors::crc::to_allocvec_u32(value, digest)
498}
499
500pub fn serialize_with_flavor<T, S, O>(value: &T, storage: S) -> Result<O>
527where
528 T: Serialize + ?Sized,
529 S: Flavor<Output = O>,
530{
531 let mut serializer = Serializer { output: storage };
532 value.serialize(&mut serializer)?;
533 serializer
534 .output
535 .finalize()
536 .map_err(|_| Error::SerializeBufferFull)
537}
538
539pub fn serialized_size<T>(value: &T) -> Result<usize>
541where
542 T: Serialize + ?Sized,
543{
544 serialize_with_flavor::<T, flavors::Size, usize>(value, flavors::Size::default())
545}
546
547#[cfg(feature = "heapless")]
548#[cfg(test)]
549mod test {
550 use super::*;
551 use crate::max_size::MaxSize;
552 use crate::varint::{varint_max, varint_usize};
553 use core::fmt::Write;
554 use core::ops::{Deref, DerefMut};
555 use heapless::{FnvIndexMap, String};
556 use serde::Deserialize;
557
558 #[test]
559 fn ser_u8() {
560 let output: Vec<u8, 1> = to_vec(&0x05u8).unwrap();
561 assert_eq!(&[5], output.deref());
562 assert!(output.len() == serialized_size(&0x05u8).unwrap());
563 assert!(output.len() <= Vec::<u8, 1>::POSTCARD_MAX_SIZE);
564 }
565
566 #[test]
567 fn ser_u16() {
568 const SZ: usize = varint_max::<u16>();
569 let output: Vec<u8, SZ> = to_vec(&0xA5C7u16).unwrap();
570 assert_eq!(&[0xC7, 0xCB, 0x02], output.deref());
571 assert!(output.len() == serialized_size(&0xA5C7u16).unwrap());
572 assert!(output.len() <= Vec::<u8, SZ>::POSTCARD_MAX_SIZE);
573 }
574
575 #[test]
576 fn ser_u32() {
577 const SZ: usize = varint_max::<u32>();
578 let output: Vec<u8, SZ> = to_vec(&0xCDAB3412u32).unwrap();
579 assert_eq!(&[0x92, 0xE8, 0xAC, 0xED, 0x0C], output.deref());
580 assert!(output.len() == serialized_size(&0xCDAB3412u32).unwrap());
581 assert!(output.len() <= Vec::<u8, SZ>::POSTCARD_MAX_SIZE);
582 }
583
584 #[test]
585 fn ser_u64() {
586 const SZ: usize = varint_max::<u64>();
587 let output: Vec<u8, SZ> = to_vec(&0x1234_5678_90AB_CDEFu64).unwrap();
588 assert_eq!(
589 &[0xEF, 0x9B, 0xAF, 0x85, 0x89, 0xCF, 0x95, 0x9A, 0x12],
590 output.deref()
591 );
592 assert!(output.len() == serialized_size(&0x1234_5678_90AB_CDEFu64).unwrap());
593 assert!(output.len() <= Vec::<u8, SZ>::POSTCARD_MAX_SIZE);
594 }
595
596 #[test]
597 fn ser_u128() {
598 const SZ: usize = varint_max::<u128>();
599 let output: Vec<u8, SZ> = to_vec(&0x1234_5678_90AB_CDEF_1234_5678_90AB_CDEFu128).unwrap();
600 assert_eq!(
601 &[
602 0xEF, 0x9B, 0xAF, 0x85, 0x89, 0xCF, 0x95, 0x9A, 0x92, 0xDE, 0xB7, 0xDE, 0x8A, 0x92,
603 0x9E, 0xAB, 0xB4, 0x24,
604 ],
605 output.deref()
606 );
607 assert!(
608 output.len()
609 == serialized_size(&0x1234_5678_90AB_CDEF_1234_5678_90AB_CDEFu128).unwrap()
610 );
611 assert!(output.len() <= Vec::<u8, SZ>::POSTCARD_MAX_SIZE);
612 }
613
614 #[derive(Serialize)]
615 struct BasicU8S {
616 st: u16,
617 ei: u8,
618 ote: u128,
619 sf: u64,
620 tt: u32,
621 }
622
623 impl MaxSize for BasicU8S {
624 const POSTCARD_MAX_SIZE: usize = {
625 u16::POSTCARD_MAX_SIZE
626 + u8::POSTCARD_MAX_SIZE
627 + u128::POSTCARD_MAX_SIZE
628 + u64::POSTCARD_MAX_SIZE
629 + u32::POSTCARD_MAX_SIZE
630 };
631 }
632
633 #[test]
634 fn ser_struct_unsigned() {
635 const SZ: usize = BasicU8S::POSTCARD_MAX_SIZE;
636 let input = BasicU8S {
637 st: 0xABCD,
638 ei: 0xFE,
639 ote: 0x1234_4321_ABCD_DCBA_1234_4321_ABCD_DCBA,
640 sf: 0x1234_4321_ABCD_DCBA,
641 tt: 0xACAC_ACAC,
642 };
643 let output: Vec<u8, SZ> = to_vec(&input).unwrap();
644
645 assert_eq!(
646 &[
647 0xCD, 0xD7, 0x02, 0xFE, 0xBA, 0xB9, 0xB7, 0xDE, 0x9A, 0xE4, 0x90, 0x9A, 0x92, 0xF4,
648 0xF2, 0xEE, 0xBC, 0xB5, 0xC8, 0xA1, 0xB4, 0x24, 0xBA, 0xB9, 0xB7, 0xDE, 0x9A, 0xE4,
649 0x90, 0x9A, 0x12, 0xAC, 0xD9, 0xB2, 0xE5, 0x0A
650 ],
651 output.deref()
652 );
653 assert!(output.len() == serialized_size(&input).unwrap());
654 assert!(output.len() <= BasicU8S::POSTCARD_MAX_SIZE);
655 }
656
657 #[test]
658 fn ser_byte_slice() {
659 let input: &[u8] = &[1u8, 2, 3, 4, 5, 6, 7, 8];
660 let output: Vec<u8, 9> = to_vec(input).unwrap();
661 assert_eq!(
662 &[0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08],
663 output.deref()
664 );
665 assert!(output.len() == serialized_size(&input).unwrap());
666
667 let mut input: Vec<u8, 1024> = Vec::new();
668 for i in 0..1024 {
669 input.push((i & 0xFF) as u8).unwrap();
670 }
671 let output: Vec<u8, 2048> = to_vec(input.deref()).unwrap();
672 assert_eq!(&[0x80, 0x08], &output.deref()[..2]);
673
674 assert_eq!(output.len(), 1026);
675 for (i, val) in output.deref()[2..].iter().enumerate() {
676 assert_eq!((i & 0xFF) as u8, *val);
677 }
678 }
679
680 #[test]
681 fn ser_str() {
682 let input: &str = "hello, postcard!";
683 let output: Vec<u8, 17> = to_vec(input).unwrap();
684 assert_eq!(0x10, output.deref()[0]);
685 assert_eq!(input.as_bytes(), &output.deref()[1..]);
686 assert!(output.len() == serialized_size(&input).unwrap());
687
688 let mut input: String<1024> = String::new();
689 for _ in 0..256 {
690 write!(&mut input, "abcd").unwrap();
691 }
692 let output: Vec<u8, 2048> = to_vec(input.deref()).unwrap();
693 assert_eq!(&[0x80, 0x08], &output.deref()[..2]);
694 assert!(String::<1024>::POSTCARD_MAX_SIZE <= output.len());
695
696 assert_eq!(output.len(), 1026);
697 for ch in output.deref()[2..].chunks(4) {
698 assert_eq!("abcd", core::str::from_utf8(ch).unwrap());
699 }
700 }
701
702 #[test]
703 fn usize_varint_encode() {
704 let mut buf = [0; varint_max::<usize>()];
705 let res = varint_usize(1, &mut buf);
706
707 assert_eq!(&[1], res);
708
709 let res = varint_usize(usize::MAX, &mut buf);
710
711 if varint_max::<usize>() == varint_max::<u32>() {
713 assert_eq!(&[0xFF, 0xFF, 0xFF, 0xFF, 0x0F], res);
714 } else if varint_max::<usize>() == varint_max::<u64>() {
715 assert_eq!(
716 &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01],
717 res
718 );
719 } else {
720 panic!("Update this test for 16/128 bit targets!");
721 }
722 }
723
724 #[allow(dead_code)]
725 #[derive(Serialize)]
726 enum BasicEnum {
727 Bib,
728 Bim,
729 Bap,
730 }
731
732 #[derive(Serialize)]
733 struct EnumStruct {
734 eight: u8,
735 sixt: u16,
736 }
737
738 #[derive(Serialize)]
739 enum DataEnum {
740 Bib(u16),
741 Bim(u64),
742 Bap(u8),
743 Kim(EnumStruct),
744 Chi { a: u8, b: u32 },
745 Sho(u16, u8),
746 }
747
748 #[test]
749 fn enums() {
750 let input = BasicEnum::Bim;
751 let output: Vec<u8, 1> = to_vec(&input).unwrap();
752 assert_eq!(&[0x01], output.deref());
753 assert!(output.len() == serialized_size(&input).unwrap());
754
755 let input = DataEnum::Bim(u64::MAX);
756 let output: Vec<u8, { 1 + varint_max::<u64>() }> = to_vec(&input).unwrap();
757 assert_eq!(
758 &[0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01],
759 output.deref()
760 );
761 assert!(output.len() == serialized_size(&input).unwrap());
762
763 let input = DataEnum::Bib(u16::MAX);
764 let output: Vec<u8, { 1 + varint_max::<u16>() }> = to_vec(&input).unwrap();
765 assert_eq!(&[0x00, 0xFF, 0xFF, 0x03], output.deref());
766 assert!(output.len() == serialized_size(&input).unwrap());
767
768 let input = DataEnum::Bap(u8::MAX);
769 let output: Vec<u8, 2> = to_vec(&input).unwrap();
770 assert_eq!(&[0x02, 0xFF], output.deref());
771 assert!(output.len() == serialized_size(&input).unwrap());
772
773 let input = DataEnum::Kim(EnumStruct {
774 eight: 0xF0,
775 sixt: 0xACAC,
776 });
777 let output: Vec<u8, 8> = to_vec(&input).unwrap();
778 assert_eq!(&[0x03, 0xF0, 0xAC, 0xD9, 0x02], output.deref());
779 assert!(output.len() == serialized_size(&input).unwrap());
780
781 let input = DataEnum::Chi {
782 a: 0x0F,
783 b: 0xC7C7C7C7,
784 };
785 let output: Vec<u8, 8> = to_vec(&input).unwrap();
786 assert_eq!(&[0x04, 0x0F, 0xC7, 0x8F, 0x9F, 0xBE, 0x0C], output.deref());
787 assert!(output.len() == serialized_size(&input).unwrap());
788
789 let input = DataEnum::Sho(0x6969, 0x07);
790 let output: Vec<u8, 8> = to_vec(&input).unwrap();
791 assert_eq!(&[0x05, 0xE9, 0xD2, 0x01, 0x07], output.deref());
792 assert!(output.len() == serialized_size(&input).unwrap());
793 }
794
795 #[test]
796 fn tuples() {
797 let input = (1u8, 10u32, "Hello!");
798 let output: Vec<u8, 128> = to_vec(&input).unwrap();
799 assert_eq!(
800 &[1u8, 0x0A, 0x06, b'H', b'e', b'l', b'l', b'o', b'!'],
801 output.deref()
802 );
803 assert!(output.len() == serialized_size(&input).unwrap());
804 }
805
806 #[test]
807 fn bytes() {
808 let x: &[u8; 32] = &[0u8; 32];
809 let output: Vec<u8, 128> = to_vec(x).unwrap();
810 assert_eq!(output.len(), 32);
811 assert!(output.len() == serialized_size(&x).unwrap());
812 assert!(<[u8; 32] as MaxSize>::POSTCARD_MAX_SIZE <= output.len());
813
814 let x: &[u8] = &[0u8; 32];
815 let output: Vec<u8, 128> = to_vec(x).unwrap();
816 assert_eq!(output.len(), 33);
817 assert!(output.len() == serialized_size(&x).unwrap());
818 }
819
820 #[derive(Serialize)]
821 pub struct NewTypeStruct(u32);
822
823 #[derive(Serialize)]
824 pub struct TupleStruct((u8, u16));
825
826 #[test]
827 fn structs() {
828 let input = NewTypeStruct(5);
829 let output: Vec<u8, 1> = to_vec(&input).unwrap();
830 assert_eq!(&[0x05], output.deref());
831 assert!(output.len() == serialized_size(&input).unwrap());
832
833 let input = TupleStruct((0xA0, 0x1234));
834 let output: Vec<u8, 3> = to_vec(&input).unwrap();
835 assert_eq!(&[0xA0, 0xB4, 0x24], output.deref());
836 assert!(output.len() == serialized_size(&input).unwrap());
837 }
838
839 #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
840 struct RefStruct<'a> {
841 bytes: &'a [u8],
842 str_s: &'a str,
843 }
844
845 #[test]
846 fn ref_struct() {
847 let message = "hElLo";
848 let bytes = [0x01, 0x10, 0x02, 0x20];
849 let input = RefStruct {
850 bytes: &bytes,
851 str_s: message,
852 };
853 let output: Vec<u8, 11> = to_vec(&input).unwrap();
854
855 assert_eq!(
856 &[0x04, 0x01, 0x10, 0x02, 0x20, 0x05, b'h', b'E', b'l', b'L', b'o',],
857 output.deref()
858 );
859 assert!(output.len() == serialized_size(&input).unwrap());
860 }
861
862 #[test]
863 fn unit() {
864 let output: Vec<u8, 1> = to_vec(&()).unwrap();
865 assert_eq!(output.len(), 0);
866 assert!(output.len() == serialized_size(&()).unwrap());
867 }
868
869 #[test]
870 fn heapless_data() {
871 let mut input: Vec<u8, 4> = Vec::new();
872 input.extend_from_slice(&[0x01, 0x02, 0x03, 0x04]).unwrap();
873 let output: Vec<u8, 5> = to_vec(&input).unwrap();
874 assert_eq!(&[0x04, 0x01, 0x02, 0x03, 0x04], output.deref());
875 assert!(output.len() == serialized_size(&input).unwrap());
876
877 let mut input: String<8> = String::new();
878 write!(&mut input, "helLO!").unwrap();
879 let output: Vec<u8, 7> = to_vec(&input).unwrap();
880 assert_eq!(&[0x06, b'h', b'e', b'l', b'L', b'O', b'!'], output.deref());
881 assert!(output.len() == serialized_size(&input).unwrap());
882
883 let mut input: FnvIndexMap<u8, u8, 4> = FnvIndexMap::new();
884 input.insert(0x01, 0x05).unwrap();
885 input.insert(0x02, 0x06).unwrap();
886 input.insert(0x03, 0x07).unwrap();
887 input.insert(0x04, 0x08).unwrap();
888 let output: Vec<u8, 100> = to_vec(&input).unwrap();
889 assert_eq!(
890 &[0x04, 0x01, 0x05, 0x02, 0x06, 0x03, 0x07, 0x04, 0x08],
891 output.deref()
892 );
893 assert!(output.len() == serialized_size(&input).unwrap());
894 }
895
896 #[test]
897 fn cobs_test() {
898 let message = "hElLo";
899 let bytes = [0x01, 0x00, 0x02, 0x20];
900 let input = RefStruct {
901 bytes: &bytes,
902 str_s: message,
903 };
904
905 let mut output: Vec<u8, 13> = to_vec_cobs(&input).unwrap();
906
907 let sz = cobs::decode_in_place(output.deref_mut()).unwrap();
908
909 let x = crate::from_bytes::<RefStruct<'_>>(&output.deref_mut()[..sz]).unwrap();
910
911 assert_eq!(input, x);
912 }
913}