pub unsafe fn cast<T>(x: &T) -> &[MaybeUninit<u8>]where
T: ?Sized,
Expand description
Reinterprets as a byte slice.
Returns &[
rather than MaybeUninit
<u8>]&[u8]
as it is undefined behavior to read padding bytes.
If the type does not contain any padding, it is safe to cast it to &[u8]
yourself.
§Safety
The type must not have interior mutability.
In other words, the type cannot contain Cell
, UnsafeCell
, and the like.
§Why?
Aliasing. See here:
let cell = Cell::new(1u8);
let raw = unsafe { all_is_bytes::cast(&cell) };
cell.set(0u8); // Erm... well that just happened...
assert_eq!(cell.get(), unsafe { raw[0].assume_init() }); // Uh oh!
This causes undefined behavior.