Function postcard::to_slice

source ·
pub fn to_slice<'a, 'b, T>(
    value: &'b T,
    buf: &'a mut [u8],
) -> Result<&'a mut [u8]>
where T: Serialize + ?Sized,
Expand description

Serialize a T to the given slice, with the resulting slice containing data in a serialized format.

When successful, this function returns the slice containing the serialized message

§Example

use postcard::to_slice;
let mut buf = [0u8; 32];

let used = to_slice(&true, &mut buf).unwrap();
assert_eq!(used, &[0x01]);

let used = to_slice("Hi!", &mut buf).unwrap();
assert_eq!(used, &[0x03, b'H', b'i', b'!']);

// NOTE: postcard handles `&[u8]` and `&[u8; N]` differently.
let data: &[u8] = &[0x01u8, 0x00, 0x20, 0x30];
let used = to_slice(data, &mut buf).unwrap();
assert_eq!(used, &[0x04, 0x01, 0x00, 0x20, 0x30]);

let data: &[u8; 4] = &[0x01u8, 0x00, 0x20, 0x30];
let used = to_slice(data, &mut buf).unwrap();
assert_eq!(used, &[0x01, 0x00, 0x20, 0x30]);