I created `#[assert_size(usize)]` and #[assert_size_fits(usize)] macros for compile-time check of struct sizes

See my pakr-assert-size crate. I provides two attributes:

  • #[assert_size(USIZE)] for the exact size match
  • #[assert_size_fits(USIZE)] for not larger than match

Sample usage:

this succeeds:

use pakr_assert_size::*;

#[repr(C, packed)]
#[assert_size(16)]
struct A {
    field1: u64,
    field2: u64,
}

#[assert_size(24)]
#[repr(C, packed)]
struct B {
    field1: u64,
    field2: u64,
    field3: u64,
}

// Exact match
#[repr(C, packed)]
#[assert_size_fits(16)]
struct A {
    field1: u64,
    field2: u64,
}

// Fits in match
#[assert_size_fits(32)]
#[repr(C, packed)]
struct B {
    field1: u64,
    field2: u64,
    field3: u64,
}

this fails at compile-time

use pakr_assert_size::*;

#[assert_size(32)]
#[repr(C, packed)]
struct C {
    field1: u64,
    field2: u64,
    field3: u64,
}

#[assert_size_fits(16)]
#[repr(C, packed)]
struct C {
    field1: u64,
    field2: u64,
    field3: u64,
}

I would be extremely grateful for any feedback, especially on my use of quote!{} which I'm not sure was used as intended (The fact it works does not imply it is done correctly).

5 Likes

Your quote usage looks like exactly what I would have written

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.