scott-griffiths / bitstring

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

`BitStream.__add__` throws `AttributeError: 'Bits' object has no attribute '_pos'` #329

Closed whitslack closed 2 months ago

whitslack commented 2 months ago

Using version 4.2.1…

This is okay:

>>> BitStream() + '0xff'
BitStream('0xff')

But this fails:

>>> BitStream() + Bits('0xff')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.12/site-packages/bitstring/bitstream.py", line 189, in __add__
    s._pos = 0
    ^^^^^^
AttributeError: 'Bits' object has no attribute '_pos'

And so does this:

>>> BitStream() + BitArray('0xff')
Traceback (most recent call last):
  File "/usr/lib/python3.12/site-packages/bitstring/bitarray_.py", line 126, in __setattr__
    super().__setattr__(attribute, value)
AttributeError: 'BitArray' object has no attribute '_pos'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.12/site-packages/bitstring/bitstream.py", line 189, in __add__
    s._pos = 0
    ^^^^^^
  File "/usr/lib/python3.12/site-packages/bitstring/bitarray_.py", line 128, in __setattr__
    dtype = bitstring.dtypes.Dtype(attribute)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/site-packages/bitstring/dtypes.py", line 63, in __new__
    x = cls._new_from_token(token, scale)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/site-packages/bitstring/dtypes.py", line 142, in _new_from_token
    return dtype_register.get_dtype(*utils.parse_name_length_token(token), scale=scale)
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/site-packages/bitstring/utils.py", line 94, in parse_name_length_token
    raise ValueError(f"Can't parse 'name[:]length' token '{fmt}'.")
ValueError: Can't parse 'name[:]length' token '_pos'.

But this is okay:

>>> BitStream() + BitStream('0xff')
BitStream('0xff')

So it would appear that BitStream._add_ is expecting its right-hand operand to be a BitStream (and have a _pos attribute), but the API is supposed to allow any Bits on the right-hand side.

This is causing a regression in one of Core Lightning's pyln-proto unit tests, whereas there was no failure when using Bitstring 4.1.4.

scott-griffiths commented 2 months ago

Hi. Thanks for reporting this.

I'm hoping to make a 4.2.2 release this weekend, and I'll make sure I get a fix in for this as part of that release.

scott-griffiths commented 2 months ago

bitstring 4.2.2 is now released. 🎉

whitslack commented 2 months ago

Thank you for the quick response.