Guarantee alignment of struct field

I'm writing an object allocator (which knows statically what type, T, it is allocating), and I'm adding support for custom alignment - that is, a runtime-specified alignment that is greater than or equal to core::mem::align_of::<T>().

In order to store metadata about allocated objects, I have a container type, Object<T>, which has the allocated T as one of its fields:

struct Object<T> {
    ... // metadata stuff
    obj: T,

Before I supported custom alignment, laying these out in memory was easy - the compiler guarantees that aligning instances of Object<T> according to core::mem::align_of::<Object<T>>() is sufficient to guarantee that the obj field is aligned according to core::mem::align_of::<T>().

However, I'm not sure how to guarantee custom alignments. I ensure that the custom alignments cannot be larger than the size of T, so I'm pretty sure that the guarantee that objects can be laid out back-to-back in an array is still maintained. However, I'm not sure what starting address I should guarantee for my array of Object<T>s in order to guarantee the custom alignment for the obj fields inside them.


According to this StackOverflow answer, repr(C) should guarantee that the fields are laid out in source code order, which means that if I place obj first, I should be able to muck with the alignment all I want. Is it actually true that repr(C) guarantees this?

Yes, repr(C) guarantees source ordering.

Cool, thanks!