Skip to content

Instantly share code, notes, and snippets.

@jdaviderb
Created December 22, 2023 04:45
Show Gist options
  • Save jdaviderb/bbd71ebc264b36ab6dbb47b680c8fd41 to your computer and use it in GitHub Desktop.
Save jdaviderb/bbd71ebc264b36ab6dbb47b680c8fd41 to your computer and use it in GitHub Desktop.
Rust Cast Low level
pub fn cast_to_parts<T>(content: &T) -> &[u8] {
let ptr = content as *const T as *const u8;
let len = mem::size_of::<T>();
unsafe { std::slice::from_raw_parts(ptr, len) }
}
pub fn cast_to<T>(value: &[u8]) -> &T {
let ptr = value.as_ptr() as *const T;
unsafe { &*ptr }
}
pub fn cast_mut_to<T>(value: &mut [u8]) -> &mut T {
let ptr = value.as_mut_ptr() as *mut T;
unsafe { &mut *ptr }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment