Robbepop / modular-bitfield

Macro to generate bitfields for structs that allow for modular use of enums.
Apache License 2.0
155 stars 40 forks source link

Add #[repr = uN] annotation support for #[bitfield] #33

Closed Robbepop closed 3 years ago

Robbepop commented 3 years ago

When given a #[bitfield] struct with a #[repr = uN], e.g. #[repr = u32] attribute the #[bitfield] macro shall make sure that the generated bitfield struct respects the bitwidth of the uN, e.g. 8 bits for u8, 16 bits for u16, etc.

Also it shall generate From<uN> and From<BitfieldStruct> for uN implementations. Obviously having #[repr(uN)] also changes the underlying representation of the bitfield type to uN.

Example

#[bitfield]
#[repr(u32)]
struct TtResp {
    mregion: u8,
    sregion: u8, 
    mrvalid: bool,
    srvalid: bool,
    r: bool,
    rw: bool,
    nsr: bool,
    nsrw: bool,
    s: bool,
    irvalid: bool,
    iregion: u8,
}

This allows the user to only conditionally have the repr(u32) effects taken place using cfg_attr:

#[bitfield]
#[cfg_attr(test, repr(u32))]
struct TtResp {
    mregion: u8,
    sregion: u8, 
    mrvalid: bool,
    srvalid: bool,
    r: bool,
    rw: bool,
    nsr: bool,
    nsrw: bool,
    s: bool,
    irvalid: bool,
    iregion: u8,
}