From d693026e4c11913741c9abafaf0e067b51506693 Mon Sep 17 00:00:00 2001 From: Scott Griffiths Date: Tue, 2 Jan 2024 20:56:22 +0000 Subject: [PATCH] More import reorganisation. --- bitstring/bits.py | 121 +++++++++++++++++----------------- bitstring/bitstore_helpers.py | 44 ++++++------- bitstring/bitstream.py | 50 +++++++------- bitstring/dtypes.py | 21 +++--- bitstring/exceptions.py | 5 +- bitstring/methods.py | 38 +++++------ bitstring/options.py | 48 +++++++------- bitstring/utils.py | 3 +- 8 files changed, 156 insertions(+), 174 deletions(-) diff --git a/bitstring/bits.py b/bitstring/bits.py index 4c82cdb9..f20f58bc 100644 --- a/bitstring/bits.py +++ b/bitstring/bits.py @@ -14,16 +14,13 @@ BinaryIO, TextIO, overload, Iterator, Type, TypeVar import bitarray import bitarray.util -from bitstring.utils import preprocess_tokens, parse_name_length_token -from bitstring.exceptions import CreationError, InterpretError, ReadError, Error -from bitstring.fp8 import e4m3float_fmt, e5m2float_fmt -from bitstring.bitstore import BitStore, offset_slice_indices_lsb0 +import bitstring +from bitstring.bitstore import BitStore from bitstring.bitstore_helpers import float2bitstore, uint2bitstore, ue2bitstore, str_to_bitstore, se2bitstore, \ bfloat2bitstore, floatle2bitstore, uintbe2bitstore, uintle2bitstore, intbe2bitstore, intle2bitstore, bfloatle2bitstore, \ bin2bitstore, bin2bitstore_unsafe, hex2bitstore, int2bitstore, oct2bitstore, sie2bitstore, uie2bitstore, \ e5m2float2bitstore, e4m3float2bitstore -import bitstring # Things that can be converted to Bits when a Bits type is needed BitsType = Union['Bits', str, Iterable[Any], bool, BinaryIO, bytearray, bytes, memoryview, bitarray.bitarray] @@ -167,7 +164,7 @@ def _initialise(self, auto: Any, /, length: Optional[int], offset: Optional[int] if isinstance(auto, numbers.Integral): # Initialise with s zero bits. if auto < 0: - raise CreationError(f"Can't create bitstring of negative length {auto}.") + raise bitstring.CreationError(f"Can't create bitstring of negative length {auto}.") self._bitstore = BitStore(int(auto)) self._bitstore.setall(0) return @@ -188,12 +185,12 @@ def _initialise(self, auto: Any, /, length: Optional[int], offset: Optional[int] self._setbitarray(v, length, offset) return if k == 'auto': - raise CreationError(f"The 'auto' parameter should not be given explicitly - just use the first positional argument. " + raise bitstring.CreationError(f"The 'auto' parameter should not be given explicitly - just use the first positional argument. " f"Instead of '{self.__class__.__name__}(auto=x)' use '{self.__class__.__name__}(x)'.") else: - raise CreationError(f"Unrecognised keyword '{k}' used to initialise.") + raise bitstring.CreationError(f"Unrecognised keyword '{k}' used to initialise.") if offset is not None: - raise CreationError("offset cannot be used when initialising with '{k}'.") + raise bitstring.CreationError("offset cannot be used when initialising with '{k}'.") setting_function(self, v, length) def __getattr__(self, attribute: str) -> Any: @@ -361,7 +358,7 @@ def __invert__(self: TBits) -> TBits: """ if len(self) == 0: - raise Error("Cannot invert empty bitstring.") + raise bitstring.Error("Cannot invert empty bitstring.") s = self._copy() s._invert_all() return s @@ -574,7 +571,7 @@ def _setauto(self, s: BitsType, length: Optional[int], offset: Optional[int], /) byteoffset, offset = divmod(offset, 8) bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset if length + byteoffset * 8 + offset > s.seek(0, 2) * 8: - raise CreationError("BytesIO object is not long enough for specified length and offset.") + raise bitstring.CreationError("BytesIO object is not long enough for specified length and offset.") self._bitstore = BitStore(frombytes=s.getvalue()[byteoffset: byteoffset + bytelength]).getslice( offset, offset + length) return @@ -585,7 +582,7 @@ def _setauto(self, s: BitsType, length: Optional[int], offset: Optional[int], /) if isinstance(s, (str, Bits, bytes, bytearray, memoryview, io.BytesIO, io.BufferedReader, bitarray.bitarray, array.array, abc.Iterable)): - raise CreationError(f"Cannot initialise bitstring from type '{type(s)}' when using explicit lengths or offsets.") + raise bitstring.CreationError(f"Cannot initialise bitstring from type '{type(s)}' when using explicit lengths or offsets.") raise TypeError(f"Cannot initialise bitstring from type '{type(s)}'.") def _setfile(self, filename: str, length: Optional[int] = None, offset: Optional[int] = None) -> None: @@ -601,23 +598,23 @@ def _setfile(self, filename: str, length: Optional[int] = None, offset: Optional temp = BitStore(buffer=m, filename=source.name, immutable=True) if length is None: if offset > len(temp): - raise CreationError(f"The offset of {offset} bits is greater than the file length ({len(temp)} bits).") + raise bitstring.CreationError(f"The offset of {offset} bits is greater than the file length ({len(temp)} bits).") self._bitstore = temp.getslice(offset, None) else: self._bitstore = temp.getslice(offset, offset + length) if len(self) != length: - raise CreationError(f"Can't use a length of {length} bits and an offset of {offset} bits as file length is only {len(temp)} bits.") + raise bitstring.CreationError(f"Can't use a length of {length} bits and an offset of {offset} bits as file length is only {len(temp)} bits.") def _setbitarray(self, ba: bitarray.bitarray, length: Optional[int], offset: Optional[int]) -> None: if offset is None: offset = 0 if offset > len(ba): - raise CreationError(f"Offset of {offset} too large for bitarray of length {len(ba)}.") + raise bitstring.CreationError(f"Offset of {offset} too large for bitarray of length {len(ba)}.") if length is None: self._bitstore = BitStore(ba[offset:]) else: if offset + length > len(ba): - raise CreationError( + raise bitstring.CreationError( f"Offset of {offset} and length of {length} too large for bitarray of length {len(ba)}.") self._bitstore = BitStore(ba[offset: offset + length]) @@ -648,13 +645,13 @@ def _setbytes_with_truncation(self, data: Union[bytearray, bytes], length: Optio length = len(data) * 8 - offset else: if length + offset > len(data) * 8: - raise CreationError(f"Not enough data present. Need {length + offset} bits, have {len(data) * 8}.") + raise bitstring.CreationError(f"Not enough data present. Need {length + offset} bits, have {len(data) * 8}.") self._bitstore = BitStore(buffer=data).getslice_msb0(offset, offset + length) def _getbytes(self) -> bytes: """Return the data as an ordinary bytes object.""" if len(self) % 8: - raise InterpretError("Cannot interpret as bytes unambiguously - not multiple of 8 bits.") + raise bitstring.InterpretError("Cannot interpret as bytes unambiguously - not multiple of 8 bits.") return self._bitstore.tobytes() _unprintable = list(range(0x00, 0x20)) # ASCII control characters @@ -673,13 +670,13 @@ def _setuint(self, uint: int, length: Optional[int] = None) -> None: if length is None and hasattr(self, 'len') and len(self) != 0: length = len(self) if length is None or length == 0: - raise CreationError("A non-zero length must be specified with a uint initialiser.") + raise bitstring.CreationError("A non-zero length must be specified with a uint initialiser.") self._bitstore = uint2bitstore(uint, length) def _getuint(self) -> int: """Return data as an unsigned int.""" if len(self) == 0: - raise InterpretError("Cannot interpret a zero length bitstring as an integer.") + raise bitstring.InterpretError("Cannot interpret a zero length bitstring as an integer.") return self._bitstore.slice_to_uint() def _setint(self, int_: int, length: Optional[int] = None) -> None: @@ -688,13 +685,13 @@ def _setint(self, int_: int, length: Optional[int] = None) -> None: if length is None and hasattr(self, 'len') and len(self) != 0: length = len(self) if length is None or length == 0: - raise CreationError("A non-zero length must be specified with an int initialiser.") + raise bitstring.CreationError("A non-zero length must be specified with an int initialiser.") self._bitstore = int2bitstore(int_, length) def _getint(self) -> int: """Return data as a two's complement signed int.""" if len(self) == 0: - raise InterpretError("Cannot interpret bitstring without a length as an integer.") + raise bitstring.InterpretError("Cannot interpret bitstring without a length as an integer.") return self._bitstore.slice_to_int() def _setuintbe(self, uintbe: int, length: Optional[int] = None) -> None: @@ -702,13 +699,13 @@ def _setuintbe(self, uintbe: int, length: Optional[int] = None) -> None: if length is None and hasattr(self, 'len') and len(self) != 0: length = len(self) if length is None or length == 0: - raise CreationError("A non-zero length must be specified with a uintbe initialiser.") + raise bitstring.CreationError("A non-zero length must be specified with a uintbe initialiser.") self._bitstore = uintbe2bitstore(uintbe, length) def _getuintbe(self) -> int: """Return data as a big-endian two's complement unsigned int.""" if len(self) % 8: - raise InterpretError(f"Big-endian integers must be whole-byte. Length = {len(self)} bits.") + raise bitstring.InterpretError(f"Big-endian integers must be whole-byte. Length = {len(self)} bits.") return self._getuint() def _setintbe(self, intbe: int, length: Optional[int] = None) -> None: @@ -716,26 +713,26 @@ def _setintbe(self, intbe: int, length: Optional[int] = None) -> None: if length is None and hasattr(self, 'len') and len(self) != 0: length = len(self) if length is None or length == 0: - raise CreationError("A non-zero length must be specified with a intbe initialiser.") + raise bitstring.CreationError("A non-zero length must be specified with a intbe initialiser.") self._bitstore = intbe2bitstore(intbe, length) def _getintbe(self) -> int: """Return data as a big-endian two's complement signed int.""" if len(self) % 8: - raise InterpretError(f"Big-endian integers must be whole-byte. Length = {len(self)} bits.") + raise bitstring.InterpretError(f"Big-endian integers must be whole-byte. Length = {len(self)} bits.") return self._getint() def _setuintle(self, uintle: int, length: Optional[int] = None) -> None: if length is None and hasattr(self, 'len') and len(self) != 0: length = len(self) if length is None or length == 0: - raise CreationError("A non-zero length must be specified with a uintle initialiser.") + raise bitstring.CreationError("A non-zero length must be specified with a uintle initialiser.") self._bitstore = uintle2bitstore(uintle, length) def _getuintle(self) -> int: """Interpret as a little-endian unsigned int.""" if len(self) % 8: - raise InterpretError(f"Little-endian integers must be whole-byte. Length = {len(self)} bits.") + raise bitstring.InterpretError(f"Little-endian integers must be whole-byte. Length = {len(self)} bits.") bs = BitStore(frombytes=self._bitstore.tobytes()[::-1]) return bs.slice_to_uint() @@ -743,29 +740,29 @@ def _setintle(self, intle: int, length: Optional[int] = None) -> None: if length is None and hasattr(self, 'len') and len(self) != 0: length = len(self) if length is None or length == 0: - raise CreationError("A non-zero length must be specified with an intle initialiser.") + raise bitstring.CreationError("A non-zero length must be specified with an intle initialiser.") self._bitstore = intle2bitstore(intle, length) def _getintle(self) -> int: """Interpret as a little-endian signed int.""" if len(self) % 8: - raise InterpretError(f"Little-endian integers must be whole-byte. Length = {len(self)} bits.") + raise bitstring.InterpretError(f"Little-endian integers must be whole-byte. Length = {len(self)} bits.") bs = BitStore(frombytes=self._bitstore.tobytes()[::-1]) return bs.slice_to_int() def _gete4m3float(self) -> float: u = self._getuint() - return e4m3float_fmt.lut_int8_to_float[u] + return bitstring.fp8.e4m3float_fmt.lut_int8_to_float[u] def _gete5m2float(self) -> float: u = self._getuint() - return e5m2float_fmt.lut_int8_to_float[u] + return bitstring.fp8.e5m2float_fmt.lut_int8_to_float[u] def _setfloatbe(self, f: float, length: Optional[int] = None) -> None: if length is None and hasattr(self, 'len') and len(self) != 0: length = len(self) if length is None or length not in [16, 32, 64]: - raise CreationError("A length of 16, 32, or 64 must be specified with a float initialiser.") + raise bitstring.CreationError("A length of 16, 32, or 64 must be specified with a float initialiser.") self._bitstore = float2bitstore(f, length) def _getfloatbe(self) -> float: @@ -777,7 +774,7 @@ def _setfloatle(self, f: float, length: Optional[int] = None) -> None: if length is None and hasattr(self, 'len') and len(self) != 0: length = len(self) if length is None or length not in [16, 32, 64]: - raise CreationError("A length of 16, 32, or 64 must be specified with a float initialiser.") + raise bitstring.CreationError("A length of 16, 32, or 64 must be specified with a float initialiser.") self._bitstore = floatle2bitstore(f, length) def _getfloatle(self) -> float: @@ -791,7 +788,7 @@ def _getbfloatbe(self) -> float: def _setbfloatbe(self, f: Union[float, str], length: Optional[int] = None) -> None: if length is not None and length != 16: - raise CreationError(f"bfloats must be length 16, received a length of {length} bits.") + raise bitstring.CreationError(f"bfloats must be length 16, received a length of {length} bits.") self._bitstore = bfloat2bitstore(f) def _getbfloatle(self) -> float: @@ -800,7 +797,7 @@ def _getbfloatle(self) -> float: def _setbfloatle(self, f: Union[float, str], length: Optional[int] = None) -> None: if length is not None and length != 16: - raise CreationError(f"bfloats must be length 16, received a length of {length} bits.") + raise bitstring.CreationError(f"bfloats must be length 16, received a length of {length} bits.") self._bitstore = bfloatle2bitstore(f) def _setue(self, i: int, length: None = None) -> None: @@ -810,9 +807,9 @@ def _setue(self, i: int, length: None = None) -> None: """ if length is not None: - raise CreationError("Cannot specify a length for exponential-Golomb codes.") + raise bitstring.CreationError("Cannot specify a length for exponential-Golomb codes.") if bitstring.options.lsb0: - raise CreationError("Exp-Golomb codes cannot be used in lsb0 mode.") + raise bitstring.CreationError("Exp-Golomb codes cannot be used in lsb0 mode.") self._bitstore = ue2bitstore(i) def _readue(self, pos: int) -> Tuple[int, int]: @@ -824,18 +821,18 @@ def _readue(self, pos: int) -> Tuple[int, int]: """ # _length is ignored - it's only present to make the function signature consistent. if bitstring.options.lsb0: - raise ReadError("Exp-Golomb codes cannot be read in lsb0 mode.") + raise bitstring.ReadError("Exp-Golomb codes cannot be read in lsb0 mode.") oldpos = pos try: while not self[pos]: pos += 1 except IndexError: - raise ReadError("Read off end of bitstring trying to read code.") + raise bitstring.ReadError("Read off end of bitstring trying to read code.") leadingzeros = pos - oldpos codenum = (1 << leadingzeros) - 1 if leadingzeros > 0: if pos + leadingzeros + 1 > len(self): - raise ReadError("Read off end of bitstring trying to read code.") + raise bitstring.ReadError("Read off end of bitstring trying to read code.") codenum += self[pos + 1:pos + 1 + leadingzeros]._getuint() pos += leadingzeros + 1 else: @@ -846,9 +843,9 @@ def _readue(self, pos: int) -> Tuple[int, int]: def _setse(self, i: int, length: None = None) -> None: """Initialise bitstring with signed exponential-Golomb code for integer i.""" if length is not None: - raise CreationError("Cannot specify a length for exponential-Golomb codes.") + raise bitstring.CreationError("Cannot specify a length for exponential-Golomb codes.") if bitstring.options.lsb0: - raise CreationError("Exp-Golomb codes cannot be used in lsb0 mode.") + raise bitstring.CreationError("Exp-Golomb codes cannot be used in lsb0 mode.") self._bitstore = se2bitstore(i) def _readse(self, pos: int) -> Tuple[int, int]: @@ -874,9 +871,9 @@ def _setuie(self, i: int, length: None = None) -> None: """ if length is not None: - raise CreationError("Cannot specify a length for exponential-Golomb codes.") + raise bitstring.CreationError("Cannot specify a length for exponential-Golomb codes.") if bitstring.options.lsb0: - raise CreationError("Exp-Golomb codes cannot be used in lsb0 mode.") + raise bitstring.CreationError("Exp-Golomb codes cannot be used in lsb0 mode.") self._bitstore = uie2bitstore(i) def _readuie(self, pos: int) -> Tuple[int, int]: @@ -887,7 +884,7 @@ def _readuie(self, pos: int) -> Tuple[int, int]: """ if bitstring.options.lsb0: - raise ReadError("Exp-Golomb codes cannot be read in lsb0 mode.") + raise bitstring.ReadError("Exp-Golomb codes cannot be read in lsb0 mode.") try: codenum: int = 1 while not self[pos]: @@ -897,16 +894,16 @@ def _readuie(self, pos: int) -> Tuple[int, int]: pos += 1 pos += 1 except IndexError: - raise ReadError("Read off end of bitstring trying to read code.") + raise bitstring.ReadError("Read off end of bitstring trying to read code.") codenum -= 1 return codenum, pos def _setsie(self, i: int, length: None = None) -> None: """Initialise bitstring with signed interleaved exponential-Golomb code for integer i.""" if length is not None: - raise CreationError("Cannot specify a length for exponential-Golomb codes.") + raise bitstring.CreationError("Cannot specify a length for exponential-Golomb codes.") if bitstring.options.lsb0: - raise CreationError("Exp-Golomb codes cannot be used in lsb0 mode.") + raise bitstring.CreationError("Exp-Golomb codes cannot be used in lsb0 mode.") self._bitstore = sie2bitstore(i) def _readsie(self, pos: int) -> Tuple[int, int]: @@ -927,19 +924,19 @@ def _readsie(self, pos: int) -> Tuple[int, int]: else: return codenum, pos + 1 except IndexError: - raise ReadError("Read off end of bitstring trying to read code.") + raise bitstring.ReadError("Read off end of bitstring trying to read code.") def _setbool(self, value: Union[bool, str], length: Optional[int] = None) -> None: # We deliberately don't want to have implicit conversions to bool here. # If we did then it would be difficult to deal with the 'False' string. if length is not None and length != 1: - raise CreationError(f"bools must be length 1, received a length of {length} bits.") + raise bitstring.CreationError(f"bools must be length 1, received a length of {length} bits.") if value in (1, 'True', '1'): self._bitstore = BitStore('1') elif value in (0, 'False', '0'): self._bitstore = BitStore('0') else: - raise CreationError(f"Cannot initialise boolean with {value}.") + raise bitstring.CreationError(f"Cannot initialise boolean with {value}.") def _getbool(self) -> bool: return self[0] @@ -969,7 +966,7 @@ def _setoct(self, octstring: str, length: None = None) -> None: def _getoct(self) -> str: """Return interpretation as an octal string.""" if len(self) % 3: - raise InterpretError("Cannot convert to octal unambiguously - not multiple of 3 bits long.") + raise bitstring.InterpretError("Cannot convert to octal unambiguously - not multiple of 3 bits long.") return self._bitstore.slice_to_oct() def _sethex(self, hexstring: str, length: None = None) -> None: @@ -983,7 +980,7 @@ def _gethex(self) -> str: """ if len(self) % 4: - raise InterpretError("Cannot convert to hex unambiguously - not a multiple of 4 bits long.") + raise bitstring.InterpretError("Cannot convert to hex unambiguously - not a multiple of 4 bits long.") return self._bitstore.slice_to_hex() def _getlength(self) -> int: @@ -1017,7 +1014,7 @@ def _readtoken(self, name: str, pos: int, length: Optional[int]) -> Tuple[Union[ """Reads a token from the bitstring and returns the result.""" dtype = bitstring.dtypes.dtype_register.get_dtype(name, length) if dtype.bitlength is not None and dtype.bitlength > len(self) - pos: - raise ReadError("Reading off the end of the data. " + raise bitstring.ReadError("Reading off the end of the data. " f"Tried to read {dtype.bitlength} bits when only {len(self) - pos} available.") try: val = dtype.read_fn(self, pos) @@ -1178,10 +1175,10 @@ def _readlist(self, fmt: Union[str, List[Union[str, int, Dtype]]], pos: int, **k elif isinstance(f_item, bitstring.dtypes.Dtype): dtype_list.append(f_item) else: - token_list = preprocess_tokens(f_item) + token_list = bitstring.utils.preprocess_tokens(f_item) for t in token_list: try: - name, length = parse_name_length_token(t, **kwargs) + name, length = bitstring.utils.parse_name_length_token(t, **kwargs) except ValueError: dtype_list.append(bitstring.dtypes.Dtype('bits', int(t))) else: @@ -1195,11 +1192,11 @@ def _read_dtype_list(self, dtypes: List[Dtype], pos: int) -> Tuple[List[Union[in stretchy = dtype.bitlength is None and dtype.is_unknown_length is False if stretchy: if has_stretchy_token: - raise Error("It's not possible to have more than one 'filler' token.") + raise bitstring.Error("It's not possible to have more than one 'filler' token.") has_stretchy_token = True elif has_stretchy_token: if dtype.is_unknown_length: - raise Error(f"It's not possible to parse a variable length token '{dtype}' after a 'filler' token.") + raise bitstring.Error(f"It's not possible to parse a variable length token '{dtype}' after a 'filler' token.") bits_after_stretchy_token += dtype.bitlength # We should have precisely zero or one stretchy token @@ -1260,7 +1257,7 @@ def _find_lsb0(self, bs: Bits, start: int, end: int, bytealigned: bool) -> Union assert start <= end assert bitstring.options.lsb0 - new_slice = offset_slice_indices_lsb0(slice(start, end, None), len(self)) + new_slice = bitstring.bitstore.offset_slice_indices_lsb0(slice(start, end, None), len(self)) msb0_start, msb0_end = self._validate_slice(new_slice.start, new_slice.stop) p = self._rfind_msb0(bs, msb0_start, msb0_end, bytealigned) @@ -1314,7 +1311,7 @@ def _findall_lsb0(self, bs: Bits, start: int, end: int, count: Optional[int], assert start <= end assert bitstring.options.lsb0 - new_slice = offset_slice_indices_lsb0(slice(start, end, None), len(self)) + new_slice = bitstring.bitstore.offset_slice_indices_lsb0(slice(start, end, None), len(self)) msb0_start, msb0_end = self._validate_slice(new_slice.start, new_slice.stop) # Search chunks starting near the end and then moving back. @@ -1377,7 +1374,7 @@ def _rfind_lsb0(self, bs: Bits, start: int, end: int, bytealigned: bool) -> Unio # A reverse find in lsb0 is very like a forward find in msb0. assert start <= end assert bitstring.options.lsb0 - new_slice = offset_slice_indices_lsb0(slice(start, end, None), len(self)) + new_slice = bitstring.bitstore.offset_slice_indices_lsb0(slice(start, end, None), len(self)) msb0_start, msb0_end = self._validate_slice(new_slice.start, new_slice.stop) p = self._find_msb0(bs, msb0_start, msb0_end, bytealigned) diff --git a/bitstring/bitstore_helpers.py b/bitstring/bitstore_helpers.py index 412ed681..6efd670e 100644 --- a/bitstring/bitstore_helpers.py +++ b/bitstring/bitstore_helpers.py @@ -5,10 +5,6 @@ import functools from typing import Union, Optional, Dict, Callable import bitarray -import bitarray.util -from bitstring.utils import tokenparser -from bitstring.exceptions import CreationError -from bitstring.fp8 import e4m3float_fmt, e5m2float_fmt from bitstring.bitstore import BitStore import bitstring @@ -22,18 +18,18 @@ def tidy_input_string(s: str) -> str: """Return string made lowercase and with all whitespace and underscores removed.""" try: - l = s.split() + t = s.split() except (AttributeError, TypeError): raise ValueError(f"Expected str object but received a {type(s)} with value {s}.") - return ''.join(l).lower().replace('_', '') + return ''.join(t).lower().replace('_', '') @functools.lru_cache(CACHE_SIZE) def str_to_bitstore(s: str) -> BitStore: try: - _, tokens = tokenparser(s) + _, tokens = bitstring.utils.tokenparser(s) except ValueError as e: - raise CreationError(*e.args) + raise bitstring.CreationError(*e.args) bs = BitStore() for token in tokens: bs += bitstore_from_token(*token) @@ -51,7 +47,7 @@ def bin2bitstore_unsafe(binstring: str) -> BitStore: try: return BitStore(binstring) except ValueError: - raise CreationError(f"Invalid character in bin initialiser {binstring}.") + raise bitstring.CreationError(f"Invalid character in bin initialiser {binstring}.") def hex2bitstore(hexstring: str) -> BitStore: @@ -60,7 +56,7 @@ def hex2bitstore(hexstring: str) -> BitStore: try: ba = bitarray.util.hex2ba(hexstring) except ValueError: - raise CreationError("Invalid symbol in hex initialiser.") + raise bitstring.CreationError("Invalid symbol in hex initialiser.") return BitStore(ba) @@ -70,14 +66,14 @@ def oct2bitstore(octstring: str) -> BitStore: try: ba = bitarray.util.base2ba(8, octstring) except ValueError: - raise CreationError("Invalid symbol in oct initialiser.") + raise bitstring.CreationError("Invalid symbol in oct initialiser.") return BitStore(ba) def ue2bitstore(i: Union[str, int]) -> BitStore: i = int(i) if i < 0: - raise CreationError("Cannot use negative initialiser for unsigned exponential-Golomb.") + raise bitstring.CreationError("Cannot use negative initialiser for unsigned exponential-Golomb.") if i == 0: return BitStore('1') tmp = i + 1 @@ -101,7 +97,7 @@ def se2bitstore(i: Union[str, int]) -> BitStore: def uie2bitstore(i: Union[str, int]) -> BitStore: i = int(i) if i < 0: - raise CreationError("Cannot use negative initialiser for unsigned interleaved exponential-Golomb.") + raise bitstring.CreationError("Cannot use negative initialiser for unsigned interleaved exponential-Golomb.") return BitStore('1' if i == 0 else '0' + '0'.join(bin(i + 1)[3:]) + '1') @@ -135,13 +131,13 @@ def bfloatle2bitstore(f: Union[str, float]) -> BitStore: def e4m3float2bitstore(f: Union[str, float]) -> BitStore: f = float(f) - u = e4m3float_fmt.float_to_int8(f) + u = bitstring.fp8.e4m3float_fmt.float_to_int8(f) return uint2bitstore(u, 8) def e5m2float2bitstore(f: Union[str, float]) -> BitStore: f = float(f) - u = e5m2float_fmt.float_to_int8(f) + u = bitstring.fp8.e5m2float_fmt.float_to_int8(f) return uint2bitstore(u, 8) @@ -155,9 +151,9 @@ def uint2bitstore(uint: Union[str, int], length: int) -> BitStore: if uint >= (1 << length): msg = f"{uint} is too large an unsigned integer for a bitstring of length {length}. " \ f"The allowed range is [0, {(1 << length) - 1}]." - raise CreationError(msg) + raise bitstring.CreationError(msg) if uint < 0: - raise CreationError("uint cannot be initialised with a negative number.") + raise bitstring.CreationError("uint cannot be initialised with a negative number.") raise e return x @@ -170,7 +166,7 @@ def int2bitstore(i: Union[str, int], length: int) -> BitStore: x = BitStore(bitarray.util.int2ba(i, length=length, endian='big', signed=True)) except OverflowError as e: if i >= (1 << (length - 1)) or i < -(1 << (length - 1)): - raise CreationError(f"{i} is too large a signed integer for a bitstring of length {length}. " + raise bitstring.CreationError(f"{i} is too large a signed integer for a bitstring of length {length}. " f"The allowed range is [{-(1 << (length - 1))}, {(1 << (length - 1)) - 1}].") else: raise e @@ -179,26 +175,26 @@ def int2bitstore(i: Union[str, int], length: int) -> BitStore: def uintbe2bitstore(i: Union[str, int], length: int) -> BitStore: if length % 8 != 0: - raise CreationError(f"Big-endian integers must be whole-byte. Length = {length} bits.") + raise bitstring.CreationError(f"Big-endian integers must be whole-byte. Length = {length} bits.") return uint2bitstore(i, length) def intbe2bitstore(i: int, length: int) -> BitStore: if length % 8 != 0: - raise CreationError(f"Big-endian integers must be whole-byte. Length = {length} bits.") + raise bitstring.CreationError(f"Big-endian integers must be whole-byte. Length = {length} bits.") return int2bitstore(i, length) def uintle2bitstore(i: int, length: int) -> BitStore: if length % 8 != 0: - raise CreationError(f"Little-endian integers must be whole-byte. Length = {length} bits.") + raise bitstring.CreationError(f"Little-endian integers must be whole-byte. Length = {length} bits.") x = uint2bitstore(i, length).tobytes() return BitStore(frombytes=x[::-1]) def intle2bitstore(i: int, length: int) -> BitStore: if length % 8 != 0: - raise CreationError(f"Little-endian integers must be whole-byte. Length = {length} bits.") + raise bitstring.CreationError(f"Little-endian integers must be whole-byte. Length = {length} bits.") x = int2bitstore(i, length).tobytes() return BitStore(frombytes=x[::-1]) @@ -253,7 +249,7 @@ def bitstore_from_token(name: str, token_length: Optional[int], value: Optional[ if name in literal_bit_funcs: bs = literal_bit_funcs[name](value) else: - raise CreationError(f"Can't parse token: {e}") + raise bitstring.CreationError(f"Can't parse token: {e}") else: b = bitstring.bits.Bits() if value is None and name != 'pad': @@ -262,6 +258,6 @@ def bitstore_from_token(name: str, token_length: Optional[int], value: Optional[ d.set_fn(b, value) bs = b._bitstore if token_length is not None and len(bs) != d.bitlength: - raise CreationError(f"Token with length {token_length} packed with value of length {len(bs)} " + raise bitstring.CreationError(f"Token with length {token_length} packed with value of length {len(bs)} " f"({name}:{token_length}={value}).") return bs diff --git a/bitstring/bitstream.py b/bitstring/bitstream.py index 96249be2..6fb460aa 100644 --- a/bitstring/bitstream.py +++ b/bitstring/bitstream.py @@ -1,9 +1,7 @@ from __future__ import annotations +import bitstring from bitstring.bits import Bits, BitsType -from bitstring.bitarray_ import BitArray -from bitstring.exceptions import ReadError, ByteAlignError, CreationError -from bitstring.dtypes import Dtype from typing import Union, List, Any, Optional, overload, TypeVar, Tuple import copy import numbers @@ -125,7 +123,7 @@ def __init__(self, auto: Optional[Union[BitsType, int]] = None, /, length: Optio if pos < 0: pos += len(self._bitstore) if pos < 0 or pos > len(self._bitstore): - raise CreationError(f"Cannot set pos to {pos} when length is {len(self._bitstore)}.") + raise bitstring.CreationError(f"Cannot set pos to {pos} when length is {len(self._bitstore)}.") self._pos = pos self._bitstore.immutable = True @@ -136,7 +134,7 @@ def _setbytepos(self, bytepos: int) -> None: def _getbytepos(self) -> int: """Return the current position in the stream in bytes. Must be byte aligned.""" if self._pos % 8: - raise ByteAlignError("Not byte aligned when using bytepos property.") + raise bitstring.ByteAlignError("Not byte aligned when using bytepos property.") return self._pos // 8 def _setbitpos(self, pos: int) -> None: @@ -201,7 +199,7 @@ def __xor__(self: TConstBitStream, bs: BitsType, /) -> TConstBitStream: s._pos = 0 return s - def __add__(self: TConstBitStream, bs: BitsType) -> TConstBitStream: + def __add__(self: TConstBitStream, bs: BitsType, /) -> TConstBitStream: """Concatenate bitstrings and return new bitstring. bs -- the bitstring to append. @@ -211,7 +209,7 @@ def __add__(self: TConstBitStream, bs: BitsType) -> TConstBitStream: s._pos = 0 return s - def append(self, bs: BitsType) -> None: + def append(self, bs: BitsType, /) -> None: """Append a bitstring to the current bitstring. bs -- The bitstring to append. @@ -230,8 +228,8 @@ def __repr__(self) -> str: """ return self._repr(self.__class__.__name__, len(self), self._bitstore.filename, self._pos) - def overwrite(self, bs: BitsType, pos: Optional[int] = None) -> None: - """Overwrite with bs at bit position pos. + def overwrite(self, bs: BitsType, /, pos: Optional[int] = None) -> None: + """Overwrite with bitstring at bit position pos. bs -- The bitstring to overwrite with. pos -- The bit position to begin overwriting from. @@ -252,7 +250,7 @@ def overwrite(self, bs: BitsType, pos: Optional[int] = None) -> None: self._overwrite(bs, pos) self._pos = pos + len(bs) - def find(self, bs: BitsType, start: Optional[int] = None, end: Optional[int] = None, + def find(self, bs: BitsType, /, start: Optional[int] = None, end: Optional[int] = None, bytealigned: Optional[bool] = None) -> Union[Tuple[int], Tuple[()]]: """Find first occurrence of substring bs. @@ -280,7 +278,7 @@ def find(self, bs: BitsType, start: Optional[int] = None, end: Optional[int] = N self._pos = p[0] return p - def rfind(self, bs: BitsType, start: Optional[int] = None, end: Optional[int] = None, + def rfind(self, bs: BitsType, /, start: Optional[int] = None, end: Optional[int] = None, bytealigned: Optional[bool] = None) -> Union[Tuple[int], Tuple[()]]: """Find final occurrence of substring bs. @@ -353,11 +351,11 @@ def read(self, fmt: Union[int, str, Dtype]) -> Union[int, float, str, Bits, bool if fmt < 0: raise ValueError("Cannot read negative amount.") if fmt > len(self) - self._pos: - raise ReadError(f"Cannot read {fmt} bits, only {len(self) - self._pos} available.") + raise bitstring.ReadError(f"Cannot read {fmt} bits, only {len(self) - self._pos} available.") bs = self._slice(self._pos, self._pos + fmt) self._pos += fmt return bs - dtype = Dtype(fmt) + dtype = bitstring.dtypes.Dtype(fmt) if dtype.bitlength is None and dtype.is_unknown_length is False: # No length specified? Try again, but read to end. bitlength = len(self) - self._pos @@ -366,7 +364,7 @@ def read(self, fmt: Union[int, str, Dtype]) -> Union[int, float, str, Bits, bool raise ValueError( f"The '{dtype.name}' type must have a bit length that is a multiple of {dtype.bits_per_item}" f" so cannot be read from the {bitlength} bits that are available.") - dtype = Dtype(fmt, items) + dtype = bitstring.dtypes.Dtype(fmt, items) if dtype.bitlength is not None: val = dtype.read_fn(self, self._pos) self._pos += dtype.bitlength @@ -375,7 +373,7 @@ def read(self, fmt: Union[int, str, Dtype]) -> Union[int, float, str, Bits, bool if self._pos > len(self): self._pos = p - raise ReadError(f"Reading off end of bitstring with fmt '{fmt}'. Only {len(self) - p} bits available.") + raise bitstring.ReadError(f"Reading off end of bitstring with fmt '{fmt}'. Only {len(self) - p} bits available.") return val def readlist(self, fmt: Union[str, List[Union[int, str]]], **kwargs) \ @@ -403,10 +401,10 @@ def readlist(self, fmt: Union[str, List[Union[int, str]]], **kwargs) \ value, self._pos = self._readlist(fmt, self._pos, **kwargs) return value - def readto(self: TConstBitStream, bs: BitsType, bytealigned: Optional[bool] = None) -> TConstBitStream: + def readto(self: TConstBitStream, bs: BitsType, /, bytealigned: Optional[bool] = None) -> TConstBitStream: """Read up to and including next occurrence of bs and return result. - bs -- The bitstring to find. An integer is not permitted. + bs -- The bitstring to find. bytealigned -- If True the bitstring will only be found on byte boundaries. @@ -420,7 +418,7 @@ def readto(self: TConstBitStream, bs: BitsType, bytealigned: Optional[bool] = No oldpos = self._pos p = self.find(bs, self._pos, bytealigned=bytealigned) if not p: - raise ReadError("Substring not found") + raise bitstring.ReadError("Substring not found") self._pos += len(bs) return self._slice(oldpos, self._pos) @@ -496,7 +494,7 @@ def bytealign(self) -> int: """) -class BitStream(ConstBitStream, BitArray): +class BitStream(ConstBitStream, bitstring.BitArray): """A container or stream holding a mutable sequence of bits Subclass of the ConstBitStream and BitArray classes. Inherits all of @@ -630,8 +628,8 @@ def __copy__(self) -> BitStream: s_copy._bitstore = self._bitstore.copy() return s_copy - def __iadd__(self, bs: BitsType) -> BitStream: - """Append bs to current bitstring. Return self. + def __iadd__(self, bs: BitsType, /) -> BitStream: + """Append to current bitstring. Return self. bs -- the bitstring to append. @@ -641,7 +639,7 @@ def __iadd__(self, bs: BitsType) -> BitStream: self._pos = len(self) return self - def prepend(self, bs: BitsType) -> None: + def prepend(self, bs: BitsType, /) -> None: """Prepend a bitstring to the current bitstring. bs -- The bitstring to prepend. @@ -651,14 +649,14 @@ def prepend(self, bs: BitsType) -> None: super().prepend(bs) self._pos = 0 - def __setitem__(self, key: Union[slice, int], value: BitsType) -> None: + def __setitem__(self, /, key: Union[slice, int], value: BitsType) -> None: length_before = len(self) super().__setitem__(key, value) if len(self) != length_before: self._pos = 0 return - def __delitem__(self, key: Union[slice, int]) -> None: + def __delitem__(self, /, key: Union[slice, int]) -> None: """Delete item or range. >>> a = BitStream('0x001122') @@ -672,8 +670,8 @@ def __delitem__(self, key: Union[slice, int]) -> None: if len(self) != length_before: self._pos = 0 - def insert(self, bs: BitsType, pos: Optional[int] = None) -> None: - """Insert bs at bit position pos. + def insert(self, bs: BitsType, /, pos: Optional[int] = None) -> None: + """Insert bitstring at bit position pos. bs -- The bitstring to insert. pos -- The bit position to insert at. diff --git a/bitstring/dtypes.py b/bitstring/dtypes.py index f6e3b6f9..869eea15 100644 --- a/bitstring/dtypes.py +++ b/bitstring/dtypes.py @@ -2,9 +2,8 @@ import functools from typing import Optional, Dict, Any, Union, Tuple -import bitstring as bs from collections.abc import Iterable -from bitstring.exceptions import ReadError, InterpretError +import bitstring CACHE_SIZE = 256 @@ -23,7 +22,7 @@ def __new__(cls, token: Union[str, Dtype, None] = None, /, length: Optional[int] def _new_from_token(cls, token: str, length: Optional[int] = None) -> Dtype: token = ''.join(token.split()) if length is None: - name, length = bs.utils.parse_name_length_token(token) + name, length = bitstring.utils.parse_name_length_token(token) else: name = token d = dtype_register.get_dtype(name, length) @@ -101,12 +100,12 @@ def __init__(self, name: str, set_fn, get_fn, return_type: Any = Any, is_signed: if len(self.fixed_length) == 1: def length_checked_get_fn(bs): if len(bs) != self.fixed_length[0]: - raise InterpretError(f"'{self.name}' dtypes must have a length of {self.fixed_length[0]}, but received a length of {len(bs)}.") + raise bitstring.InterpretError(f"'{self.name}' dtypes must have a length of {self.fixed_length[0]}, but received a length of {len(bs)}.") return get_fn(bs) else: def length_checked_get_fn(bs): if len(bs) not in self.fixed_length: - raise InterpretError(f"'{self.name}' dtypes must have one of the lengths {self.fixed_length}, but received a length of {len(bs)}.") + raise bitstring.InterpretError(f"'{self.name}' dtypes must have one of the lengths {self.fixed_length}, but received a length of {len(bs)}.") return get_fn(bs) self.get_fn = length_checked_get_fn # Interpret everything and check the length else: @@ -119,8 +118,8 @@ def length_checked_get_fn(bs): def new_get_fn(bs): try: value, length = self.read_fn(bs, 0) - except ReadError: - raise InterpretError + except bitstring.ReadError: + raise bitstring.InterpretError if length != len(bs): raise ValueError # TODO return value @@ -177,9 +176,9 @@ def add_dtype(cls, definition: DtypeDefinition): cls.names[definition.name] = definition cls._modified_flag = True if definition.get_fn is not None: - setattr(bs.bits.Bits, definition.name, property(fget=definition.get_fn, doc=f"The bitstring as {definition.description}. Read only.")) + setattr(bitstring.bits.Bits, definition.name, property(fget=definition.get_fn, doc=f"The bitstring as {definition.description}. Read only.")) if definition.set_fn is not None: - setattr(bs.bitarray_.BitArray, definition.name, property(fget=definition.get_fn, fset=definition.set_fn, doc=f"The bitstring as {definition.description}. Read and write.")) + setattr(bitstring.bitarray_.BitArray, definition.name, property(fget=definition.get_fn, fset=definition.set_fn, doc=f"The bitstring as {definition.description}. Read and write.")) @classmethod def add_dtype_alias(cls, name: str, alias: str): @@ -187,9 +186,9 @@ def add_dtype_alias(cls, name: str, alias: str): definition = cls.names[alias] cls._modified_flag = True if definition.get_fn is not None: - setattr(bs.bits.Bits, alias, property(fget=definition.get_fn, doc=f"An alias for '{name}'. Read only.")) + setattr(bitstring.bits.Bits, alias, property(fget=definition.get_fn, doc=f"An alias for '{name}'. Read only.")) if definition.set_fn is not None: - setattr(bs.bitarray_.BitArray, alias, property(fget=definition.get_fn, fset=definition.set_fn, doc=f"An alias for '{name}'. Read and write.")) + setattr(bitstring.bitarray_.BitArray, alias, property(fget=definition.get_fn, fset=definition.set_fn, doc=f"An alias for '{name}'. Read and write.")) @classmethod def get_dtype(cls, name: str, length: Optional[int]) -> Dtype: diff --git a/bitstring/exceptions.py b/bitstring/exceptions.py index 6ec0a8b4..5a5e0b85 100644 --- a/bitstring/exceptions.py +++ b/bitstring/exceptions.py @@ -10,14 +10,15 @@ def __init__(self, *params: object) -> None: class ReadError(Error, IndexError): """Reading or peeking past the end of a bitstring.""" -"""Inappropriate interpretation of binary data.""" + InterpretError = ValueError +"""Inappropriate interpretation of binary data.""" class ByteAlignError(Error): """Whole-byte position or length needed.""" -"""Inappropriate argument during bitstring creation.""" CreationError = ValueError +"""Inappropriate argument during bitstring creation.""" diff --git a/bitstring/methods.py b/bitstring/methods.py index 70e76f0f..0b94310e 100644 --- a/bitstring/methods.py +++ b/bitstring/methods.py @@ -1,18 +1,10 @@ from __future__ import annotations -from bitstring.bits import Bits -from bitstring.bitstream import BitStream -from bitstring.utils import tokenparser -from bitstring.exceptions import CreationError from typing import Union, List -from bitstring.bitstore import BitStore -from bitstring.bitstore_helpers import bitstore_from_token -from bitstring.dtypes import dtype_register -from bitstring.options import Options +import bitstring -options = Options() -def pack(fmt: Union[str, List[str]], *values, **kwargs) -> BitStream: +def pack(fmt: Union[str, List[str]], *values, **kwargs) -> bitstring.BitStream: """Pack the values according to the format string and return a new BitStream. fmt -- A single string or a list of strings with comma separated tokens @@ -52,12 +44,12 @@ def pack(fmt: Union[str, List[str]], *values, **kwargs) -> BitStream: fmt = [fmt] try: for f_item in fmt: - _, tkns = tokenparser(f_item, tuple(sorted(kwargs.keys()))) + _, tkns = bitstring.utils.tokenparser(f_item, tuple(sorted(kwargs.keys()))) tokens.extend(tkns) except ValueError as e: - raise CreationError(*e.args) + raise bitstring.CreationError(*e.args) value_iter = iter(values) - bsl: List[BitStore] = [] + bsl: List[bitstring.BitStore] = [] try: for name, length, value in tokens: # If the value is in the kwd dictionary then it takes precedence. @@ -68,7 +60,7 @@ def pack(fmt: Union[str, List[str]], *values, **kwargs) -> BitStream: length = kwargs[length] # Also if we just have a dictionary name then we want to use it if name in kwargs and length is None and value is None: - bsl.append(BitStream(kwargs[name])._bitstore) + bsl.append(bitstring.BitStream(kwargs[name])._bitstore) continue if length is not None: length = int(length) @@ -76,25 +68,25 @@ def pack(fmt: Union[str, List[str]], *values, **kwargs) -> BitStream: # Take the next value from the ones provided value = next(value_iter) if name == 'bits': - value = Bits(value) + value = bitstring.Bits(value) if length is not None and length != len(value): - raise CreationError(f"Token with length {length} packed with value of length {len(value)}.") + raise bitstring.CreationError(f"Token with length {length} packed with value of length {len(value)}.") bsl.append(value._bitstore) continue - bsl.append(bitstore_from_token(name, length, value)) + bsl.append(bitstring.bitstore_helpers.bitstore_from_token(name, length, value)) except StopIteration: - raise CreationError(f"Not enough parameters present to pack according to the " + raise bitstring.CreationError(f"Not enough parameters present to pack according to the " f"format. {len(tokens)} values are needed.") try: next(value_iter) except StopIteration: # Good, we've used up all the *values. - s = BitStream() - if options.lsb0: + s = bitstring.BitStream() + if bitstring.options.lsb0: for name, _, _ in tokens: - if name in dtype_register.unknowable_length_names(): - raise CreationError(f"Unknown length tokens ('{name}') cannot be used in lsb0 mode.") + if name in bitstring.dtypes.dtype_register.unknowable_length_names(): + raise bitstring.CreationError(f"Unknown length tokens ('{name}') cannot be used in lsb0 mode.") for b in bsl[::-1]: s._bitstore += b else: @@ -102,4 +94,4 @@ def pack(fmt: Union[str, List[str]], *values, **kwargs) -> BitStream: s._bitstore += b return s - raise CreationError(f"Too many parameters present to pack according to the format. Only {len(tokens)} values were expected.") + raise bitstring.CreationError(f"Too many parameters present to pack according to the format. Only {len(tokens)} values were expected.") diff --git a/bitstring/options.py b/bitstring/options.py index 97288b48..cb3b366c 100644 --- a/bitstring/options.py +++ b/bitstring/options.py @@ -1,8 +1,6 @@ from __future__ import annotations -import bitstring.bits -import bitstring.bitarray_ -from bitstring.bitstore import BitStore +import bitstring class Options: @@ -27,39 +25,41 @@ def lsb0(self, value: bool) -> None: def set_lsb0(self, value: bool) -> None: self._lsb0 = bool(value) - + Bits = bitstring.bits.Bits + BitArray = bitstring.bitarray_.BitArray + BitStore = bitstring.bitstore.BitStore if self._lsb0: - bitstring.bits.Bits._find = bitstring.bits.Bits._find_lsb0 # type: ignore - bitstring.bits.Bits._rfind = bitstring.bits.Bits._rfind_lsb0 # type: ignore - bitstring.bits.Bits._findall = bitstring.bits.Bits._findall_lsb0 # type: ignore + Bits._find = Bits._find_lsb0 # type: ignore + Bits._rfind = Bits._rfind_lsb0 # type: ignore + Bits._findall = Bits._findall_lsb0 # type: ignore - bitstring.bitarray_.BitArray._ror = bitstring.bitarray_.BitArray._rol_msb0 # type: ignore - bitstring.bitarray_.BitArray._rol = bitstring.bitarray_.BitArray._ror_msb0 # type: ignore - bitstring.bitarray_.BitArray._append = bitstring.bitarray_.BitArray._append_lsb0 # type: ignore + BitArray._ror = BitArray._rol_msb0 # type: ignore + BitArray._rol = BitArray._ror_msb0 # type: ignore + BitArray._append = BitArray._append_lsb0 # type: ignore # An LSB0 prepend is an MSB0 append - bitstring.bitarray_.BitArray._prepend = bitstring.bitarray_.BitArray._append_msb0 # type: ignore + BitArray._prepend = BitArray._append_msb0 # type: ignore BitStore.__setitem__ = BitStore.setitem_lsb0 # type: ignore BitStore.__delitem__ = BitStore.delitem_lsb0 # type: ignore - BitStore.getindex = BitStore.getindex_lsb0 - BitStore.getslice = BitStore.getslice_lsb0 - BitStore.getslice_withstep = BitStore.getslice_withstep_lsb0 + BitStore.getindex = BitStore.getindex_lsb0 # type: ignore + BitStore.getslice = BitStore.getslice_lsb0 # type: ignore + BitStore.getslice_withstep = BitStore.getslice_withstep_lsb0 # type: ignore BitStore.invert = BitStore.invert_lsb0 # type: ignore else: - bitstring.bits.Bits._find = bitstring.bits.Bits._find_msb0 # type: ignore - bitstring.bits.Bits._rfind = bitstring.bits.Bits._rfind_msb0 # type: ignore - bitstring.bits.Bits._findall = bitstring.bits.Bits._findall_msb0 # type: ignore + Bits._find = Bits._find_msb0 # type: ignore + Bits._rfind = Bits._rfind_msb0 # type: ignore + Bits._findall = Bits._findall_msb0 # type: ignore - bitstring.bitarray_.BitArray._ror = bitstring.bitarray_.BitArray._ror_msb0 # type: ignore - bitstring.bitarray_.BitArray._rol = bitstring.bitarray_.BitArray._rol_msb0 # type: ignore - bitstring.bitarray_.BitArray._append = bitstring.bitarray_.BitArray._append_msb0 # type: ignore - bitstring.bitarray_.BitArray._prepend = bitstring.bitarray_.BitArray._append_lsb0 # type: ignore + BitArray._ror = BitArray._ror_msb0 # type: ignore + BitArray._rol = BitArray._rol_msb0 # type: ignore + BitArray._append = BitArray._append_msb0 # type: ignore + BitArray._prepend = BitArray._append_lsb0 # type: ignore BitStore.__setitem__ = BitStore.setitem_msb0 # type: ignore BitStore.__delitem__ = BitStore.delitem_msb0 # type: ignore - BitStore.getindex = BitStore.getindex_msb0 - BitStore.getslice = BitStore.getslice_msb0 - BitStore.getslice_withstep = BitStore.getslice_withstep_msb0 + BitStore.getindex = BitStore.getindex_msb0 # type: ignore + BitStore.getslice = BitStore.getslice_msb0 # type: ignore + BitStore.getslice_withstep = BitStore.getslice_withstep_msb0 # type: ignore BitStore.invert = BitStore.invert_msb0 # type: ignore @property diff --git a/bitstring/utils.py b/bitstring/utils.py index e8827d83..52e0c3e0 100644 --- a/bitstring/utils.py +++ b/bitstring/utils.py @@ -1,9 +1,8 @@ from __future__ import annotations + import functools import re from typing import Tuple, List, Optional, Pattern, Dict, Union, Match -import sys -byteorder: str = sys.byteorder # A token name followed by optional : then an integer number