Skip to content

Instantly share code, notes, and snippets.

@jdaviderb
Created August 13, 2022 23:17
Show Gist options
  • Save jdaviderb/82d4ace4513c0d9dba588f5c3afa034b to your computer and use it in GitHub Desktop.
Save jdaviderb/82d4ace4513c0d9dba588f5c3afa034b to your computer and use it in GitHub Desktop.
rust zero copy serialization
fn serialize(value: &[i32]) -> &[u8] {
let len = value.len() * 4;
unsafe { std::slice::from_raw_parts(value.as_ptr().cast(), len) }
}
fn deserialize(bytes: &[u8]) -> Vec<i32> {
assert!(bytes.len() % 4 == 0);
let mut vec = Vec::<i32>::with_capacity(bytes.len() / 4);
unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), vec.as_mut_ptr().cast(), bytes.len());
vec.set_len(bytes.len() / 4);
}
vec
}
fn main() {
let vec = vec![15, 11, -2, 300];
println!("vec = {vec:?}");
let bytes = serialize(&vec);
println!("bytes = {bytes:?}");
let copied_bytes = Vec::from(bytes);
let restored = deserialize(&copied_bytes);
println!("restored = {restored:?}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment