Skip to main content

Crate compact_option_proc_macro

Crate compact_option_proc_macro 

Source
Expand description

Attribute macro #[compact_option(repr(R = …, sentinel = …))] for emitting CompactRepr for enums and structs.

Used with CompactOption for niche-packing optional storage: NONE/Some(T) encoded in exactly as much memory as raw R, by reserving one of R’s spare bit patterns as the sentinel. Primarily #[repr(u8)] enums with fewer than 256 variants.

§What this macro does (and does not)

Does: parses R and sentinel, re-emits your item, and appends unsafe impl const CompactRepr<R>. For structs it also emits const size_of / align_of checks against R so layout mismatches fail in rustc const-eval (not token comparison).

Does not: read #[repr(...)], compute enum discriminants, compare sentinel to discriminants, or validate repr(transparent) / field count. Those invariants are the implementer’s responsibility per the CompactRepr safety contract; use tests and Miri.

A trailing , verify_discriminants = … after repr(...) is accepted for compatibility and ignored.

§Examples

§repr(u8) enum

use compact_option_proc_macro::compact_option;

#[compact_option(repr(R = u8, sentinel = 0xFF))]
#[repr(u8)]
#[derive(Clone, Copy)]
pub enum Letter {
    A = 0,
    B = 1,
}

§repr(transparent) newtype

use compact_option_proc_macro::compact_option;

#[compact_option(repr(R = u8, sentinel = 0xFE))]
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct ByteSlot(pub u8);

§Safety

This macro only emits unsafe impl const CompactRepr plus struct layout asserts. It does not prove transmute soundness. Use Miri and the CompactRepr documentation.

Attribute Macros§

compact_option
#[compact_option(repr(R = <type>, sentinel = <expr>))] on an enum or struct.