Function rkyv::util::to_bytes

source ·
pub fn to_bytes<T, const N: usize>(
    value: &T
) -> Result<AlignedVec, <AllocSerializer<N> as Fallible>::Error>where
    T: Serialize<AllocSerializer<N>>,
Expand description

Serializes the given value and returns the resulting bytes.

The const generic parameter N specifies the number of bytes to pre-allocate as scratch space. Choosing a good default value for your data can be difficult without any data, so consider using ScratchTracker to determine how much scratch space is typically used.

This function is only available with the alloc feature because it uses a general-purpose serializer. In no-alloc and high-performance environments, the serializer should be customized for the specific situation.

Examples

let value = vec![1, 2, 3, 4];

let bytes = rkyv::to_bytes::<_, 1024>(&value).expect("failed to serialize vec");
// SAFETY:
// - The byte slice represents an archived object
// - The root of the object is stored at the end of the slice
let deserialized = unsafe {
    rkyv::from_bytes_unchecked::<Vec<i32>>(&bytes)
        .expect("failed to deserialize vec")
};

assert_eq!(deserialized, value);