| Crates.io | assert-size-derive |
| lib.rs | assert-size-derive |
| version | 0.1.0 |
| created_at | 2026-01-02 05:15:42.012577+00 |
| updated_at | 2026-01-02 05:15:42.012577+00 |
| description | Compile time type size assertion attribute macro |
| homepage | |
| repository | https://github.com/dolphindalt/assert-size-derive |
| max_upload_size | |
| id | 2018003 |
| size | 11,649 |
A Rust procedural macro for compile-time type size assertions.
assert-size-derive provides a simple attribute macro that verifies types have the expected size in bytes at compile time. If the actual size doesn't match the expected size, compilation fails with a clear error message.
Add this to your Cargo.toml:
[dependencies]
assert-size-derive = "0.1.0"
Apply the #[assert_size(N)] attribute to any type definition, where N is the expected size in bytes:
use assert_size_derive::assert_size;
#[assert_size(2)]
struct MyData {
foo: u8,
bar: u8,
}
#[assert_size(16)]
enum MyEnum {
Variant1(u64),
Variant2(u32),
}
#[assert_size(8)]
union MyUnion {
unsigned: u64,
signed: i64,
}
If the size doesn't match, you'll get a compile-time error:
// This will fail to compile!
#[assert_size(1)]
struct TooLarge {
a: u8,
b: u8, // Actual size is 2 bytes
}
#[repr(C)], #[repr(packed)], etc.no_std compatible - works in embedded and bare-metal environmentsrepr attributes#[assert_size(15)]
#[repr(packed)]
struct PackedData {
data: [u8; 11],
ident: u32,
}
#[assert_size(1)]
#[repr(u8)]
enum SmallEnum {
A,
B,
C,
}
#[assert_size(0)]
struct Marker;
#[assert_size(0)]
struct EmptyStruct {}
#[assert_size(8)]
struct Wrapper(u64);
The macro generates a compile-time assertion using core::mem::size_of and const evaluation:
const _: () = assert!(EXPECTED_SIZE == ::core::mem::size_of::<YourType>());
The type definition itself is preserved unchanged, so there's no impact on the generated code. Using core ensures compatibility with both std and no_std environments.
Licensed under the MIT License.
Contributions are welcome! Please feel free to submit a Pull Request.