2 ms·
Structs already insert padding to give them alignment: struct One { foo: u8, } struct Two { bar: u16, } struct Three
by steveklabnik 10y ago
Structs already insert padding to give them alignment:
struct One {
foo: u8,
}
struct Two {
bar: u16,
}
struct Three {
foo: u8,
bar: u16,
}
struct Four {
foo: u16,
bar: u16,
}
fn main() {
assert_eq!(1, std::mem::size_of::<One>());
assert_eq!(2, std::mem::size_of::<Two>());
assert_eq!(4, std::mem::size_of::<Three>());
assert_eq!(4, std::mem::size_of::<Four>());
}
- alkonaut 10y agoWhat I needed to do was to place e.g. a N byte struct exactly on an M byte alignment (e.g. 11 byte struct on 32 byte alignment etc).
- steveklabnik 10y agoAh! Yeah, that's different, and as far as I know your way is the current right way to do it, but I'm not an expert on the subject.
- Thiez 10y agoWell given that Rust leaves struct layout undefined unless #[repr(C)] is specified, std::mem::size_of::<Three> is actually not guaranteed to be 4.
- steveklabnik 10y agoWhile this is true, it's a weird angle that's not itself super well defined. That is, the definition of repr(packed) implies that the alignment will always be there without it...