Native Bitfields


#1

Before anyone mentions it. I do know that this has been brought up before but that was back in 2014. I also know that there is a crate for producing something like this. However, I still think that first-party support is a needed thing, especially with C compatibility.

Part 1: Bitfields

  • A new “enum” type. This would be done like the following:
enum CtrlFlag <u8, big_endion> {
    high,
    _blank,
    low
};

or

enum CtrlFlag <u16, little_endion> {
    high,
    _blank<2>,
    low
};
  • These have either the size of a u8 or a u16. That type would have to be an unsigned integer.
  • The bitfields can either be big_endion or little_endion. The default would be the compile target layout.
  • The _blank context word would “skip over” a certain number of bits (more than one can be designated as specified in the second example)

These are exactly enums since they can hold more than one of these values and they cannot have containing data. We also wouldn’t want the have to explicitly use bitwise operations on them so the in keyword could be used instead:

ex:

let flag: CtrlFlag = low;

if CtrlFlag::low in flag {
    ...
}

Part 2:

This would also make a good reason for a “waterfall match” or a “match many” (that I have suggested in the past but ran into trouble with an amazing reason why it shouldn’t be added naively).

  • A “match many” is very similar to a match but instead of only executing the first match’s branch. Every branch that matches is executed (in order). There was also the idea of a “no match” branch that executes if no other match exists. This branch is different from the _ pattern since that matches everything.

This is a good fit for bitfields because you can have many different combinations of bits set and not set and the benefit over just using if let's is the exhaustiveness portion of the match.


#2

I don’t think it makes sense to put this in an enum. We already need a mechanism to do this in structs, and given that mechanism, we could use it for standalone bitfields as well.

Also, s/endion/endian/g. :slight_smile: