Skip to content

Commit

Permalink
Fix to some bugs using bytes in Array.
Browse files Browse the repository at this point in the history
  • Loading branch information
scott-griffiths committed Jan 24, 2024
1 parent f5b65c9 commit 3102226
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
4 changes: 2 additions & 2 deletions bitstring/array_.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def __init__(self, dtype: Union[str, Dtype], initializer: Optional[Union[int, Ar
raise CreationError(e)

if isinstance(initializer, numbers.Integral):
self.data = BitArray(initializer * self._dtype.length)
self.data = BitArray(initializer * self._dtype.bitlength)
elif isinstance(initializer, (Bits, bytes, bytearray, memoryview)):
self.data += initializer
elif isinstance(initializer, io.BufferedReader):
Expand All @@ -93,7 +93,7 @@ def itemsize(self) -> int:

@property
def trailing_bits(self) -> BitArray:
trailing_bit_length = len(self.data) % self._dtype.length
trailing_bit_length = len(self.data) % self._dtype.bitlength
return BitArray() if trailing_bit_length == 0 else self.data[-trailing_bit_length:]

# Converting array.array typecodes to our equivalents.
Expand Down
7 changes: 4 additions & 3 deletions bitstring/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def __str__(self) -> str:
def __repr__(self) -> str:
hide_length = self.variable_length or len(dtype_register.names[self.name].allowed_lengths) == 1 or self.length is None
length_str = '' if hide_length else ', ' + str(self.length)
return f"{self.__class__.__name__}('{self.name}{length_str}')"
return f"{self.__class__.__name__}('{self.name}'{length_str})"

def __eq__(self, other: Any) -> bool:
if isinstance(other, Dtype):
Expand Down Expand Up @@ -120,9 +120,10 @@ def __init__(self, name: str, set_fn, get_fn, return_type: Any = Any, is_signed:

self.multiplier = multiplier

self.set_fn = set_fn
# Can work out if set_fn needs length based on its signature.
self.set_fn_needs_length = self.set_fn is not None and 'length' in inspect.signature(self.set_fn).parameters
self.set_fn_needs_length = set_fn is not None and 'length' in inspect.signature(set_fn).parameters
self.set_fn = set_fn


if self.allowed_lengths:
def length_checked_get_fn(bs):
Expand Down
12 changes: 12 additions & 0 deletions tests/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -901,3 +901,15 @@ def testSetOutOfRangeElement(self):
a[4] = 100.0
with self.assertRaises(IndexError):
a[-5] = 100.0

def testBytes(self):
a = Array('bytes8', 5)
self.assertEqual(a.data, b'\x00'*40)

b = Array('bytes1', 5)
self.assertEqual(b.data, b'\x00'*5)

def testBytesTrailingBits(self):
b = Bits('0x000000, 0b111')
a = Array('bytes1', b)
self.assertEqual(a.trailing_bits, '0b111')

0 comments on commit 3102226

Please sign in to comment.