third draft: add bitfields to D

Quirin Schroll qs.il.paperinik at gmail.com
Fri Jul 12 12:50:20 UTC 2024


On Thursday, 4 July 2024 at 12:20:52 UTC, Dom DiSc wrote:
> On Wednesday, 3 July 2024 at 19:02:59 UTC, Dave P. wrote:
>> Wouldn’t a more D-like syntax be to have the number of bits 
>> following the type instead of following the variable name? 
>> This would be more consistent with how D arrays are different 
>> than C arrays.
>>
>> ```D
>> struct Foo {
>>     uint:4 x;
>>     uint:5 y;
>> }
>> ```
>
> I like this. As for arrays it's much more readable than the C 
> syntax.

What I dislike about this is that `uint:4` and `ushort:4` would 
be different types, but that makes no sense. The only way this 
would make sense to me is if `uint` were fixed and not an 
arbitrary type, but a more natural approach to D would be using a 
`__traits` trait or adding new keywords e.g. `__bits` and 
`__ubits` with them producing `__bits(4)`.

To pack those in structs, we could be cheeky and extend the 
`align` concept with fractions. Alignment is in bytes, but two 
`__bits(4)` can be aligned so that they overlap, and `align(0.5)` 
could do that. Of course, the argument to `align` must be a 
multiple of `0.125` and be a power of 2. Or we just allow 
`align(0.125)` as a special exception to specify that `__bits(n)` 
fields of a struct are packed.

```D
struct Foo {
     __bits(3) x;
     __bits(5) y;
}
```
There, `x` and `y` have different addresses and `Foo.sizeof` is 2.

```D
struct Foo {
     align(0.125) __bits(3) x;
     align(0.125) __bits(5) y;
}
```
Here, `x` and `y` are stored in the same byte and `Foo.sizeof` is 
1.


More information about the dip.development mailing list