Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I over-align a variable in Rust?

Tags:

pointers

rust

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)

like image 773
Bert Peters Avatar asked Jul 13 '26 08:07

Bert Peters


1 Answers

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]);
like image 119
Kornel Avatar answered Jul 16 '26 15:07

Kornel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!