#What is the difference between structs and bitfields?

1 messages ยท Page 1 of 1 (latest)

odd plaza
#

I've been testing out the pattern language and found it quite convenient to turn my struct into a bitfield for encoded flags part (instead of making a nested type and cluttering everything). That got me thinking, what is the advantage of using structs? I can't see any problem with using bitfields instead to have the ability to integrate flags inside when you need it.

autumn summit
#

Structs maps bytes, bitfields - bits in one or several bytes

#

You probably need to map your structure to struct, and few bytes with flags to bitfield.

#

This may look like this

bitfield  bf0 {
        flag0 : 1;
        flag1 : 2;
}

struct st {
    u8 a;
    u8 b;
    u8 c;
    bf0 bfa;
}

st st0 @ 0;

// to read bit
st0.bfa.flag0;
// to read value
st0.a;
#

I think bitfields can map a limited number of bits

#

You can use [[inline]] directives to simplify layout of Pattern Data, but this will not remove nesting from the value reading code

odd plaza
#

Actually, I'm asking because I don't understand the disadvantage of using bitfields (except for probable performance issues). I've just turned my struct into a bitfield (12 bytes so bitfields seem unlimited) and it seems to work the same way except for having some fields that are bitwise.
I may be mistaken but I think it makes the code much cleaner.
For example I did this (instead of a ton of nested types and repetition):

bitfield Filter {
    FILTER_ID id;
    VarInt size;
    match (id) {
        (FILTER_ID::LZMA2): {
            dictionary_size: 6;
            reserved: 2;
        }
        // something else here maybe
    };
};
quasi hound
#

Bitfields are gonna be many orders of magnitude slower than structs and also if you have e.g arrays of bitfields, they will not be properly aligned to full bytes.
But besides that it's also just intention. With a bitfield you make it clear to the reader that you're interested in the data on a bit level instead of on a byte level. Things are displayed a bit differently compared to a struct in the pattern data view and so on

#

The differences aren't as massive anymore as they once were (e.g in the past you couldn't use regular types inside of bitfields, only bit values) but I'd still recommend you to use structs as the default