danlehmann / bitfield

Rust crate for bitfields and bit-enums
MIT License
46 stars 9 forks source link

Retire `new()` and introduce `DEFAULT` const instead #21

Closed danlehmann closed 8 months ago

danlehmann commented 1 year ago

One of the thing that everyone has been confused about is that default: 0x123 creates a new() function.

The problem is that new() looks pretty harmless and like the preferred way to create a bitfield. However, when using bitfields with hardware, the correct way is to read from hardware, modify and write-back. So it's pretty easy to write code that accidentally overwrites unrelated bits.

Example: Let's assume we have a bitfield like this:

#[bitfield(u32, default: 0x2)]
pub struct MyBitfield {
    #[bit(0, rw)]
    bit0: bool,

    #[bit(1, rw)]
    bit1: bool,
}

It is very easy to create a new bitfield like this: let foo = MyBitfield::new()

This will set the bits of foo to the default value specified in the definition of MyBitfield, which is 0x2.

A much more obvious syntax would be this however: let foo = MyBitfield::DEFAULT;

Of course, we can't just remove the current syntax as that would break clients. But we can make the switch gradually:

danlehmann commented 1 year ago

Another option would be to emit a warning on "default: 0x2" but instead ask to use a newer syntax, which then generates the new const DEFAULT?

danlehmann commented 1 year ago

I think the most sensible thing to do for now is to support both new() and DEFAULT, but deprecate new().

danlehmann commented 8 months ago

This was merged a while ago