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

.with_field(value) syntax #17

Closed lkolbly closed 3 years ago

lkolbly commented 3 years ago

Currently, we expose set_XYZ methods that return void, so if you want to populate a bitfield you have to have a mutable variable:

    let mut example = Example::new();
    example.set_a(true);
    example.set_b(0b0001_1111_1111_u16);
    example.set_c(42_u16);
    example.set_d(DeliveryMode::Startup);
    example.set_e(1);

What if there were a with_XYZ method which returned the bitfield object itself:

let example = Example::new()
    .with_a(true)
    .with_b(0b0001_1111_1111_u16)
    .with_c(42_u16)
    .with_d(DeliveryMode::Startup)
    .with_e(1);

?

I'm thinking a signature like:

fn set_a(self, value: bool) -> Self;

And, I guess, a with_a_checked which returns Result<Self>:

let example = Example::new()
    .with_a_checked(true)?
    .with_b_checked(...)?;

I think this would fit better in a closure-based modification API (similar to the API svd2rust provides):

my_register.modify(|value| { value.with_a(!value.a()) });

vs.

my_register.modify(|mut value| {
    value.set_a(!value.a());
    value
});

I can throw together a PR, but wanted to get thoughts first.

Robbepop commented 3 years ago

sounds like a decent addition to me!