In my code, I have a type that is aligned to 1 byte, and a function that requires a type that is aligned to 8 bytes. The following hypothetical code shows this usage:
fn use_bar(bar: &mut [u64; 25]) {
unimplemented!()
}
fn main() {
let mut foo: [u8; 200] = get_foo();
unsafe {
// Option 1
use_bar(mem::transmute::<&mut [u8; 200], &mut [u64; 25]>::(&mut foo));
// Option 2
use_bar(&mut *(&mut foo as *mut [u8; 200] as *mut [u64; 25]));
}
}
Unfortunately, this doesn't necessarily work. If you ask clippy about the first option, it will tell you that transmuting references is a bad thing to do. Option 2 may work, however, it will then tell you that the alignment requirements for [u64; 25] are more strict (8 byte alignment) than for [u8; 200] (1 byte alignment) so this may cause undefined behaviour.
Since I don't control the type returned by get_foo(), is there any way I can force foo to be 8 byte aligned? (other than wrapping it in a struct that is properly aligned)
Use align_to to get an aligned slice.
To get data aligned in the first place, you can use a wrapper with #[repr(align(x))]:
#[repr(align(8))]
struct Wrapper([u8; 200]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With