Overview
repr_fits provides a small attribute macro for checking that enum discriminants fit into a fixed number of bits.
This is useful when an enum is stored inside a compact protocol field, packed integer id, file format, or wire representation where Rust's normal #[repr(u8)] is too wide. Rust does not have #[repr(u5)], so repr_fits lets you keep a normal enum definition while adding compile-time bit-width checks.
Example
use repr_fits;
The enum remains a normal Rust enum. The macro only appends compile-time assertions for each variant:
assert!;
assert!;
assert!;
If a discriminant does not fit, compilation fails with a message naming the offending variant:
use repr_fits;
The generated assertion message is shaped like:
PacketKind::Control discriminant does not fit in 2 bits
Why not just use #[repr(u8)]?
#[repr(u8)] guarantees that discriminants fit in 8 bits. It does not help when the packed representation reserves fewer bits, such as:
5 bits region code
2 bits packet kind
25 bits sequence id
repr_fits documents and enforces that smaller bit budget at compile time.
Limitations
- Supports enum items only.
- Supports unit variants only.
- The macro checks discriminants by casting variants in a generated
constassertion block, so the enum must be castable to an integer. In practice, use a primitive representation such as#[repr(u8)].
License
MIT