Equivalents to struct.calcsize() and struct.iter_unpack()? #316
-
I'm wondering if there's any equivalent to I need this function because in my use-case the Currently, the horrible "solution" I have is this: def bitstring_calcsize(fmt):
# FIXME https://github.com/scott-griffiths/bitstring/discussions/316
bs = BitArray()
b_0 = Bits(1)
while True:
try:
bs.unpack(fmt)
except bitstring.exceptions.ReadError:
bs += b_0
else:
break
return len(bs) On the same note, anything for def bitstring_iter_unpack(buffer_or_file: 'Union[Buffer, BinaryIO]', fmt, *, pad_reads_to_byte_boundary=False):
# FIXME https://github.com/scott-griffiths/bitstring/discussions/316
bs = ConstBitStream(buffer_or_file)
size = bitstring_calcsize(fmt)
if pad_reads_to_byte_boundary:
size += ((8 - size) % 8)
assert bs.length % size == 0
while bs.pos != bs.length:
yield bs.read(size).unpack(fmt) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hi. Those are both very good questions. For the first part, It would be easier to use In general however there is no way to do a For the Thanks. |
Beta Was this translation helpful? Give feedback.
-
Having now read the docs for Which means that the equivalent is much easier to do in bitstring, but also less interesting (to me). This was my first attempt as a new method in the
The thing to notice is that |
Beta Was this translation helpful? Give feedback.
Hi. Those are both very good questions.
For the first part, It would be easier to use
pack
to create a dummy bitstring and just measure the length of that. You would need to know how many values to pack (and their types) but it's slightly less horrible?In general however there is no way to do a
calcsize
as the length of some data types depends on their values - in particular you don't know how long exponential-Golomb codes are going to be until you read them. There is room for a method for when it is possible though, and I think it's a good idea. I've recently started work on a new project calledbitformat
where this sort of thing would be easy. Possibly I could port that new functionali…