From 64524f5b77943bb2cc3989a6b81800d96be4ed3d Mon Sep 17 00:00:00 2001 From: Scott Griffiths Date: Sun, 5 May 2024 14:50:41 +0100 Subject: [PATCH] Raising ReadError more consistently when reading off end of bitstring. Should fix Bug #325. --- bitstring/bits.py | 2 +- bitstring/dtypes.py | 2 ++ tests/test_constbitstream.py | 9 +++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/bitstring/bits.py b/bitstring/bits.py index 94dfad7f..9b87202e 100644 --- a/bitstring/bits.py +++ b/bitstring/bits.py @@ -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) diff --git a/bitstring/dtypes.py b/bitstring/dtypes.py index c53ba160..e1a93e91 100644 --- a/bitstring/dtypes.py +++ b/bitstring/dtypes.py @@ -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: diff --git a/tests/test_constbitstream.py b/tests/test_constbitstream.py index 053ecb01..ef15cca8 100644 --- a/tests/test_constbitstream.py +++ b/tests/test_constbitstream.py @@ -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') \ No newline at end of file