Skip to content

Instantly share code, notes, and snippets.

@mosmeh
Created May 20, 2020 14:13
Show Gist options
  • Save mosmeh/dccc8afa07d492ca080dbbb66b2e6e3d to your computer and use it in GitHub Desktop.
Save mosmeh/dccc8afa07d492ca080dbbb66b2e6e3d to your computer and use it in GitHub Desktop.
unsafe fn slice_from_bytes<T>(bytes: &[u8]) -> &[T] {
assert_eq!(0, std::mem::size_of::<T>() % std::mem::size_of::<u8>());
assert_eq!(0, bytes.len() % std::mem::size_of::<T>());
let ratio = std::mem::size_of::<T>() / std::mem::size_of::<u8>();
let ptr = bytes.as_ptr() as *const T;
let length = bytes.len() / ratio;
std::slice::from_raw_parts(ptr, length)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment