Writing default values of fields#105
Writing default values of fields#105SebastianHambura wants to merge 3 commits intodanlehmann:mainfrom
Conversation
Creating an Implementation module, to keep the sett function private and hidden if they aren't wanted.
…ssion. Allows for bool (true/false) and enum to be passed as default for fields
|
Hey, thanks for your contribution. First of all, this does solve a real usecase - which is that sometimes it is quite annoying to have to calculate the default value yourself as that's exactly the type of thing this library is supposed to solve. I have however three fundamental concerns.
pub struct WithDefaultFieldValues {
#[bits(0..=2, rw)] // <- decimal ok
val3: u3 = 4,
//#[bits(2..=16, rw, default = 0xFFFF)] //<- Will raise an error
#[bits(3..=16, rw)] // Accepts 0x and 0h (as base16 indicator)
val2: u14 = 0xBEF,
#[bits(17..=23, rw)] // Accepts 0d (as base10 indicator)
val1: u7 = 0xd42,
#[bits(24..=31, rw)] // Can parse negative values
val0: i8 = -1,
}
#[bitfield(u32)]
pub struct RiscVExtensions {
// .
}
impl RiscVExtensions {
const IMA: Self = Self::ZERO.with_m(true).with_a(true);
const IMAC: Self = Self::IMA.with_c(true);
}While this is some more code, it allows having multiple defaults with proper names. That really helps with the intention of the code. |
|
Hi, thanks for your feedback on this ! If I remember correctly, I started with your proposed solution of const + builder pattern, but it's not possible to give a read-only field a non-0 default value without having to make the math to write down the full default value of the register. How do you currently handle theses cases ? About your comments:
|
I wanted to be able to define default values at the field level, and not only at the struct level, so I started working on this feature.
Is this something that you/the community would find interesting ? If yes, I can try to continue working on it to make it more polished, if not I'll just keep it as an internal tool for me.
Currently, what this does is if there is a default for a field, it creates a
pub const fieldname_DEFAULT, and then if there isdefault = use_field_defaultsat the struct level, it creates apub const DEFAULTS_FROM_FIELDS = Self::ZERO.with_field1(field1_DEFAULT).with_field2(field2_DEFAULT)etc...To make that work, I always generate the setter functions inside a module (with
pubif it's a write field), so that internally we can always callwith_fieldfunction.I think if the field_overlaps, the behaviour is undefined, and I haven't checked how it behaves with enums and arrays.
It's my first time working on a macro library, so any feedback is welcome :)