How can I create a struct that needs to be both packed and aligned?

I'm modelling the FXSAVE area for the x86 / x86-64 CPUs, and I need to create a wrapping struct that is both packed and 64-byte aligned on the stack. How?

According to https://doc.rust-lang.org/reference/type-layout.html#the-align-representation it's not possible to have a packed struct have any alignment apart from 1.

Of course, I can cheat in various horrible ways:-

  • have the struct fields as just arrays of different lengths (yuck)
  • create an array of twice the size needed on the stack and then cast a pointer from an aligned offset with it.
  • anon mmap a 4Kb page

However, none of these particularly pleasant, and none of them protect any future code from knowing the alignment restrictions of said struct.

Wrapping the packed struct into a #[repr(C, align(N))] struct should work.

1 Like

@Riateche - thank you, that works and will be good enough for now. It's a shame that a completely artificial wrap is required but I can also use it to wrap unaligned accessors, too.