Skip to main content

postcard/ser/
mod.rs

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
22/// Serialize a `T` to the given slice, with the resulting slice containing
23/// data in a serialized then COBS encoded format. The terminating sentinel
24/// `0x00` byte is included in the output buffer.
25///
26/// When successful, this function returns the slice containing the
27/// serialized and encoded message.
28///
29/// ## Example
30///
31/// ```rust
32/// use postcard::to_slice_cobs;
33/// let mut buf = [0u8; 32];
34///
35/// let used = to_slice_cobs(&false, &mut buf).unwrap();
36/// assert_eq!(used, &[0x01, 0x01, 0x00]);
37///
38/// let used = to_slice_cobs("1", &mut buf).unwrap();
39/// assert_eq!(used, &[0x03, 0x01, b'1', 0x00]);
40///
41/// let used = to_slice_cobs("Hi!", &mut buf).unwrap();
42/// assert_eq!(used, &[0x05, 0x03, b'H', b'i', b'!', 0x00]);
43///
44/// let data: &[u8] = &[0x01u8, 0x00, 0x20, 0x30];
45/// let used = to_slice_cobs(data, &mut buf).unwrap();
46/// assert_eq!(used, &[0x03, 0x04, 0x01, 0x03, 0x20, 0x30, 0x00]);
47/// ```
48pub 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
58/// Serialize a `T` to the given slice, with the resulting slice containing
59/// data in a serialized format.
60///
61/// When successful, this function returns the slice containing the
62/// serialized message
63///
64/// ## Example
65///
66/// ```rust
67/// use postcard::to_slice;
68/// let mut buf = [0u8; 32];
69///
70/// let used = to_slice(&true, &mut buf).unwrap();
71/// assert_eq!(used, &[0x01]);
72///
73/// let used = to_slice("Hi!", &mut buf).unwrap();
74/// assert_eq!(used, &[0x03, b'H', b'i', b'!']);
75///
76/// // NOTE: postcard handles `&[u8]` and `&[u8; N]` differently.
77/// let data: &[u8] = &[0x01u8, 0x00, 0x20, 0x30];
78/// let used = to_slice(data, &mut buf).unwrap();
79/// assert_eq!(used, &[0x04, 0x01, 0x00, 0x20, 0x30]);
80///
81/// let data: &[u8; 4] = &[0x01u8, 0x00, 0x20, 0x30];
82/// let used = to_slice(data, &mut buf).unwrap();
83/// assert_eq!(used, &[0x01, 0x00, 0x20, 0x30]);
84/// ```
85pub 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/// Serialize a `T` to a `heapless::Vec<u8>`, with the `Vec` containing
93/// data in a serialized then COBS encoded format. The terminating sentinel
94/// `0x00` byte is included in the output `Vec`.
95///
96/// ## Example
97///
98/// ```rust
99/// use postcard::to_vec_cobs;
100/// use heapless::Vec;
101/// use core::ops::Deref;
102///
103/// let ser: Vec<u8, 32> = to_vec_cobs(&false).unwrap();
104/// assert_eq!(ser.deref(), &[0x01, 0x01, 0x00]);
105///
106/// let ser: Vec<u8, 32> = to_vec_cobs("Hi!").unwrap();
107/// assert_eq!(ser.deref(), &[0x05, 0x03, b'H', b'i', b'!', 0x00]);
108///
109/// // NOTE: postcard handles `&[u8]` and `&[u8; N]` differently.
110/// let data: &[u8] = &[0x01u8, 0x00, 0x20, 0x30];
111/// let ser: Vec<u8, 32> = to_vec_cobs(data).unwrap();
112/// assert_eq!(ser.deref(), &[0x03, 0x04, 0x01, 0x03, 0x20, 0x30, 0x00]);
113///
114/// let data: &[u8; 4] = &[0x01u8, 0x00, 0x20, 0x30];
115/// let ser: Vec<u8, 32> = to_vec_cobs(data).unwrap();
116/// assert_eq!(ser.deref(), &[0x02, 0x01, 0x03, 0x20, 0x30, 0x00]);
117/// ```
118///
119/// This function uses `heapless` v0.7, which is affected by [RUSTSEC-2026-0575] and
120/// will not be fixed. Prefer [`heapless_v0_9::to_vec_cobs`], enabled by the
121/// `heapless-v0_9` feature:
122///
123/// ```rust
124/// # #[cfg(feature = "heapless-v0_9")] {
125/// use postcard::heapless_v0_9::{heapless::Vec, to_vec_cobs};
126///
127/// let ser: Vec<u8, 32> = to_vec_cobs("Hi!").unwrap();
128/// assert_eq!(&ser[..], &[0x05, 0x03, b'H', b'i', b'!', 0x00]);
129/// # }
130/// ```
131///
132/// [RUSTSEC-2026-0575]: https://rustsec.org/advisories/RUSTSEC-2026-0575.html
133/// [`heapless_v0_9::to_vec_cobs`]: crate::heapless_v0_9::to_vec_cobs
134#[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/// Serialize a `T` to a `heapless::Vec<u8>`, with the `Vec` containing
144/// data in a serialized format.
145///
146/// ## Example
147///
148/// ```rust
149/// use postcard::to_vec;
150/// use heapless::Vec;
151/// use core::ops::Deref;
152///
153/// let ser: Vec<u8, 32> = to_vec(&true).unwrap();
154/// assert_eq!(ser.deref(), &[0x01]);
155///
156/// let ser: Vec<u8, 32> = to_vec("Hi!").unwrap();
157/// assert_eq!(ser.deref(), &[0x03, b'H', b'i', b'!']);
158///
159/// // NOTE: postcard handles `&[u8]` and `&[u8; N]` differently.
160/// let data: &[u8] = &[0x01u8, 0x00, 0x20, 0x30];
161/// let ser: Vec<u8, 32> = to_vec(data).unwrap();
162/// assert_eq!(ser.deref(), &[0x04, 0x01, 0x00, 0x20, 0x30]);
163///
164/// let data: &[u8; 4] = &[0x01u8, 0x00, 0x20, 0x30];
165/// let ser: Vec<u8, 32> = to_vec(data).unwrap();
166/// assert_eq!(ser.deref(), &[0x01, 0x00, 0x20, 0x30]);
167/// ```
168///
169/// This function uses `heapless` v0.7, which is affected by [RUSTSEC-2026-0575] and
170/// will not be fixed. Prefer [`heapless_v0_9::to_vec`], enabled by the `heapless-v0_9` feature:
171///
172/// ```rust
173/// # #[cfg(feature = "heapless-v0_9")] {
174/// use postcard::heapless_v0_9::{heapless::Vec, to_vec};
175///
176/// let ser: Vec<u8, 32> = to_vec("Hi!").unwrap();
177/// assert_eq!(&ser[..], &[0x03, b'H', b'i', b'!']);
178/// # }
179/// ```
180///
181/// [RUSTSEC-2026-0575]: https://rustsec.org/advisories/RUSTSEC-2026-0575.html
182/// [`heapless_v0_9::to_vec`]: crate::heapless_v0_9::to_vec
183#[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/// Serialize a `T` to a `std::vec::Vec<u8>`.
193///
194/// ## Example
195///
196/// ```rust
197/// use postcard::to_stdvec;
198///
199/// let ser: Vec<u8> = to_stdvec(&true).unwrap();
200/// assert_eq!(ser.as_slice(), &[0x01]);
201///
202/// let ser: Vec<u8> = to_stdvec("Hi!").unwrap();
203/// assert_eq!(ser.as_slice(), &[0x03, b'H', b'i', b'!']);
204/// ```
205#[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/// Serialize and COBS encode a `T` to a `std::vec::Vec<u8>`.
216///
217/// The terminating sentinel `0x00` byte is included in the output.
218///
219/// ## Example
220///
221/// ```rust
222/// use postcard::to_stdvec_cobs;
223///
224/// let ser: Vec<u8> = to_stdvec_cobs(&true).unwrap();
225/// assert_eq!(ser.as_slice(), &[0x02, 0x01, 0x00]);
226///
227/// let ser: Vec<u8> = to_stdvec_cobs("Hi!").unwrap();
228/// assert_eq!(ser.as_slice(), &[0x05, 0x03, b'H', b'i', b'!', 0x00]);
229/// ```
230#[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/// Serialize a `T` to an `alloc::vec::Vec<u8>`.
241///
242/// ## Example
243///
244/// ```rust
245/// use postcard::to_allocvec;
246///
247/// let ser: Vec<u8> = to_allocvec(&true).unwrap();
248/// assert_eq!(ser.as_slice(), &[0x01]);
249///
250/// let ser: Vec<u8> = to_allocvec("Hi!").unwrap();
251/// assert_eq!(ser.as_slice(), &[0x03, b'H', b'i', b'!']);
252/// ```
253#[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/// Serialize and COBS encode a `T` to an `alloc::vec::Vec<u8>`.
263///
264/// The terminating sentinel `0x00` byte is included in the output.
265///
266/// ## Example
267///
268/// ```rust
269/// use postcard::to_allocvec_cobs;
270///
271/// let ser: Vec<u8> = to_allocvec_cobs(&true).unwrap();
272/// assert_eq!(ser.as_slice(), &[0x02, 0x01, 0x00]);
273///
274/// let ser: Vec<u8> = to_allocvec_cobs("Hi!").unwrap();
275/// assert_eq!(ser.as_slice(), &[0x05, 0x03, b'H', b'i', b'!', 0x00]);
276/// ```
277#[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
289/// Serialize a `T` to a [`core::iter::Extend`],
290/// ## Example
291///
292/// ```rust
293/// use postcard::to_extend;
294/// let mut vec = Vec::new();
295///
296/// let ser = to_extend(&true, vec).unwrap();
297/// let vec = to_extend("Hi!", ser).unwrap();
298/// assert_eq!(&vec[0..5], &[0x01, 0x03, b'H', b'i', b'!']);
299/// ```
300pub 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/// Serialize a `T` to an [`embedded_io Write`](crate::eio::Write),
309/// ## Example
310///
311/// ```rust
312/// use postcard::to_eio;
313/// let mut buf: [u8; 32] = [0; 32];
314/// let mut writer: &mut [u8] = &mut buf;
315///
316/// let ser = to_eio(&true, &mut writer).unwrap();
317/// to_eio("Hi!", ser).unwrap();
318/// assert_eq!(&buf[0..5], &[0x01, 0x03, b'H', b'i', b'!']);
319/// ```
320#[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/// Serialize a `T` to a [`std::io::Write`],
330/// ## Example
331///
332/// ```rust
333/// use postcard::to_io;
334/// let mut buf: [u8; 32] = [0; 32];
335/// let mut writer: &mut [u8] = &mut buf;
336///
337/// let ser = to_io(&true, &mut writer).unwrap();
338/// to_io("Hi!", ser).unwrap();
339/// assert_eq!(&buf[0..5], &[0x01, 0x03, b'H', b'i', b'!']);
340/// ```
341#[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/// Conveniently serialize a `T` to the given slice, with the resulting slice containing
351/// data followed by a 32-bit CRC. The CRC bytes are included in the output buffer.
352///
353/// When successful, this function returns the slice containing the
354/// serialized and encoded message.
355///
356/// ## Example
357///
358/// ```rust
359/// use crc::{Crc, CRC_32_ISCSI};
360///
361/// let mut buf = [0; 9];
362///
363/// let data: &[u8] = &[0x01, 0x00, 0x20, 0x30];
364/// let crc = Crc::<u32>::new(&CRC_32_ISCSI);
365/// let used = postcard::to_slice_crc32(data, &mut buf, crc.digest()).unwrap();
366/// assert_eq!(used, &[0x04, 0x01, 0x00, 0x20, 0x30, 0x8E, 0xC8, 0x1A, 0x37]);
367/// ```
368///
369/// See the `ser_flavors::crc` module for the complete set of functions.
370#[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/// Conveniently serialize a `T` to a `heapless::Vec<u8>`, with the `Vec` containing
385/// data followed by a 32-bit  CRC. The CRC bytes are included in the output `Vec`.
386///
387/// ## Example
388///
389/// ```rust
390/// use crc::{Crc, CRC_32_ISCSI};
391/// use heapless::Vec;
392/// use core::ops::Deref;
393///
394/// // NOTE: postcard handles `&[u8]` and `&[u8; N]` differently.
395/// let data: &[u8] = &[0x01u8, 0x00, 0x20, 0x30];
396/// let crc = Crc::<u32>::new(&CRC_32_ISCSI);
397/// let ser: Vec<u8, 32> = postcard::to_vec_crc32(data, crc.digest()).unwrap();
398/// assert_eq!(ser.deref(), &[0x04, 0x01, 0x00, 0x20, 0x30, 0x8E, 0xC8, 0x1A, 0x37]);
399///
400/// let data: &[u8; 4] = &[0x01u8, 0x00, 0x20, 0x30];
401/// let ser: Vec<u8, 32> = postcard::to_vec_crc32(data, crc.digest()).unwrap();
402/// assert_eq!(ser.deref(), &[0x01, 0x00, 0x20, 0x30, 0xCC, 0x4B, 0x4A, 0xDA]);
403/// ```
404///
405/// See the `ser_flavors::crc` module for the complete set of functions.
406///
407/// This function uses `heapless` v0.7, which is affected by [RUSTSEC-2026-0575] and
408/// will not be fixed. Prefer [`heapless_v0_9::to_vec_crc32`], enabled by the
409/// `heapless-v0_9` feature:
410///
411/// ```rust
412/// # #[cfg(all(feature = "heapless-v0_9", feature = "use-crc"))] {
413/// use crc::{Crc, CRC_32_ISCSI};
414/// use postcard::heapless_v0_9::{heapless::Vec, to_vec_crc32};
415///
416/// let data: &[u8] = &[0x01u8, 0x00, 0x20, 0x30];
417/// let crc = Crc::<u32>::new(&CRC_32_ISCSI);
418/// let ser: Vec<u8, 32> = to_vec_crc32(data, crc.digest()).unwrap();
419/// assert_eq!(&ser[..], &[0x04, 0x01, 0x00, 0x20, 0x30, 0x8E, 0xC8, 0x1A, 0x37]);
420/// # }
421/// ```
422///
423/// [RUSTSEC-2026-0575]: https://rustsec.org/advisories/RUSTSEC-2026-0575.html
424/// [`heapless_v0_9::to_vec_crc32`]: crate::heapless_v0_9::to_vec_crc32
425#[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/// Conveniently serialize a `T` to a `std::vec::Vec<u8>`, with the `Vec` containing
439/// data followed by a 32-bit  CRC. The CRC bytes are included in the output `Vec`.
440///
441/// ## Example
442///
443/// ```rust
444/// use crc::{Crc, CRC_32_ISCSI};
445/// use core::ops::Deref;
446///
447/// // NOTE: postcard handles `&[u8]` and `&[u8; N]` differently.
448/// let data: &[u8] = &[0x01u8, 0x00, 0x20, 0x30];
449/// let crc = Crc::<u32>::new(&CRC_32_ISCSI);
450/// let ser: Vec<u8> = postcard::to_stdvec_crc32(data, crc.digest()).unwrap();
451/// assert_eq!(ser.deref(), &[0x04, 0x01, 0x00, 0x20, 0x30, 0x8E, 0xC8, 0x1A, 0x37]);
452///
453/// let data: &[u8; 4] = &[0x01u8, 0x00, 0x20, 0x30];
454/// let ser: Vec<u8> = postcard::to_stdvec_crc32(data, crc.digest()).unwrap();
455/// assert_eq!(ser.deref(), &[0x01, 0x00, 0x20, 0x30, 0xCC, 0x4B, 0x4A, 0xDA]);
456/// ```
457///
458/// See the `ser_flavors::crc` module for the complete set of functions.
459#[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/// Conveniently serialize a `T` to an `alloc::vec::Vec<u8>`, with the `Vec` containing
470/// data followed by a 32-bit  CRC. The CRC bytes are included in the output `Vec`.
471///
472/// ## Example
473///
474/// ```rust
475/// use crc::{Crc, CRC_32_ISCSI};
476/// use core::ops::Deref;
477///
478/// // NOTE: postcard handles `&[u8]` and `&[u8; N]` differently.
479/// let data: &[u8] = &[0x01u8, 0x00, 0x20, 0x30];
480/// let crc = Crc::<u32>::new(&CRC_32_ISCSI);
481/// let ser: Vec<u8> = postcard::to_allocvec_crc32(data, crc.digest()).unwrap();
482/// assert_eq!(ser.deref(), &[0x04, 0x01, 0x00, 0x20, 0x30, 0x8E, 0xC8, 0x1A, 0x37]);
483///
484/// let data: &[u8; 4] = &[0x01u8, 0x00, 0x20, 0x30];
485/// let ser: Vec<u8> = postcard::to_allocvec_crc32(data, crc.digest()).unwrap();
486/// assert_eq!(ser.deref(), &[0x01, 0x00, 0x20, 0x30, 0xCC, 0x4B, 0x4A, 0xDA]);
487/// ```
488///
489/// See the `ser_flavors::crc` module for the complete set of functions.
490#[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
500/// `serialize_with_flavor()` has three generic parameters, `T, F, O`.
501///
502/// * `T`: This is the type that is being serialized
503/// * `S`: This is the Storage that is used during serialization
504/// * `O`: This is the resulting storage type that is returned containing the serialized data
505///
506/// For more information about how Flavors work, please see the
507/// [`flavors` module documentation](./flavors/index.html).
508///
509/// ```rust
510/// use postcard::{
511///     serialize_with_flavor,
512///     ser_flavors::{Cobs, Slice},
513/// };
514///
515/// let mut buf = [0u8; 32];
516///
517/// let data: &[u8] = &[0x01, 0x00, 0x20, 0x30];
518/// let buffer = &mut [0u8; 32];
519/// let res = serialize_with_flavor::<[u8], Cobs<Slice>, &mut [u8]>(
520///     data,
521///     Cobs::try_new(Slice::new(buffer)).unwrap(),
522/// ).unwrap();
523///
524/// assert_eq!(res, &[0x03, 0x04, 0x01, 0x03, 0x20, 0x30, 0x00]);
525/// ```
526pub 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
539/// Compute the size of the postcard serialization of `T`.
540pub 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        //
712        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}