Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 786
Johannes Hoff Avatar asked Sep 06 '15 20:09

Johannes Hoff


1 Answers

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>());
}
like image 52
Cornstalks Avatar answered Sep 29 '22 07:09

Cornstalks