The OpenD Programming Language

bitfields

Allows creating bitfields inside structs, classes and unions.

A bitfield consists of one or more entries with a fixed number of bits reserved for each of the entries. The types of the entries can be bools, integral types or enumerated types, arbitrarily mixed. The most efficient type to store in bitfields is bool, followed by unsigned types, followed by signed types.

Each non-bool entry of the bitfield will be represented by the number of bits specified by the user. The minimum and the maximum numbers that represent this domain can be queried by using the name of the variable followed by _min or _max.

Limitation: The number of bits in a bitfield is limited to 8, 16, 32 or 64. If padding is needed, an entry should be explicitly allocated with an empty name.

More...
string
bitfields
(
T...
)
()

Return Value

Type: string

A string that can be used in a mixin to add the bitfield.

Detailed Description

Implementation details

Bitfields are internally stored in an ubyte, ushort, uint or ulong depending on the number of bits used. The bits are filled in the order given by the parameters, starting with the lowest significant bit. The name of the (private) variable used for saving the bitfield is created by a prefix _bf and concatenating all of the variable names, each preceded by an underscore.

Examples

Create a bitfield pack of eight bits, which fit in one ubyte. The bitfields are allocated starting from the least significant bit, i.e. x occupies the two least significant bits of the bitfields storage.

struct A
{
    int a;
    mixin(bitfields!(
        uint, "x",    2,
        int,  "y",    3,
        uint, "z",    2,
        bool, "flag", 1));
}

A obj;
obj.x = 2;
obj.z = obj.x;

assert(obj.x == 2);
assert(obj.y == 0);
assert(obj.z == 2);
assert(obj.flag == false);

The sum of all bit lengths in one bitfield instantiation must be exactly 8, 16, 32, or 64. If padding is needed, just allocate one bitfield with an empty name.

struct A
{
    mixin(bitfields!(
        bool, "flag1",    1,
        bool, "flag2",    1,
        uint, "",         6));
}

A a;
assert(a.flag1 == 0);
a.flag1 = 1;
assert(a.flag1 == 1);
a.flag1 = 0;
assert(a.flag1 == 0);

enums can be used too

enum ABC { A, B, C }
struct EnumTest
{
    mixin(bitfields!(
              ABC, "x", 2,
              bool, "y", 1,
              ubyte, "z", 5));
}

See Also

Meta