Search code examples
rustmemory-alignment

How can I align a struct to a specified byte boundary?


I need to align a struct to a 16 byte boundary in Rust. It seems possible to give hints about alignment through the repr attribute, but it doesn't support this exact use case.

A functional test of what I'm trying to achieve is a type Foo such that

assert_eq!(mem::align_of::<Foo>(), 16);

or alternatively, a struct Bar with a field baz such that

println!("{:p}", Bar::new().baz);

always prints a number divisible by 16.

Is this currently possible in Rust? Are there any work-arounds?


Solution

  • huon's answer is good, but it's out of date.

    As of Rust 1.25.0, you may now align a type to N bytes using the attribute #[repr(align(N))]. It is documented under the reference's Type Layout section. Note that the alignment must be a power of 2, you may not mix align and packed representations, and aligning a type may add extra padding to the type. Here's an example of how to use the feature:

    #[repr(align(64))]
    struct S(u8);
    
    fn main() {
        println!("size of S: {}", std::mem::size_of::<S>());
        println!("align of S: {}", std::mem::align_of::<S>());
    }