Created
December 22, 2023 04:45
-
-
Save jdaviderb/bbd71ebc264b36ab6dbb47b680c8fd41 to your computer and use it in GitHub Desktop.
Rust Cast Low level
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
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