Created
August 13, 2022 23:17
-
-
Save jdaviderb/82d4ace4513c0d9dba588f5c3afa034b to your computer and use it in GitHub Desktop.
rust zero copy serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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