www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Transitive bit-packing of fields

reply =?UTF-8?B?Tm9yZGzDtnc=?= <per.nordlow gmail.com> writes:
Have anybody found a way to do transitive packing of bitfields?

For instance, in


import std.bitmanip : bitfields;

struct X
{
     // one bit too many to fit in one byte
     mixin(bitfields!(bool, `a`, 1,
                      bool, `b`, 1,
                      ubyte, `c`, 7,
                      ubyte, `_pad`, 7);
}

struct Y
{
     // one unused bit
     mixin(bitfields!(ubyte, `d`, 7,
                      ubyte, `_pad`, 1);
}

struct XY
{
     X x;
     Y y;
}


`XY` will currently occupy 4 bytes, when only 1+1+7+7=16 bits are 
actually used in `a`, `b`, `c` and `d`.

Rust just got support for this.
Apr 30 2017
parent reply Stefan Koch <uplink.coder googlemail.com> writes:
On Sunday, 30 April 2017 at 11:02:52 UTC, Nordlöw wrote:
 Have anybody found a way to do transitive packing of bitfields?

 For instance, in


 import std.bitmanip : bitfields;

 struct X
 {
     // one bit too many to fit in one byte
     mixin(bitfields!(bool, `a`, 1,
                      bool, `b`, 1,
                      ubyte, `c`, 7,
                      ubyte, `_pad`, 7);
 }

 struct Y
 {
     // one unused bit
     mixin(bitfields!(ubyte, `d`, 7,
                      ubyte, `_pad`, 1);
 }

 struct XY
 {
     X x;
     Y y;
 }


 `XY` will currently occupy 4 bytes, when only 1+1+7+7=16 bits 
 are actually used in `a`, `b`, `c` and `d`.

 Rust just got support for this.
You'd have to write your own template to do it; it's easy though :)
Apr 30 2017
parent Per =?UTF-8?B?Tm9yZGzDtnc=?= <per.nordlow gmail.com> writes:
On Sunday, 30 April 2017 at 13:22:49 UTC, Stefan Koch wrote:
 On Sunday, 30 April 2017 at 11:02:52 UTC, Nordlöw wrote:
 Have anybody found a way to do transitive packing of bitfields?

 For instance, in


 import std.bitmanip : bitfields;

 struct X
 {
     // one bit too many to fit in one byte
     mixin(bitfields!(bool, `a`, 1,
                      bool, `b`, 1,
                      ubyte, `c`, 7,
                      ubyte, `_pad`, 7);
 }

 struct Y
 {
     // one unused bit
     mixin(bitfields!(ubyte, `d`, 7,
                      ubyte, `_pad`, 1);
 }

 struct XY
 {
     X x;
     Y y;
 }


 `XY` will currently occupy 4 bytes, when only 1+1+7+7=16 bits 
 are actually used in `a`, `b`, `c` and `d`.

 Rust just got support for this.
You'd have to write your own template to do it; it's easy though :)
Yeah, I thought so too. The question then becomes I have to write my own version of bitfields that can introspect the bitsize of it's arguments via some new trait bitsizeOf.
Apr 30 2017