How can I align a structure with a given byte boundary?

I need to align the structure with a 16 byte border in Rust. It seems possible to give alignment hints, a completely repr attribute , but it does not support this particular use case.

The 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 baz field such that

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

always prints a number divisible by 16.

Is this possible in Rust? Are there any problems?

+5
source share
1 answer

There is currently no way to specify alignment, but it is definitely desirable and useful. It is covered by issue # 33626 and its RFC Problem .

The current work to force alignment of some Foo structure should be as large as alignment of some type T to include a field of type [T; 0] [T; 0] , the size of which is zero, and therefore differently affect the behavior of the structure, for example, struct Foo { data: A, more_data: B, _align: [T; 0] } struct Foo { data: A, more_data: B, _align: [T; 0] } .

At night, this can be combined with SIMD types to get a certain high alignment, because they have an alignment equal to their size (well, the next power of two), for example

 #[repr(simd)] struct SixteenBytes(u64, u64); struct Foo { data: A, more_data: B, _align: [SixteenBytes; 0] } 
+10
source

All Articles