Enum support
Closed this issue · 2 comments
Hi! I started using your crate on embedded and really like it.
The only think I am missing is enum support, I use it to write structs for spi/i2c devices with often pack some modes settings into they registers.
Some examples:
#[bitfield(u8)]
pub struct PowerCtl {
#[bits(2)]
mesure_mode: u8,
autosleep: bool,
wakeup: bool,
#[bits(2)]
low_noise_mode: u8,
ext_clk: bool,
#[bits(1)]
_unused: u8,
}
#[repr(u8)]
pub enum PowerCtlMesureMode {
Standby = 0b00,
Measurement = 0b10,
}
#[repr(u8)]
pub enum PowerCtlLowNoiseMode {
Normal = 0b00,
Low = 0b01,
Ultralow = 0b10,
}
It would be nice if that could become this:
#[bitfield(u8)]
pub struct PowerCtl {
#[bits(2)]
mesure_mode: PowerCtlMesureMode,
autosleep: bool,
wakeup: bool,
#[bits(2)]
low_noise_mode: PowerCtlLowNoiseMode,
ext_clk: bool,
#[bits(1)]
_unused: u8,
}
And in this case when reading a enum value from the struct it should return Option<Enum>
so when the registers has a value with isn't allowed by the enum it returns None.
I would love to see that!
I was thinking about supporting any type that implements From/Into of the underlying bitfield type.
Unfortunately, this is not directly compatible with the raw integer types as they only implement TryFrom/TryInto (which might fail and possibly panic) or casting via as. This means I have to distinguish between ints and custom types and generate different code for them (similar to bools).
Currently I'm quite occupied. So it would take a few weeks before I'm able to implement this. But if you want, you can look into this and contribute it.