proper bit fields in the D2 language?
grauzone
none at example.net
Tue Apr 21 23:25:04 PDT 2009
nobody wrote:
> == Quote from Brad Roberts (braddr at puremagic.com)'s article
>> The auto-generated code from the library is the same code the compiler
>> would end up generating. You can test that theory by comparing the
>> produced assembly for a C vs a D implementation.
>
> If the generated code are same, and it's in the std library, which means no
> difference in the backend.
>
> Then I'd rather write:
>
> struct A
> {
> bool flag1: 1;
> bool flag2: 1;
> // uint "", 6; // this should be auto-magically generated by the compiler
> }
>
> (the code is more clear, and the compiler can give better message).
>
> than this:
>
> struct A
> {
> mixin(bitfields!(
> bool, "flag1", 1,
> bool, "flag2", 1,
> uint, "", 6));
> }
Bitfields are a rather obscure feature. There's no real reason to have
it in the compiler. But because D is so great, you still can have it in
the standard library. Sadly, this comes with a bit more ugly syntax. If
we had macros (which were ditched for the oh-so-great [actually
questionable] features const and immutable), then it could be at least a
_bit_ more beautiful. Like defining identifiers as identifiers, and not
strings.
What I'm really concerned about is that this mixin MAGICALLY inserts
unknown symbols into the current scope. I was too lazy to look in the
Phobos code, but it's clear that the mixin must generate "hidden" fields
to store the actual bit values. (With a bit of luck, the author
[Andrei?] was careful enough to allow several bitfield mixins in the
same struct.) I also will blow up if later you add serialization or
anything in this direction.
A clean way would to to let the bitfields thing generate a real struct type:
alias Bitfields!(bool, "flag1", 1, bool, "flag2", 6) MyBitfields;
No more magical insertion of identifiers into your code. And a
serialization mechanism just could detect the type Bitfields and write
its actual members, and not the hidden bit array field (or whatever the
implementation uses, it just insert its own, unknown-to-you symbols into
YOUR scope).
More information about the Digitalmars-d
mailing list