hecatia-elegua / bilge

Use bitsized types as if they were a feature of rust.
Apache License 2.0
171 stars 17 forks source link

Optionally support specifying the bit-range of a field instead #28

Open hecatia-elegua opened 1 year ago

hecatia-elegua commented 1 year ago

So that

#[bitsize(32)]
struct Register {
    padding: u4,
    field: u8,
    flag1: bool,
    padding: u4,
    flag2: bool,
    padding: u14,
}

is the same as

#[bitsize(32)]
struct Register {
    #[at(4..=11)]
    field: u8,
    flag1: bool,
    #[at(17)]
    flag2: bool,
}

or

#[bitsize(32)]
struct Register {
    #[at(4)]
    field: u8,
    flag1: bool,
    #[at(17)]
    flag2: bool,
}

Here, we use a similar logic to enum discriminant counting: The first field starts at 0, unless a range is given. The next field starts at the end of the previous field's range, unless a range is given.

This could be expanded, again similar to enums, to allow reordering.

pickx commented 1 year ago

To be clear, would this allow FromBits? How would this interact with non-zero patterns for padding? For example,

#[bitsize(4)]
#[derive(FromBits)]
struct Tiny {
    #[at(2)]
    field: u2
}

what would you get for Tiny::from(u4::new(0b1111))?

hecatia-elegua commented 1 year ago

In my head it would basically expand to

struct Tiny {
    reserved_i: u2,
    field: u2
}
JohnstonJ commented 3 weeks ago

+1 to this idea. Additionally:

In general, I like the way it could potentially show and enforce the offsets that can easily be compared with a datasheet or other external specification showing the bit field we are modeling. Whereas if no offsets are set, then I have to do math to figure out if everything is correct, or go through the list and hope I figured out the size of each thing correctly, etc.

It's all maybe a little nit-picky for most people, but seems like would be a nice touch.