Skip to content

Commit

Permalink
Raising ReadError more consistently when reading off end of bitstring.
Browse files Browse the repository at this point in the history
Should fix Bug #325.
  • Loading branch information
scott-griffiths committed May 5, 2024
1 parent e423175 commit 64524f5
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
2 changes: 1 addition & 1 deletion bitstring/bits.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def __getattr__(self, attribute: str) -> Any:
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attribute}'.")
if d.bitlength is not None and len(self) != d.bitlength:
raise ValueError(f"bitstring length {len(self)} doesn't match length {d.bitlength} of property '{attribute}'.")
return d.read_fn(self, 0)
return d.get_fn(self)

def __iter__(self) -> Iterable[bool]:
return iter(self._bitstore)
Expand Down
2 changes: 2 additions & 0 deletions bitstring/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,8 @@ def read_fn(bs, start):
return self.get_fn(bs[start:start + self.allowed_lengths.values[0]])
else:
def read_fn(bs, start, length):
if len(bs) < start + length:
raise bitstring.ReadError(f"Needed a length of at least {length} bits, but only {len(bs) - start} bits were available.")
return self.get_fn(bs[start:start + length])
self.read_fn = read_fn
else:
Expand Down
9 changes: 9 additions & 0 deletions tests/test_constbitstream.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,3 +263,12 @@ def test_windows_file_lock_bug():
if platform.system() == 'Windows':
# Expected failure. See bug #308
pass

def test_readerrors():
s = CBS('0b110')
s.read(3)
with pytest.raises(bitstring.ReadError):
_ = s.read(1)
s.pos = 1
with pytest.raises(bitstring.ReadError):
_ = s.read('u3')

0 comments on commit 64524f5

Please sign in to comment.