scott-griffiths / bitstring

A Python module to help you manage your bits
https://bitstring.readthedocs.io/en/stable/index.html
MIT License
404 stars 68 forks source link

Support naming bits #239

Closed andreas-0815-qwertz closed 1 year ago

andreas-0815-qwertz commented 1 year ago

For my use cases, it would be useful to be able to name bits, so that they can be accessed as members of the class (instead of indices).

As an example take the control flags of the TCP header as a random example and assume you have the received flag byte value available in rval:

tcp_control_flags = Bits(uint=rval, length=8, cwr=0, ece=1, urg=2, ack=3, psh=4, rst=5, syn=6, fin=7)
assert tcp_control_flags.syn == True

NB: I haven' thought too much about the interface for associating indices with bit names as keyword arguments for the constructor.

scott-griffiths commented 1 year ago

Hi. Interesting idea. I think that in general I'm against having bits named in a bitstring as that creates quite a few issues (e.g. are bitstrings with the same bit pattern but different names equal?)

You can already so something like:

    fmt = 'bool=cwr, bool=ece, ...'
    d = {'cwr': 1, 'ece': 0, ...}
    flags = bitstring.pack(fmt, **d)   

but then the flags has no memory of how it's formed. You can still query d though.

For your example you can also do the reverse:

    b = Bits(uint=rval, length=8)
    v = b.unpack(fmt)

but this returns a list of items in v, whereas it might be nice to get an OrderedDict instead. In essence the names in the fmt are being ignored when unpack is done. The OrderedDict idea falls apart if some of the sub-bitstrings have names and some don't.

It might be nice at least if the docs had an example of a good way to do this as it is a reasonable workflow.

andreas-0815-qwertz commented 1 year ago

Thanks for the information about the format string. You are right, it is not necessary to build this feature into bitstring, as it is always possible to do the same thing via delegation (of even inheritance). That is what I am doing right now.