Skip to main content

assert_no_padding

Attribute Macro assert_no_padding 

Source
#[assert_no_padding]
Expand description

Attribute macro that causes a compile-time error if the struct has any padding bytes.

Padding is detected by asserting that size_of::<Struct>() equals the sum of size_of::<FieldType>() for every field. If the compiler inserts padding (alignment gaps or trailing bytes), the sizes will differ and the assertion fails.

§Example

#[padlock::assert_no_padding]
#[repr(C)]
struct Packed {
    a: u64,
    b: u32,
    c: u32,
}
// ✓ compiles: 8 + 4 + 4 = 16 = size_of::<Packed>()

#[padlock::assert_no_padding]
struct Padded {
    a: u8,
    b: u64,  // ← 7 bytes of padding inserted before this
}
// ✗ compile error: 1 + 8 = 9 ≠ 16 = size_of::<Padded>()

§Limitations

  • Works for named-field structs only (tuple structs and unit structs are accepted without checking).
  • Generic structs are accepted but the assertion uses concrete field type tokens; monomorphisation errors may give confusing messages.
  • The check operates on size_of values, which means repr(Rust) structs where the compiler reorders fields but eliminates padding will still pass.