Skip to main content

to_bytes

Function to_bytes 

Source
pub fn to_bytes<T: Serialize + ?Sized>(
    value: &T,
) -> Result<Box<[u8], AlignedAlloc<T>>, SerializeError>
Expand description

Serialize a value to bytes.

Returns the serialized bytes in a [Box<[u8]>].

ยงExample

#![feature(ptr_alignment_type)]

use core::fmt::Debug;

use nibblecode::{Serialize, access, to_bytes};

#[derive(Serialize, Debug)]
#[nibblecode(compare(PartialEq), derive(Debug))]
struct Example {
	name: String,
	value: i32,
}

let value = Example {
	name: "pi".to_string(),
	value: 31415926,
};

let bytes = to_bytes(&value).unwrap();
let deserialized = access::<Example>(&bytes).unwrap();

assert_eq!(*deserialized, value);