Why must butfields sum to a multiple of a byte?

monarch_dodra monarchdodra at gmail.com
Mon Jul 30 07:38:41 PDT 2012


On Monday, 30 July 2012 at 14:19:56 UTC, Andrej Mitrovic wrote:
> It says for std.bitmanip.bitfields:
>
> "The sum of all bit lengths in one bitfield instantiation must 
> be
> exactly 8, 16, 32, or 64."
> It has a static assert to verify this. But why does this 
> limitation exist?
>
> I was thinking of cases where I'm wrapping a C++ POD struct 
> which has
> bitfields and is packed on a 1-byte boundary. GCC example:
>
> #include <stdio.h>
> #pragma pack(1)
> struct Foo
> {
>     unsigned int bits1 : 1;
>     unsigned int bits2 : 2;
> };
>
> int main()
> {
>     printf("%d\n", sizeof(Foo));
>     return 0;
> }
>
> I can't translate this to D using the bitfields mixin since it
> requires a multiple of a byte, 3 bits isn't a byte:
>
> import std.stdio;
> import std.bitmanip;
>
> align(1) struct Foo
> {
>     mixin(bitfields!(
>         uint, "bits1", 1,
>         uint, "bits2", 2
>     ));
> }
>
> void main() { writeln(Foo.sizeof); }
>
> std\bitmanip.d(151): Error: static assert  "Field widths must 
> sum to
> 8, 16, 32, or 64"
>
> Is this a language limitation? I guess because 'byte' is the 
> smallest
> legal type in D this is what the bitfields mixin uses 
> internally?
I think you are supposed to explicitly pad the field yourself:

----
align(1) struct Foo
{
    mixin(bitfields!(
        uint, "bits1", 1,
        uint, "bits2", 2,
        uint, "", 5
    ));
}
----
The rationale (I *think*) Is that bitfields wants to know how big 
it should be: While YOU know you want to put it into a "Foo" 
object that is 1 byte big, bitfields has no idea.

Either that, or having the developer provide this by hand made 
the implementation easier enough to justify the burden?

Even then, I think it would have been more convenient to specify 
the total size as a first argument, rather than manually padding 
at the end.

Either way, nothing world shattering for me :D




More information about the Digitalmars-d-learn mailing list