#[padding_struct]Expand description
Procedural macro to automatically add padding fields to a #[repr(C)] struct.
This macro generates two structs:
- A reference struct (prefixed and suffixed with
__) containing the original fields without padding. - A padded struct (using the original name) with
__padNpadding fields after each original field.
§Padding Calculation Rules
- For non-last fields: padding size = next field’s offset - current field’s offset - current field’s size.
- For the last field: padding size = struct total size - current field’s offset - current field’s size.
§Requirements
- The struct must have a
#[repr(C)]attribute. - The struct must have named fields.
§Examples
use padding_struct::padding_struct;
#[repr(C)]
#[padding_struct]
struct MyStruct {
a: u8,
b: u32,
}This generates code equivalent to:
use core::mem::offset_of;
#[repr(C)]
struct __MyStruct__ {
a: u8,
b: u32,
}
#[repr(C)]
struct MyStruct {
a: u8,
pub __pad1:
[u8; const { offset_of!(__MyStruct__, b) - offset_of!(__MyStruct__, a) - size_of::<u8>() }],
b: u32,
pub __pad2:
[u8; const { size_of::<__MyStruct__>() - offset_of!(__MyStruct__, b) - size_of::<u32>() }],
}