dzamlo / rust-bitfield

This crate provides macros to generate bitfield-like struct.
Apache License 2.0
157 stars 19 forks source link

Generate masks for the fields #38

Closed sosthene-nitrokey closed 8 months ago

sosthene-nitrokey commented 8 months ago

Hi!

When dealing with bitfields we often also want to address the fields with bit masks.

I'm thinking of the following:

bitfield!{
  pub struct BitField1(u16);
  impl Debug;
  // The fields default to u16
  mask FIELD1_MASK, field1, set_field1: 5, 2;
  pub field2, _ : 12, 3;
}

would generate an associated constant for field1:

impl BitField1 {
     const FIELD1_MASK: u16 = 0b00000000_0111100;
}
ithinuel commented 8 months ago

In my experience, things are usually generated with masks lsb aligned and combined with a "pos" constant for the required shifts. Used like in ((value >> FIELD1_POS) & FIELD1_MASK) which is essentially what bitfield does for us.

What is you usecase for such a thing though? Doesn’t handling masking/shifting manualy defeat the point of using bitfield! ?

sosthene-nitrokey commented 8 months ago

Writing device drivers for embedded I'm encountering the case where the device I'm communicating has "registers" that I can read/write.

Bitfields allows me to create/parse values for these registers. But the devices also accepts writing to specific bits of the register. In that case you send the full byte, plus a mask for which bits should actually be written.

Bitfield does not give me a straightforward way to build this mask. I could build the mask by setting each bit that I want to change, but that is not really explicit, and not straightforward for some cases where a field spans multiple bits.

ithinuel commented 7 months ago

That's right, I'm too used to the svd2rust generated API hiding all this.