pax_global_header00006660000000000000000000000064145316763360014530gustar00rootroot0000000000000052 comment=bf0d6e46dec489078b9ef19502245c9ddc153bf1 bitstring-bitstring-4.1.4/000077500000000000000000000000001453167633600155465ustar00rootroot00000000000000bitstring-bitstring-4.1.4/.github/000077500000000000000000000000001453167633600171065ustar00rootroot00000000000000bitstring-bitstring-4.1.4/.github/workflows/000077500000000000000000000000001453167633600211435ustar00rootroot00000000000000bitstring-bitstring-4.1.4/.github/workflows/ci.yml000066400000000000000000000114741453167633600222700ustar00rootroot00000000000000name: CI on: push: branches: - stable - main - 4.1-update tags: - v* pull_request: branches: - '**' concurrency: group: ${{ github.ref }}-${{ github.workflow }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/main' && github.sha || '' }} cancel-in-progress: true defaults: run: shell: bash jobs: build: name: Build ${{ matrix.os.name }} ${{ matrix.python.name }} runs-on: ${{ matrix.os.runs-on }} strategy: fail-fast: false matrix: os: - name: 🐧 runs-on: ubuntu-latest python: - name: CPython 3.10 major_dot_minor: '3.10' action: '3.10' steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: # This allows the matrix to specify just the major.minor version while still # expanding it to get the latest patch version including alpha releases. # This avoids the need to update for each new alpha, beta, release candidate, # and then finally an actual release version. actions/setup-python doesn't # support this for PyPy presently so we get no help there. # # CPython -> 3.9.0-alpha - 3.9.X # PyPy -> pypy-3.7 python-version: ${{ fromJSON(format('["{0}", "{1}"]', format('{0}.0-alpha - {0}.X', matrix.python.action), matrix.python.action))[startsWith(matrix.python.action, 'pypy')] }} architecture: x64 - name: Setup environment run: | python -m pip install --upgrade pip python -m pip install build - name: Build sdist and wheel run: | python -m build - name: Publish package files if: always() uses: actions/upload-artifact@v3 with: name: packages path: dist/* if-no-files-found: error test: name: Test ${{ matrix.os.name }} ${{ matrix.python.name }} needs: - build runs-on: ${{ matrix.os.runs-on }} strategy: fail-fast: false matrix: os: - name: 🐧 runs-on: ubuntu-latest - name: 🍎 runs-on: macos-latest - name: 🪟 runs-on: windows-latest python: - name: CPython 3.7 major_dot_minor: '3.7' action: '3.7' - name: CPython 3.8 major_dot_minor: '3.8' action: '3.8' - name: CPython 3.9 major_dot_minor: '3.9' action: '3.9' - name: CPython 3.10 major_dot_minor: '3.10' action: '3.10' - name: CPython 3.11 major_dot_minor: '3.11' action: '3.11' # Failing due to error using temporary file in a unittest. I think it's a PyPy bug, not a bitstring one! # - name: PyPy 3.7 # major_dot_minor: '3.7' # action: 'pypy-3.7' # - name: PyPy 3.8 # major_dot_minor: '3.8' # action: 'pypy-3.8' steps: - uses: actions/checkout@v3 with: path: repo - name: Download package files uses: actions/download-artifact@v3 with: name: packages path: dist - uses: actions/setup-python@v4 with: # This allows the matrix to specify just the major.minor version while still # expanding it to get the latest patch version including alpha releases. # This avoids the need to update for each new alpha, beta, release candidate, # and then finally an actual release version. actions/setup-python doesn't # support this for PyPy presently so we get no help there. # # CPython -> 3.9.0-alpha - 3.9.X # PyPy -> pypy-3.7 python-version: ${{ fromJSON(format('["{0}", "{1}"]', format('{0}.0-alpha - {0}.X', matrix.python.action), matrix.python.action))[startsWith(matrix.python.action, 'pypy')] }} architecture: x64 - name: Setup environment run: | python --version --version # make sure we test the installed code cp -R repo/tests/ tests/ python -m pip install --upgrade pip python -m pip install ./dist/*.whl # show the directory contents for diagnostics ls -la - name: Run unittest run: | python -m unittest all: name: All successful runs-on: ubuntu-latest # The always() part is very important. # If not set, the job will be skipped on failing dependencies. if: always() needs: # This is the list of CI job that we are interested to be green before # a merge. - build - test steps: - name: Require all successes uses: re-actors/alls-green@v1.2.2 with: jobs: ${{ toJSON(needs) }} bitstring-bitstring-4.1.4/.gitignore000066400000000000000000000000651453167633600175370ustar00rootroot00000000000000venv .git *cache* .idea build dist manifest *egg-infobitstring-bitstring-4.1.4/.readthedocs.yaml000066400000000000000000000013011453167633600207700ustar00rootroot00000000000000# .readthedocs.yaml # Read the Docs configuration file # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details # Required version: 2 # Set the version of Python and other tools you might need build: os: ubuntu-22.04 tools: python: "3.11" # You can also specify other tool versions: # nodejs: "16" # rust: "1.55" # golang: "1.17" # Build documentation in the docs/ directory with Sphinx sphinx: configuration: doc/conf.py # If using Sphinx, optionally build your docs in additional formats such as PDF #formats: # - pdf # Optionally declare the Python requirements required to build your docs python: install: - requirements: doc/requirements.txtbitstring-bitstring-4.1.4/LICENSE000066400000000000000000000021221453167633600165500ustar00rootroot00000000000000The MIT License Copyright (c) 2006 Scott Griffiths (dr.scottgriffiths@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. bitstring-bitstring-4.1.4/MANIFEST.in000066400000000000000000000002561453167633600173070ustar00rootroot00000000000000include tests/test.m1v include tests/smalltestfile include tests/__init__.py include release_notes.txt include README.md include bitstring/py.typed prune doc include LICENSE bitstring-bitstring-4.1.4/README.md000066400000000000000000000111341453167633600170250ustar00rootroot00000000000000 ![bitstring](https://raw.githubusercontent.com/scott-griffiths/bitstring/main/doc/bitstring_logo_small.png "bitstring") **bitstring** is a Python module to help make the creation and analysis of binary data as simple and efficient as possible. It has been maintained since 2006 and now has many millions of downloads per year. [![CI badge](https://github.com/scott-griffiths/bitstring/actions/workflows/.github/workflows/ci.yml/badge.svg)](https://github.com/scott-griffiths/bitstring/actions/workflows/ci.yml) [![Docs](https://img.shields.io/readthedocs/bitstring)](https://bitstring.readthedocs.io/en/latest/) [![Codacy Badge](https://img.shields.io/codacy/grade/8869499b2eed44548fa1a5149dd451f4)](https://app.codacy.com/gh/scott-griffiths/bitstring/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) [![Downloads](https://img.shields.io/pypi/dm/bitstring?color=blue)](https://pypistats.org/packages/bitstring)     [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/scott-griffiths/bitstring/main?labpath=doc%2Fwalkthrough.ipynb) News ---- **November 2023**: bitstring 4.1.3 released. Version 4.1 is a large update in terms of how much of the code has changed. * Speed increased with bitarray dependency. * New Array class for homogeneous data. * Support for 8-bit floating point values. See the [release notes](https://github.com/scott-griffiths/bitstring/blob/main/release_notes.txt) for details. Please let me know if you encounter any problems. Overview -------- * Efficiently store and manipulate binary data in idiomatic Python. * Create bitstrings from hex, octal, binary, files, formatted strings, bytes, integers and floats of different endiannesses. * Powerful binary packing and unpacking functions. * Bit-level slicing, joining, searching, replacing and more. * Create and manipulate arrays of fixed-length bitstrings. * Read from and interpret bitstrings as streams of binary data. * Rich API - chances are that whatever you want to do there's a simple and elegant way of doing it. * Open source software, released under the MIT licence. Documentation ------------- Extensive documentation for the bitstring module is available. Some starting points are given below: * [Overview](https://bitstring.readthedocs.io/en/stable/index.html) * [Quick Reference](https://bitstring.readthedocs.io/en/stable/quick_reference.html) * [Full Reference](https://bitstring.readthedocs.io/en/stable/reference.html) You can also try out the interactive walkthrough notebook on [binder](https://mybinder.org/v2/gh/scott-griffiths/bitstring/main?labpath=doc%2Fwalkthrough.ipynb). Release Notes ------------- To see what been added, improved or fixed, and also to see what's coming in the next version, see the [release notes](https://github.com/scott-griffiths/bitstring/blob/main/release_notes.txt). Examples -------- ### Installation $ pip install bitstring ### Creation >>> from bitstring import Bits, BitArray, BitStream, pack >>> a = BitArray(bin='00101') >>> b = Bits(a_file_object) >>> c = BitArray('0xff, 0b101, 0o65, uint6=22') >>> d = pack('intle16, hex=a, 0b1', 100, a='0x34f') >>> e = pack('<16h', *range(16)) ### Different interpretations, slicing and concatenation >>> a = BitArray('0x3348') >>> a.hex, a.bin, a.uint, a.float, a.bytes ('3348', '0011001101001000', 13128, 0.2275390625, b'3H') >>> a[10:3:-1].bin '0101100' >>> '0b100' + 3*a BitArray('0x866906690669, 0b000') ### Reading data sequentially >>> b = BitStream('0x160120f') >>> b.read(12).hex '160' >>> b.pos = 0 >>> b.read('uint12') 352 >>> b.readlist('uint12, bin3') [288, '111'] ### Searching, inserting and deleting >>> c = BitArray('0b00010010010010001111') # c.hex == '0x1248f' >>> c.find('0x48') (8,) >>> c.replace('0b001', '0xabc') >>> c.insert('0b0000', pos=3) >>> del c[12:16] ### Arrays of fixed-length formats >>> from bitstring import Array >>> a = Array('uint7', [9, 100, 3, 1]) >>> a.data BitArray('0x1390181') >>> a[::2] *= 5 >>> a Array('uint7', [45, 100, 15, 1]) Unit Tests ---------- The 700+ unit tests should all pass. They can be run from the root of the project with python -m unittest Credits ------- Created by Scott Griffiths in 2006 to help with ad hoc parsing and creation of compressed video files. Maintained and expanded ever since as it became unexpectedly popular. Thanks to all those who have contributed ideas and code (and bug reports) over the years. Copyright (c) 2006 - 2023 Scott Griffiths bitstring-bitstring-4.1.4/bitstring/000077500000000000000000000000001453167633600175535ustar00rootroot00000000000000bitstring-bitstring-4.1.4/bitstring/__init__.py000066400000000000000000000220701453167633600216650ustar00rootroot00000000000000#!/usr/bin/env python r""" This package defines classes that simplify bit-wise creation, manipulation and interpretation of data. Classes: Bits -- An immutable container for binary data. BitArray -- A mutable container for binary data. ConstBitStream -- An immutable container with streaming methods. BitStream -- A mutable container with streaming methods. Array -- An efficient list-like container where each item has a fixed-length binary format. Functions: pack -- Create a BitStream from a format string. Module Properties: bytealigned -- Determines whether a number of methods default to working only on byte boundaries. lsb0 -- If True, the least significant bit (the final bit) is indexed as bit zero. Exceptions: Error -- Module exception base class. CreationError -- Error during creation. InterpretError -- Inappropriate interpretation of binary data. ByteAlignError -- Whole byte position or length needed. ReadError -- Reading or peeking past the end of a bitstring. https://github.com/scott-griffiths/bitstring """ __licence__ = """ The MIT License Copyright (c) 2006 Scott Griffiths (dr.scottgriffiths@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ __version__ = "4.1.4" __author__ = "Scott Griffiths" import sys from .bits import Bits from .options import Options from .bitarray import BitArray from .bitstream import ConstBitStream, BitStream from .methods import pack from .array_ import Array from .exceptions import Error, ReadError, InterpretError, ByteAlignError, CreationError from .dtypes import MetaDtype, Register import types from typing import List, Tuple from .utils import initialise_constants # We initialise the Options singleton after the base classes have been created. # This avoids a nasty circular import. options = Options() Bits._initialise_options() # These get defined properly by the module magic below. This just stops mypy complaining about them. bytealigned = lsb0 = None # An opaque way of adding module level properties. Taken from https://peps.python.org/pep-0549/ class _MyModuleType(types.ModuleType): @property def bytealigned(self) -> bool: """Determines whether a number of methods default to working only on byte boundaries.""" return options.bytealigned @bytealigned.setter def bytealigned(self, value: bool) -> None: """Determines whether a number of methods default to working only on byte boundaries.""" options.bytealigned = value @property def lsb0(self) -> bool: """If True, the least significant bit (the final bit) is indexed as bit zero.""" return options.lsb0 @lsb0.setter def lsb0(self, value: bool) -> None: """If True, the least significant bit (the final bit) is indexed as bit zero.""" options.lsb0 = value sys.modules[__name__].__class__ = _MyModuleType dtypes = [ MetaDtype('uint', "a two's complement unsigned int", Bits._setuint, Bits._readuint, Bits._getuint, True, False, False, False, None), MetaDtype('uintle', "a two's complement little-endian unsigned int", Bits._setuintle, Bits._readuintle, Bits._getuintle, True, False, False, False, None), MetaDtype('uintne', "a two's complement native-endian unsigned int", Bits._setuintne, Bits._readuintne, Bits._getuintne, True, False, False, False, None), MetaDtype('uintbe', "a two's complement big-endian unsigned int", Bits._setuintbe, Bits._readuintbe, Bits._getuintbe, True, False, False, False, None), MetaDtype('int', "a two's complement signed int", Bits._setint, Bits._readint, Bits._getint,True, False, True, False, None), MetaDtype('intle', "a two's complement little-endian signed int", Bits._setintle, Bits._readintle, Bits._getintle, True, False, True, False, None), MetaDtype('intne', "a two's complement native-endian signed int", Bits._setintne, Bits._readintne, Bits._getintne, True, False, True, False, None), MetaDtype('intbe', "a two's complement big-endian signed int", Bits._setintbe, Bits._readintbe, Bits._getintbe, True, False, True, False, None), MetaDtype('hex', 'a hexadecimal string', Bits._sethex, Bits._readhex, Bits._gethex, False, False, False, False, None), MetaDtype('bin', 'a binary string', Bits._setbin_safe, Bits._readbin, Bits._getbin, False, False, False, False, None), MetaDtype('oct', 'an octal string', Bits._setoct, Bits._readoct, Bits._getoct,False, False, False, False, None), MetaDtype('e5m2float', 'an 8 bit float with e5m2float format', Bits._sete5m2float, Bits._reade5m2float, Bits._gete5m2float, False, True, True, False, 8), MetaDtype('e4m3float', 'an 8 bit float with e4m3float format', Bits._sete4m3float, Bits._reade4m3float, Bits._gete4m3float, False, True, True, False, 8), MetaDtype('float', 'a big-endian floating point number', Bits._setfloatbe, Bits._readfloatbe, Bits._getfloatbe, False, True, True, False, None), MetaDtype('floatne', 'a native-endian floating point number', Bits._setfloatne, Bits._readfloatne, Bits._getfloatne, False, True, True, False, None), MetaDtype('floatle', 'a little-endian floating point number', Bits._setfloatle, Bits._readfloatle, Bits._getfloatle, False, True, True, False, None), MetaDtype('bfloat', 'a 16 bit big-endian bfloat floating point number', Bits._setbfloatbe, Bits._readbfloatbe, Bits._getbfloatbe, False, True, True, False, 16), MetaDtype('bfloatle', 'a 16 bit little-endian bfloat floating point number', Bits._setbfloatle, Bits._readbfloatle, Bits._getbfloatle, False, True, True, False, 16), MetaDtype('bfloatne', 'a 16 bit native-endian bfloat floating point number', Bits._setbfloatne, Bits._readbfloatne, Bits._getbfloatne, False, True, True, False, 16), MetaDtype('bits', 'a bitstring object', Bits._setbits, Bits._readbits, None, False, False, False, False, None), MetaDtype('bytes', 'a bytes object', Bits._setbytes, Bits._readbytes, Bits._getbytes,False, False, False, False, None), MetaDtype('bool', 'a bool (True or False)', Bits._setbool, Bits._readbool, Bits._getbool, True, False, False, False, 1), MetaDtype('se', 'a signed exponential-Golomb code', Bits._setse, Bits._readse, Bits._getse,True, False, True, True, None), MetaDtype('ue', 'an unsigned exponential-Golomb code', Bits._setue, Bits._readue, Bits._getue, True, False, False, True, None), MetaDtype('sie', 'a signed interleaved exponential-Golomb code', Bits._setsie, Bits._readsie, Bits._getsie, True, False, True, True, None), MetaDtype('uie', 'an unsigned interleaved exponential-Golomb code', Bits._setuie, Bits._readuie, Bits._getuie, True, False, False, True, None), MetaDtype('pad', 'a skipped section of padding', None, Bits._readpad, None, False, False, False, False, None), ] aliases: List[Tuple[str, str]] = [ ('float', 'floatbe'), ('bfloat', 'bfloatbe'), ('int', 'i'), ('uint', 'u'), ('hex', 'h'), ('oct', 'o'), ('bin', 'b'), ('float', 'f') ] register = Register() for dt in dtypes: register.add_meta_dtype(dt) for alias in aliases: register.add_meta_dtype_alias(alias[0], alias[1]) # Create properties for those meta dtypes that have a 'get' function. for dt_name in register.name_to_meta_dtype: dt = register.name_to_meta_dtype[dt_name] if dt.get_fn is not None: setattr(Bits, dt_name, property(fget=dt.get_fn, doc=f"The bitstring as {dt.description}. Read only.")) setattr(BitArray, dt_name, property(fget=dt.get_fn, fset=dt.set_fn, doc=f"The bitstring as {dt.description}. Read and write.")) init_names = [dt_name for dt_name in register.name_to_meta_dtype] unknowable_length_names = register.unknowable_length_names() initialise_constants(init_names, unknowable_length_names) __all__ = ['ConstBitStream', 'BitStream', 'BitArray', 'Array', 'Bits', 'pack', 'Error', 'ReadError', 'InterpretError', 'ByteAlignError', 'CreationError', 'bytealigned', 'lsb0'] bitstring-bitstring-4.1.4/bitstring/__main__.py000066400000000000000000000032231453167633600216450ustar00rootroot00000000000000import sys from bitstring.bits import Bits from bitstring.dtypes import Register dtype_register = Register() def main() -> None: # check if final parameter is an interpretation string fp = sys.argv[-1] if fp in ['-h', '--help'] or len(sys.argv) == 1: print("""Create and interpret a bitstring from command-line parameters. Command-line parameters are concatenated and a bitstring created from them. If the final parameter is either an interpretation string or ends with a '.' followed by an interpretation string then that interpretation of the bitstring will be used when printing it. Typical usage might be invoking the Python module from a console as a one-off calculation: $ python -m bitstring int:16=-400 0xfe70 $ python -m bitstring float:32=0.2 bin 00111110010011001100110011001101 $ python -m bitstring 0xff 3*0b01,0b11 uint 65367 $ python -m bitstring hex=01, uint:12=352.hex 01160 """) return if fp in dtype_register.name_to_meta_dtype: # concatenate all other parameters and interpret using the final one b1 = Bits(','.join(sys.argv[1: -1])) print(b1._readtoken(fp, 0, b1.__len__())[0]) else: # does final parameter end with a dot then an interpretation string? interp = fp[fp.rfind('.') + 1:] if interp in dtype_register.name_to_meta_dtype: sys.argv[-1] = fp[:fp.rfind('.')] b1 = Bits(','.join(sys.argv[1:])) print(b1._readtoken(interp, 0, b1.__len__())[0]) else: # No interpretation - just use default print b1 = Bits(','.join(sys.argv[1:])) print(b1) if __name__ == '__main__': main()bitstring-bitstring-4.1.4/bitstring/array_.py000066400000000000000000001014471453167633600214110ustar00rootroot00000000000000from __future__ import annotations import math import numbers from collections.abc import Sized from bitstring.exceptions import CreationError, InterpretError from typing import Union, List, Iterable, Any, Optional, BinaryIO, overload, TextIO from bitstring.bits import Bits, BitsType from bitstring.bitarray import BitArray from bitstring.dtypes import Dtype, Register from bitstring.utils import tokenparser, parse_name_length_token import copy import array import operator import io import sys # The possible types stored in each element of the Array ElementType = Union[float, str, int, bytes, bool, Bits] dtype_register = Register() class Array: """Return an Array whose elements are initialised according to the fmt string. The dtype string can be typecode as used in the struct module or any fixed-length bitstring format. a = Array('>H', [1, 15, 105]) b = Array('int5', [-9, 0, 4]) The Array data is stored compactly as a BitArray object and the Array behaves very like a list of items of the given format. Both the Array data and fmt properties can be freely modified after creation. If the data length is not a multiple of the fmt length then the Array will have 'trailing_bits' which will prevent some methods from appending to the Array. Methods: append() -- Append a single item to the end of the Array. byteswap() -- Change byte endianness of all items. count() -- Count the number of occurences of a value. extend() -- Append new items to the end of the Array from an iterable. fromfile() -- Append items read from a file object. insert() -- Insert an item at a given position. pop() -- Remove and return an item. pp() -- Pretty print the Array. reverse() -- Reverse the order of all items. tobytes() -- Return Array data as bytes object, padding with zero bits at the end if needed. tofile() -- Write Array data to a file, padding with zero bits at the end if needed. tolist() -- Return Array items as a list. Special methods: Also available are the operators [], ==, !=, +, *, <<, >>, &, |, ^, plus the mutating operators [], +=, *=, <<=, >>=, &=, |=, ^=. Properties: data -- The BitArray binary data of the Array. Can be freely modified. dtype -- The format string or typecode. Can be freely modified. itemsize -- The length *in bits* of a single item. Read only. trailing_bits -- If the data length is not a multiple of the fmt length, this BitArray gives the leftovers at the end of the data. """ def __init__(self, dtype: Union[str, Dtype], initializer: Optional[Union[int, Array, array.array, Iterable, Bits, bytes, bytearray, memoryview, BinaryIO]] = None, trailing_bits: Optional[BitsType] = None) -> None: self.data = BitArray() try: self.dtype = dtype except ValueError as e: raise CreationError(e) if isinstance(initializer, numbers.Integral): self.data = BitArray(initializer * self._dtype.length) elif isinstance(initializer, (Bits, bytes, bytearray, memoryview)): self.data += initializer elif isinstance(initializer, io.BufferedReader): self.fromfile(initializer) elif initializer is not None: self.extend(initializer) if trailing_bits is not None: self.data += BitArray._create_from_bitstype(trailing_bits) @property def itemsize(self) -> int: return self._dtype.length @property def trailing_bits(self) -> BitArray: trailing_bit_length = len(self.data) % self._dtype.length return BitArray() if trailing_bit_length == 0 else self.data[-trailing_bit_length:] # Converting array.array typecodes to our equivalents. _array_typecodes: dict[str, str] = {'b': 'int8', 'B': 'uint8', 'h': 'intne16', 'H': 'uintne16', 'l': 'intne32', 'L': 'uintne32', 'q': 'intne64', 'Q': 'uintne64', 'e': 'floatne16', 'f': 'floatne32', 'd': 'floatne64'} @property def dtype(self) -> str: return self._fmt @dtype.setter def dtype(self, new_dtype: Union[str, Dtype]) -> None: if isinstance(new_dtype, Dtype): self._dtype = new_dtype self._fmt = str(self._dtype) else: dtype = dtype_register.get_dtype(*parse_name_length_token(new_dtype)) if dtype.length == 0: raise ValueError(f"A fixed length format is needed for an Array, received '{new_dtype}'.") self._dtype = dtype self._fmt = new_dtype def _create_element(self, value: ElementType) -> Bits: """Create Bits from value according to the token_name and token_length""" b = Bits() self._dtype.set_fn(b, value) if len(b) != self._dtype.length: raise ValueError(f"The value {value!r} has the wrong length for the format '{self._fmt}'.") return b def __len__(self) -> int: return len(self.data) // self._dtype.length @overload def __getitem__(self, key: slice) -> Array: ... @overload def __getitem__(self, key: int) -> ElementType: ... def __getitem__(self, key: Union[slice, int]) -> Union[Array, ElementType]: if isinstance(key, slice): start, stop, step = key.indices(len(self)) if step != 1: d = BitArray() for s in range(start * self._dtype.length, stop * self._dtype.length, step * self._dtype.length): d.append(self.data[s: s + self._dtype.length]) a = Array(self._dtype) a.data = d return a else: a = Array(self._dtype) a.data = self.data[start * self._dtype.length: stop * self._dtype.length] return a else: if key < 0: key += len(self) if key < 0 or key >= len(self): raise IndexError(f"Index {key} out of range for Array of length {len(self)}.") return self._dtype.read_fn(self.data, start=self._dtype.length * key) @overload def __setitem__(self, key: slice, value: Iterable[ElementType]) -> None: ... @overload def __setitem__(self, key: int, value: ElementType) -> None: ... def __setitem__(self, key: Union[slice, int], value: Union[Iterable[ElementType], ElementType]) -> None: if isinstance(key, slice): start, stop, step = key.indices(len(self)) if not isinstance(value, Iterable): raise TypeError("Can only assign an iterable to a slice.") if step == 1: new_data = BitArray() for x in value: new_data += self._create_element(x) self.data[start * self._dtype.length: stop * self._dtype.length] = new_data return items_in_slice = len(range(start, stop, step)) if not isinstance(value, Sized): value = list(value) if len(value) == items_in_slice: for s, v in zip(range(start, stop, step), value): self.data.overwrite(self._create_element(v), s * self._dtype.length) else: raise ValueError(f"Can't assign {len(value)} values to an extended slice of length {stop - start}.") else: if key < 0: key += len(self) if key < 0 or key >= len(self): raise IndexError(f"Index {key} out of range for Array of length {len(self)}.") start = self._dtype.length * key self.data.overwrite(self._create_element(value), start) return def __delitem__(self, key: Union[slice, int]) -> None: if isinstance(key, slice): start, stop, step = key.indices(len(self)) if step == 1: self.data.__delitem__(slice(start * self._dtype.length, stop * self._dtype.length)) return # We need to delete from the end or the earlier positions will change r = reversed(range(start, stop, step)) if step > 0 else range(start, stop, step) for s in r: self.data.__delitem__(slice(s * self._dtype.length, (s + 1) * self._dtype.length)) else: if key < 0: key += len(self) if key < 0 or key >= len(self): raise IndexError start = self._dtype.length * key del self.data[start: start + self._dtype.length] def __repr__(self) -> str: list_str = f"{self.tolist()}" trailing_bit_length = len(self.data) % self._dtype.length final_str = "" if trailing_bit_length == 0 else ", trailing_bits=" + repr( self.data[-trailing_bit_length:]) return f"Array('{self._fmt}', {list_str}{final_str})" def astype(self, dtype: Union[str, Dtype]) -> Array: """Return Array with elements of new dtype, initialised from current Array.""" new_array = Array(dtype, self.tolist()) return new_array def tolist(self) -> List[ElementType]: return [self._dtype.read_fn(self.data, start=start) for start in range(0, len(self.data) - self._dtype.length + 1, self._dtype.length)] def append(self, x: ElementType) -> None: if len(self.data) % self._dtype.length != 0: raise ValueError("Cannot append to Array as its length is not a multiple of the format length.") self.data += self._create_element(x) def extend(self, iterable: Union[Array, array.array, Iterable]) -> None: if len(self.data) % self._dtype.length != 0: raise ValueError(f"Cannot extend Array as its data length ({len(self.data)} bits) is not a multiple of the format length ({self._dtype.length} bits).") if isinstance(iterable, Array): if self._dtype.name != iterable._dtype.name or self._dtype.length != iterable._dtype.length: raise TypeError( f"Cannot extend an Array with format '{self._fmt}' from an Array of format '{iterable._fmt}'.") # No need to iterate over the elements, we can just append the data self.data.append(iterable.data) elif isinstance(iterable, array.array): other_fmt = Array._array_typecodes.get(iterable.typecode, iterable.typecode) token_name, token_length, _ = tokenparser(other_fmt)[1][0] if self._dtype.name != token_name or self._dtype.length != token_length: raise ValueError( f"Cannot extend an Array with format '{self._fmt}' from an array with typecode '{iterable.typecode}'.") self.data += iterable.tobytes() else: if isinstance(iterable, str): raise TypeError("Can't extend an Array with a str.") for item in iterable: self.data += self._create_element(item) def insert(self, i: int, x: ElementType) -> None: """Insert a new element into the Array at position i. """ i = min(i, len(self)) # Inserting beyond len of array inserts at the end (copying standard behaviour) self.data.insert(self._create_element(x), i * self._dtype.length) def pop(self, i: int = -1) -> ElementType: """Return and remove an element of the Array. Default is to return and remove the final element. """ if len(self) == 0: raise IndexError("Can't pop from an empty Array.") x = self[i] del self[i] return x def byteswap(self) -> None: """Change the endianness in-place of all items in the Array. If the Array format is not a whole number of bytes a ValueError will be raised. """ if self._dtype.length % 8 != 0: raise ValueError( f"byteswap can only be used for whole-byte elements. The '{self._fmt}' format is {self._dtype.length} bits long.") self.data.byteswap(self.itemsize // 8) def count(self, value: ElementType) -> int: """Return count of Array items that equal value. value -- The quantity to compare each Array element to. Type should be appropriate for the Array format. For floating point types using a value of float('nan') will count the number of elements that are NaN. """ if math.isnan(value): return sum(math.isnan(i) for i in self) else: return sum(i == value for i in self) def tobytes(self) -> bytes: """Return the Array data as a bytes object, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align. """ return self.data.tobytes() def tofile(self, f: BinaryIO) -> None: """Write the Array data to a file object, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align. """ self.data.tofile(f) def fromfile(self, f: BinaryIO, n: Optional[int] = None) -> None: trailing_bit_length = len(self.data) % self._dtype.length if trailing_bit_length != 0: raise ValueError(f"Cannot extend Array as its data length ({len(self.data)} bits) is not a multiple of the format length ({self._dtype.length} bits).") new_data = Bits(f) max_items = len(new_data) // self._dtype.length items_to_append = max_items if n is None else min(n, max_items) self.data += new_data[0: items_to_append * self._dtype.length] if n is not None and items_to_append < n: raise EOFError(f"Only {items_to_append} were appended, not the {n} items requested.") def reverse(self) -> None: trailing_bit_length = len(self.data) % self._dtype.length if trailing_bit_length != 0: raise ValueError(f"Cannot reverse the items in the Array as its data length ({len(self.data)} bits) is not a multiple of the format length ({self._dtype.length} bits).") for start_bit in range(0, len(self.data) // 2, self._dtype.length): start_swap_bit = len(self.data) - start_bit - self._dtype.length temp = self.data[start_bit: start_bit + self._dtype.length] self.data[start_bit: start_bit + self._dtype.length] = self.data[ start_swap_bit: start_swap_bit + self._dtype.length] self.data[start_swap_bit: start_swap_bit + self._dtype.length] = temp def pp(self, fmt: Optional[str] = None, width: int = 120, show_offset: bool = False, stream: TextIO = sys.stdout) -> None: """Pretty-print the Array contents. fmt -- Data format string. Defaults to current Array dtype. width -- Max width of printed lines in characters. Defaults to 120. A single group will always be printed per line even if it exceeds the max width. show_offset -- If True shows the element offset in the first column of each line. stream -- A TextIO object with a write() method. Defaults to sys.stdout. """ sep = ' ' fmt_is_dtype = False if fmt is None: fmt = self.dtype fmt_is_dtype = True tokens = tokenparser(fmt)[1] token_names_and_lengths = [(x[0], x[1]) for x in tokens] if len(token_names_and_lengths) not in [1, 2]: raise ValueError( f"Only one or two tokens can be used in an Array.pp() format - '{fmt}' has {len(token_names_and_lengths)} tokens.") token_name, token_length = token_names_and_lengths[0] token_name2, token_length2 = None, None getter_func2 = None if len(token_names_and_lengths) == 1: if token_length is None: token_length = self.itemsize fmt += str(token_length) if len(token_names_and_lengths) == 2: token_name2, token_length2 = token_names_and_lengths[1] if token_length is None and token_length2 is None: token_length = token_length2 = self.itemsize fmt += str(token_length) if token_length is None: token_length = token_length2 if token_length2 is None: token_length2 = token_length if token_length != token_length2: raise ValueError(f"Two different format lengths specified ('{fmt}'). Either specify just one, or two the same length.") getter_func2 = dtype_register.get_dtype(token_name2, token_length2).read_fn getter_func = dtype_register.get_dtype(token_name, token_length).read_fn # Check that the getter functions will work temp = BitArray(token_length) try: getter_func(temp, 0) except InterpretError as e: raise ValueError(f"Pretty print format not valid: {e.msg}") if token_name2 is not None: try: getter_func2(temp, 0) except InterpretError as e: raise ValueError(f"Pretty print format not valid: {e.msg}") trailing_bit_length = len(self.data) % token_length format_sep = " : " # String to insert on each line between multiple formats if trailing_bit_length == 0: data = self.data else: data = self.data[0: -trailing_bit_length] length = len(self.data) // token_length parameter_name = "dtype" if fmt_is_dtype else "fmt" stream.write(f"\n[\n") data._pp(token_name, token_name2, token_length, width, sep, format_sep, show_offset, stream, False, token_length, getter_func, getter_func2) stream.write("]") if trailing_bit_length != 0: stream.write(" + trailing_bits = " + str(self.data[-trailing_bit_length:])) stream.write("\n") def equals(self, other: Any) -> bool: """Return True if format and all Array items are equal.""" if isinstance(other, Array): if self._dtype.length != other._dtype.length: return False if self._dtype.name != other._dtype.name: return False if self.data != other.data: return False return True elif isinstance(other, array.array): # Assume we are comparing with an array type if self.trailing_bits: return False # array's itemsize is in bytes, not bits. if self.itemsize != other.itemsize * 8: return False if len(self) != len(other): return False if self.tolist() != other.tolist(): return False return True return False def __iter__(self) -> Iterable[ElementType]: start = 0 for _ in range(len(self)): yield self._dtype.read_fn(self.data, start=start) start += self._dtype.length def __copy__(self) -> Array: a_copy = Array(self._fmt) a_copy.data = copy.copy(self.data) return a_copy def _apply_op_to_all_elements(self, op, value: Union[int, float, None], is_comparison: bool = False) -> Array: """Apply op with value to each element of the Array and return a new Array""" new_array = Array('bool' if is_comparison else self._dtype) new_data = BitArray() failures = index = 0 msg = '' if value is not None: def partial_op(a): return op(a, value) else: def partial_op(a): return op(a) for i in range(len(self)): v = self._dtype.read_fn(self.data, start=self._dtype.length * i) try: new_data.append(new_array._create_element(partial_op(v))) except (CreationError, ZeroDivisionError, ValueError) as e: if failures == 0: msg = str(e) index = i failures += 1 if failures != 0: raise ValueError(f"Applying operator '{op.__name__}' to Array caused {failures} errors. " f'First error at index {index} was: "{msg}"') new_array.data = new_data return new_array def _apply_op_to_all_elements_inplace(self, op, value: Union[int, float]) -> Array: """Apply op with value to each element of the Array in place.""" # This isn't really being done in-place, but it's simpler and faster for now? new_data = BitArray() failures = index = 0 msg = '' for i in range(len(self)): v = self._dtype.read_fn(self.data, start=self._dtype.length * i) try: new_data.append(self._create_element(op(v, value))) except (CreationError, ZeroDivisionError, ValueError) as e: if failures == 0: msg = str(e) index = i failures += 1 if failures != 0: raise ValueError(f"Applying operator '{op.__name__}' to Array caused {failures} errors. " f'First error at index {index} was: "{msg}"') self.data = new_data return self def _apply_bitwise_op_to_all_elements(self, op, value: BitsType) -> Array: """Apply op with value to each element of the Array as an unsigned integer and return a new Array""" a_copy = self[:] a_copy._apply_bitwise_op_to_all_elements_inplace(op, value) return a_copy def _apply_bitwise_op_to_all_elements_inplace(self, op, value: BitsType) -> Array: """Apply op with value to each element of the Array as an unsigned integer in place.""" value = BitArray._create_from_bitstype(value) if len(value) != self._dtype.length: raise ValueError(f"Bitwise op needs a bitstring of length {self._dtype.length} to match format {self._fmt}.") for start in range(0, len(self) * self._dtype.length, self._dtype.length): self.data[start: start + self._dtype.length] = op(self.data[start: start + self._dtype.length], value) return self def _apply_op_between_arrays(self, op, other: Array, is_comparison: bool = False) -> Array: if len(self) != len(other): msg = f"Cannot operate element-wise on Arrays with different lengths ({len(self)} and {len(other)})." if op == operator.add or op == operator.iadd: msg += " Use extend() if you want to concatenate Arrays." raise ValueError(msg) if is_comparison: new_type = dtype_register.get_dtype('bool', 1) else: new_type = self._promotetype(self._dtype, other._dtype) new_array = Array(new_type) new_data = BitArray() failures = index = 0 msg = '' for i in range(len(self)): a = self._dtype.read_fn(self.data, start=self._dtype.length * i) b = other._dtype.read_fn(other.data, start=other._dtype.length * i) try: new_data.append(new_array._create_element(op(a, b))) except (CreationError, ValueError, ZeroDivisionError) as e: if failures == 0: msg = str(e) index = i failures += 1 if failures != 0: raise ValueError(f"Applying operator '{op.__name__}' between Arrays caused {failures} errors. " f'First error at index {index} was: "{msg}"') new_array.data = new_data return new_array @classmethod def _promotetype(cls, type1: Dtype, type2: Dtype) -> Dtype: """When combining types which one wins? 1. We only deal with types representing floats or integers. 2. One of the two types gets returned. We never create a new one. 3. Floating point types always win against integer types. 4. Signed integer types always win against unsigned integer types. 5. Longer types win against shorter types. 6. In a tie the first type wins against the second type. """ if type1.is_float + type1.is_integer + type2.is_float + type2.is_integer != 2: raise ValueError(f"Only integer and floating point types can be combined - not '{type1}' and '{type2}'.") # If same type choose the widest if type1.name == type2.name: return type1 if type1.length > type2.length else type2 # We choose floats above integers, irrespective of the widths if type1.is_float and type2.is_integer: return type1 if type1.is_integer and type2.is_float: return type2 if type1.is_float and type2.is_float: return type2 if type2.length > type1.length else type1 assert type1.is_integer and type2.is_integer if type1.is_signed and not type2.is_signed: return type1 if type2.is_signed and not type1.is_signed: return type2 return type2 if type2.length > type1.length else type1 # Operators between Arrays or an Array and scalar value def __add__(self, other: Union[int, float, Array]) -> Array: """Add int or float to all elements.""" if isinstance(other, Array): return self._apply_op_between_arrays(operator.add, other) return self._apply_op_to_all_elements(operator.add, other) def __iadd__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.add, other) return self._apply_op_to_all_elements_inplace(operator.add, other) def __isub__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.sub, other) return self._apply_op_to_all_elements_inplace(operator.sub, other) def __sub__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.sub, other) return self._apply_op_to_all_elements(operator.sub, other) def __mul__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.mul, other) return self._apply_op_to_all_elements(operator.mul, other) def __imul__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.mul, other) return self._apply_op_to_all_elements_inplace(operator.mul, other) def __floordiv__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.floordiv, other) return self._apply_op_to_all_elements(operator.floordiv, other) def __ifloordiv__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.floordiv, other) return self._apply_op_to_all_elements_inplace(operator.floordiv, other) def __truediv__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.truediv, other) return self._apply_op_to_all_elements(operator.truediv, other) def __itruediv__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.truediv, other) return self._apply_op_to_all_elements_inplace(operator.truediv, other) def __rshift__(self, other: Union[int, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.rshift, other) return self._apply_op_to_all_elements(operator.rshift, other) def __lshift__(self, other: Union[int, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.lshift, other) return self._apply_op_to_all_elements(operator.lshift, other) def __irshift__(self, other: Union[int, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.rshift, other) return self._apply_op_to_all_elements_inplace(operator.rshift, other) def __ilshift__(self, other: Union[int, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.lshift, other) return self._apply_op_to_all_elements_inplace(operator.lshift, other) def __mod__(self, other: Union[int, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.mod, other) return self._apply_op_to_all_elements(operator.mod, other) def __imod__(self, other: Union[int, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.mod, other) return self._apply_op_to_all_elements_inplace(operator.mod, other) # Bitwise operators def __and__(self, other: BitsType) -> Array: return self._apply_bitwise_op_to_all_elements(operator.iand, other) def __iand__(self, other: BitsType) -> Array: return self._apply_bitwise_op_to_all_elements_inplace(operator.iand, other) def __or__(self, other: BitsType) -> Array: return self._apply_bitwise_op_to_all_elements(operator.ior, other) def __ior__(self, other: BitsType) -> Array: return self._apply_bitwise_op_to_all_elements_inplace(operator.ior, other) def __xor__(self, other: BitsType) -> Array: return self._apply_bitwise_op_to_all_elements(operator.ixor, other) def __ixor__(self, other: BitsType) -> Array: return self._apply_bitwise_op_to_all_elements_inplace(operator.ixor, other) # Reverse operators between a scalar value and an Array def __rmul__(self, other: Union[int, float]) -> Array: return self._apply_op_to_all_elements(operator.mul, other) def __radd__(self, other: Union[int, float]) -> Array: return self._apply_op_to_all_elements(operator.add, other) def __rsub__(self, other: Union[int, float]) -> Array: # i - A == (-A) + i neg = self._apply_op_to_all_elements(operator.neg, None) return neg._apply_op_to_all_elements(operator.add, other) # Reverse operators between a scalar and something that can be a BitArray. def __rand__(self, other: BitsType) -> Array: return self._apply_bitwise_op_to_all_elements(operator.iand, other) def __ror__(self, other: BitsType) -> Array: return self._apply_bitwise_op_to_all_elements(operator.ior, other) def __rxor__(self, other: BitsType) -> Array: return self._apply_bitwise_op_to_all_elements(operator.ixor, other) # Comparison operators def __lt__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.lt, other, is_comparison=True) return self._apply_op_to_all_elements(operator.lt, other, is_comparison=True) def __gt__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.gt, other, is_comparison=True) return self._apply_op_to_all_elements(operator.gt, other, is_comparison=True) def __ge__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.ge, other, is_comparison=True) return self._apply_op_to_all_elements(operator.ge, other, is_comparison=True) def __le__(self, other: Union[int, float, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.le, other, is_comparison=True) return self._apply_op_to_all_elements(operator.le, other, is_comparison=True) def __eq__(self, other: Union[int, float, str, BitsType, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.eq, other, is_comparison=True) return self._apply_op_to_all_elements(operator.eq, other, is_comparison=True) def __ne__(self, other: Union[int, float, str, BitsType, Array]) -> Array: if isinstance(other, Array): return self._apply_op_between_arrays(operator.ne, other, is_comparison=True) return self._apply_op_to_all_elements(operator.ne, other, is_comparison=True) # Unary operators def __neg__(self): return self._apply_op_to_all_elements(operator.neg, None) def __abs__(self): return self._apply_op_to_all_elements(operator.abs, None)bitstring-bitstring-4.1.4/bitstring/bitarray.py000066400000000000000000000603261453167633600217510ustar00rootroot00000000000000from __future__ import annotations import copy import numbers import re from collections import abc from typing import Union, List, Iterable, Any, Optional, Pattern, Dict, Callable from bitstring.utils import BYTESWAP_STRUCT_PACK_RE, STRUCT_SPLIT_RE, PACK_CODE_SIZE from bitstring.exceptions import CreationError, Error from bitstring.bits import Bits, BitsType, TBits class BitArray(Bits): """A container holding a mutable sequence of bits. Subclass of the immutable Bits class. Inherits all of its methods (except __hash__) and adds mutating methods. Mutating methods: append() -- Append a bitstring. byteswap() -- Change byte endianness in-place. clear() -- Remove all bits from the bitstring. insert() -- Insert a bitstring. invert() -- Flip bit(s) between one and zero. overwrite() -- Overwrite a section with a new bitstring. prepend() -- Prepend a bitstring. replace() -- Replace occurrences of one bitstring with another. reverse() -- Reverse bits in-place. rol() -- Rotate bits to the left. ror() -- Rotate bits to the right. set() -- Set bit(s) to 1 or 0. Methods inherited from Bits: all() -- Check if all specified bits are set to 1 or 0. any() -- Check if any of specified bits are set to 1 or 0. copy() -- Return a copy of the bitstring. count() -- Count the number of bits set to 1 or 0. cut() -- Create generator of constant sized chunks. endswith() -- Return whether the bitstring ends with a sub-string. find() -- Find a sub-bitstring in the current bitstring. findall() -- Find all occurrences of a sub-bitstring in the current bitstring. join() -- Join bitstrings together using current bitstring. pp() -- Pretty print the bitstring. rfind() -- Seek backwards to find a sub-bitstring. split() -- Create generator of chunks split by a delimiter. startswith() -- Return whether the bitstring starts with a sub-bitstring. tobitarray() -- Return bitstring as a bitarray from the bitarray package. tobytes() -- Return bitstring as bytes, padding if needed. tofile() -- Write bitstring to file, padding if needed. unpack() -- Interpret bits using format string. Special methods: Mutating operators are available: [], <<=, >>=, +=, *=, &=, |= and ^= in addition to the inherited [], ==, !=, +, *, ~, <<, >>, &, | and ^. Properties: bin -- The bitstring as a binary string. hex -- The bitstring as a hexadecimal string. oct -- The bitstring as an octal string. bytes -- The bitstring as a bytes object. int -- Interpret as a two's complement signed integer. uint -- Interpret as a two's complement unsigned integer. float / floatbe -- Interpret as a big-endian floating point number. bool -- For single bit bitstrings, interpret as True or False. se -- Interpret as a signed exponential-Golomb code. ue -- Interpret as an unsigned exponential-Golomb code. sie -- Interpret as a signed interleaved exponential-Golomb code. uie -- Interpret as an unsigned interleaved exponential-Golomb code. floatle -- Interpret as a little-endian floating point number. floatne -- Interpret as a native-endian floating point number. bfloat / bfloatbe -- Interpret as a big-endian 16-bit bfloat type. bfloatle -- Interpret as a little-endian 16-bit bfloat type. bfloatne -- Interpret as a native-endian 16-bit bfloat type. intbe -- Interpret as a big-endian signed integer. intle -- Interpret as a little-endian signed integer. intne -- Interpret as a native-endian signed integer. uintbe -- Interpret as a big-endian unsigned integer. uintle -- Interpret as a little-endian unsigned integer. uintne -- Interpret as a native-endian unsigned integer. len -- Length of the bitstring in bits. """ __slots__ = () # As BitArray objects are mutable, we shouldn't allow them to be hashed. __hash__: None = None def __init__(self, __auto: Optional[Union[BitsType, int]] = None, length: Optional[int] = None, offset: Optional[int] = None, **kwargs) -> None: """Either specify an 'auto' initialiser: A string of comma separated tokens, an integer, a file object, a bytearray, a boolean iterable or another bitstring. Or initialise via **kwargs with one (and only one) of: bin -- binary string representation, e.g. '0b001010'. hex -- hexadecimal string representation, e.g. '0x2ef' oct -- octal string representation, e.g. '0o777'. bytes -- raw data as a bytes object, for example read from a binary file. int -- a signed integer. uint -- an unsigned integer. float / floatbe -- a big-endian floating point number. bool -- a boolean (True or False). se -- a signed exponential-Golomb code. ue -- an unsigned exponential-Golomb code. sie -- a signed interleaved exponential-Golomb code. uie -- an unsigned interleaved exponential-Golomb code. floatle -- a little-endian floating point number. floatne -- a native-endian floating point number. bfloat / bfloatbe - a big-endian bfloat format 16-bit floating point number. bfloatle -- a little-endian bfloat format 16-bit floating point number. bfloatne -- a native-endian bfloat format 16-bit floating point number. intbe -- a signed big-endian whole byte integer. intle -- a signed little-endian whole byte integer. intne -- a signed native-endian whole byte integer. uintbe -- an unsigned big-endian whole byte integer. uintle -- an unsigned little-endian whole byte integer. uintne -- an unsigned native-endian whole byte integer. filename -- the path of a file which will be opened in binary read-only mode. Other keyword arguments: length -- length of the bitstring in bits, if needed and appropriate. It must be supplied for all integer and float initialisers. offset -- bit offset to the data. These offset bits are ignored and this is intended for use when initialising using 'bytes' or 'filename'. """ if self._bitstore.immutable: self._bitstore = self._bitstore.copy() self._bitstore.immutable = False _letter_to_setter: Dict[str, Callable[..., None]] = \ {'u': Bits._setuint, 'i': Bits._setint, 'f': Bits._setfloatbe, 'b': Bits._setbin_safe, 'o': Bits._setoct, 'h': Bits._sethex} _name_length_pattern: Pattern[str] = re.compile(r'^(?P[a-z]+)(?P\d+)$', re.IGNORECASE) def __setattr__(self, attribute, value) -> None: try: # First try the ordinary attribute setter super().__setattr__(attribute, value) except AttributeError: name_length = BitArray._name_length_pattern.match(attribute) if name_length: name = name_length.group('name') length = name_length.group('len') if length is not None: length = int(length) if name == 'bytes': if len(value) != length: raise CreationError( f"Wrong amount of byte data preset - {length} bytes needed, have {len(value)} bytes.") length *= 8 try: x = Bits(length=length, offset=None, **{name: value}) if len(x) != length: raise CreationError(f"Can't initialise with value of length {len(x)} bits, " f"as attribute has length of {length} bits.") self._bitstore = x._bitstore return except AttributeError: pass raise AttributeError(f"Can't set attribute {attribute} with value {value}.") def __iadd__(self, bs: BitsType) -> BitArray: """Append bs to current bitstring. Return self. bs -- the bitstring to append. """ self._append(bs) return self def __copy__(self) -> BitArray: """Return a new copy of the BitArray.""" s_copy = BitArray() s_copy._bitstore = self._bitstore.copy() assert s_copy._bitstore.immutable is False return s_copy def _setitem_int(self, key: int, value: Union[BitsType, int]) -> None: if isinstance(value, numbers.Integral): if value == 0: self._bitstore[key] = 0 return if value in (1, -1): self._bitstore[key] = 1 return raise ValueError(f"Cannot set a single bit with integer {value}.") try: value = self._create_from_bitstype(value) except TypeError: raise TypeError(f"Bitstring, integer or string expected. Got {type(value)}.") positive_key = key + self.len if key < 0 else key if positive_key < 0 or positive_key >= len(self._bitstore): raise IndexError(f"Bit position {key} out of range.") self._bitstore[positive_key: positive_key + 1] = value._bitstore def _setitem_slice(self, key: slice, value: BitsType) -> None: if isinstance(value, numbers.Integral): if key.step not in [None, -1, 1]: if value in [0, 1]: self.set(value, range(*key.indices(len(self)))) return else: raise ValueError("Can't assign an integer except 0 or 1 to a slice with a step value.") # To find the length we first get the slice s = self._bitstore.getslice(key) length = len(s) # Now create an int of the correct length if value >= 0: value = self.__class__(uint=value, length=length) else: value = self.__class__(int=value, length=length) else: try: value = self._create_from_bitstype(value) except TypeError: raise TypeError(f"Bitstring, integer or string expected. Got {type(value)}.") self._bitstore.__setitem__(key, value._bitstore) def __setitem__(self, key: Union[slice, int], value: BitsType) -> None: if isinstance(key, numbers.Integral): self._setitem_int(key, value) else: self._setitem_slice(key, value) def __delitem__(self, key: Union[slice, int]) -> None: """Delete item or range. >>> a = BitArray('0x001122') >>> del a[8:16] >>> print a 0x0022 """ self._bitstore.__delitem__(key) return def __ilshift__(self: TBits, n: int) -> TBits: """Shift bits by n to the left in place. Return self. n -- the number of bits to shift. Must be >= 0. """ if n < 0: raise ValueError("Cannot shift by a negative amount.") if not self.len: raise ValueError("Cannot shift an empty bitstring.") if not n: return self n = min(n, self.len) return self._ilshift(n) def __irshift__(self: TBits, n: int) -> TBits: """Shift bits by n to the right in place. Return self. n -- the number of bits to shift. Must be >= 0. """ if n < 0: raise ValueError("Cannot shift by a negative amount.") if not self.len: raise ValueError("Cannot shift an empty bitstring.") if not n: return self n = min(n, self.len) return self._irshift(n) def __imul__(self: TBits, n: int) -> TBits: """Concatenate n copies of self in place. Return self. Called for expressions of the form 'a *= 3'. n -- The number of concatenations. Must be >= 0. """ if n < 0: raise ValueError("Cannot multiply by a negative integer.") return self._imul(n) def __ior__(self: TBits, bs: BitsType) -> TBits: bs = self._create_from_bitstype(bs) if self.len != bs.len: raise ValueError("Bitstrings must have the same length for |= operator.") self._bitstore |= bs._bitstore return self def __iand__(self: TBits, bs: BitsType) -> TBits: bs = self._create_from_bitstype(bs) if self.len != bs.len: raise ValueError("Bitstrings must have the same length for &= operator.") self._bitstore &= bs._bitstore return self def __ixor__(self: TBits, bs: BitsType) -> TBits: bs = self._create_from_bitstype(bs) if self.len != bs.len: raise ValueError("Bitstrings must have the same length for ^= operator.") self._bitstore ^= bs._bitstore return self def _replace(self, old: Bits, new: Bits, start: int, end: int, count: int, bytealigned: Optional[bool]) -> int: if bytealigned is None: bytealigned = BitArray._options.bytealigned # First find all the places where we want to do the replacements starting_points: List[int] = [] for x in self.findall(old, start, end, bytealigned=bytealigned): if not starting_points: starting_points.append(x) elif x >= starting_points[-1] + old.len: # Can only replace here if it hasn't already been replaced! starting_points.append(x) if count != 0 and len(starting_points) == count: break if not starting_points: return 0 replacement_list = [self._bitstore.getslice(slice(0, starting_points[0], None))] for i in range(len(starting_points) - 1): replacement_list.append(new._bitstore) replacement_list.append( self._bitstore.getslice(slice(starting_points[i] + old.len, starting_points[i + 1], None))) # Final replacement replacement_list.append(new._bitstore) replacement_list.append(self._bitstore.getslice(slice(starting_points[-1] + old.len, None, None))) if BitArray._options.lsb0: # Addition of bitarray is always on the right, so assemble from other end replacement_list.reverse() self._bitstore.clear() for r in replacement_list: self._bitstore += r return len(starting_points) def replace(self, old: BitsType, new: BitsType, start: Optional[int] = None, end: Optional[int] = None, count: Optional[int] = None, bytealigned: Optional[bool] = None) -> int: """Replace all occurrences of old with new in place. Returns number of replacements made. old -- The bitstring to replace. new -- The replacement bitstring. start -- Any occurrences that start before this will not be replaced. Defaults to 0. end -- Any occurrences that finish after this will not be replaced. Defaults to len(self). count -- The maximum number of replacements to make. Defaults to replace all occurrences. bytealigned -- If True replacements will only be made on byte boundaries. Raises ValueError if old is empty or if start or end are out of range. """ if count == 0: return 0 old = self._create_from_bitstype(old) new = self._create_from_bitstype(new) if not old.len: raise ValueError("Empty bitstring cannot be replaced.") start, end = self._validate_slice(start, end) if new is self: # Prevent self assignment woes new = copy.copy(self) return self._replace(old, new, start, end, 0 if count is None else count, bytealigned) def insert(self, bs: BitsType, pos: int) -> None: """Insert bs at bit position pos. bs -- The bitstring to insert. pos -- The bit position to insert at. Raises ValueError if pos < 0 or pos > len(self). """ bs = self._create_from_bitstype(bs) if not bs.len: return if bs is self: bs = self._copy() if pos < 0: pos += self._getlength() if not 0 <= pos <= self._getlength(): raise ValueError("Invalid insert position.") self._insert(bs, pos) def overwrite(self, bs: BitsType, pos: int) -> None: """Overwrite with bs at bit position pos. bs -- The bitstring to overwrite with. pos -- The bit position to begin overwriting from. Raises ValueError if pos < 0 or pos > len(self). """ bs = self._create_from_bitstype(bs) if not bs.len: return if pos < 0: pos += self._getlength() if pos < 0 or pos > self.len: raise ValueError("Overwrite starts outside boundary of bitstring.") self._overwrite(bs, pos) def append(self, bs: BitsType) -> None: """Append a bitstring to the current bitstring. bs -- The bitstring to append. """ self._append(bs) def prepend(self, bs: BitsType) -> None: """Prepend a bitstring to the current bitstring. bs -- The bitstring to prepend. """ self._prepend(bs) def _append_msb0(self, bs: BitsType) -> None: self._addright(self._create_from_bitstype(bs)) def _append_lsb0(self, bs: BitsType) -> None: bs = self._create_from_bitstype(bs) self._addleft(bs) def reverse(self, start: Optional[int] = None, end: Optional[int] = None) -> None: """Reverse bits in-place. start -- Position of first bit to reverse. Defaults to 0. end -- One past the position of the last bit to reverse. Defaults to len(self). Using on an empty bitstring will have no effect. Raises ValueError if start < 0, end > len(self) or end < start. """ start, end = self._validate_slice(start, end) if start == 0 and end == self.len: self._bitstore.reverse() return s = self._slice(start, end) s._bitstore.reverse() self[start:end] = s def set(self, value: Any, pos: Optional[Union[int, Iterable[int]]] = None) -> None: """Set one or many bits to 1 or 0. value -- If bool(value) is True bits are set to 1, otherwise they are set to 0. pos -- Either a single bit position or an iterable of bit positions. Negative numbers are treated in the same way as slice indices. Defaults to the entire bitstring. Raises IndexError if pos < -len(self) or pos >= len(self). """ if pos is None: # Set all bits to either 1 or 0 self._setint(-1 if value else 0) return if not isinstance(pos, abc.Iterable): pos = (pos,) v = 1 if value else 0 if isinstance(pos, range): self._bitstore.__setitem__(slice(pos.start, pos.stop, pos.step), v) return for p in pos: self._bitstore[p] = v def invert(self, pos: Optional[Union[Iterable[int], int]] = None) -> None: """Invert one or many bits from 0 to 1 or vice versa. pos -- Either a single bit position or an iterable of bit positions. Negative numbers are treated in the same way as slice indices. Raises IndexError if pos < -len(self) or pos >= len(self). """ if pos is None: self._invert_all() return if not isinstance(pos, abc.Iterable): pos = (pos,) length = self.len for p in pos: if p < 0: p += length if not 0 <= p < length: raise IndexError(f"Bit position {p} out of range.") self._invert(p) def ror(self, bits: int, start: Optional[int] = None, end: Optional[int] = None) -> None: """Rotate bits to the right in-place. bits -- The number of bits to rotate by. start -- Start of slice to rotate. Defaults to 0. end -- End of slice to rotate. Defaults to len(self). Raises ValueError if bits < 0. """ if not self.len: raise Error("Cannot rotate an empty bitstring.") if bits < 0: raise ValueError("Cannot rotate by negative amount.") self._ror(bits, start, end) def _ror_msb0(self, bits: int, start: Optional[int] = None, end: Optional[int] = None) -> None: start, end = self._validate_slice(start, end) # the _slice deals with msb0/lsb0 bits %= (end - start) if not bits: return rhs = self._slice(end - bits, end) self._delete(bits, end - bits) self._insert(rhs, start) def rol(self, bits: int, start: Optional[int] = None, end: Optional[int] = None) -> None: """Rotate bits to the left in-place. bits -- The number of bits to rotate by. start -- Start of slice to rotate. Defaults to 0. end -- End of slice to rotate. Defaults to len(self). Raises ValueError if bits < 0. """ if not self.len: raise Error("Cannot rotate an empty bitstring.") if bits < 0: raise ValueError("Cannot rotate by negative amount.") self._rol(bits, start, end) def _rol_msb0(self, bits: int, start: Optional[int] = None, end: Optional[int] = None): start, end = self._validate_slice(start, end) bits %= (end - start) if bits == 0: return lhs = self._slice(start, start + bits) self._delete(bits, start) self._insert(lhs, end - bits) def byteswap(self, fmt: Optional[Union[int, Iterable[int], str]] = None, start: Optional[int] = None, end: Optional[int] = None, repeat: bool = True) -> int: """Change the endianness in-place. Return number of repeats of fmt done. fmt -- A compact structure string, an integer number of bytes or an iterable of integers. Defaults to 0, which byte reverses the whole bitstring. start -- Start bit position, defaults to 0. end -- End bit position, defaults to len(self). repeat -- If True (the default) the byte swapping pattern is repeated as much as possible. """ start_v, end_v = self._validate_slice(start, end) if fmt is None or fmt == 0: # reverse all of the whole bytes. bytesizes = [(end_v - start_v) // 8] elif isinstance(fmt, numbers.Integral): if fmt < 0: raise ValueError(f"Improper byte length {fmt}.") bytesizes = [fmt] elif isinstance(fmt, str): m = BYTESWAP_STRUCT_PACK_RE.match(fmt) if not m: raise ValueError(f"Cannot parse format string {fmt}.") # Split the format string into a list of 'q', '4h' etc. formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt')) # Now deal with multiplicative factors, 4h -> hhhh etc. bytesizes = [] for f in formatlist: if len(f) == 1: bytesizes.append(PACK_CODE_SIZE[f]) else: bytesizes.extend([PACK_CODE_SIZE[f[-1]]] * int(f[:-1])) elif isinstance(fmt, abc.Iterable): bytesizes = fmt for bytesize in bytesizes: if not isinstance(bytesize, numbers.Integral) or bytesize < 0: raise ValueError(f"Improper byte length {bytesize}.") else: raise TypeError("Format must be an integer, string or iterable.") repeats = 0 totalbitsize: int = 8 * sum(bytesizes) if not totalbitsize: return 0 if repeat: # Try to repeat up to the end of the bitstring. finalbit = end_v else: # Just try one (set of) byteswap(s). finalbit = start_v + totalbitsize for patternend in range(start_v + totalbitsize, finalbit + 1, totalbitsize): bytestart = patternend - totalbitsize for bytesize in bytesizes: byteend = bytestart + bytesize * 8 self._reversebytes(bytestart, byteend) bytestart += bytesize * 8 repeats += 1 return repeats def clear(self) -> None: """Remove all bits, reset to zero length.""" self._clear() bitstring-bitstring-4.1.4/bitstring/bits.py000066400000000000000000002570551453167633600211040ustar00rootroot00000000000000from __future__ import annotations import numbers import pathlib import sys import re import mmap import struct import array import io from collections import abc import functools from typing import Tuple, Union, List, Iterable, Any, Optional, Pattern, Dict, \ BinaryIO, TextIO, Callable, overload, Iterator, Type, TypeVar import bitarray import bitarray.util from bitstring.utils import tokenparser 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 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 # 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] TBits = TypeVar("TBits", bound='Bits') byteorder: str = sys.byteorder # Maximum number of digits to use in __str__ and __repr__. MAX_CHARS: int = 250 class Bits: """A container holding an immutable sequence of bits. For a mutable container use the BitArray class instead. Methods: all() -- Check if all specified bits are set to 1 or 0. any() -- Check if any of specified bits are set to 1 or 0. copy() - Return a copy of the bitstring. count() -- Count the number of bits set to 1 or 0. cut() -- Create generator of constant sized chunks. endswith() -- Return whether the bitstring ends with a sub-string. find() -- Find a sub-bitstring in the current bitstring. findall() -- Find all occurrences of a sub-bitstring in the current bitstring. join() -- Join bitstrings together using current bitstring. pp() -- Pretty print the bitstring. rfind() -- Seek backwards to find a sub-bitstring. split() -- Create generator of chunks split by a delimiter. startswith() -- Return whether the bitstring starts with a sub-bitstring. tobitarray() -- Return bitstring as a bitarray from the bitarray package. tobytes() -- Return bitstring as bytes, padding if needed. tofile() -- Write bitstring to file, padding if needed. unpack() -- Interpret bits using format string. Special methods: Also available are the operators [], ==, !=, +, *, ~, <<, >>, &, |, ^. Properties: bin -- The bitstring as a binary string. hex -- The bitstring as a hexadecimal string. oct -- The bitstring as an octal string. bytes -- The bitstring as a bytes object. int -- Interpret as a two's complement signed integer. uint -- Interpret as a two's complement unsigned integer. float / floatbe -- Interpret as a big-endian floating point number. bool -- For single bit bitstrings, interpret as True or False. se -- Interpret as a signed exponential-Golomb code. ue -- Interpret as an unsigned exponential-Golomb code. sie -- Interpret as a signed interleaved exponential-Golomb code. uie -- Interpret as an unsigned interleaved exponential-Golomb code. floatle -- Interpret as a little-endian floating point number. floatne -- Interpret as a native-endian floating point number. bfloat / bfloatbe -- Interpret as a big-endian 16-bit bfloat type. bfloatle -- Interpret as a little-endian 16-bit bfloat type. bfloatne -- Interpret as a native-endian 16-bit bfloat type. intbe -- Interpret as a big-endian signed integer. intle -- Interpret as a little-endian signed integer. intne -- Interpret as a native-endian signed integer. uintbe -- Interpret as a big-endian unsigned integer. uintle -- Interpret as a little-endian unsigned integer. uintne -- Interpret as a native-endian unsigned integer. len -- Length of the bitstring in bits. """ __slots__ = ('_bitstore') _options = None _register = None @classmethod def _initialise_options(cls): # To avoid circular imports this happens after all the classes are initialised. from .options import Options cls._options = Options() from .dtypes import Register cls._register = Register() # Creates dictionaries to quickly reverse single bytes _int8ReversalDict: Dict[int, int] = {i: int("{0:08b}".format(i)[::-1], 2) for i in range(0x100)} _byteReversalDict: Dict[int, bytes] = {i: bytes([int("{0:08b}".format(i)[::-1], 2)]) for i in range(0x100)} def __init__(self, __auto: Optional[Union[BitsType, int]] = None, length: Optional[int] = None, offset: Optional[int] = None, **kwargs) -> None: """Either specify an 'auto' initialiser: A string of comma separated tokens, an integer, a file object, a bytearray, a boolean iterable, an array or another bitstring. Or initialise via **kwargs with one (and only one) of: bin -- binary string representation, e.g. '0b001010'. hex -- hexadecimal string representation, e.g. '0x2ef' oct -- octal string representation, e.g. '0o777'. bytes -- raw data as a bytes object, for example read from a binary file. int -- a signed integer. uint -- an unsigned integer. float / floatbe -- a big-endian floating point number. bool -- a boolean (True or False). se -- a signed exponential-Golomb code. ue -- an unsigned exponential-Golomb code. sie -- a signed interleaved exponential-Golomb code. uie -- an unsigned interleaved exponential-Golomb code. floatle -- a little-endian floating point number. floatne -- a native-endian floating point number. bfloat / bfloatbe - a big-endian bfloat format 16-bit floating point number. bfloatle -- a little-endian bfloat format 16-bit floating point number. bfloatne -- a native-endian bfloat format 16-bit floating point number. intbe -- a signed big-endian whole byte integer. intle -- a signed little-endian whole byte integer. intne -- a signed native-endian whole byte integer. uintbe -- an unsigned big-endian whole byte integer. uintle -- an unsigned little-endian whole byte integer. uintne -- an unsigned native-endian whole byte integer. filename -- the path of a file which will be opened in binary read-only mode. Other keyword arguments: length -- length of the bitstring in bits, if needed and appropriate. It must be supplied for all integer and float initialisers. offset -- bit offset to the data. These offset bits are ignored and this is mainly intended for use when initialising using 'bytes' or 'filename'. """ self._bitstore.immutable = True def __new__(cls: Type[TBits], __auto: Optional[Union[BitsType, int]] = None, length: Optional[int] = None, offset: Optional[int] = None, pos: Optional[int] = None, **kwargs) -> TBits: x = object.__new__(cls) if __auto is None and not kwargs: # No initialiser so fill with zero bits up to length if length is not None: x._bitstore = BitStore(length) x._bitstore.setall(0) else: x._bitstore = BitStore() return x x._initialise(__auto, length, offset, **kwargs) return x @classmethod def _create_empty_instance(cls): x = object.__new__(cls) x._bitstore = BitStore._create_empty_instance() return x @classmethod def _create_from_bitstype(cls: Type[TBits], auto: Optional[BitsType]) -> TBits: b = cls._create_empty_instance() if auto is None: return b b._setauto(auto, None, None) return b def _initialise(self, __auto: Any, length: Optional[int], offset: Optional[int], **kwargs) -> None: if length is not None and length < 0: raise CreationError("bitstring length cannot be negative.") if offset is not None and offset < 0: raise CreationError("offset must be >= 0.") if __auto is not None: if isinstance(__auto, numbers.Integral): # Initialise with s zero bits. if __auto < 0: raise CreationError(f"Can't create bitstring of negative length {__auto}.") self._bitstore = BitStore(int(__auto)) self._bitstore.setall(0) return self._setauto(__auto, length, offset) return k, v = kwargs.popitem() try: setting_function = Bits._register.name_to_meta_dtype[k].set_fn except KeyError: if k == 'filename': setting_function = Bits._setfile elif k == 'bitarray': setting_function = Bits._setbitarray elif k == 'auto': raise 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.") setting_function(self, v, length, offset) def __getattr__(self, attribute: str) -> Any: # Support for arbitrary attributes like u16 or f64. # Try to split into [name][length], then try standard properties name_length_pattern: Pattern[str] = re.compile(r'^(?P[a-z]+):?(?P\d+)$', re.IGNORECASE) name_length = name_length_pattern.match(attribute) if name_length: name = name_length.group('name') length = int(name_length.group('len')) if name == 'bytes' and length is not None: length *= 8 if length is not None and self.len != int(length): raise InterpretError(f"bitstring length {self.len} doesn't match length of property {attribute}.") try: return getattr(self, name) except AttributeError: pass raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attribute}'.") def __iter__(self) -> Iterable[bool]: return iter(self._bitstore) def __copy__(self: TBits) -> TBits: """Return a new copy of the Bits for the copy module.""" # Note that if you want a new copy (different ID), use _copy instead. # The copy can return self as it's immutable. return self def __lt__(self, other: Any) -> bool: # bitstrings can't really be ordered. return NotImplemented def __gt__(self, other: Any) -> bool: return NotImplemented def __le__(self, other: Any) -> bool: return NotImplemented def __ge__(self, other: Any) -> bool: return NotImplemented def __add__(self: TBits, bs: BitsType) -> TBits: """Concatenate bitstrings and return new bitstring. bs -- the bitstring to append. """ bs = self.__class__._create_from_bitstype(bs) if bs.len <= self.len: s = self._copy() s._addright(bs) else: s = bs._copy() s = self.__class__(s) s._addleft(self) return s def __radd__(self: TBits, bs: BitsType) -> TBits: """Append current bitstring to bs and return new bitstring. bs -- An object that can be 'auto' initialised as a bitstring that will be appended to. """ bs = self.__class__._create_from_bitstype(bs) return bs.__add__(self) @overload def __getitem__(self: TBits, key: slice) -> TBits: ... @overload def __getitem__(self, key: int) -> bool: ... def __getitem__(self: TBits, key: Union[slice, int]) -> Union[TBits, bool]: """Return a new bitstring representing a slice of the current bitstring. Indices are in units of the step parameter (default 1 bit). Stepping is used to specify the number of bits in each item. >>> print(BitArray('0b00110')[1:4]) '0b011' >>> print(BitArray('0x00112233')[1:3:8]) '0x1122' """ if isinstance(key, numbers.Integral): return bool(self._bitstore.getindex(key)) x = self._bitstore.getslice(key) bs = self.__class__() bs._bitstore = x return bs def __len__(self) -> int: """Return the length of the bitstring in bits.""" return self._getlength() def __bytes__(self) -> bytes: return self.tobytes() def __str__(self) -> str: """Return approximate string representation of bitstring for printing. Short strings will be given wholly in hexadecimal or binary. Longer strings may be part hexadecimal and part binary. Very long strings will be truncated with '...'. """ length = self.len if not length: return '' if length > MAX_CHARS * 4: # Too long for hex. Truncate... return ''.join(('0x', self._readhex(0, MAX_CHARS * 4), '...')) # If it's quite short and we can't do hex then use bin if length < 32 and length % 4 != 0: return '0b' + self.bin # If we can use hex then do so if not length % 4: return '0x' + self.hex # Otherwise first we do as much as we can in hex # then add on 1, 2 or 3 bits on at the end bits_at_end = length % 4 return ''.join(('0x', self._readhex(0, length - bits_at_end), ', ', '0b', self._readbin(length - bits_at_end, bits_at_end))) def _repr(self, classname: str, length: int, offset: int, filename: str, pos: int): pos_string = f', pos={pos}' if pos else '' if filename: offsetstring = f', offset={offset}' if offset else '' return f"{classname}(filename={repr(filename)}, length={length}{offsetstring}{pos_string})" else: s = self.__str__() lengthstring = '' if s.endswith('...'): lengthstring = f' # length={length}' return f"{classname}('{s}'{pos_string}){lengthstring}" def __repr__(self) -> str: """Return representation that could be used to recreate the bitstring. If the returned string is too long it will be truncated. See __str__(). """ return self._repr(self.__class__.__name__, len(self), self._bitstore.offset, self._bitstore.filename, 0) def __eq__(self, bs: Any) -> bool: """Return True if two bitstrings have the same binary representation. >>> BitArray('0b1110') == '0xe' True """ try: bs = Bits._create_from_bitstype(bs) except TypeError: return False return self._bitstore == bs._bitstore def __ne__(self, bs: Any) -> bool: """Return False if two bitstrings have the same binary representation. >>> BitArray('0b111') == '0x7' False """ return not self.__eq__(bs) def __invert__(self: TBits) -> TBits: """Return bitstring with every bit inverted. Raises Error if the bitstring is empty. """ if not self.len: raise Error("Cannot invert empty bitstring.") s = self._copy() s._invert_all() return s def __lshift__(self: TBits, n: int) -> TBits: """Return bitstring with bits shifted by n to the left. n -- the number of bits to shift. Must be >= 0. """ if n < 0: raise ValueError("Cannot shift by a negative amount.") if not self.len: raise ValueError("Cannot shift an empty bitstring.") n = min(n, self.len) s = self._absolute_slice(n, self.len) s._addright(Bits(n)) return s def __rshift__(self: TBits, n: int) -> TBits: """Return bitstring with bits shifted by n to the right. n -- the number of bits to shift. Must be >= 0. """ if n < 0: raise ValueError("Cannot shift by a negative amount.") if not self.len: raise ValueError("Cannot shift an empty bitstring.") if not n: return self._copy() s = self.__class__(length=min(n, self.len)) n = min(n, self.len) s._addright(self._absolute_slice(0, self.len - n)) return s def __mul__(self: TBits, n: int) -> TBits: """Return bitstring consisting of n concatenations of self. Called for expression of the form 'a = b*3'. n -- The number of concatenations. Must be >= 0. """ if n < 0: raise ValueError("Cannot multiply by a negative integer.") if not n: return self.__class__() s = self._copy() s._imul(n) return s def __rmul__(self: TBits, n: int) -> TBits: """Return bitstring consisting of n concatenations of self. Called for expressions of the form 'a = 3*b'. n -- The number of concatenations. Must be >= 0. """ return self.__mul__(n) def __and__(self: TBits, bs: BitsType) -> TBits: """Bit-wise 'and' between two bitstrings. Returns new bitstring. bs -- The bitstring to '&' with. Raises ValueError if the two bitstrings have differing lengths. """ bs = Bits._create_from_bitstype(bs) if self.len != bs.len: raise ValueError("Bitstrings must have the same length for & operator.") s = self._copy() s._bitstore &= bs._bitstore return s def __rand__(self: TBits, bs: BitsType) -> TBits: """Bit-wise 'and' between two bitstrings. Returns new bitstring. bs -- the bitstring to '&' with. Raises ValueError if the two bitstrings have differing lengths. """ return self.__and__(bs) def __or__(self: TBits, bs: BitsType) -> TBits: """Bit-wise 'or' between two bitstrings. Returns new bitstring. bs -- The bitstring to '|' with. Raises ValueError if the two bitstrings have differing lengths. """ bs = Bits._create_from_bitstype(bs) if self.len != bs.len: raise ValueError("Bitstrings must have the same length for | operator.") s = self._copy() s._bitstore |= bs._bitstore return s def __ror__(self: TBits, bs: BitsType) -> TBits: """Bit-wise 'or' between two bitstrings. Returns new bitstring. bs -- The bitstring to '|' with. Raises ValueError if the two bitstrings have differing lengths. """ return self.__or__(bs) def __xor__(self: TBits, bs: BitsType) -> TBits: """Bit-wise 'xor' between two bitstrings. Returns new bitstring. bs -- The bitstring to '^' with. Raises ValueError if the two bitstrings have differing lengths. """ bs = Bits._create_from_bitstype(bs) if self.len != bs.len: raise ValueError("Bitstrings must have the same length for ^ operator.") s = self._copy() s._bitstore ^= bs._bitstore return s def __rxor__(self: TBits, bs: BitsType) -> TBits: """Bit-wise 'xor' between two bitstrings. Returns new bitstring. bs -- The bitstring to '^' with. Raises ValueError if the two bitstrings have differing lengths. """ return self.__xor__(bs) def __contains__(self, bs: BitsType) -> bool: """Return whether bs is contained in the current bitstring. bs -- The bitstring to search for. """ found = Bits.find(self, bs, bytealigned=False) return bool(found) def __hash__(self) -> int: """Return an integer hash of the object.""" # Only requirement is that equal bitstring should return the same hash. # For equal bitstrings the bytes at the start/end will be the same and they will have the same length # (need to check the length as there could be zero padding when getting the bytes). We do not check any # bit position inside the bitstring as that does not feature in the __eq__ operation. if self.len <= 2000: # Use the whole bitstring. return hash((self.tobytes(), self.len)) else: # We can't in general hash the whole bitstring (it could take hours!) # So instead take some bits from the start and end. return hash(((self[:800] + self[-800:]).tobytes(), self.len)) def __bool__(self) -> bool: """Return True if any bits are set to 1, otherwise return False.""" return len(self) != 0 def _clear(self) -> None: """Reset the bitstring to an empty state.""" self._bitstore = BitStore() def _setauto(self, s: BitsType, length: Optional[int], offset: Optional[int]) -> None: """Set bitstring from a bitstring, file, bool, array, iterable or string.""" # As s can be so many different things it's important to do the checks # in the correct order, as some types are also other allowed types. # So str must be checked before Iterable # and bytes/bytearray before Iterable but after str! if offset is None: offset = 0 if isinstance(s, Bits): if length is None: length = s._getlength() - offset self._bitstore = s._bitstore.getslice(slice(offset, offset + length, None)) return if isinstance(s, io.BytesIO): if length is None: length = s.seek(0, 2) * 8 - offset 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.") self._bitstore = BitStore(frombytes=s.getvalue()[byteoffset: byteoffset + bytelength]).getslice( slice(offset, offset + length)) return if isinstance(s, io.BufferedReader): m = mmap.mmap(s.fileno(), 0, access=mmap.ACCESS_READ) self._bitstore = BitStore(buffer=m, offset=offset, length=length, filename=s.name, immutable=True) return if isinstance(s, bitarray.bitarray): if length is None: if offset > len(s): raise CreationError(f"Offset of {offset} too large for bitarray of length {len(s)}.") self._bitstore = BitStore(s[offset:]) else: if offset + length > len(s): raise CreationError( f"Offset of {offset} and length of {length} too large for bitarray of length {len(s)}.") self._bitstore = BitStore(s[offset: offset + length]) return if length is not None: raise CreationError("The length keyword isn't applicable to this initialiser.") if offset > 0: raise CreationError("The offset keyword isn't applicable to this initialiser.") if isinstance(s, str): self._bitstore = str_to_bitstore(s) return if isinstance(s, (bytes, bytearray, memoryview)): self._bitstore = BitStore(frombytes=bytearray(s)) return if isinstance(s, array.array): self._bitstore = BitStore(frombytes=bytearray(s.tobytes())) return if isinstance(s, abc.Iterable): # Evaluate each item as True or False and set bits to 1 or 0. self._setbin_unsafe(''.join(str(int(bool(x))) for x in s)) return if isinstance(s, numbers.Integral): raise TypeError(f"It's no longer possible to auto initialise a bitstring from an integer." f" Use '{self.__class__.__name__}({s})' instead of just '{s}' as this makes it " f"clearer that a bitstring of {int(s)} zero bits will be created.") raise TypeError(f"Cannot initialise bitstring from {type(s)}.") def _setfile(self, filename: str, length: Optional[int], offset: Optional[int]) -> None: """Use file as source of bits.""" with open(pathlib.Path(filename), 'rb') as source: if offset is None: offset = 0 m = mmap.mmap(source.fileno(), 0, access=mmap.ACCESS_READ) self._bitstore = BitStore(buffer=m, offset=offset, length=length, filename=source.name, immutable=True) 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)}.") if length is None: self._bitstore = BitStore(ba[offset:]) else: if offset + length > len(ba): raise CreationError( f"Offset of {offset} and length of {length} too large for bitarray of length {len(ba)}.") self._bitstore = BitStore(ba[offset: offset + length]) def _setbits(self, bs: BitsType, length: None = None, offset: None = None) -> None: bs = Bits._create_from_bitstype(bs) self._bitstore = bs._bitstore def _sete5m2float(self, f: float, length: None = None, _offset: None = None): u = e5m2float_fmt.float_to_int8(f) self._bitstore = uint2bitstore(u, 8) def _sete4m3float(self, f: float, length: None = None, _offset: None = None): u = e4m3float_fmt.float_to_int8(f) self._bitstore = uint2bitstore(u, 8) def _setbytes(self, data: Union[bytearray, bytes], length: Optional[int] = None, offset: Optional[int] = None) -> None: """Set the data from a bytes or bytearray object.""" if offset is None and length is None: self._bitstore = BitStore(frombytes=bytearray(data)) return data = bytearray(data) if offset is None: offset = 0 if length is None: # Use to the end of the data 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}.") self._bitstore = BitStore(buffer=data).getslice_msb0(slice(offset, offset + length, None)) def _readbytes(self, start: int, length: int) -> bytes: """Read bytes and return them. Note that length is in bits.""" assert length % 8 == 0 assert start + length <= self.len return self._bitstore.getslice(slice(start, start + length, None)).tobytes() def _getbytes(self) -> bytes: """Return the data as an ordinary bytes object.""" if self.len % 8: raise InterpretError("Cannot interpret as bytes unambiguously - not multiple of 8 bits.") return self._readbytes(0, self.len) _unprintable = list(range(0x00, 0x20)) # ASCII control characters _unprintable.extend(range(0x7f, 0xff)) # DEL char + non-ASCII def _getbytes_printable(self) -> str: """Return an approximation of the data as a string of printable characters.""" bytes_ = self._getbytes() # For everything that isn't printable ASCII, use value from 'Latin Extended-A' unicode block. string = ''.join(chr(0x100 + x) if x in Bits._unprintable else chr(x) for x in bytes_) return string def _setuint(self, uint: int, length: Optional[int] = None, _offset: None = None) -> None: """Reset the bitstring to have given unsigned int interpretation.""" # If no length given, and we've previously been given a length, use it. if length is None and hasattr(self, 'len') and self.len != 0: length = self.len if length is None or length == 0: raise CreationError("A non-zero length must be specified with a uint initialiser.") if _offset is not None: raise CreationError("An offset can't be specified with an integer initialiser.") self._bitstore = uint2bitstore(uint, length) def _readuint(self, start: int, length: int) -> int: """Read bits and interpret as an unsigned int.""" if length == 0: raise InterpretError("Cannot interpret a zero length bitstring as an integer.") ip = bitarray.util.ba2int(self._bitstore.getslice(slice(start, start + length, None)), signed=False) return ip def _getuint(self) -> int: """Return data as an unsigned int.""" if self.len == 0: raise InterpretError("Cannot interpret a zero length bitstring as an integer.") bs = self._bitstore.copy() if self._bitstore.modified else self._bitstore return bitarray.util.ba2int(bs, signed=False) def _setint(self, int_: int, length: Optional[int] = None, _offset: None = None) -> None: """Reset the bitstring to have given signed int interpretation.""" # If no length given, and we've previously been given a length, use it. if length is None and hasattr(self, 'len') and self.len != 0: length = self.len if length is None or length == 0: raise CreationError("A non-zero length must be specified with an int initialiser.") if _offset is not None: raise CreationError("An offset can't be specified with an integer initialiser.") self._bitstore = int2bitstore(int_, length) def _readint(self, start: int, length: int) -> int: """Read bits and interpret as a signed int""" if length == 0: raise InterpretError("Cannot interpret bitstring without a length as an integer.") ip = bitarray.util.ba2int(self._bitstore.getslice(slice(start, start + length, None)), signed=True) return ip def _getint(self) -> int: """Return data as a two's complement signed int.""" if self.len == 0: raise InterpretError("Cannot interpret bitstring without a length as an integer.") bs = self._bitstore.copy() if self._bitstore.modified else self._bitstore return bitarray.util.ba2int(bs, signed=True) def _setuintbe(self, uintbe: int, length: Optional[int] = None, _offset: None = None) -> None: """Set the bitstring to a big-endian unsigned int interpretation.""" if length is None and hasattr(self, 'len') and self.len != 0: length = self.len if length is None or length == 0: raise CreationError("A non-zero length must be specified with a uintbe initialiser.") self._bitstore = uintbe2bitstore(uintbe, length) def _readuintbe(self, start: int, length: int) -> int: """Read bits and interpret as a big-endian unsigned int.""" if length % 8: raise InterpretError(f"Big-endian integers must be whole-byte. Length = {length} bits.") return self._readuint(start, length) def _getuintbe(self) -> int: """Return data as a big-endian two's complement unsigned int.""" return self._readuintbe(0, self.len) def _setintbe(self, intbe: int, length: Optional[int] = None, _offset: None = None) -> None: """Set bitstring to a big-endian signed int interpretation.""" if length is None and hasattr(self, 'len') and self.len != 0: length = self.len if length is None or length == 0: raise CreationError("A non-zero length must be specified with a intbe initialiser.") self._bitstore = intbe2bitstore(intbe, length) def _readintbe(self, start: int, length: int) -> int: """Read bits and interpret as a big-endian signed int.""" if length % 8: raise InterpretError(f"Big-endian integers must be whole-byte. Length = {length} bits.") return self._readint(start, length) def _getintbe(self) -> int: """Return data as a big-endian two's complement signed int.""" return self._readintbe(0, self.len) def _setuintle(self, uintle: int, length: Optional[int] = None, _offset: None = None) -> None: if length is None and hasattr(self, 'len') and self.len != 0: length = self.len if length is None or length == 0: raise CreationError("A non-zero length must be specified with a uintle initialiser.") if _offset is not None: raise CreationError("An offset can't be specified with an integer initialiser.") self._bitstore = uintle2bitstore(uintle, length) def _readuintle(self, start: int, length: int) -> int: """Read bits and interpret as a little-endian unsigned int.""" if length % 8: raise InterpretError(f"Little-endian integers must be whole-byte. Length = {length} bits.") bs = BitStore(frombytes=self._bitstore.getslice(slice(start, start + length, None)).tobytes()[::-1]) val = bitarray.util.ba2int(bs, signed=False) return val def _getuintle(self) -> int: return self._readuintle(0, self.len) def _setintle(self, intle: int, length: Optional[int] = None, _offset: None = None) -> None: if length is None and hasattr(self, 'len') and self.len != 0: length = self.len if length is None or length == 0: raise CreationError("A non-zero length must be specified with an intle initialiser.") if _offset is not None: raise CreationError("An offset can't be specified with an integer initialiser.") self._bitstore = intle2bitstore(intle, length) def _readintle(self, start: int, length: int) -> int: """Read bits and interpret as a little-endian signed int.""" if length % 8: raise InterpretError(f"Little-endian integers must be whole-byte. Length = {length} bits.") bs = BitStore(frombytes=self._bitstore.getslice(slice(start, start + length, None)).tobytes()[::-1]) val = bitarray.util.ba2int(bs, signed=True) return val def _getintle(self) -> int: return self._readintle(0, self.len) def _readfloat(self, start: int, length: int, struct_dict: Dict[int, str]) -> float: """Read bits and interpret as a float.""" try: fmt = struct_dict[length] except KeyError: raise InterpretError(f"Floats can only be 16, 32 or 64 bits long, not {length} bits") offset = start % 8 if offset == 0: return struct.unpack(fmt, self._bitstore.getslice(slice(start, start + length, None)).tobytes())[0] else: return struct.unpack(fmt, self._readbytes(start, length))[0] def _reade4m3float(self, start: int, length: int = 0) -> float: # length is ignored - it's only present to make the function signature consistent. u = self._readuint(start, length=8) return e4m3float_fmt.lut_int8_to_float[u] def _gete4m3float(self) -> float: if len(self) != 8: raise InterpretError(f"A e4m3float must be 8 bits long, not {len(self)} bits.") return self._reade4m3float(0) def _reade5m2float(self, start: int, length: int = 0) -> float: # length is ignored - it's only present to make the function signature consistent. u = self._readuint(start, length=8) return e5m2float_fmt.lut_int8_to_float[u] def _gete5m2float(self) -> float: if len(self) != 8: raise InterpretError(f"A e5m2float must be 8 bits long, not {len(self)} bits.") return self._reade5m2float(start=0) def _setfloatbe(self, f: float, length: Optional[int] = None, _offset: None = None) -> None: if length is None and hasattr(self, 'len') and self.len != 0: length = self.len 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.") self._bitstore = float2bitstore(f, length) def _readfloatbe(self, start: int, length: int) -> float: """Read bits and interpret as a big-endian float.""" return self._readfloat(start, length, {16: '>e', 32: '>f', 64: '>d'}) def _getfloatbe(self) -> float: """Interpret the whole bitstring as a big-endian float.""" return self._readfloatbe(0, self.len) def _setfloatle(self, f: float, length: Optional[int] = None, _offset: None = None) -> None: if length is None and hasattr(self, 'len') and self.len != 0: length = self.len 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.") self._bitstore = floatle2bitstore(f, length) def _readfloatle(self, start: int, length: int) -> float: """Read bits and interpret as a little-endian float.""" return self._readfloat(start, length, {16: ' float: """Interpret the whole bitstring as a little-endian float.""" return self._readfloatle(0, self.len) def _getbfloatbe(self) -> float: return self._readbfloatbe(0, self.len) def _readbfloatbe(self, start: int, length: int) -> float: if length != 16: raise InterpretError(f"bfloats must be length 16, received a length of {length} bits.") two_bytes = self._slice(start, start + 16) zero_padded = two_bytes + Bits(16) return zero_padded._getfloatbe() def _setbfloatbe(self, f: Union[float, str], length: Optional[int] = None, _offset: None = None) -> None: if length is not None and length != 16: raise CreationError(f"bfloats must be length 16, received a length of {length} bits.") self._bitstore = bfloat2bitstore(f) def _getbfloatle(self) -> float: return self._readbfloatle(0, self.len) def _readbfloatle(self, start: int, length: int) -> float: two_bytes = self._slice(start, start + 16) zero_padded = Bits(16) + two_bytes return zero_padded._getfloatle() def _setbfloatle(self, f: Union[float, str], length: Optional[int] = None, _offset: None = None) -> None: if length is not None and length != 16: raise 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, _offset: None = None) -> None: """Initialise bitstring with unsigned exponential-Golomb code for integer i. Raises CreationError if i < 0. """ if _length is not None or _offset is not None: raise CreationError("Cannot specify a length of offset for exponential-Golomb codes.") if Bits._options.lsb0: raise CreationError("Exp-Golomb codes cannot be used in lsb0 mode.") self._bitstore = ue2bitstore(i) def _readue(self, pos: int, length: int = 0) -> Tuple[int, int]: """Return interpretation of next bits as unsigned exponential-Golomb code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ # _length is ignored - it's only present to make the function signature consistent. if Bits._options.lsb0: raise 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.") leadingzeros = pos - oldpos codenum = (1 << leadingzeros) - 1 if leadingzeros > 0: if pos + leadingzeros + 1 > self.len: raise ReadError("Read off end of bitstring trying to read code.") codenum += self._readuint(pos + 1, leadingzeros) pos += leadingzeros + 1 else: assert codenum == 0 pos += 1 return codenum, pos def _getue(self) -> int: """Return data as unsigned exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readue(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single exponential-Golomb code.") return value def _setse(self, i: int, _length: None = None, _offset: None = None) -> None: """Initialise bitstring with signed exponential-Golomb code for integer i.""" if _length is not None or _offset is not None: raise CreationError("Cannot specify a length of offset for exponential-Golomb codes.") if Bits._options.lsb0: raise CreationError("Exp-Golomb codes cannot be used in lsb0 mode.") self._bitstore = se2bitstore(i) def _getse(self) -> int: """Return data as signed exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readse(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single exponential-Golomb code.") return value def _readse(self, pos: int, length: int = 0) -> Tuple[int, int]: """Return interpretation of next bits as a signed exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ codenum, pos = self._readue(pos) m = (codenum + 1) // 2 if not codenum % 2: return -m, pos else: return m, pos def _setuie(self, i: int, _length: None = None, _offset: None = None) -> None: """Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i. Raises CreationError if i < 0. """ if _length is not None or _offset is not None: raise CreationError("Cannot specify a length of offset for exponential-Golomb codes.") if Bits._options.lsb0: raise CreationError("Exp-Golomb codes cannot be used in lsb0 mode.") self._bitstore = uie2bitstore(i) def _readuie(self, pos: int, length: int = 0) -> Tuple[int, int]: """Return interpretation of next bits as unsigned interleaved exponential-Golomb code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ # _length is ignored - it's only present to make the function signature consistent. if Bits._options.lsb0: raise ReadError("Exp-Golomb codes cannot be read in lsb0 mode.") try: codenum: int = 1 while not self[pos]: pos += 1 codenum <<= 1 codenum += self[pos] pos += 1 pos += 1 except IndexError: raise ReadError("Read off end of bitstring trying to read code.") codenum -= 1 return codenum, pos def _getuie(self) -> int: """Return data as unsigned interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readuie(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.") return value def _setsie(self, i: int, length: None = None, _offset: None = None) -> None: """Initialise bitstring with signed interleaved exponential-Golomb code for integer i.""" if length is not None or _offset is not None: raise CreationError("Cannot specify a length of offset for exponential-Golomb codes.") if Bits._options.lsb0: raise CreationError("Exp-Golomb codes cannot be used in lsb0 mode.") self._bitstore = sie2bitstore(i) def _getsie(self) -> int: """Return data as signed interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readsie(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.") return value def _readsie(self, pos: int, length: int = 0) -> Tuple[int, int]: """Return interpretation of next bits as a signed interleaved exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ codenum, pos = self._readuie(pos) if not codenum: return 0, pos try: if self[pos]: return -codenum, pos + 1 else: return codenum, pos + 1 except IndexError: raise ReadError("Read off end of bitstring trying to read code.") def _setbool(self, value: Union[bool, str], length: Optional[int] = None, _offset: None = 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.") if value in (1, 'True'): self._bitstore = BitStore('1') elif value in (0, 'False'): self._bitstore = BitStore('0') else: raise CreationError(f"Cannot initialise boolean with {value}.") def _getbool(self) -> bool: if self.length != 1: raise InterpretError(f"For a bool interpretation a bitstring must be 1 bit long, not {self.length} bits.") return self[0] def _readbool(self, start: int, length: int = 0) -> int: # length is ignored - it's only present to make the function signature consistent. return self[start] def _readpad(self, pos, length) -> None: return None def _setbin_safe(self, binstring: str, length: None = None, _offset: None = None) -> None: """Reset the bitstring to the value given in binstring.""" self._bitstore = bin2bitstore(binstring) def _setbin_unsafe(self, binstring: str, length: None = None, _offset: None = None) -> None: """Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.""" self._bitstore = bin2bitstore_unsafe(binstring) def _readbin(self, start: int, length: int) -> str: """Read bits and interpret as a binary string.""" if length == 0: return '' return self._bitstore.getslice(slice(start, start + length, None)).to01() def _getbin(self) -> str: """Return interpretation as a binary string.""" return self._readbin(0, self.len) def _setoct(self, octstring: str, length: None = None, _offset: None = None) -> None: """Reset the bitstring to have the value given in octstring.""" self._bitstore = oct2bitstore(octstring) def _readoct(self, start: int, length: int) -> str: """Read bits and interpret as an octal string.""" if length % 3: raise InterpretError("Cannot convert to octal unambiguously - not multiple of 3 bits long.") s = bitarray.util.ba2base(8, self._bitstore.getslice(slice(start, start + length, None))) return s def _getoct(self) -> str: """Return interpretation as an octal string.""" if self.len % 3: raise InterpretError("Cannot convert to octal unambiguously - not multiple of 3 bits long.") ba = self._bitstore.copy() if self._bitstore.modified else self._bitstore return bitarray.util.ba2base(8, ba) def _sethex(self, hexstring: str, length: None = None, _offset: None = None) -> None: """Reset the bitstring to have the value given in hexstring.""" self._bitstore = hex2bitstore(hexstring) def _readhex(self, start: int, length: int) -> str: """Read bits and interpret as a hex string.""" if length % 4: raise InterpretError("Cannot convert to hex unambiguously - not a multiple of 4 bits long.") return bitarray.util.ba2hex(self._bitstore.getslice(slice(start, start + length, None))) def _gethex(self) -> str: """Return the hexadecimal representation as a string. Raises an InterpretError if the bitstring's length is not a multiple of 4. """ if self.len % 4: raise InterpretError("Cannot convert to hex unambiguously - not a multiple of 4 bits long.") ba = self._bitstore.copy() if self._bitstore.modified else self._bitstore return bitarray.util.ba2hex(ba) def _getlength(self) -> int: """Return the length of the bitstring in bits.""" return len(self._bitstore) def _copy(self: TBits) -> TBits: """Create and return a new copy of the Bits (always in memory).""" # Note that __copy__ may choose to return self if it's immutable. This method always makes a copy. s_copy = self.__class__() s_copy._bitstore = self._bitstore.copy() return s_copy def _slice(self: TBits, start: int, end: int) -> TBits: """Used internally to get a slice, without error checking.""" bs = self.__class__() bs._bitstore = self._bitstore.getslice(slice(start, end, None)) return bs def _absolute_slice(self: TBits, start: int, end: int) -> TBits: """Used internally to get a slice, without error checking. Uses MSB0 bit numbering even if LSB0 is set.""" if end == start: return self.__class__() assert start < end, f"start={start}, end={end}" bs = self.__class__() bs._bitstore = self._bitstore.getslice_msb0(slice(start, end, None)) return bs def _readtoken(self, name: str, pos: int, length: Optional[int]) -> Tuple[Union[float, int, str, None, Bits], int]: """Reads a token from the bitstring and returns the result.""" if length is not None and length > self.length - pos: raise ReadError("Reading off the end of the data. " f"Tried to read {length} bits when only {self.length - pos} available.") if length is None: meta_type = Bits._register.name_to_meta_dtype[name] if not meta_type.is_fixed_length and not meta_type.is_unknown_length: length = len(self) - pos dtype = Bits._register.get_dtype(name, length) try: val = dtype.read_fn(self, pos) if isinstance(val, tuple): return val else: assert length is not None return val, pos + length except KeyError: raise ValueError(f"Can't parse token {name}:{length}") def _addright(self, bs: Bits) -> None: """Add a bitstring to the RHS of the current bitstring.""" self._bitstore += bs._bitstore def _addleft(self, bs: Bits) -> None: """Prepend a bitstring to the current bitstring.""" if bs._bitstore.immutable: self._bitstore = bs._bitstore.copy() + self._bitstore else: self._bitstore = bs._bitstore + self._bitstore def _truncateleft(self: TBits, bits: int) -> TBits: """Truncate bits from the start of the bitstring. Return the truncated bits.""" assert 0 <= bits <= self.len if not bits: return self.__class__() truncated_bits = self._absolute_slice(0, bits) if bits == self.len: self._clear() return truncated_bits self._bitstore = self._bitstore.getslice_msb0(slice(bits, None, None)) return truncated_bits def _truncateright(self: TBits, bits: int) -> TBits: """Truncate bits from the end of the bitstring. Return the truncated bits.""" assert 0 <= bits <= self.len if bits == 0: return self.__class__() truncated_bits = self._absolute_slice(self.length - bits, self.length) if bits == self.len: self._clear() return truncated_bits self._bitstore = self._bitstore.getslice_msb0(slice(None, -bits, None)) return truncated_bits def _insert(self, bs: Bits, pos: int) -> None: """Insert bs at pos.""" assert 0 <= pos <= self.len self._bitstore[pos: pos] = bs._bitstore return def _overwrite(self, bs: Bits, pos: int) -> None: """Overwrite with bs at pos.""" assert 0 <= pos <= self.len if bs is self: # Just overwriting with self, so do nothing. assert pos == 0 return self._bitstore[pos: pos + bs.len] = bs._bitstore def _delete(self, bits: int, pos: int) -> None: """Delete bits at pos.""" assert 0 <= pos <= self.len assert pos + bits <= self.len, f"pos={pos}, bits={bits}, len={self.len}" del self._bitstore[pos: pos + bits] return def _reversebytes(self, start: int, end: int) -> None: """Reverse bytes in-place.""" assert (end - start) % 8 == 0 self._bitstore[start:end] = BitStore(frombytes=self._bitstore.getslice(slice(start, end, None)).tobytes()[::-1]) def _invert(self, pos: int) -> None: """Flip bit at pos 1<->0.""" assert 0 <= pos < self.len self._bitstore.invert(pos) def _invert_all(self) -> None: """Invert every bit.""" self._bitstore.invert() def _ilshift(self: TBits, n: int) -> TBits: """Shift bits by n to the left in place. Return self.""" assert 0 < n <= self.len self._addright(Bits(n)) self._truncateleft(n) return self def _irshift(self: TBits, n: int) -> TBits: """Shift bits by n to the right in place. Return self.""" assert 0 < n <= self.len self._addleft(Bits(n)) self._truncateright(n) return self def _imul(self: TBits, n: int) -> TBits: """Concatenate n copies of self in place. Return self.""" assert n >= 0 if not n: self._clear() return self m: int = 1 old_len: int = self.len while m * 2 < n: self._addright(self) m *= 2 self._addright(self[0:(n - m) * old_len]) return self def _readbits(self: TBits, start: int, length: int) -> TBits: """Read some bits from the bitstring and return newly constructed bitstring.""" return self._slice(start, start + length) def _validate_slice(self, start: Optional[int], end: Optional[int]) -> Tuple[int, int]: """Validate start and end and return them as positive bit positions.""" if start is None: start = 0 elif start < 0: start += self._getlength() if end is None: end = self._getlength() elif end < 0: end += self._getlength() if not 0 <= end <= self._getlength(): raise ValueError("end is not a valid position in the bitstring.") if not 0 <= start <= self._getlength(): raise ValueError("start is not a valid position in the bitstring.") if end < start: raise ValueError("end must not be less than start.") return start, end def unpack(self, fmt: Union[str, List[Union[str, int]]], **kwargs) -> List[Union[int, float, str, Bits, bool, bytes, None]]: """Interpret the whole bitstring using fmt and return list. fmt -- A single string or a list of strings with comma separated tokens describing how to interpret the bits in the bitstring. Items can also be integers, for reading new bitstring of the given length. kwargs -- A dictionary or keyword-value pairs - the keywords used in the format string will be replaced with their given value. Raises ValueError if the format is not understood. If not enough bits are available then all bits to the end of the bitstring will be used. See the docstring for 'read' for token examples. """ return self._readlist(fmt, 0, **kwargs)[0] def _readlist(self, fmt: Union[str, List[Union[str, int]]], pos: int, **kwargs: int) \ -> Tuple[List[Union[int, float, str, Bits, bool, bytes, None]], int]: tokens: List[Tuple[str, Optional[Union[str, int]], Optional[str]]] = [] if isinstance(fmt, str): fmt = [fmt] keys: Tuple[str, ...] = tuple(sorted(kwargs.keys())) def convert_length_strings(length_: Optional[Union[str, int]]) -> Optional[int]: int_length: Optional[int] = None if isinstance(length_, str): if length_ in kwargs: int_length = kwargs[length_] if name == 'bytes': int_length *= 8 else: int_length = length_ return int_length has_stretchy_token = False for f_item in fmt: # Replace integers with 'bits' tokens if isinstance(f_item, numbers.Integral): tokens.append(('bits', f_item, None)) else: stretchy, tkns = tokenparser(f_item, keys) if stretchy: if has_stretchy_token: raise Error("It's not possible to have more than one 'filler' token.") has_stretchy_token = True tokens.extend(tkns) if not has_stretchy_token: lst = [] for name, length, _ in tokens: length = convert_length_strings(length) if name in kwargs and length is None: # Using default 'bits' - the name is really the length. value, pos = self._readtoken('bits', pos, kwargs[name]) lst.append(value) continue value, pos = self._readtoken(name, pos, length) if value is not None: # Don't append pad tokens lst.append(value) return lst, pos stretchy_token: Optional[tuple] = None bits_after_stretchy_token = 0 for token in tokens: name, length, _ = token length = convert_length_strings(length) if stretchy_token: if name in Bits._register.unknowable_length_names(): raise Error(f"It's not possible to parse a variable length token ('{name}') after a 'filler' token.") else: if length is None: raise Error("It's not possible to have more than one 'filler' token.") bits_after_stretchy_token += length if length is None and name not in Bits._register.unknowable_length_names(): assert not stretchy_token stretchy_token = token bits_left = self.len - pos return_values = [] for token in tokens: name, length, _ = token if token is stretchy_token: # Set length to the remaining bits length = max(bits_left - bits_after_stretchy_token, 0) length = convert_length_strings(length) value, newpos = self._readtoken(name, pos, length) bits_left -= newpos - pos pos = newpos if value is not None: return_values.append(value) return return_values, pos 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. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to start the search. Defaults to 0. end -- The bit position one past the last bit to search. Defaults to len(self). bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > len(self) or if end < start. >>> BitArray('0xc3e').find('0b1111') (6,) """ bs = Bits._create_from_bitstype(bs) if len(bs) == 0: raise ValueError("Cannot find an empty bitstring.") start, end = self._validate_slice(start, end) ba = Bits._options.bytealigned if bytealigned is None else bytealigned p = self._find(bs, start, end, ba) return p def _find_lsb0(self, bs: Bits, start: int, end: int, bytealigned: bool) -> Union[Tuple[int], Tuple[()]]: # A forward find in lsb0 is very like a reverse find in msb0. assert start <= end assert Bits._options.lsb0 new_slice = offset_slice_indices_lsb0(slice(start, end, None), len(self), 0) msb0_start, msb0_end = self._validate_slice(new_slice.start, new_slice.stop) p = self._rfind_msb0(bs, msb0_start, msb0_end, bytealigned) if p: return (self.length - p[0] - bs.length,) else: return () def _find_msb0(self, bs: Bits, start: int, end: int, bytealigned: bool) -> Union[Tuple[int], Tuple[()]]: """Find first occurrence of a binary string.""" while True: p = self._bitstore.find(bs._bitstore, start, end) if p == -1: return () if not bytealigned or (p % 8) == 0: return (p,) # Advance to just beyond the non-byte-aligned match and try again... start = p + 1 def findall(self, bs: BitsType, start: Optional[int] = None, end: Optional[int] = None, count: Optional[int] = None, bytealigned: Optional[bool] = None) -> Iterable[int]: """Find all occurrences of bs. Return generator of bit positions. bs -- The bitstring to find. start -- The bit position to start the search. Defaults to 0. end -- The bit position one past the last bit to search. Defaults to len(self). count -- The maximum number of occurrences to find. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > len(self) or if end < start. Note that all occurrences of bs are found, even if they overlap. """ if count is not None and count < 0: raise ValueError("In findall, count must be >= 0.") bs = Bits._create_from_bitstype(bs) start, end = self._validate_slice(start, end) ba = Bits._options.bytealigned if bytealigned is None else bytealigned return self._findall(bs, start, end, count, ba) def _findall_msb0(self, bs: Bits, start: int, end: int, count: Optional[int], bytealigned: bool) -> Iterable[int]: c = 0 for i in self._bitstore.getslice_msb0(slice(start, end, None)).itersearch(bs._bitstore): if count is not None and c >= count: return if bytealigned: if (start + i) % 8 == 0: c += 1 yield start + i else: c += 1 yield start + i return def _findall_lsb0(self, bs: Bits, start: int, end: int, count: Optional[int], bytealigned: bool) -> Iterable[int]: assert start <= end assert Bits._options.lsb0 new_slice = offset_slice_indices_lsb0(slice(start, end, None), len(self), 0) msb0_start, msb0_end = self._validate_slice(new_slice.start, new_slice.stop) # Search chunks starting near the end and then moving back. c = 0 increment = max(8192, bs.len * 80) buffersize = min(increment + bs.len, msb0_end - msb0_start) pos = max(msb0_start, msb0_end - buffersize) while True: found = list(self._findall_msb0(bs, start=pos, end=pos + buffersize, count=None, bytealigned=False)) if not found: if pos == msb0_start: return pos = max(msb0_start, pos - increment) continue while found: if count is not None and c >= count: return c += 1 lsb0_pos = self.len - found.pop() - bs.len if not bytealigned or lsb0_pos % 8 == 0: yield lsb0_pos pos = max(msb0_start, pos - increment) if pos == msb0_start: return 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. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to end the reverse search. Defaults to 0. end -- The bit position one past the first bit to reverse search. Defaults to len(self). bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > len(self) or if end < start. """ bs = Bits._create_from_bitstype(bs) start, end = self._validate_slice(start, end) ba = Bits._options.bytealigned if bytealigned is None else bytealigned if not bs.len: raise ValueError("Cannot find an empty bitstring.") p = self._rfind(bs, start, end, ba) return p def _rfind_msb0(self, bs: Bits, start: int, end: int, bytealigned: bool) -> Union[Tuple[int], Tuple[()]]: """Find final occurrence of a binary string.""" increment = max(4096, len(bs) * 64) buffersize = increment + len(bs) p = end while p > start: start_pos = max(start, p - buffersize) ps = list(self._findall_msb0(bs, start_pos, p, count=None, bytealigned=False)) if ps: while ps: if not bytealigned or (ps[-1] % 8 == 0): return (ps[-1],) ps.pop() p -= increment return () def _rfind_lsb0(self, bs: Bits, start: int, end: int, bytealigned: bool) -> Union[Tuple[int], Tuple[()]]: # A reverse find in lsb0 is very like a forward find in msb0. assert start <= end assert Bits._options.lsb0 new_slice = offset_slice_indices_lsb0(slice(start, end, None), len(self), 0) msb0_start, msb0_end = self._validate_slice(new_slice.start, new_slice.stop) p = self._find_msb0(bs, msb0_start, msb0_end, bytealigned) if p: return (self.len - p[0] - bs.length,) else: return () def cut(self, bits: int, start: Optional[int] = None, end: Optional[int] = None, count: Optional[int] = None) -> Iterator[Bits]: """Return bitstring generator by cutting into bits sized chunks. bits -- The size in bits of the bitstring chunks to generate. start -- The bit position to start the first cut. Defaults to 0. end -- The bit position one past the last bit to use in the cut. Defaults to len(self). count -- If specified then at most count items are generated. Default is to cut as many times as possible. """ start_, end_ = self._validate_slice(start, end) if count is not None and count < 0: raise ValueError("Cannot cut - count must be >= 0.") if bits <= 0: raise ValueError("Cannot cut - bits must be >= 0.") c = 0 while count is None or c < count: c += 1 nextchunk = self._slice(start_, min(start_ + bits, end_)) if nextchunk.len == 0: return yield nextchunk if nextchunk._getlength() != bits: return start_ += bits return def split(self, delimiter: BitsType, start: Optional[int] = None, end: Optional[int] = None, count: Optional[int] = None, bytealigned: Optional[bool] = None) -> Iterable[Bits]: """Return bitstring generator by splitting using a delimiter. The first item returned is the initial bitstring before the delimiter, which may be an empty bitstring. delimiter -- The bitstring used as the divider. start -- The bit position to start the split. Defaults to 0. end -- The bit position one past the last bit to use in the split. Defaults to len(self). count -- If specified then at most count items are generated. Default is to split as many times as possible. bytealigned -- If True splits will only occur on byte boundaries. Raises ValueError if the delimiter is empty. """ delimiter = Bits._create_from_bitstype(delimiter) if len(delimiter) == 0: raise ValueError("split delimiter cannot be empty.") start, end = self._validate_slice(start, end) bytealigned_: bool = Bits._options.bytealigned if bytealigned is None else bytealigned if count is not None and count < 0: raise ValueError("Cannot split - count must be >= 0.") if count == 0: return f = functools.partial(self._find_msb0, bs=delimiter, bytealigned=bytealigned_) found = f(start=start, end=end) if not found: # Initial bits are the whole bitstring being searched yield self._slice(start, end) return # yield the bytes before the first occurrence of the delimiter, even if empty yield self._slice(start, found[0]) startpos = pos = found[0] c = 1 while count is None or c < count: pos += delimiter.len found = f(start=pos, end=end) if not found: # No more occurrences, so return the rest of the bitstring yield self._slice(startpos, end) return c += 1 yield self._slice(startpos, found[0]) startpos = pos = found[0] # Have generated count bitstrings, so time to quit. return def join(self: TBits, sequence: Iterable[Any]) -> TBits: """Return concatenation of bitstrings joined by self. sequence -- A sequence of bitstrings. """ s = self.__class__() if len(self) == 0: # Optimised version that doesn't need to add self between every item for item in sequence: s._addright(Bits._create_from_bitstype(item)) else: i = iter(sequence) try: s._addright(Bits._create_from_bitstype(next(i))) while True: n = next(i) s._addright(self) s._addright(Bits._create_from_bitstype(n)) except StopIteration: pass return s def tobytes(self) -> bytes: """Return the bitstring as bytes, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align. """ return self._bitstore.tobytes() def tobitarray(self) -> bitarray.bitarray: """Convert the bitstring to a bitarray object.""" if self._bitstore.modified: # Removes the offset and truncates to length return bitarray.bitarray(self._bitstore.copy()) else: return bitarray.bitarray(self._bitstore) def tofile(self, f: BinaryIO) -> None: """Write the bitstring to a file object, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align. """ # If the bitstring is file based then we don't want to read it all in to memory first. chunk_size = 8 * 100 * 1024 * 1024 # 100 MiB for chunk in self.cut(chunk_size): f.write(chunk.tobytes()) def startswith(self, prefix: BitsType, start: Optional[int] = None, end: Optional[int] = None) -> bool: """Return whether the current bitstring starts with prefix. prefix -- The bitstring to search for. start -- The bit position to start from. Defaults to 0. end -- The bit position to end at. Defaults to len(self). """ prefix = self._create_from_bitstype(prefix) start, end = self._validate_slice(start, end) if end < start + prefix._getlength(): return False end = start + prefix._getlength() return self._slice(start, end) == prefix def endswith(self, suffix: BitsType, start: Optional[int] = None, end: Optional[int] = None) -> bool: """Return whether the current bitstring ends with suffix. suffix -- The bitstring to search for. start -- The bit position to start from. Defaults to 0. end -- The bit position to end at. Defaults to len(self). """ suffix = self._create_from_bitstype(suffix) start, end = self._validate_slice(start, end) if start + suffix.len > end: return False start = end - suffix._getlength() return self._slice(start, end) == suffix def all(self, value: Any, pos: Optional[Iterable[int]] = None) -> bool: """Return True if one or many bits are all set to bool(value). value -- If value is True then checks for bits set to 1, otherwise checks for bits set to 0. pos -- An iterable of bit positions. Negative numbers are treated in the same way as slice indices. Defaults to the whole bitstring. """ value = bool(value) length = self.len if pos is None: if value is True: return self._bitstore.all_set() else: return not self._bitstore.any_set() for p in pos: if p < 0: p += length if not 0 <= p < length: raise IndexError(f"Bit position {p} out of range.") if not bool(self._bitstore.getindex(p)) is value: return False return True def any(self, value: Any, pos: Optional[Iterable[int]] = None) -> bool: """Return True if any of one or many bits are set to bool(value). value -- If value is True then checks for bits set to 1, otherwise checks for bits set to 0. pos -- An iterable of bit positions. Negative numbers are treated in the same way as slice indices. Defaults to the whole bitstring. """ value = bool(value) length = self.len if pos is None: if value is True: return self._bitstore.any_set() else: return not self._bitstore.all_set() for p in pos: if p < 0: p += length if not 0 <= p < length: raise IndexError(f"Bit position {p} out of range.") if bool(self._bitstore.getindex(p)) is value: return True return False def count(self, value: Any) -> int: """Return count of total number of either zero or one bits. value -- If bool(value) is True then bits set to 1 are counted, otherwise bits set to 0 are counted. >>> Bits('0xef').count(1) 7 """ # count the number of 1s (from which it's easy to work out the 0s). count = self._bitstore.count(1) return count if value else self.len - count @staticmethod def _chars_in_pp_token(fmt: str) -> Tuple[str, Optional[int]]: """ bin8 -> 'bin', 8 hex12 -> 'hex', 3 o9 -> 'oct', 3 b -> 'bin', None """ bpc_dict = {'bin': 1, 'oct': 3, 'hex': 4, 'bytes': 8} # bits represented by each printed character short_token: Pattern[str] = re.compile(r'(?Pbytes|bin|oct|hex|b|o|h):?(?P\d+)$') m1 = short_token.match(fmt) if m1: length = int(m1.group('len')) name = m1.group('name') else: length = None name = fmt aliases = {'hex': 'hex', 'oct': 'oct', 'bin': 'bin', 'bytes': 'bytes', 'b': 'bin', 'o': 'oct', 'h': 'hex'} try: name = aliases[name] except KeyError: pass # Should be dealt with in the next check if name not in bpc_dict.keys(): raise ValueError(f"Pretty print formats only support {'/'.join(bpc_dict.keys())}. Received '{fmt}'.") bpc = bpc_dict[name] if length is None: return name, None if length % bpc != 0: raise ValueError(f"Bits per group must be a multiple of {bpc} for '{fmt}' format.") return name, length @staticmethod def _format_bits(bits: Bits, chars_per_group: int, bits_per_group: int, sep: str, fmt: str, getter_fn=None) -> str: if fmt in ['bin', 'oct', 'hex', 'bytes']: raw = {'bin': bits._getbin, 'oct': bits._getoct, 'hex': bits._gethex, 'bytes': bits._getbytes_printable}[fmt]() if chars_per_group == 0: return raw formatted = sep.join(raw[i: i + chars_per_group] for i in range(0, len(raw), chars_per_group)) return formatted else: if fmt == 'bits': formatted = sep.join(str(getter_fn(b, 0)) for b in bits.cut(bits_per_group)) return formatted else: values = [] for i in range(0, len(bits), bits_per_group): b = bits[i: i + bits_per_group] values.append(f"{getter_fn(b, 0): >{chars_per_group}}") formatted = sep.join(values) return formatted @staticmethod def _chars_per_group(bits_per_group: int, fmt: Optional[str]): # TODO: This method is very fragile, and should use the dtype register. if fmt is None: return 0 bpc = {'bin': 1, 'b': 1, 'oct': 3, 'o': 3, 'hex': 4, 'h': 4, 'bytes': 8} # bits represented by each printed character try: return bits_per_group // bpc[fmt] except KeyError: # Work out how many chars are needed for each format given the number of bits if fmt in ['u', 'uint', 'uintne', 'uintbe', 'uintle']: # How many chars is largest uint? chars_per_value = len(str((1 << bits_per_group) - 1)) elif fmt in ['i', 'int', 'intne', 'intbe', 'intle']: # Use largest negative int so we get the '-' sign chars_per_value = len(str((-1 << (bits_per_group - 1)))) elif fmt in ['bfloat', 'bfloatne', 'bfloatbe', 'bfloatle']: chars_per_value = 23 # Empirical value elif fmt in ['f', 'float', 'floatne', 'floatbe', 'floatle']: if bits_per_group in [16, 32]: chars_per_value = 23 # Empirical value elif bits_per_group == 64: chars_per_value = 24 # Empirical value elif fmt == 'e4m3float': chars_per_value = 13 # Empirical value elif fmt == 'e5m2float': chars_per_value = 19 # Empirical value elif fmt == 'bool': chars_per_value = 1 # '0' or '1' elif fmt == 'bits': temp = Bits(bits_per_group) chars_per_value = len(str(temp)) else: assert False, f"Unsupported format string {fmt}." raise ValueError(f"Unsupported format string {fmt}.") return chars_per_value def _pp(self, name1: str, name2: Optional[str], bits_per_group: int, width: int, sep: str, format_sep: str, show_offset: bool, stream: TextIO, lsb0: bool, offset_factor: int, getter_fn=None, getter_fn2=None) -> None: """Internal pretty print method.""" bpc = {'bin': 1, 'oct': 3, 'hex': 4, 'bytes': 8} # bits represented by each printed character offset_width = 0 offset_sep = ' :' if lsb0 else ': ' if show_offset: # This could be 1 too large in some circumstances. Slightly recurrent logic needed to fix it... offset_width = len(str(len(self))) + len(offset_sep) if bits_per_group > 0: group_chars1 = Bits._chars_per_group(bits_per_group, name1) group_chars2 = Bits._chars_per_group(bits_per_group, name2) # The number of characters that get added when we add an extra group (after the first one) total_group_chars = group_chars1 + group_chars2 + len(sep) + len(sep) * bool(group_chars2) width_excluding_offset_and_final_group = width - offset_width - group_chars1 - group_chars2 - len( format_sep) * bool(group_chars2) width_excluding_offset_and_final_group = max(width_excluding_offset_and_final_group, 0) groups_per_line = 1 + width_excluding_offset_and_final_group // total_group_chars max_bits_per_line = groups_per_line * bits_per_group # Number of bits represented on each line else: assert bits_per_group == 0 # Don't divide into groups group_chars1 = group_chars2 = 0 width_available = width - offset_width - len(format_sep) * (name2 is not None) width_available = max(width_available, 1) if name2 is None: max_bits_per_line = width_available * bpc[name1] else: chars_per_24_bits = 24 // bpc[name1] + 24 // bpc[name2] max_bits_per_line = 24 * (width_available // chars_per_24_bits) if max_bits_per_line == 0: max_bits_per_line = 24 # We can't fit into the width asked for. Show something small. assert max_bits_per_line > 0 bitpos = 0 first_fb_width = second_fb_width = None for bits in self.cut(max_bits_per_line): offset = bitpos // offset_factor if Bits._options.lsb0: offset_str = f'{offset_sep}{offset: >{offset_width - len(offset_sep)}}' if show_offset else '' else: offset_str = f'{offset: >{offset_width - len(offset_sep)}}{offset_sep}' if show_offset else '' fb = Bits._format_bits(bits, group_chars1, bits_per_group, sep, name1, getter_fn) if first_fb_width is None: first_fb_width = len(fb) if len(fb) < first_fb_width: # Pad final line with spaces to align it if Bits._options.lsb0: fb = ' ' * (first_fb_width - len(fb)) + fb else: fb += ' ' * (first_fb_width - len(fb)) fb2 = '' if name2 is None else format_sep + Bits._format_bits(bits, group_chars2, bits_per_group, sep, name2, getter_fn2) if second_fb_width is None: second_fb_width = len(fb2) if len(fb2) < second_fb_width: if Bits._options.lsb0: fb2 = ' ' * (second_fb_width - len(fb2)) + fb2 else: fb2 += ' ' * (second_fb_width - len(fb2)) if Bits._options.lsb0 is True: line_fmt = fb + fb2 + offset_str + '\n' else: line_fmt = offset_str + fb + fb2 + '\n' stream.write(line_fmt) bitpos += len(bits) return def pp(self, fmt: Optional[str] = None, width: int = 120, sep: str = ' ', show_offset: bool = True, stream: TextIO = sys.stdout) -> None: """Pretty print the bitstring's value. fmt -- Printed data format. One or two of 'bin', 'oct', 'hex' or 'bytes'. The number of bits represented in each printed group defaults to 8 for hex and bin, 12 for oct and 32 for bytes. This can be overridden with an explicit length, e.g. 'hex:64'. Use a length of 0 to not split into groups, e.g. `bin:0`. width -- Max width of printed lines. Defaults to 120. A single group will always be printed per line even if it exceeds the max width. sep -- A separator string to insert between groups. Defaults to a single space. show_offset -- If True (the default) shows the bit offset in the first column of each line. stream -- A TextIO object with a write() method. Defaults to sys.stdout. >>> s.pp('hex16') >>> s.pp('b, h', sep='_', show_offset=False) """ if fmt is None: fmt = 'bin' if len(self) % 4 != 0 else 'bin, hex' bpc = {'bin': 1, 'oct': 3, 'hex': 4, 'bytes': 8} # bits represented by each printed character formats = [f.strip() for f in fmt.split(',')] if len(formats) == 1: fmt1, fmt2 = formats[0], None elif len(formats) == 2: fmt1, fmt2 = formats[0], formats[1] else: raise ValueError(f"Either 1 or 2 comma separated formats must be specified, not {len(formats)}." " Format string was {fmt}.") name1, length1 = Bits._chars_in_pp_token(fmt1) if fmt2 is not None: name2, length2 = Bits._chars_in_pp_token(fmt2) if fmt2 is not None and length2 is not None and length1 is not None: # Both lengths defined so must be equal if length1 != length2: raise ValueError(f"Differing bit lengths of {length1} and {length2} in format string '{fmt}'.") bits_per_group = None if fmt2 is not None and length2 is not None: bits_per_group = length2 elif length1 is not None: bits_per_group = length1 if bits_per_group is None: if fmt2 is None: bits_per_group = 8 # Default for 'bin' and 'hex' if name1 == 'oct': bits_per_group = 12 elif name1 == 'bytes': bits_per_group = 32 else: # Rule of thumb seems to work OK for all combinations. bits_per_group = 2 * bpc[name1] * bpc[name2] if bits_per_group >= 24: bits_per_group //= 2 format_sep = " " # String to insert on each line between multiple formats self._pp(name1, name2 if fmt2 is not None else None, bits_per_group, width, sep, format_sep, show_offset, stream, Bits._options.lsb0, 1) return def copy(self: TBits) -> TBits: """Return a copy of the bitstring.""" return self._copy() # Create native-endian functions as aliases depending on the byteorder if byteorder == 'little': _setfloatne = _setfloatle _readfloatne = _readfloatle _getfloatne = _getfloatle _setbfloatne = _setbfloatle _readbfloatne = _readbfloatle _getbfloatne = _getbfloatle _setuintne = _setuintle _readuintne = _readuintle _getuintne = _getuintle _setintne = _setintle _readintne = _readintle _getintne = _getintle else: _setfloatne = _setfloatbe _readfloatne = _readfloatbe _getfloatne = _getfloatbe _setbfloatne = _setbfloatbe _readbfloatne = _readbfloatbe _getbfloatne = _getbfloatbe _setuintne = _setuintbe _readuintne = _readuintbe _getuintne = _getuintbe _setintne = _setintbe _readintne = _readintbe _getintne = _getintbe len = length = property(_getlength, doc="The length of the bitstring in bits. Read only.") bitstring-bitstring-4.1.4/bitstring/bitstore.py000066400000000000000000000143741453167633600217710ustar00rootroot00000000000000from __future__ import annotations import bitarray from bitstring.exceptions import CreationError from typing import Union, Iterable, Optional, overload def offset_slice_indices_lsb0(key: slice, length: int, offset: int) -> slice: # First convert slice to all integers # Length already should take account of the offset start, stop, step = key.indices(length) new_start = length - stop - offset new_stop = length - start - offset # For negative step we sometimes get a negative stop, which can't be used correctly in a new slice return slice(new_start, None if new_stop < 0 else new_stop, step) def offset_slice_indices_msb0(key: slice, length: int, offset: int) -> slice: # First convert slice to all integers # Length already should take account of the offset start, stop, step = key.indices(length) start += offset stop += offset # For negative step we sometimes get a negative stop, which can't be used correctly in a new slice return slice(start, None if stop < 0 else stop, step) class BitStore(bitarray.bitarray): """A light wrapper around bitarray that does the LSB0 stuff""" __slots__ = ('modified', 'length', 'offset', 'filename', 'immutable') def __init__(self, *args, immutable: bool = False, frombytes: Optional[Union[bytes, bytearray]] = None, offset: int = 0, length: Optional[int] = None, filename: str = '', **kwargs) -> None: if frombytes is not None: self.frombytes(frombytes) self.immutable = immutable self.offset = offset self.filename = filename # Here 'modified' means that it isn't just the underlying bitarray. It could have a different start and end, and be from a file. # This also means that it shouldn't be changed further, so setting deleting etc. are disallowed. self.modified = offset != 0 or length is not None or filename != '' if self.modified: assert immutable is True # These class variable only exist if modified is True. self.length = super().__len__() - self.offset if length is None else length if self.length < 0: raise CreationError("Can't create bitstring with a negative length.") if self.length + self.offset > super().__len__(): self.length = super().__len__() - self.offset raise CreationError( f"Can't create bitstring with a length of {self.length} and an offset of {self.offset} from {super().__len__()} bits of data.") def __new__(cls, *args, **kwargs) -> bitarray.bitarray: # Just pass on the buffer keyword, not the length, offset, filename and frombytes new_kwargs = {'buffer': kwargs.get('buffer', None)} return bitarray.bitarray.__new__(cls, *args, **new_kwargs) @classmethod def _create_empty_instance(cls): return bitarray.bitarray() def __add__(self, other: bitarray.bitarray) -> BitStore: assert not self.immutable return BitStore(super().__add__(other)) def __iter__(self) -> Iterable[bool]: for i in range(len(self)): yield self.getindex(i) def copy(self) -> BitStore: x = BitStore(self.getslice(slice(None, None, None))) return x def __getitem__(self, item: Union[int, slice]) -> Union[int, BitStore]: # Use getindex or getslice instead raise NotImplementedError def getindex_msb0(self, index: int) -> bool: if self.modified and index >= 0: index += self.offset return bool(super().__getitem__(index)) def getslice_msb0(self, key: slice) -> BitStore: if self.modified: key = offset_slice_indices_msb0(key, len(self), self.offset) return BitStore(super().__getitem__(key)) def getindex_lsb0(self, index: int) -> bool: if self.modified and index >= 0: index += self.offset return bool(super().__getitem__(-index - 1)) def getslice_lsb0(self, key: slice) -> BitStore: if self.modified: key = offset_slice_indices_lsb0(key, len(self), self.offset) else: key = offset_slice_indices_lsb0(key, len(self), 0) return BitStore(super().__getitem__(key)) @overload def setitem_lsb0(self, key: int, value: int) -> None: ... @overload def setitem_lsb0(self, key: slice, value: BitStore) -> None: ... def setitem_lsb0(self, key: Union[int, slice], value: Union[int, BitStore]) -> None: assert not self.immutable if isinstance(key, slice): new_slice = offset_slice_indices_lsb0(key, len(self), 0) super().__setitem__(new_slice, value) else: super().__setitem__(-key - 1, value) def delitem_lsb0(self, key: Union[int, slice]) -> None: assert not self.immutable if isinstance(key, slice): new_slice = offset_slice_indices_lsb0(key, len(self), 0) super().__delitem__(new_slice) else: super().__delitem__(-key - 1) def invert_msb0(self, index: Optional[int] = None) -> None: assert not self.immutable if index is not None: super().invert(index) else: super().invert() def invert_lsb0(self, index: Optional[int] = None) -> None: assert not self.immutable if index is not None: super().invert(-index - 1) else: super().invert() def any_set(self) -> bool: if self.modified: return super().__getitem__(slice(self.offset, self.offset + self.length, None)).any() else: return super().any() def all_set(self) -> bool: if self.modified: return super().__getitem__(slice(self.offset, self.offset + self.length, None)).all() else: return super().all() def __len__(self) -> int: if self.modified: return self.length return super().__len__() setitem_msb0 = bitarray.bitarray.__setitem__ delitem_msb0 = bitarray.bitarray.__delitem__ # Default to the MSB0 methods (mainly to stop mypy from complaining) getslice = getslice_msb0 getindex = getindex_msb0 __setitem__ = bitarray.bitarray.__setitem__ __delitem__ = bitarray.bitarray.__delitem__bitstring-bitstring-4.1.4/bitstring/bitstore_helpers.py000066400000000000000000000260251453167633600235070ustar00rootroot00000000000000from __future__ import annotations import sys import struct import functools from typing import Union, Optional, Dict, Callable import bitarray import bitarray.util from bitstring.utils import tokenparser from bitstring.exceptions import CreationError, InterpretError from bitstring.fp8 import e4m3float_fmt, e5m2float_fmt from bitstring.bitstore import BitStore byteorder: str = sys.byteorder # The size of various caches used to improve performance CACHE_SIZE = 256 def tidy_input_string(s: str) -> str: """Return string made lowercase and with all whitespace and underscores removed.""" try: l = s.split() except (AttributeError, TypeError): raise ValueError(f"Expected str object but received a {type(s)} with value {s}.") return ''.join(l).lower().replace('_', '') # TODO: Shouldn't this be different for LSB0? The bitstores should be reversed before concatenating and we can raise an error for variable length tokens. @functools.lru_cache(CACHE_SIZE) def str_to_bitstore(s: str) -> BitStore: try: _, tokens = tokenparser(s) except ValueError as e: raise CreationError(*e.args) bs = BitStore() if tokens: bs = bs + bitstore_from_token(*tokens[0]) for token in tokens[1:]: bs = bs + bitstore_from_token(*token) bs.immutable = True return bs def bin2bitstore(binstring: str) -> BitStore: binstring = tidy_input_string(binstring) binstring = binstring.replace('0b', '') return bin2bitstore_unsafe(binstring) def bin2bitstore_unsafe(binstring: str) -> BitStore: try: return BitStore(binstring) except ValueError: raise CreationError(f"Invalid character in bin initialiser {binstring}.") def hex2bitstore(hexstring: str) -> BitStore: hexstring = tidy_input_string(hexstring) hexstring = hexstring.replace('0x', '') try: ba = bitarray.util.hex2ba(hexstring) except ValueError: raise CreationError("Invalid symbol in hex initialiser.") return BitStore(ba) def oct2bitstore(octstring: str) -> BitStore: octstring = tidy_input_string(octstring) octstring = octstring.replace('0o', '') try: ba = bitarray.util.base2ba(8, octstring) except ValueError: raise 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.") if i == 0: return BitStore('1') tmp = i + 1 leadingzeros = -1 while tmp > 0: tmp >>= 1 leadingzeros += 1 remainingpart = i + 1 - (1 << leadingzeros) return BitStore('0' * leadingzeros + '1') + uint2bitstore(remainingpart, leadingzeros) def se2bitstore(i: Union[str, int]) -> BitStore: i = int(i) if i > 0: u = (i * 2) - 1 else: u = -2 * i return ue2bitstore(u) def uie2bitstore(i: Union[str, int]) -> BitStore: i = int(i) if i < 0: raise 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') def sie2bitstore(i: Union[str, int]) -> BitStore: i = int(i) if i == 0: return BitStore('1') else: return uie2bitstore(abs(i)) + (BitStore('1') if i < 0 else BitStore('0')) def bfloat2bitstore(f: Union[str, float]) -> BitStore: f = float(f) try: b = struct.pack('>f', f) except OverflowError: # For consistency we overflow to 'inf'. b = struct.pack('>f', float('inf') if f > 0 else float('-inf')) return BitStore(frombytes=b[0:2]) def bfloatle2bitstore(f: Union[str, float]) -> BitStore: f = float(f) try: b = struct.pack(' 0 else float('-inf')) return BitStore(frombytes=b[2:4]) def e4m3float_2bitstore(f: Union[str, float]) -> BitStore: f = float(f) u = e4m3float_fmt.float_to_int8(f) return uint2bitstore(u, 8) def e5m2float_2bitstore(f: Union[str, float]) -> BitStore: f = float(f) u = e5m2float_fmt.float_to_int8(f) return uint2bitstore(u, 8) def uint2bitstore(uint: Union[str, int], length: int) -> BitStore: uint = int(uint) try: if length is None: raise ValueError("No bit length provided when initialising from unsigned int.") x = BitStore(bitarray.util.int2ba(uint, length=length, endian='big', signed=False)) except OverflowError as e: 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) if uint < 0: raise CreationError("uint cannot be initialised with a negative number.") raise e return x def int2bitstore(i: Union[str, int], length: int) -> BitStore: i = int(i) try: if length is None: raise ValueError("No bit length provided when initialising from signed int.") 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}. " f"The allowed range is [{-(1 << (length - 1))}, {(1 << (length - 1)) - 1}].") else: raise e return x 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.") 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.") 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.") 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.") x = int2bitstore(i, length).tobytes() return BitStore(frombytes=x[::-1]) def float2bitstore(f: Union[str, float], length: int) -> BitStore: f = float(f) try: fmt = {16: '>e', 32: '>f', 64: '>d'}[length] except KeyError: raise InterpretError(f"Floats can only be 16, 32 or 64 bits long, not {length} bits") try: b = struct.pack(fmt, f) assert len(b) * 8 == length except (OverflowError, struct.error) as e: # If float64 doesn't fit it automatically goes to 'inf'. This reproduces that behaviour for other types. if length in [16, 32]: b = struct.pack(fmt, float('inf') if f > 0 else float('-inf')) else: raise e return BitStore(frombytes=b) def floatle2bitstore(f: Union[str, float], length: int) -> BitStore: f = float(f) try: fmt = {16: ' 0 else float('-inf')) else: raise e return BitStore(frombytes=b) def bytes2bitstore(b: bytes, length: int) -> BitStore: return BitStore(frombytes=b[:length]) # Create native-endian functions as aliases depending on the byteorder if byteorder == 'little': uintne2bitstore = uintle2bitstore intne2bitstore = intle2bitstore bfloatne2bitstore = bfloatle2bitstore floatne2bitstore = floatle2bitstore else: uintne2bitstore = uintbe2bitstore intne2bitstore = intbe2bitstore bfloatne2bitstore = bfloat2bitstore floatne2bitstore = float2bitstore # Given a string of the format 'name=value' get a bitstore representing it by using # _name2bitstore_func[name](value) name2bitstore_func: Dict[str, Callable[..., BitStore]] = { 'hex': hex2bitstore, 'h': hex2bitstore, '0x': hex2bitstore, '0X': hex2bitstore, 'bin': bin2bitstore, 'b': bin2bitstore, '0b': bin2bitstore, '0B': bin2bitstore, 'oct': oct2bitstore, 'o': oct2bitstore, '0o': oct2bitstore, '0O': oct2bitstore, 'se': se2bitstore, 'ue': ue2bitstore, 'sie': sie2bitstore, 'uie': uie2bitstore, 'bfloat': bfloat2bitstore, 'bfloatbe': bfloat2bitstore, 'bfloatle': bfloatle2bitstore, 'bfloatne': bfloatne2bitstore, 'e4m3float': e4m3float_2bitstore, 'e5m2float': e5m2float_2bitstore, } # Given a string of the format 'name[:]length=value' get a bitstore representing it by using # _name2bitstore_func_with_length[name](value, length) name2bitstore_func_with_length: Dict[str, Callable[..., BitStore]] = { 'uint': uint2bitstore, 'int': int2bitstore, 'u': uint2bitstore, 'i': int2bitstore, 'uintbe': uintbe2bitstore, 'intbe': intbe2bitstore, 'uintle': uintle2bitstore, 'intle': intle2bitstore, 'uintne': uintne2bitstore, 'intne': intne2bitstore, 'float': float2bitstore, 'f': float2bitstore, 'floatbe': float2bitstore, # same as 'float' 'floatle': floatle2bitstore, 'floatne': floatne2bitstore, 'bytes': bytes2bitstore } def bitstore_from_token(name: str, token_length: Optional[int], value: Optional[str]) -> BitStore: if token_length == 0: return BitStore() # For pad token just return the length in zero bits if name == 'pad': bs = BitStore(token_length) bs.setall(0) return bs if value is None: if token_length is None: raise ValueError(f"Token has no value ({name}=???).") else: raise ValueError(f"Token has no value ({name}:{token_length}=???).") if name in name2bitstore_func: bs = name2bitstore_func[name](value) elif name in name2bitstore_func_with_length: bs = name2bitstore_func_with_length[name](value, token_length) elif name == 'bool': if value in (1, 'True', '1'): bs = BitStore('1') elif value in (0, 'False', '0'): bs = BitStore('0') else: raise CreationError("bool token can only be 'True' or 'False'.") else: raise CreationError(f"Can't parse token name {name}.") if token_length is not None and len(bs) != token_length: raise CreationError(f"Token with length {token_length} packed with value of length {len(bs)} " f"({name}:{token_length}={value}).") return bs bitstring-bitstring-4.1.4/bitstring/bitstream.py000066400000000000000000000712151453167633600221250ustar00rootroot00000000000000from __future__ import annotations from bitstring.bits import Bits, BitsType from bitstring.bitarray import BitArray from bitstring.utils import tokenparser from bitstring.exceptions import ReadError, ByteAlignError, CreationError, InterpretError from typing import Union, List, Any, Optional, overload, TypeVar, Tuple import copy import numbers TConstBitStream = TypeVar("TConstBitStream", bound='ConstBitStream') class ConstBitStream(Bits): """A container or stream holding an immutable sequence of bits. For a mutable container use the BitStream class instead. Methods inherited from Bits: all() -- Check if all specified bits are set to 1 or 0. any() -- Check if any of specified bits are set to 1 or 0. copy() -- Return a copy of the bitstring. count() -- Count the number of bits set to 1 or 0. cut() -- Create generator of constant sized chunks. endswith() -- Return whether the bitstring ends with a sub-string. find() -- Find a sub-bitstring in the current bitstring. findall() -- Find all occurrences of a sub-bitstring in the current bitstring. join() -- Join bitstrings together using current bitstring. pp() -- Pretty print the bitstring. rfind() -- Seek backwards to find a sub-bitstring. split() -- Create generator of chunks split by a delimiter. startswith() -- Return whether the bitstring starts with a sub-bitstring. tobitarray() -- Return bitstring as a bitarray from the bitarray package. tobytes() -- Return bitstring as bytes, padding if needed. tofile() -- Write bitstring to file, padding if needed. unpack() -- Interpret bits using format string. Other methods: bytealign() -- Align to next byte boundary. peek() -- Peek at and interpret next bits as a single item. peeklist() -- Peek at and interpret next bits as a list of items. read() -- Read and interpret next bits as a single item. readlist() -- Read and interpret next bits as a list of items. readto() -- Read up to and including next occurrence of a bitstring. Special methods: Also available are the operators [], ==, !=, +, *, ~, <<, >>, &, |, ^. Properties: bin -- The bitstring as a binary string. hex -- The bitstring as a hexadecimal string. oct -- The bitstring as an octal string. bytes -- The bitstring as a bytes object. int -- Interpret as a two's complement signed integer. uint -- Interpret as a two's complement unsigned integer. float / floatbe -- Interpret as a big-endian floating point number. bool -- For single bit bitstrings, interpret as True or False. se -- Interpret as a signed exponential-Golomb code. ue -- Interpret as an unsigned exponential-Golomb code. sie -- Interpret as a signed interleaved exponential-Golomb code. uie -- Interpret as an unsigned interleaved exponential-Golomb code. floatle -- Interpret as a little-endian floating point number. floatne -- Interpret as a native-endian floating point number. bfloat / bfloatbe -- Interpret as a big-endian 16-bit bfloat type. bfloatle -- Interpret as a little-endian 16-bit bfloat type. bfloatne -- Interpret as a native-endian 16-bit bfloat type. intbe -- Interpret as a big-endian signed integer. intle -- Interpret as a little-endian signed integer. intne -- Interpret as a native-endian signed integer. uintbe -- Interpret as a big-endian unsigned integer. uintle -- Interpret as a little-endian unsigned integer. uintne -- Interpret as a native-endian unsigned integer. len -- Length of the bitstring in bits. pos -- The current bit position in the bitstring. """ __slots__ = ('_pos') def __init__(self, __auto: Optional[Union[BitsType, int]] = None, length: Optional[int] = None, offset: Optional[int] = None, pos: int = 0, **kwargs) -> None: """Either specify an 'auto' initialiser: A string of comma separated tokens, an integer, a file object, a bytearray, a boolean iterable or another bitstring. Or initialise via **kwargs with one (and only one) of: bin -- binary string representation, e.g. '0b001010'. hex -- hexadecimal string representation, e.g. '0x2ef' oct -- octal string representation, e.g. '0o777'. bytes -- raw data as a bytes object, for example read from a binary file. int -- a signed integer. uint -- an unsigned integer. float / floatbe -- a big-endian floating point number. bool -- a boolean (True or False). se -- a signed exponential-Golomb code. ue -- an unsigned exponential-Golomb code. sie -- a signed interleaved exponential-Golomb code. uie -- an unsigned interleaved exponential-Golomb code. floatle -- a little-endian floating point number. floatne -- a native-endian floating point number. bfloat / bfloatbe - a big-endian bfloat format 16-bit floating point number. bfloatle -- a little-endian bfloat format 16-bit floating point number. bfloatne -- a native-endian bfloat format 16-bit floating point number. intbe -- a signed big-endian whole byte integer. intle -- a signed little-endian whole byte integer. intne -- a signed native-endian whole byte integer. uintbe -- an unsigned big-endian whole byte integer. uintle -- an unsigned little-endian whole byte integer. uintne -- an unsigned native-endian whole byte integer. filename -- the path of a file which will be opened in binary read-only mode. Other keyword arguments: length -- length of the bitstring in bits, if needed and appropriate. It must be supplied for all integer and float initialisers. offset -- bit offset to the data. These offset bits are ignored and this is mainly intended for use when initialising using 'bytes' or 'filename'. pos -- Initial bit position, defaults to 0. """ 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)}.") self._pos = pos self._bitstore.immutable = True def _setbytepos(self, bytepos: int) -> None: """Move to absolute byte-aligned position in stream.""" self._setbitpos(bytepos * 8) 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.") return self._pos // 8 def _setbitpos(self, pos: int) -> None: """Move to absolute position bit in bitstream.""" if pos < 0: raise ValueError("Bit position cannot be negative.") if pos > self.len: raise ValueError("Cannot seek past the end of the data.") self._pos = pos def _getbitpos(self) -> int: """Return the current position in the stream in bits.""" return self._pos def _clear(self) -> None: Bits._clear(self) self._pos = 0 def __copy__(self: TConstBitStream) -> TConstBitStream: """Return a new copy of the ConstBitStream for the copy module.""" # Note that if you want a new copy (different ID), use _copy instead. # The copy can use the same datastore as it's immutable. s = self.__class__() s._bitstore = self._bitstore # Reset the bit position, don't copy it. s._pos = 0 return s def __add__(self: TConstBitStream, bs: BitsType) -> TConstBitStream: """Concatenate bitstrings and return new bitstring. bs -- the bitstring to append. """ s = Bits.__add__(self, bs) s._pos = 0 return s def append(self, bs: BitsType) -> None: """Append a bitstring to the current bitstring. bs -- The bitstring to append. The current bit position will be moved to the end of the BitStream. """ self._append(bs) self._pos = len(self) def __repr__(self) -> str: """Return representation that could be used to recreate the bitstring. If the returned string is too long it will be truncated. See __str__(). """ return self._repr(self.__class__.__name__, len(self), self._bitstore.offset, self._bitstore.filename, self._pos) def overwrite(self, bs: BitsType, pos: Optional[int] = None) -> None: """Overwrite with bs at bit position pos. bs -- The bitstring to overwrite with. pos -- The bit position to begin overwriting from. The current bit position will be moved to the end of the overwritten section. Raises ValueError if pos < 0 or pos > len(self). """ bs = Bits._create_from_bitstype(bs) if not bs.len: return if pos is None: pos = self._pos if pos < 0: pos += self._getlength() if pos < 0 or pos > self.len: raise ValueError("Overwrite starts outside boundary of bitstring.") self._overwrite(bs, pos) self._pos = pos + bs.len 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. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to start the search. Defaults to 0. end -- The bit position one past the last bit to search. Defaults to len(self). bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > len(self) or if end < start. >>> BitStream('0xc3e').find('0b1111') (6,) """ p = super().find(bs, start, end, bytealigned) if p: self._pos = p[0] return p 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. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to end the reverse search. Defaults to 0. end -- The bit position one past the first bit to reverse search. Defaults to len(self). bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > len(self) or if end < start. """ p = super().rfind(bs, start, end, bytealigned) if p: self._pos = p[0] return p @overload def read(self, fmt: int) -> Bits: ... @overload def read(self, fmt: str) -> Any: ... def read(self, fmt: Union[int, str]) -> Union[int, float, str, Bits, bool, bytes, None]: """Interpret next bits according to the format string and return result. fmt -- Token string describing how to interpret the next bits. Token examples: 'int:12' : 12 bits as a signed integer 'uint:8' : 8 bits as an unsigned integer 'float:64' : 8 bytes as a big-endian float 'intbe:16' : 2 bytes as a big-endian signed integer 'uintbe:16' : 2 bytes as a big-endian unsigned integer 'intle:32' : 4 bytes as a little-endian signed integer 'uintle:32' : 4 bytes as a little-endian unsigned integer 'floatle:64': 8 bytes as a little-endian float 'intne:24' : 3 bytes as a native-endian signed integer 'uintne:24' : 3 bytes as a native-endian unsigned integer 'floatne:32': 4 bytes as a native-endian float 'hex:80' : 80 bits as a hex string 'oct:9' : 9 bits as an octal string 'bin:1' : single bit binary string 'ue' : next bits as unsigned exp-Golomb code 'se' : next bits as signed exp-Golomb code 'uie' : next bits as unsigned interleaved exp-Golomb code 'sie' : next bits as signed interleaved exp-Golomb code 'bits:5' : 5 bits as a bitstring 'bytes:10' : 10 bytes as a bytes object 'bool' : 1 bit as a bool 'pad:3' : 3 bits of padding to ignore - returns None fmt may also be an integer, which will be treated like the 'bits' token. The position in the bitstring is advanced to after the read items. Raises ReadError if not enough bits are available. Raises ValueError if the format is not understood. """ if isinstance(fmt, numbers.Integral): if fmt < 0: raise ValueError("Cannot read negative amount.") if fmt > self.len - self._pos: raise ReadError(f"Cannot read {fmt} bits, only {self.len - self._pos} available.") bs = self._slice(self._pos, self._pos + fmt) self._pos += fmt return bs p = self._pos _, token = tokenparser(fmt) if len(token) != 1: self._pos = p raise ValueError(f"Format string should be a single token, not {len(token)} " "tokens - use readlist() instead.") name, length, _ = token[0] try: value, self._pos = self._readtoken(name, self._pos, length) except ValueError as e: raise InterpretError(e) return value def readlist(self, fmt: Union[str, List[Union[int, str]]], **kwargs) \ -> List[Union[int, float, str, Bits, bool, bytes, None]]: """Interpret next bits according to format string(s) and return list. fmt -- A single string or list of strings with comma separated tokens describing how to interpret the next bits in the bitstring. Items can also be integers, for reading new bitstring of the given length. kwargs -- A dictionary or keyword-value pairs - the keywords used in the format string will be replaced with their given value. The position in the bitstring is advanced to after the read items. Raises ReadError is not enough bits are available. Raises ValueError if the format is not understood. See the docstring for 'read' for token examples. 'pad' tokens are skipped and not added to the returned list. >>> h, b1, b2 = s.readlist('hex:20, bin:5, bin:3') >>> i, bs1, bs2 = s.readlist(['uint:12', 10, 10]) """ value, self._pos = self._readlist(fmt, self._pos, **kwargs) return value 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. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty. Raises ReadError if bs is not found. """ if isinstance(bs, numbers.Integral): raise ValueError("Integers cannot be searched for") bs = Bits._create_from_bitstype(bs) oldpos = self._pos p = self.find(bs, self._pos, bytealigned=bytealigned) if not p: raise ReadError("Substring not found") self._pos += bs.len return self._slice(oldpos, self._pos) @overload def peek(self: TConstBitStream, fmt: int) -> TConstBitStream: ... @overload def peek(self, fmt: str) -> Union[int, float, str, TConstBitStream, bool, bytes, None]: ... def peek(self: TConstBitStream, fmt: Union[int, str]) -> Union[int, float, str, TConstBitStream, bool, bytes, None]: """Interpret next bits according to format string and return result. fmt -- Token string describing how to interpret the next bits. The position in the bitstring is not changed. If not enough bits are available then all bits to the end of the bitstring will be used. Raises ReadError if not enough bits are available. Raises ValueError if the format is not understood. See the docstring for 'read' for token examples. """ pos_before = self._pos value = self.read(fmt) self._pos = pos_before return value def peeklist(self, fmt: Union[str, List[Union[int, str]]], **kwargs) \ -> List[Union[int, float, str, Bits, None]]: """Interpret next bits according to format string(s) and return list. fmt -- One or more integers or strings with comma separated tokens describing how to interpret the next bits in the bitstring. kwargs -- A dictionary or keyword-value pairs - the keywords used in the format string will be replaced with their given value. The position in the bitstring is not changed. If not enough bits are available then all bits to the end of the bitstring will be used. Raises ReadError if not enough bits are available. Raises ValueError if the format is not understood. See the docstring for 'read' for token examples. """ pos = self._pos return_values = self.readlist(fmt, **kwargs) self._pos = pos return return_values def bytealign(self) -> int: """Align to next byte and return number of skipped bits. Raises ValueError if the end of the bitstring is reached before aligning to the next byte. """ skipped = (8 - (self._pos % 8)) % 8 self.pos += skipped return skipped pos = property(_getbitpos, _setbitpos, doc="""The position in the bitstring in bits. Read and write. """) bitpos = property(_getbitpos, _setbitpos, doc="""The position in the bitstring in bits. Read and write. """) bytepos = property(_getbytepos, _setbytepos, doc="""The position in the bitstring in bytes. Read and write. """) class BitStream(ConstBitStream, BitArray): """A container or stream holding a mutable sequence of bits Subclass of the ConstBitStream and BitArray classes. Inherits all of their methods. Methods: all() -- Check if all specified bits are set to 1 or 0. any() -- Check if any of specified bits are set to 1 or 0. append() -- Append a bitstring. bytealign() -- Align to next byte boundary. byteswap() -- Change byte endianness in-place. clear() -- Remove all bits from the bitstring. copy() -- Return a copy of the bitstring. count() -- Count the number of bits set to 1 or 0. cut() -- Create generator of constant sized chunks. endswith() -- Return whether the bitstring ends with a sub-string. find() -- Find a sub-bitstring in the current bitstring. findall() -- Find all occurrences of a sub-bitstring in the current bitstring. insert() -- Insert a bitstring. invert() -- Flip bit(s) between one and zero. join() -- Join bitstrings together using current bitstring. overwrite() -- Overwrite a section with a new bitstring. peek() -- Peek at and interpret next bits as a single item. peeklist() -- Peek at and interpret next bits as a list of items. pp() -- Pretty print the bitstring. prepend() -- Prepend a bitstring. read() -- Read and interpret next bits as a single item. readlist() -- Read and interpret next bits as a list of items. readto() -- Read up to and including next occurrence of a bitstring. replace() -- Replace occurrences of one bitstring with another. reverse() -- Reverse bits in-place. rfind() -- Seek backwards to find a sub-bitstring. rol() -- Rotate bits to the left. ror() -- Rotate bits to the right. set() -- Set bit(s) to 1 or 0. split() -- Create generator of chunks split by a delimiter. startswith() -- Return whether the bitstring starts with a sub-bitstring. tobitarray() -- Return bitstring as a bitarray from the bitarray package. tobytes() -- Return bitstring as bytes, padding if needed. tofile() -- Write bitstring to file, padding if needed. unpack() -- Interpret bits using format string. Special methods: Mutating operators are available: [], <<=, >>=, +=, *=, &=, |= and ^= in addition to [], ==, !=, +, *, ~, <<, >>, &, | and ^. Properties: bin -- The bitstring as a binary string. hex -- The bitstring as a hexadecimal string. oct -- The bitstring as an octal string. bytes -- The bitstring as a bytes object. int -- Interpret as a two's complement signed integer. uint -- Interpret as a two's complement unsigned integer. float / floatbe -- Interpret as a big-endian floating point number. bool -- For single bit bitstrings, interpret as True or False. se -- Interpret as a signed exponential-Golomb code. ue -- Interpret as an unsigned exponential-Golomb code. sie -- Interpret as a signed interleaved exponential-Golomb code. uie -- Interpret as an unsigned interleaved exponential-Golomb code. floatle -- Interpret as a little-endian floating point number. floatne -- Interpret as a native-endian floating point number. bfloat / bfloatbe -- Interpret as a big-endian 16-bit bfloat type. bfloatle -- Interpret as a little-endian 16-bit bfloat type. bfloatne -- Interpret as a native-endian 16-bit bfloat type. intbe -- Interpret as a big-endian signed integer. intle -- Interpret as a little-endian signed integer. intne -- Interpret as a native-endian signed integer. uintbe -- Interpret as a big-endian unsigned integer. uintle -- Interpret as a little-endian unsigned integer. uintne -- Interpret as a native-endian unsigned integer. len -- Length of the bitstring in bits. pos -- The current bit position in the bitstring. """ __slots__ = () def __init__(self, __auto: Optional[Union[BitsType, int]] = None, length: Optional[int] = None, offset: Optional[int] = None, pos: int = 0, **kwargs) -> None: """Either specify an 'auto' initialiser: A string of comma separated tokens, an integer, a file object, a bytearray, a boolean iterable or another bitstring. Or initialise via **kwargs with one (and only one) of: bin -- binary string representation, e.g. '0b001010'. hex -- hexadecimal string representation, e.g. '0x2ef' oct -- octal string representation, e.g. '0o777'. bytes -- raw data as a bytes object, for example read from a binary file. int -- a signed integer. uint -- an unsigned integer. float / floatbe -- a big-endian floating point number. bool -- a boolean (True or False). se -- a signed exponential-Golomb code. ue -- an unsigned exponential-Golomb code. sie -- a signed interleaved exponential-Golomb code. uie -- an unsigned interleaved exponential-Golomb code. floatle -- a little-endian floating point number. floatne -- a native-endian floating point number. bfloat / bfloatbe - a big-endian bfloat format 16-bit floating point number. bfloatle -- a little-endian bfloat format 16-bit floating point number. bfloatne -- a native-endian bfloat format 16-bit floating point number. intbe -- a signed big-endian whole byte integer. intle -- a signed little-endian whole byte integer. intne -- a signed native-endian whole byte integer. uintbe -- an unsigned big-endian whole byte integer. uintle -- an unsigned little-endian whole byte integer. uintne -- an unsigned native-endian whole byte integer. filename -- the path of a file which will be opened in binary read-only mode. Other keyword arguments: length -- length of the bitstring in bits, if needed and appropriate. It must be supplied for all integer and float initialisers. offset -- bit offset to the data. These offset bits are ignored and this is intended for use when initialising using 'bytes' or 'filename'. pos -- Initial bit position, defaults to 0. """ ConstBitStream.__init__(self, __auto, length, offset, pos, **kwargs) if self._bitstore.immutable: self._bitstore = self._bitstore.copy() self._bitstore.immutable = False def __copy__(self) -> BitStream: """Return a new copy of the BitStream.""" s_copy = BitStream() s_copy._pos = 0 s_copy._bitstore = self._bitstore.copy() return s_copy def __iadd__(self, bs: BitsType) -> BitStream: """Append bs to current bitstring. Return self. bs -- the bitstring to append. The current bit position will be moved to the end of the BitStream. """ self._append(bs) self._pos = len(self) return self def prepend(self, bs: BitsType) -> None: """Prepend a bitstring to the current bitstring. bs -- The bitstring to prepend. """ bs = Bits._create_from_bitstype(bs) super().prepend(bs) self._pos = 0 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: """Delete item or range. >>> a = BitStream('0x001122') >>> del a[8:16] >>> print a 0x0022 """ length_before = len(self) self._bitstore.__delitem__(key) if len(self) != length_before: self._pos = 0 def insert(self, bs: BitsType, pos: Optional[int] = None) -> None: """Insert bs at bit position pos. bs -- The bitstring to insert. pos -- The bit position to insert at. The current bit position will be moved to the end of the inserted section. Raises ValueError if pos < 0 or pos > len(self). """ bs = Bits._create_from_bitstype(bs) if len(bs) == 0: return if bs is self: bs = self._copy() if pos is None: pos = self._pos if pos < 0: pos += self._getlength() if not 0 <= pos <= self._getlength(): raise ValueError("Invalid insert position.") self._insert(bs, pos) self._pos = pos + len(bs) def replace(self, old: BitsType, new: BitsType, start: Optional[int] = None, end: Optional[int] = None, count: Optional[int] = None, bytealigned: Optional[bool] = None) -> int: """Replace all occurrences of old with new in place. Returns number of replacements made. old -- The bitstring to replace. new -- The replacement bitstring. start -- Any occurrences that start before this will not be replaced. Defaults to 0. end -- Any occurrences that finish after this will not be replaced. Defaults to len(self). count -- The maximum number of replacements to make. Defaults to replace all occurrences. bytealigned -- If True replacements will only be made on byte boundaries. Raises ValueError if old is empty or if start or end are out of range. """ if count == 0: return 0 old = Bits._create_from_bitstype(old) new = Bits._create_from_bitstype(new) if not old.len: raise ValueError("Empty bitstring cannot be replaced.") start, end = self._validate_slice(start, end) if new is self: # Prevent self assignment woes new = copy.copy(self) length_before = len(self) replacement_count = self._replace(old, new, start, end, 0 if count is None else count, bytealigned) if len(self) != length_before: self._pos = 0 return replacement_countbitstring-bitstring-4.1.4/bitstring/dtypes.py000066400000000000000000000110271453167633600214360ustar00rootroot00000000000000from __future__ import annotations import functools from bitstring.exceptions import InterpretError from bitstring.bits import Bits from typing import Optional, Dict, List class Dtype: def __init__(self, name: str, length: Optional[int], set_fn, read_fn, get_fn, is_integer, is_float, is_signed, is_unknown_length, is_fixed_length) -> None: self.name = name self.length = length self.read_fn = functools.partial(read_fn, length=length) if set_fn is None: self.set_fn = None else: self.set_fn = functools.partial(set_fn, length=length) self.get_fn = get_fn self.is_integer = is_integer self.is_signed = is_signed self.is_float = is_float self.is_fixed_length = is_fixed_length self.is_unknown_length = is_unknown_length def __str__(self) -> str: length_str = '' if (self.length == 0 or self.is_fixed_length) else str(self.length) return f"{self.name}{length_str}" def __repr__(self) -> str: s = self.__str__() return f"{self.__class__.__name__}('{s}')" class MetaDtype: # Represents a class of dtypes, such as uint or float, rather than a concrete dtype such as uint8. def __init__(self, name: str, description: str, set_fn, read_fn, get_fn, is_integer: bool, is_float: bool, is_signed: bool, is_unknown_length: bool, length: Optional[int] = None): # Consistency checks if is_unknown_length and length is not None: raise ValueError("Can't set is_unknown_length and give a value for length.") if is_float and is_integer: raise ValueError("Can't have type that is both float and integer.") self.name = name self.description = description self.is_float = is_float self.is_integer = is_integer self.is_signed = is_signed self.is_fixed_length = length is not None self.is_unknown_length = is_unknown_length self.length = length self.set_fn = set_fn self.read_fn = read_fn # With a start and usually a length self.get_fn = get_fn # Interpret everything def getDtype(self, length: Optional[int] = None) -> Dtype: if length is None: if not self.is_fixed_length and not self.is_unknown_length: raise ValueError(f"No length given for dtype '{self.name}', and meta type is not fixed length.") d = Dtype(self.name, None, self.set_fn, self.read_fn, self.get_fn, self.is_integer, self.is_float, self.is_signed, self.is_unknown_length, self.is_fixed_length) return d if self.is_unknown_length: raise ValueError("Length shouldn't be supplied for dtypes that are variable length.") if self.is_fixed_length: if length != 0 and length != self.length: raise ValueError # TODO length = self.length d = Dtype(self.name, length, self.set_fn, self.read_fn, self.get_fn, self.is_integer, self.is_float, self.is_signed, self.is_unknown_length, self.is_fixed_length) return d class Register: _instance: Optional[Register] = None def __new__(cls) -> Register: if cls._instance is None: cls._instance = super(Register, cls).__new__(cls) cls.name_to_meta_dtype: Dict[str, MetaDtype] = {} return cls._instance @classmethod def add_meta_dtype(cls, meta_dtype: MetaDtype): cls.name_to_meta_dtype[meta_dtype.name] = meta_dtype @classmethod def add_meta_dtype_alias(cls, name: str, alias: str): cls.name_to_meta_dtype[alias] = cls.name_to_meta_dtype[name] @classmethod def get_dtype(cls, name: str, length: Optional[int]) -> Dtype: try: meta_type = cls.name_to_meta_dtype[name] except KeyError: raise ValueError d = meta_type.getDtype(length) # Test if the length makes sense by trying out the getter. # TODO: Optimise! if length != 0 and not d.is_unknown_length: temp = Bits(length) try: _ = d.read_fn(temp, 0) except InterpretError as e: raise ValueError(f"Invalid Dtype: {e.msg}") return d # TODO: This should be only calculated if the register has been altered since the last time it was called. @classmethod def unknowable_length_names(cls) -> List[str]: return [dt_name for dt_name in cls.name_to_meta_dtype if cls.name_to_meta_dtype[dt_name].is_unknown_length] bitstring-bitstring-4.1.4/bitstring/exceptions.py000066400000000000000000000011131453167633600223020ustar00rootroot00000000000000 class Error(Exception): """Base class for errors in the bitstring module.""" def __init__(self, *params: object) -> None: self.msg = params[0] if params else '' self.params = params[1:] class ReadError(Error, IndexError): """Reading or peeking past the end of a bitstring.""" class InterpretError(Error, ValueError): """Inappropriate interpretation of binary data.""" class ByteAlignError(Error): """Whole-byte position or length needed.""" class CreationError(Error, ValueError): """Inappropriate argument during bitstring creation.""" bitstring-bitstring-4.1.4/bitstring/fp8.py000066400000000000000000000215041453167633600206240ustar00rootroot00000000000000""" The 8-bit float formats used here are from a proposal supported by Graphcore, AMD and Qualcomm. See https://arxiv.org/abs/2206.02915 """ import struct import zlib # When uncompressed this gives the conversion from every possible float16 value to a e4m3float value. lut_float16_to_e4m3float_compressed = b"x\x01\xed\xdde\xb6\x96\x05\x00E\xe1\x8f\xee\x06\xe9FZA\xa4\xbb\xbb;\xa4SB\xba\xeb\xd2\xdd\x8dt\x97\x92J(\xa14\xa2\x84" \ b"\x92\x8a\xa4\x82\xd2\x1d\x12\x0e\xe2\xfe\xd8k\xf1\xeeg\x06gO\xe0\x84B\xb2\x80\x05,`\x01\x0bX\xc0\x02\x16\xb0\x80\x05,`\x01\x0bX\xc0\x02\x16\xb0\x80\x05\xde" \ b"\xd7\x02\x11d\x01\x0b\x04\xb6@D\x05\xba@$\x05\xba@\xe4\x80\x8b\x12pQ\x03.Z\xc0E\x87\xc5\x80\xc5\x84\xc5\x82\xc5\x86\xc5\x81\xc5\x85\xc5\x83\xc5\x87%\x80%\x84" \ b"%\x82%\x86%\x81}\x00K\nK\x06K\x0eK\x01K\tK\x05K\rK\x03K\x0bK\x07K\x0f\xcb\x00\xcb\x08\xcb\x04\xfb\x10\x96\x19\x96\x05\x96\x15\x96\r\x96\x1d\x96\x03\x96\x13" \ b"\xf6\x11\xeccX.Xn\xd8'\xb0<\xb0Oaya\xf9`\xf9a\x05`\x05a\x85`\x85aE`Ea\xc5`\xc5a%`%a\xa5`\xa5ae`ea\xe5`\xe5a\x15`\x15a\x95`\x95aU`Ua\xd5`\xd5a5`5a\xb5`\xb5au`" \ b"ua\xf5`\xf5a\r`\ra\x8d`\x8daM`\x9f\xc1\x9a\xc2\x9a\xc1\x9a\xc3Z\xc0Z\xc2Z\xc1Z\xc3\xda\xc0\xda\xc2\xda\xc1\xda\xc3:\xc0>\x87u\x84u\x82u\x86u\x81}\x01\xeb\n" \ b"\xeb\x06\xeb\x0e\xeb\x01\xeb\t\xeb\x05\xeb\r\xeb\x03\xeb\x0b\xeb\x07\xeb\x0f\x1b\x00\x1b\x08\x1b\x04\x1b\x0c\x1b\x02\x1b*\x0bX\xc0\x02\x16\xb0\x80\x05,`\x01" \ b"\x0bX\xc0\x02\x16\xb0\x80\x05,`\x01\x0bX\xc0\x02\x16\xb0\x80\x05,`\x01\x0bX\xc0\x02\x16\xb0\x80\x05,\x10\xde\x02a\xb2\x80\x05\x82Z\xe0}\xfd5s\x97\x05,`\x01" \ b"\x0bX\xc0\x02\x16\xb0\x80\x05,`\x01\x0bX\xc0\x02\x16\xb0\x80\x05,\x10\n\r\x93\x05,\x10\xd8\x02\xc3\x15\xe8\x02#\x14\xe8\x02#\x03nT\xc0\x8d\x0e\xb81\x017\x166" \ b"\x0e6\x1e6\x016\x116\t6\x196\x056\x156\r6\x1d6\x036\x136\x0b6\x1b6\x076\x176\x0f6\x1f\xf6%l\x01l!l\x11l1l\tl)l\x19l9l\x05l%l\x15l5l\rl-l\x1dl=l\x03\xec+\xd8" \ b"\xd7\xb0\x8d\xb0M\xb0\xcd\xb0-\xb0\xad\xb0m\xb0o`\xdf\xc2\xb6\xc3v\xc0v\xc2v\xc1\xbe\x83}\x0f\xdb\r\xdb\x03\xdb\x0b\xdb\x07\xfb\x01\xf6#l?\xec\x00\xec \xec" \ b"\x10\xec0\xec\x08\xec(\xec\x18\xec'\xd8q\xd8\xcf\xb0_`'`'a\xa7`\xa7a\xbf\xc2~\x83\x9d\x81\x9d\x85\x9d\x83\x9d\x87]\x80]\x84\xfd\x0e\xfb\x03v\t\xf6'\xec2\xec" \ b"\n\xec*\xec\x1a\xec:\xec\x06\xec/\xd8\xdf\xb0\x9b\xb0[\xb0\x7f`\xff\xc2n\xc3\xee\xc0\xee\xc2\xee\xc1\xee\xc3\x1e\xc0\x1e\xc2\x1e\xc1\x1e\xc3\x9e\xc0\x9e\xc2" \ b"\x9e\xc1\x9e\xc3^\xc0^\xc2^\xc1\xfe\x83\xbd\x86\xbd\x81\xbd\x85\xbd\x93\x05,`\x01\x0bX\xc0\x02\x16\xb0\x80\x05,`\x01\x0bX\xc0\x02\x16\xb0\x80\x05,`\x01\x0bX" \ b"\xc0\x02\x16\xb0\x80\x05,`\x01\x0bX\xc0\x02\x16\x08o\x81\xa0\x1e\x9f\xbb\xdb\x02\x16\x08\xfb\x1f\x0b\xd9\xb3x" # When uncompressed this gives the conversion from every possible float16 value to a e5m2float value. lut_float16_to_e5m2float_compressed = b'x\x01\xed\xdde\xa2\x16T\x00E\xd1\x07\n\x82R\x92J\nJHK7"\xa1H#\xd2HIwwI\xa7R\xd2H\xab(\xdd%(\xadt\x89A\xa7\xd2\xdd1\x8c' \ b'\xfbc}k\x06gO\xe0DE\x85\x15-\xb0\xe8\x81\xbd\x12\xd8\xab\x81\xc5\x08,f`\xaf\x05\x16\x0b\x17\x1b\xf7:\xee\r\\\x1c\\\\\\<\\|\\\x02\xdc\x9b\xb8\x84\xb8D\xb8\xc4' \ b'\xb8$\xb8\xa4\xb8d\xb8\xb7po\xe3\x92\xe3R\xe0R\xe2R\xe1R\xe3\xd2\xe0\xde\xc1\xa5\xc5\xa5\xc3\xbd\x8b{\x0f\x97\x1e\x97\x01\x97\x11\x97\t\xf7>.3.\x0b.+.\x1b.;.' \ b'\x07.\'\xee\x03\\.\\n\\\x1e\\^\\>\\~\\\x01\\A\\!\\a\\\x11\\Q\\1\\q\xdc\x87\xb8\x12\xb8\x8fp%q\xa5p\xa5qep\x1f\xe3>\xc1\x95\xc5}\x8a+\x87+\x8f\xab\x80\xab\x88' \ b'\xab\x84\xab\x8c\xab\x82\xab\x8a\xfb\x0cW\r\xf79\xae:\xae\x06\xae&\xae\x16\xae6\xae\x0e\xae.\xae\x1e\xee\x0b\\}\\\x03\\C\\#\\c\xdc\x97\xb8&\xb8\xa6\xb8f\xb8' \ b'\xe6\xb8\x16\xb8\x96\xb8V\xb8\xd6\xb86\xb8\xb6\xb8v\xb8\xf6\xb8\x0e\xb8\x8e\xb8N\xb8\xce\xb8.\xb8\xae\xb8n\xb8\xee\xb8\x1e\xb8\x9e\xb8^\xb8\xde\xb8>\xb8\xbe' \ b'\xb8~\xba\xfe\x11\x91\x02\x91\x02j\x81\xa8\xc0\x06\x04\xf6U`\x03\x03\x1b\x14\xd8\xe0\xc0\x86\x0464\xb0a\xb8\xe1\xb8\x11\xb8\x91\xb8Q\xb8\xd1\xb81\xb8\xafq' \ b'\xdf\xe0\xc6\xe2\xc6\xe1\xc6\xe3&\xe0&\xe2\xbe\xc5M\xc2M\xc6M\xc1M\xc5M\xc3M\xc7\xcd\xc0\xcd\xc4}\x87\x9b\x85\x9b\x8d\x9b\x83\x9b\x8b\x9b\x87\x9b\x8f[\x80' \ b'\xfb\x1e\xf7\x03\xeeG\xdcB\xdcO\xb8\x9fq\x8bp\x8bqKpKq\xcbp\xcbq+p+q\xabp\xabqkpkq\xebp\xebq\x1bp\x1bq\x9bp\xbf\xe06\xe3\xb6\xe0~\xc5\xfd\x86\xdb\x8a\xdb' \ b'\x86\xdb\x8e\xdb\x81\xdb\x89\xdb\x85\xdb\x8d\xfb\x1d\xf7\x07n\x0fn/n\x1fn?\xee\x00\xee \xee\x10\xee0\xee\x08\xee(\xee\x18\xeeO\xdcq\xdc_\xb8\xbfq\xff\xe0\xfe' \ b'\xc5\x9d\xc0\x9d\xc4\x9d\xc2\x9d\xc6\x9d\xc1\x9d\xc5\x9d\xc3\x9d\xc7]\xc0]\xc4]\xc2]\xc6\xfd\x87\xfb\x1fw\x05w\x15w\rw\x1dw\x03w\x13w\x0bw\x1bw\x07w\x17w\x0f' \ b'w\x1f\xf7\x00\xf7\x10\xf7\x08\xf7\x18\xf7\x04\xf7\x14\xf7\x0c\xf7\x1c\xf7B\xa7\x1e\x9fGvG\nD\n\xf4\x7f\tz_,\x0e' # When uncompressed this maps each single byte integer to the Python float value that it represents when interpreted as a e4m3float value. lut_int8_to_e4m3float_compressed = b'x\x01\x15\xcc[\xb5\x90!\x10\x80Q"\x18\x81\x08<\xabGQ\x0b\x10\x81\x084\x90\x08D \x02\xcf^\xd1S\xe0\x8f@\x04"\xb8e\xad=/3\x1f!\xfc\x7f\xfd\xad\xf1.\x84Lg\xb29' \ b'\x84\xf7!\xbc!\x92\xc8\x14*\x8d\xce`\xb2\xd8<\x1c.\xe1EO$\x91)T\x1a\x9d\xc1d\xb1y8\\\xc2\x07=\x91D\xa6Pit\x06\x93\xc5\xe6\xe1p\t\x1f\xf5D\x12\x99B\xa5\xd1\x19' \ b'L\x16\x9b\x87\xc3%d=\x91D\xa6Pit\x06\x93\xc5\xe6\xe1p\t\x9f\xf4D\x12\x99B\xa5\xd1\x19L\x16\x9b\x87\xc3%|\xd6\x13Id\n\x95Fg0Yl\x1e\x0e\x97\xf0EO$\x91)T\x1a\xfb' \ b'\xab?\xbe\xb9\xfbnGg\xb29\x84\x1fz"\x89L\xa1\xd2\xe8\x0c&\x8b\xcd\xc3\xe1\x12~\xea\x89$2\x85J\xa33\x98,6\x0f\x87K\xf8\xa5\'\x92\xc8\x14*\x8d\xce`\xb2\xd8<\x1c' \ b'.\xe1\xb7\x9eH"S\xa84:\x83\xc9b\xf3p\xb8\x84\xad\'\x92\xc8\x14*\x8d\xce`\xb2\xd8<\x1c.\xe1\x8f\x9eH"S\xa84:\x83\xc9b\xf3p\xb8\x84\xbfz"\x89L\xa1\xd2\xe8\x0c&\x8b' \ b'\xcd\xc3\xe1\x12^\xf5D\x12\x99B\xa5\xbd\xfe\x03\xc2b\xf2\xc8' # When uncompressed this maps each single byte integer to the Python float value that it represents when interpreted as a e5m2float value. lut_int8_to_e5m2float_compressed = b'x\x01\x1d\xca\xd9\x11\x10\x06\x08EQJ\xb1\x0b\x8d[\xd0\xb8\xb4A\'R\n]\xc45\xc1\xb8\xb5A)\x9e\t3\xe7\x87\xfb"\xfe\xbf\x87\x11\xcd\x12\x8f"\x1e\x90\x14\xcd\xb0\x1c' \ b'\xf1\x87NR4\xc3r\xc4c\x9d\xa4h\x86\xe5\x88\':I\xd1\x0c\xcb\x11Ou\x92\xa2\x19\x96#\x9e\xe9$E3,G<\xd7I\x8afX\x8e\xf8S\')\x9aa9"u\x92\xa2\x19\x96#^\xe8$E3,G\xbc\xd4' \ b'I\x8afX\x8e\xf8K\')\x9aa9\xe2\x95NR4\xc3r\xc4k\x9d\xa4h\x86\xe5\x887:I\xd1\x0c\xcb\x11ou\x92b\xdf\xf9\xfdm\xc7\x12\xefu\x92\xa2\x19\x96#>\xe8$E3,G|\xd4I\x8afX' \ b'\x8e\xf8\xa4\x93\x14\xcd\xb0\x1c\xf1Y\')\x9aa9\xe2\x8bNR4\xc3r\xc4?:I\xd1\x0c\xcb\x11\xff\xea$E3,G\xacNR4\xc3r\xc4W\x9d\xa4h\x86\xe5\x88\xfft\x92\xa2\x19\x96#' \ b'\xbe\xe9$E3,G|\xd7I\x8afX\x8e\xf8\xa1\x93\x14\xcd\xb0\x1c\xf1S\')\x9aa9\xe2\x97NR\xbf~\x03\x96j\xecR' class FP8Format: """Defining an 8-bit floating point format""" def __init__(self, exp_bits: int, bias: int): # We use look up tables to go from an IEEE float16 to the best float8 representation. # For startup efficiency they've been precalculated and zipped up if exp_bits == 4 and bias == 8: self.lut_float16_to_float8 = zlib.decompress(lut_float16_to_e4m3float_compressed) self.lut_int8_to_float = struct.unpack('<256f', zlib.decompress(lut_int8_to_e4m3float_compressed)) elif exp_bits == 5 and bias == 16: self.lut_float16_to_float8 = zlib.decompress(lut_float16_to_e5m2float_compressed) self.lut_int8_to_float = struct.unpack('<256f', zlib.decompress(lut_int8_to_e5m2float_compressed)) else: # pragma: no cover raise RuntimeError("Unsupported float8 format trying to be created. Only e4m3float and e5m2float available for now.") # # This is how the LUTs above were calculated. For reference only - shouldn't be needed any more # self.lut_int8_to_float = self.createLUT_for_int8_to_float() # self.lut_float16_to_float8 = self.createLUT_for_float16_to_float8() # # Then we used a line like this to create the constants: # lut_float16_to_e4m3float_compressed = zlib.compress(self.lut_float16_to_float8, 1) # # See also the test_fp8.py unit tests which check the equivalence. def float_to_int8(self, f: float) -> int: """Given a Python float convert to the best float8 (expressed as an integer in 0-255 range).""" # First convert the float to a float16, then a 16 bit uint try: b = struct.pack('>e', f) except (OverflowError, struct.error): # Return the largest representable positive or negative value return 0b01111111 if f > 0 else 0b11111111 f16_int = int.from_bytes(b, byteorder='big') # Then use this as an index to our large LUT return self.lut_float16_to_float8[f16_int] # We create the 1.5.2 and 1.4.3 formats. The proposed 1.3.4 format isn't supported here. e4m3float_fmt = FP8Format(exp_bits=4, bias=8) e5m2float_fmt = FP8Format(exp_bits=5, bias=16) bitstring-bitstring-4.1.4/bitstring/methods.py000066400000000000000000000111401453167633600215650ustar00rootroot00000000000000from __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, name2bitstore_func_with_length def pack(fmt: Union[str, List[str]], *values, **kwargs) -> 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 describing how to create the BitStream. values -- Zero or more values to pack according to the format. kwargs -- A dictionary or keyword-value pairs - the keywords used in the format string will be replaced with their given value. Token examples: 'int:12' : 12 bits as a signed integer 'uint:8' : 8 bits as an unsigned integer 'float:64' : 8 bytes as a big-endian float 'intbe:16' : 2 bytes as a big-endian signed integer 'uintbe:16' : 2 bytes as a big-endian unsigned integer 'intle:32' : 4 bytes as a little-endian signed integer 'uintle:32' : 4 bytes as a little-endian unsigned integer 'floatle:64': 8 bytes as a little-endian float 'intne:24' : 3 bytes as a native-endian signed integer 'uintne:24' : 3 bytes as a native-endian unsigned integer 'floatne:32': 4 bytes as a native-endian float 'hex:80' : 80 bits as a hex string 'oct:9' : 9 bits as an octal string 'bin:1' : single bit binary string 'ue' / 'uie': next bits as unsigned exp-Golomb code 'se' / 'sie': next bits as signed exp-Golomb code 'bits:5' : 5 bits as a bitstring object 'bytes:10' : 10 bytes as a bytes object 'bool' : 1 bit as a bool 'pad:3' : 3 zero bits as padding >>> s = pack('uint:12, bits', 100, '0xffe') >>> t = pack(['bits', 'bin:3'], s, '111') >>> u = pack('uint:8=a, uint:8=b, uint:55=a', a=6, b=44) """ tokens = [] if isinstance(fmt, str): fmt = [fmt] try: for f_item in fmt: _, tkns = tokenparser(f_item, tuple(sorted(kwargs.keys()))) tokens.extend(tkns) except ValueError as e: raise CreationError(*e.args) value_iter = iter(values) bsl: List[BitStore] = [] try: for name, length, value in tokens: # If the value is in the kwd dictionary then it takes precedence. if value in kwargs: value = kwargs[value] # If the length is in the kwd dictionary then use that too. if length in kwargs: 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) continue if length is not None: length = int(length) if value is None and name != 'pad': # Take the next value from the ones provided value = next(value_iter) if name == 'bits': value = 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)}.") bsl.append(value._bitstore) continue bsl.append(bitstore_from_token(name, length, value)) except StopIteration: raise 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 Bits._options.lsb0: for name, _, _ in tokens: if name in Bits._register.unknowable_length_names(): raise CreationError(f"Variable length tokens ('{name}') cannot be used in lsb0 mode.") for b in bsl[::-1]: s._bitstore += b else: for b in bsl: s._bitstore += b return s raise CreationError(f"Too many parameters present to pack according to the format. Only {len(tokens)} values were expected.") bitstring-bitstring-4.1.4/bitstring/options.py000066400000000000000000000047651453167633600216340ustar00rootroot00000000000000from __future__ import annotations from bitstring.bits import Bits from bitstring.bitarray import BitArray from bitstring.bitstore import BitStore class Options: """Internal class to create singleton module options instance.""" _instance = None def __init__(self): self.set_lsb0(False) self._bytealigned = False @property def lsb0(self) -> bool: return self._lsb0 @lsb0.setter def lsb0(self, value: bool) -> None: self.set_lsb0(value) def set_lsb0(self, value: bool) -> None: self._lsb0 = bool(value) if self._lsb0: Bits._find = Bits._find_lsb0 # type: ignore Bits._rfind = Bits._rfind_lsb0 # type: ignore Bits._findall = Bits._findall_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 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.invert = BitStore.invert_lsb0 # type: ignore else: Bits._find = Bits._find_msb0 # type: ignore Bits._rfind = Bits._rfind_msb0 # type: ignore Bits._findall = Bits._findall_msb0 # 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.invert = BitStore.invert_msb0 # type: ignore @property def bytealigned(self) -> bool: return self._bytealigned @bytealigned.setter def bytealigned(self, value: bool) -> None: self._bytealigned = bool(value) def __new__(cls): if cls._instance is None: cls._instance = super(Options, cls).__new__(cls) return cls._instance bitstring-bitstring-4.1.4/bitstring/py.typed000066400000000000000000000000001453167633600212400ustar00rootroot00000000000000bitstring-bitstring-4.1.4/bitstring/utils.py000066400000000000000000000253121453167633600212700ustar00rootroot00000000000000from __future__ import annotations import itertools import functools import re from typing import Tuple, List, Optional, Pattern, Dict, Union, Match import sys from bitstring.exceptions import Error byteorder: str = sys.byteorder TOKEN_RE: Pattern[str] = None # A token name followed by optional : then an integer number TOKEN_INT_RE: Pattern[str] = None # Tokens which have an unknowable (in advance) length, so it must not be supplied. UNKNOWABLE_LENGTH_TOKENS: List[str] = None def initialise_constants(init_names: List[str], unknowable_length_names: List[str]) -> None: global TOKEN_RE, TOKEN_INT_RE, UNKNOWABLE_LENGTH_TOKENS init_names.sort(key=len, reverse=True) TOKEN_RE = re.compile(r'^(?P' + '|'.join(init_names) + r'):?(?P[^=]+)?(=(?P.*))?$', re.IGNORECASE) TOKEN_INT_RE = re.compile(r'^(?P' + '|'.join(init_names) + r'):?(?P\d*)$') UNKNOWABLE_LENGTH_TOKENS = unknowable_length_names CACHE_SIZE = 256 DEFAULT_BITS: Pattern[str] = re.compile(r'^(?P[^=]+)?(=(?P.*))?$', re.IGNORECASE) MULTIPLICATIVE_RE: Pattern[str] = re.compile(r'^(?P.*)\*(?P.+)') # Hex, oct or binary literals LITERAL_RE: Pattern[str] = re.compile(r'^(?P0([xob]))(?P.+)', re.IGNORECASE) # An endianness indicator followed by one or more struct.pack codes STRUCT_PACK_RE: Pattern[str] = re.compile(r'^(?P[<>@=]){1}(?P(?:\d*[bBhHlLqQefd])+)$') # The same as above, but it doesn't insist on an endianness as it's byteswapping anyway. BYTESWAP_STRUCT_PACK_RE: Pattern[str] = re.compile(r'^(?P[<>@=])?(?P(?:\d*[bBhHlLqQefd])+)$') # An endianness indicator followed by exactly one struct.pack codes SINGLE_STRUCT_PACK_RE: Pattern[str] = re.compile(r'^(?P[<>@=]){1}(?P(?:[bBhHlLqQefd]))$') # A number followed by a single character struct.pack code STRUCT_SPLIT_RE: Pattern[str] = re.compile(r'\d*[bBhHlLqQefd]') # These replicate the struct.pack codes # Big-endian REPLACEMENTS_BE: Dict[str, str] = {'b': 'int:8', 'B': 'uint:8', 'h': 'intbe:16', 'H': 'uintbe:16', 'l': 'intbe:32', 'L': 'uintbe:32', 'q': 'intbe:64', 'Q': 'uintbe:64', 'e': 'floatbe:16', 'f': 'floatbe:32', 'd': 'floatbe:64'} # Little-endian REPLACEMENTS_LE: Dict[str, str] = {'b': 'int:8', 'B': 'uint:8', 'h': 'intle:16', 'H': 'uintle:16', 'l': 'intle:32', 'L': 'uintle:32', 'q': 'intle:64', 'Q': 'uintle:64', 'e': 'floatle:16', 'f': 'floatle:32', 'd': 'floatle:64'} # Native-endian REPLACEMENTS_NE: Dict[str, str] = {'b': 'int:8', 'B': 'uint:8', 'h': 'intne:16', 'H': 'uintne:16', 'l': 'intne:32', 'L': 'uintne:32', 'q': 'intne:64', 'Q': 'uintne:64', 'e': 'floatne:16', 'f': 'floatne:32', 'd': 'floatne:64'} # Tokens which are always the same length, so it doesn't need to be supplied. ALWAYS_FIXED_LENGTH_TOKENS: Dict[str, int] = {'bool': 1, 'bfloat': 16, 'e4m3float': 8, 'e5m2float': 8} # Size in bytes of all the pack codes. PACK_CODE_SIZE: Dict[str, int] = {'b': 1, 'B': 1, 'h': 2, 'H': 2, 'l': 4, 'L': 4, 'q': 8, 'Q': 8, 'e': 2, 'f': 4, 'd': 8} def structparser(m: Match[str]) -> List[str]: """Parse struct-like format string token into sub-token list.""" endian = m.group('endian') # Split the format string into a list of 'q', '4h' etc. formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt')) # Now deal with multiplicative factors, 4h -> hhhh etc. fmt = ''.join([f[-1] * int(f[:-1]) if len(f) != 1 else f for f in formatlist]) if endian in '@=': # Native endianness tokens = [REPLACEMENTS_NE[c] for c in fmt] elif endian == '<': tokens = [REPLACEMENTS_LE[c] for c in fmt] else: assert endian == '>' tokens = [REPLACEMENTS_BE[c] for c in fmt] return tokens @functools.lru_cache(CACHE_SIZE) def parse_name_length_token(fmt: str) -> Tuple[str, int]: # Any single token with just a name and length m = SINGLE_STRUCT_PACK_RE.match(fmt) if m: endian = m.group('endian') f = m.group('fmt') if endian == '>': fmt = REPLACEMENTS_BE[f] elif endian == '<': fmt = REPLACEMENTS_LE[f] else: assert endian in '=@' fmt = REPLACEMENTS_NE[f] m2 = TOKEN_INT_RE.match(fmt) if m2: name = m2.group('name') length_str = m2.group('length') length = 0 if length_str == '' else int(length_str) else: raise ValueError(f"Can't parse 'name[:]length' token '{fmt}'.") if name in UNKNOWABLE_LENGTH_TOKENS: if length is not None: raise ValueError( f"The token '{name}' has a variable length and can't be given the fixed length of {length}.") if name in ALWAYS_FIXED_LENGTH_TOKENS.keys(): token_length = ALWAYS_FIXED_LENGTH_TOKENS[name] if length not in [0, token_length]: raise ValueError(f"{name} tokens can only be {token_length} bits long, not {length} bits.") length = token_length if length is None: length = 0 return name, length @functools.lru_cache(CACHE_SIZE) def parse_single_token(token: str) -> Tuple[str, str, Optional[str]]: m1 = TOKEN_RE.match(token) if m1: name = m1.group('name') length = m1.group('len') value = m1.group('value') else: # If you don't specify a 'name' then the default is 'bits': name = 'bits' m2 = DEFAULT_BITS.match(token) if not m2: raise ValueError(f"Don't understand token '{token}'.") length = m2.group('len') value = m2.group('value') if name in ALWAYS_FIXED_LENGTH_TOKENS.keys(): token_length = str(ALWAYS_FIXED_LENGTH_TOKENS[name]) if length is not None and length != token_length: raise ValueError(f"{name} tokens can only be {token_length} bits long, not {length} bits.") length = token_length return name, length, value @functools.lru_cache(CACHE_SIZE) def tokenparser(fmt: str, keys: Tuple[str, ...] = ()) -> \ Tuple[bool, List[Tuple[str, Union[int, str, None], Optional[str]]]]: """Divide the format string into tokens and parse them. Return stretchy token and list of [initialiser, length, value] initialiser is one of: hex, oct, bin, uint, int, se, ue, 0x, 0o, 0b etc. length is None if not known, as is value. If the token is in the keyword dictionary (keys) then it counts as a special case and isn't messed with. tokens must be of the form: [factor*][initialiser][:][length][=value] """ # Remove whitespace fmt = ''.join(fmt.split()) # Expand any brackets. fmt = expand_brackets(fmt) # Split tokens by ',' and remove whitespace # The meta_tokens can either be ordinary single tokens or multiple # struct-format token strings. meta_tokens = [f.strip() for f in fmt.split(',')] return_values: List[Tuple[str, Union[int, str, None], Optional[str]]] = [] stretchy_token = False for meta_token in meta_tokens: # See if it has a multiplicative factor m = MULTIPLICATIVE_RE.match(meta_token) if not m: factor = 1 else: factor = int(m.group('factor')) meta_token = m.group('token') # See if it's a struct-like format m = STRUCT_PACK_RE.match(meta_token) if m: tokens = structparser(m) else: tokens = [meta_token] ret_vals: List[Tuple[str, Union[str, int, None], Optional[str]]] = [] for token in tokens: if keys and token in keys: # Don't bother parsing it, it's a keyword argument ret_vals.append((token, None, None)) continue if token == '': continue # Match literal tokens of the form 0x... 0o... and 0b... m = LITERAL_RE.match(token) if m: ret_vals.append((m.group('name'), None, m.group('value'))) continue name, length, value = parse_single_token(token) if name in UNKNOWABLE_LENGTH_TOKENS: if length is not None: raise ValueError(f"The token '{name}' has a variable length and can't be given the fixed length of {length}.") else: if length is None: stretchy_token = True if length is not None: # Try converting length to int, otherwise check it's a key. try: length = int(length) if length < 0: raise Error # For the 'bytes' token convert length to bits. if name == 'bytes': length *= 8 except Error: raise ValueError("Can't read a token with a negative length.") except ValueError: if not keys or length not in keys: raise ValueError(f"Don't understand length '{length}' of token.") ret_vals.append((name, length, value)) return_values.extend(itertools.repeat(ret_vals, factor)) return_values = itertools.chain.from_iterable(return_values) return stretchy_token, list(return_values) def expand_brackets(s: str) -> str: """Expand all brackets.""" while True: start = s.find('(') if start == -1: break count = 1 # Number of hanging open brackets p = start + 1 while p < len(s): if s[p] == '(': count += 1 if s[p] == ')': count -= 1 if not count: break p += 1 if count: raise ValueError(f"Unbalanced parenthesis in '{s}'.") if start == 0 or s[start - 1] != '*': s = s[0:start] + s[start + 1:p] + s[p + 1:] else: # Looks for first number*( bracket_re = re.compile(r'(?P\d+)\*\(') m = bracket_re.search(s) if m: factor = int(m.group('factor')) matchstart = m.start('factor') s = s[0:matchstart] + (factor - 1) * (s[start + 1:p] + ',') + s[start + 1:p] + s[p + 1:] else: raise ValueError(f"Failed to parse '{s}'.") return s bitstring-bitstring-4.1.4/doc/000077500000000000000000000000001453167633600163135ustar00rootroot00000000000000bitstring-bitstring-4.1.4/doc/_static/000077500000000000000000000000001453167633600177415ustar00rootroot00000000000000bitstring-bitstring-4.1.4/doc/_static/custom.css000066400000000000000000000031341453167633600217660ustar00rootroot00000000000000 :root { --mainNavColor: #348ad1; --sidebarColor: #f8f8ff; --inlineCodeBackgroundColor: rgb(0 0 0 / 0%); } div#top_nav nav { background-image: linear-gradient(#348ad1, #046ab1); padding: 0.2rem 1rem; } div#top_nav nav h1 img{ height: 3rem; } .highlight { background: #f8f8f8; } div.document { margin-bottom: 1rem; } div.document div.documentwrapper { max-width: 55rem; } div.document div.highlight { border-radius: 0.0rem; border-left: 3px dotted rgba(128, 128, 128, 40%); background-color: var(--mainBackgroundColor); } h1, h2, h3 { color: #046ab1; } div.document div.admonition.attention, div.document div.admonition.caution, div.document div.admonition.warning { border: 2px solid #d77732; } div.document div.admonition.attention p.admonition-title, div.document div.admonition.caution p.admonition-title, div.document div.admonition.warning p.admonition-title { color: #ffffff; background-color: #d77732; } div.document div.admonition.attention, div.document div.admonition.caution, div.document div.admonition.note { border: 2px solid #587f9f; } div.document div.admonition.attention p.admonition-title, div.document div.admonition.caution p.admonition-title, div.document div.admonition.note p.admonition-title { color: #ffffff; background-color: #587f9f; } div.document li p { margin: 0 0 0.3rem 0; } div.document table.docutils td { border: none; padding: 0.1rem 1rem; } div.document table.docutils th { border: none; padding: 0.1rem 1rem; } div.document hr { height: 0.25rem; background-color: #d03434; }bitstring-bitstring-4.1.4/doc/appendices.rst000066400000000000000000000006111453167633600211560ustar00rootroot00000000000000.. currentmodule:: bitstring ########### Appendices ########### Gathered together here are a few odds and ends that didn't fit well into either the user manual or the reference section. The only unifying theme is that none of them provide any vital knowledge about :mod:`bitstring`, and so they can all be safely ignored. .. toctree:: :maxdepth: 2 exp-golomb fp8 optimisation bitstring-bitstring-4.1.4/doc/array.rst000066400000000000000000000475111453167633600201730ustar00rootroot00000000000000.. currentmodule:: bitstring .. note:: The Array class is new in version 4.1 of bitstring, and is considered a 'beta' feature for now. There may be some small changes in future point releases and it hasn't been tested as well as the rest of the library. This documentation may also be a bit 'beta'. Array ===== .. class:: Array(dtype: str, initializer: Iterable | int | Array | array.array | Bits | bytes | bytearray | memoryview | BinaryIO | None = None, trailing_bits: BitsType | None = None) Create a new ``Array`` whose elements are set by the `dtype` (data-type) string. This can be any format which has a fixed length. See :ref:`format_tokens` and :ref:`compact_format` for details on allowed dtype strings, noting that only formats with well defined bit lengths are allowed. The ``Array`` class is a way to efficiently store data that has a single type with a set length. The ``bitstring.Array`` type is meant as a more flexible version of the standard ``array.array``, and can be used the same way. :: import array import bitstring x = array.array('f', [1.0, 2.0, 3.14]) y = bitstring.Array('=f', [1.0, 2.0, 3.14]) assert x.tobytes() == y.tobytes() This example packs three 32-bit floats into objects using both libraries. The only difference is the explicit native endianness for the format string of the bitstring version. The bitstring Array's advantage lies in the way that any fixed-length bitstring format can be used instead of just the dozen or so typecodes supported by the ``array`` module. For example ``'uint4'``, ``'bfloat'`` or ``'hex12'`` can be used, and the endianness of multi-byte dtypes can be properly specified. Each element in the ``Array`` must then be something that makes sense for the ``dtype``. Some examples will help illustrate:: from bitstring import Array # Each unsigned int is stored in 4 bits a = Array('uint4', [0, 5, 5, 3, 2]) # Convert and store floats in 8 bits each b = Array('e5m2float', [-56.0, 0.123, 99.6]) # Each element is a 7 bit signed integer c = Array('int7', [-3, 0, 120]) You can then access and modify the ``Array`` with the usual notation:: a[1:4] # Array('uint4', [5, 5, 3]) b[0] # -56.0 c[-1] # 120 a[0] = 2 b.extend([0.0, -1.5]) Conversion between ``Array`` types can be done using the :meth:`astype` method. If elements of the old array don't fit or don't make sense in the new array then the relevant exceptions will be raised. :: >>> x = Array('float64', [89.3, 1e34, -0.00000001, 34]) >>> y = x.astype('float16') >>> y Array('float16', [89.3125, inf, -0.0, 34.0]) >>> y = y.astype('e4m3float') >>> y Array('e4m3float', [88.0, 240.0, 0.0, 32.0]) >>> y.astype('uint8') Array('uint8', [88, 240, 0, 32]) >>> y.astype('uint7') bitstring.CreationError: 240 is too large an unsigned integer for a bitstring of length 7. The allowed range is [0, 127]. You can also reinterpret the data by changing the :attr:`dtype` property directly. This will not copy any data but will cause the current data to be shown differently. :: >>> x = Array('int16', [-5, 100, -4]) >>> x Array('int16', [-5, 100, -4]) >>> x.dtype = 'int8' >>> x Array('int8', [-1, -5, 0, 100, -1, -4]) The data for the array is stored internally as a :class:`BitArray` object. It can be directly accessed using the :attr:`data` property. You can freely manipulate the internal data using all of the methods available for the :class:`BitArray` class. The :class:`Array` object also has a :attr:`trailing_bits` read-only data member, which consists of the end bits of the :attr:`data` that are left over when the :class:`Array` is interpreted using the :attr:`dtype`. Typically :attr:`trailing_bits` will be an empty :class:`BitArray` but if you change the length of the :attr:`data` or change the :attr:`dtype` specification there may be some bits left over. Some methods, such as :meth:`~Array.append` and :meth:`~Array.extend` will raise an exception if used when :attr:`trailing_bits` is not empty, as it not clear how these should behave in this case. You can however still use :meth:`~Array.insert` which will always leave the :attr:`trailing_bits` unchanged. The :attr:`dtype` string can be a type code such as ``'>H'`` or ``'=d'`` but it can also be a string defining any format which has a fixed-length in bits, for example ``'int12'``, ``'bfloat'``, ``'bytes5'`` or ``'bool'``. Note that the typecodes must include an endianness character to give the byte ordering. This is more like the ``struct`` module typecodes, and is different to the ``array.array`` typecodes which are always native-endian. The correspondence between the big-endian type codes and bitstring dtype strings is given in the table below. ========= =================== Type code bitstring dtype ========= =================== ``'>b'`` ``'int8'`` ``'>B'`` ``'uint8'`` ``'>h'`` ``'int16'`` ``'>H'`` ``'uint16'`` ``'>l'`` ``'int32'`` ``'>L'`` ``'uint32'`` ``'>q'`` ``'int64'`` ``'>Q'`` ``'uint64'`` ``'>e'`` ``'float16'`` ``'>f'`` ``'float32'`` ``'>d'`` ``'float64'`` ========= =================== The endianness character can be ``'>'`` for big-endian, ``'<'`` for little-endian or ``'='`` for native-endian (``'@'`` can also be used for native-endian). In the bitstring dtypes the default is big-endian, but you can specify little or native endian using ``'le'`` or ``'ne'`` modifiers, for example: ============ ============================= Type code bitstring dtype ============ ============================= ``'>H'`` ``'uint16'`` / ``'uintbe16'`` ``'=H'`` ``'uintne16'`` ``' None Add a new element with value `x` to the end of the Array. The type of `x` should be appropriate for the type of the Array. Raises a ``ValueError`` if the Array's bit length is not a multiple of its dtype length (see :attr:`~Array.trailing_bits`). .. method:: Array.astype(dtype: str) -> Array Cast the ``Array`` to the new `dtype` and return the result. :: >>> a = Array('float64', [-990, 34, 1, 0.25]) >>> a.data BitArray('0xc08ef0000000000040410000000000003ff00000000000003fd0000000000000') >>> b = a.astype('float16') >>> b.data BitArray('0xe3bc50403c003400') >>> a == b Array('bool', [True, True, True, True]) .. method:: Array.byteswap() -> None Change the byte endianness of each element. Raises a ``ValueError`` if the format is not an integer number of bytes long. :: >>> a = Array('uint32', [100, 1, 999]) >>> a.byteswap() >>> a Array('uint32', [1677721600, 16777216, 3875733504]) >>> a.dtype = 'uintle32' >>> a Array('uintle32', [100, 1, 999]) .. method:: Array.count(value: float | int | str | bytes) -> int Returns the number of elements set to *value*. :: >>> a = Array('hex4') >>> a.data += '0xdeadbeef' >>> a Array('hex4', ['d', 'e', 'a', 'd', 'b', 'e', 'e', 'f']) >>> a.count('e') 3 For floating point types using a `value` of ``float('nan')`` will count the number of elements for which ``math.isnan()`` returns ``True``. .. method:: Array.equals(other: Any) -> bool Equality test - `other` can be either another bitstring Array or an ``array``. Returns ``True`` if the dtypes are equivalent and the underlying bit data is the same, otherwise returns ``False``. :: >>> a = Array('u8', [1, 2, 3, 2, 1]) >>> a[0:3].equals(a[-1:-4:-1]) True >>> b = Array('i8', [1, 2, 3, 2, 1]) >>> a.equals(b) False To compare only the values contained in the Array, extract them using :meth:`~Array.tolist` first:: >>> a.tolist() == b.tolist() True Note that the ``==`` operator will perform an element-wise equality check and return a new ``Array`` of dtype ``'bool'`` (or raise an exception). >>> a == b Array('bool', [True, True, True, True, True]) .. method:: Array.extend(iterable: Iterable | Array) -> None Extend the Array by constructing new elements from the values in a list or other iterable. The `iterable` can be another ``Array`` or an ``array.array``, but only if the dtype is the same. :: >>> a = Array('int5', [-5, 0, 10]) >>> a.extend([3, 2, 1]) >>> a.extend(a[0:3] // 5) >>> a Array('int5', [-5, 0, 10, 3, 2, 1, -1, 0, 2]) .. method:: Array.fromfile(f: BinaryIO, n: int | None = None) -> None Append items read from a file object. .. method:: Array.insert(i: int, x: float | int | str | bytes) -> None Insert an item at a given position. :: >>> a = Array('e5m2float', [-10, -5, -0.5, 5, 10]) >>> a.insert(3, 0.5) >>> a Array('e5m2float', [-10.0, -5.0, -0.5, 0.5, 5.0, 10.0]) .. method:: Array.pop(i: int | None = None) -> float | int | str | bytes Remove and return the item at position i. If a position isn't specified the final item is returned and removed. :: >>> Array('bytes3', [b'ABC', b'DEF', b'ZZZ']) >>> a.pop(0) b'ABC' >>> a.pop() b'ZZZ' >>> a.pop() b'DEF' .. method:: Array.pp(fmt: str | None = None, width: int = 120, show_offset: bool = False, stream: TextIO = sys.stdout) -> None Pretty print the Array. The format string `fmt` defaults to the Array's current :attr:`dtype`, but any other valid Array format string can be used. If a `fmt` doesn't have an explicit length, the Array's :attr:`itemsize` will be used. A pair of comma-separated format strings can also be used - if both formats specify a length they must be the same. For example ``'float, hex16'`` or ``'u4, b4'``. The output will try to stay within `width` characters per line, but will always output at least one element value. Setting `show_offset` to ``True`` will add a element index to each line of the output. An output `stream` can be specified. This should be an object with a ``write`` method and the default is ``sys.stdout``. >>> a = Array('u20', bytearray(range(100))) >>> a.pp(width=70) [ 16 131844 20576 460809 41136 789774 61697 70163 82257 399128 102817 728093 123378 8482 143938 337447 164498 666412 185058 995377 205619 275766 226179 604731 246739 933696 267300 214085 287860 543050 308420 872015 328981 152404 349541 481369 370101 810334 390662 90723 ] >>> a.pp('hex32', show_offset=True, width=70) [ 0: 00010203 04050607 08090a0b 0c0d0e0f 10111213 14151617 18191a1b 7: 1c1d1e1f 20212223 24252627 28292a2b 2c2d2e2f 30313233 34353637 14: 38393a3b 3c3d3e3f 40414243 44454647 48494a4b 4c4d4e4f 50515253 21: 54555657 58595a5b 5c5d5e5f 60616263 ] >>> a.pp('i12, hex', width=70) [ 0 258 48 1029 96 1800 : 000 102 030 405 060 708 144 -1525 192 -754 241 17 : 090 a0b 0c0 d0e 0f1 011 289 788 337 1559 385 -1766 : 121 314 151 617 181 91a 433 -995 481 -224 530 547 : 1b1 c1d 1e1 f20 212 223 578 1318 626 -2007 674 -1236 : 242 526 272 829 2a2 b2c 722 -465 771 306 819 1077 : 2d2 e2f 303 132 333 435 867 1848 915 -1477 963 -706 : 363 738 393 a3b 3c3 d3e 1012 65 1060 836 1108 1607 : 3f4 041 424 344 454 647 1156 -1718 1204 -947 1252 -176 : 484 94a 4b4 c4d 4e4 f50 1301 595 1349 1366 1397 -1959 : 515 253 545 556 575 859 1445 -1188 1493 -417 1542 354 : 5a5 b5c 5d5 e5f 606 162 ] + trailing_bits = 0x63 .. method:: Array.reverse() -> None Reverse the order of all items in the Array. :: >>> a = Array('>L', [100, 200, 300]) >>> a.reverse() >>> a Array('>L', [300, 200, 100]) .. method:: Array.tobytes() -> bytes Return Array data as bytes object, padding with zero bits at the end if needed. :: >>> a = Array('i4', [3, -6, 2, -3, 2, -7]) >>> a.tobytes() b':-)' .. method:: Array.tofile(f: BinaryIO) -> None Write Array data to a file, padding with zero bits at the end if needed. .. method:: Array.tolist() -> List[float | int | str | bytes] Return Array items as a list. Each packed element of the Array is converted to an ordinary Python object such as a ``float`` or an ``int`` depending on the Array's format, and returned in a Python list. Special Methods --------------- Type promotion """""""""""""" Many operations can be performed between two ``Array`` objects. For these to be valid the dtypes of the ``Array`` objects must be numerical, that is they must represent an integer or floating point value. Some operations have tighter restrictions, such as the shift operators ``<<`` and ``>>`` requiring integers only. The dtype of the resulting ``Array`` is calculated by applying these rules: 0. For comparison operators (``<``, ``>=``, ``==``, ``!=`` etc.) the result is always an ``Array`` of dtype ``'bool'``. For other operators, one of the two input ``Array`` dtypes is used as the ouput dtype by applying the remaining rules in order until a winner is found: 1. Floating point types always win against integer types. 2. Signed integer types always win against unsigned integer types. 3. Longer types win against shorter types. 4. In a tie the first type wins. Some examples should help illustrate: ======= ================ ============ ================ === ================== Rule 0 ``'uint8'`` ``<=`` ``'float64'`` → ``'bool'`` Rule 1 ``'int32'`` ``+`` ``'float16'`` → ``'float16'`` Rule 2 ``'uint20'`` ``//`` ``'int10'`` → ``'int10'`` Rule 3 ``'int8'`` ``*`` ``'int16'`` → ``'int16'`` Rule 4 ``'float16'`` ``-=`` ``'bfloat'`` → ``'float16'`` ======= ================ ============ ================ === ================== Comparison operators """""""""""""""""""" Comparison operators can operate between two ``Array`` objects, or between an ``Array`` and a scalar quantity (usually a number). Note that they always produce an ``Array`` of :attr:`~Array.dtype` ``'bool'``, including the equality and inequality operators. To test the boolean equality of two Arrays use the :meth:`~Array.equals` method instead. .. method:: Array.__eq__(self, other: int | float | str | BitsType | Array) -> Array ``a1 == a2`` .. method:: Array.__ne__(self, other: int | float | str | BitsType | Array) -> Array ``a1 != a2`` .. method:: Array.__lt__(self, other: int | float | Array) -> Array ``a1 < a2`` .. method:: Array.__le__(self, other: int | float | Array) -> Array ``a1 <= a2`` .. method:: Array.__gt__(self, other: int | float | Array) -> Array ``a1 > a2`` .. method:: Array.__ge__(self, other: int | float | Array) -> Array ``a1 >= a2`` Numerical operators """"""""""""""""""" .. method:: Array.__add__(other: int | float | Array) -> Array ``a + x`` .. method:: Array.__sub__(self, other: int | float | Array) -> Array ``a - x`` .. method:: Array.__mul__(self, other: int | float | Array) -> Array ``a * x`` .. method:: Array.__truediv__(self, other: int | float | Array) -> Array ``a / x`` .. method:: Array.__floordiv__(self, other: int | float | Array) -> Array ``a // x`` .. method:: Array.__rshift__(self, other: int | Array) -> Array ``a >> i`` .. method:: Array.__lshift__(self, other: int | Array) -> Array ``a << i`` .. method:: Array.__mod__(self, other: int | Array) -> Array ``a % i`` .. method:: Array.__neg__(self) -> Array ``-a`` .. method:: Array.__abs__(self) -> Array ``abs(a)`` Bitwise operators """"""""""""""""" .. method:: Array.__and__(self, other: Bits) -> Array ``a & bs`` >>> a &= '0b1110' .. method:: Array.__or__(self, other: Bits) -> Array ``a | bs`` >>> a |= '0x7fff' .. method:: Array.__xor__(self, other: Bits) -> Array ``a ^ bs`` >>> a ^= bytearray([56, 23]) Python language operators """"""""""""""""""""""""" .. method:: Array.__len__(self) -> int ``len(a)`` Return the number of elements in the Array. :: >>> a = Array('uint20', [1, 2, 3]) >>> len(a) 3 >>> a.dtype = 'uint1' >>> len(a) 60 .. method:: Array.__getitem__(self, key: int | slice) -> float | int | str | bytes | Array ``a[i]`` ``a[start:end:step]`` .. method:: Array.__setitem__(self, key: int | slice, value) -> None ``a[i] = x`` ``a[start:end:step] = x`` .. method:: Array.__delitem__(self, key: int | slice) -> None ``del a[i]`` ``del[start:end:step]`` Properties ---------- .. attribute:: Array.data :type: BitArray The bit data of the ``Array``, as a ``BitArray``. Read and write, and can be freely manipulated with all of ``BitArray`` methods. Note that some ``Array`` methods such as :meth:`~Array.append` and :meth:`~Array.extend` require the :attr:`~Array.data` to have a length that is a multiple of the ``Array``'s :attr:`~Array.itemsize`. .. attribute:: Array.dtype :type: str The data type string used to initialise the ``Array`` type. Read and write. Changing the ``dtype`` for an already formed ``Array`` will cause all of the bit data to be reinterpreted and can change the length of the ``Array``. However, changing the ``dtype`` won't change the underlying bit data in any way. Note that some ``Array`` methods such as :meth:`~Array.append` and :meth:`~Array.extend` require the bit data to have a length that is a multiple of the ``Array``'s :attr:`~Array.itemsize`. .. attribute:: Array.itemsize :type: int The size *in bits* of each item in the ``Array``. Read-only. Note that this gives a value in bits, unlike the equivalent in the ``array`` module which gives a value in bytes. :: >>> a = Array('>h') >>> b = Array('bool') >>> a.itemsize 16 >>> b.itemsize 1 .. attribute:: Array.trailing_bits :type: BitArray A ``BitArray`` object equal to the end of the ``data`` that is not a multiple of the ``itemsize``. Read only. This will typically be an empty ``BitArray``, but if the ``dtype`` or the ``data`` of an ``Array`` object has been altered after its creation then there may be left-over bits at the end of the data. Note that any methods that append items to the ``Array`` will fail with a ``ValueError`` if there are any trailing bits. bitstring-bitstring-4.1.4/doc/bitarray.rst000066400000000000000000000353471453167633600206760ustar00rootroot00000000000000.. currentmodule:: bitstring BitArray ======== .. class:: BitArray(__auto: BitsType | int | None, length: int | None = None, offset: int | None = None, **kwargs) The :class:`Bits` class is the base class for :class:`BitArray` and so (with the exception of :meth:`~Bits.__hash__`) all of its methods are also available for :class:`BitArray` objects. The initialiser is also the same as for :class:`Bits` and so won't be repeated here. A :class:`BitArray` is a mutable :class:`Bits`, and so the one thing all of the methods listed here have in common is that they can modify the contents of the bitstring. Methods ------- .. method:: BitArray.append(bs: BitsType) -> None Join a :class:`BitArray` to the end of the current :class:`BitArray`. :: >>> s = BitArray('0xbad') >>> s.append('0xf00d') >>> s BitArray('0xbadf00d') .. method:: BitArray.byteswap(fmt: str | int | Iterable[int] | None = None, start: int | None = None, end: int | None = None, repeat: bool = True) -> int Change the endianness of the :class:`BitArray` in-place according to *fmt*. Return the number of swaps done. The *fmt* can be an integer, an iterable of integers or a compact format string similar to those used in :func:`pack` (described in :ref:`compact_format`). It defaults to 0, which means reverse as many bytes as possible. The *fmt* gives a pattern of byte sizes to use to swap the endianness of the :class:`BitArray`. Note that if you use a compact format string then the endianness identifier (``<``, ``>`` or ``=``) is not needed, and if present it will be ignored. *start* and *end* optionally give a slice to apply the transformation to (it defaults to the whole :class:`BitArray`). If *repeat* is ``True`` then the byte swapping pattern given by the *fmt* is repeated in its entirety as many times as possible. >>> s = BitArray('0x00112233445566') >>> s.byteswap(2) 3 >>> s BitArray('0x11003322554466') >>> s.byteswap('h') 3 >>> s BitArray('0x00112233445566') >>> s.byteswap([2, 5]) 1 >>> s BitArray('0x11006655443322') It can also be used to swap the endianness of the whole :class:`BitArray`. :: >>> s = BitArray('uintle32=1234') >>> s.byteswap() >>> print(s.uintbe) 1234 .. method:: BitArray.clear() -> None Removes all bits from the bitstring. ``s.clear()`` is equivalent to ``del s[:]`` and simply makes the bitstring empty. .. method:: BitArray.insert(bs: BitsType, pos: int) -> None Inserts *bs* at *pos*. When used with the :class:`BitStream` class the *pos* is optional, and if not present the current bit position will be used. After insertion the property :attr:`~ConstBitStream.pos` will be immediately after the inserted bitstring. :: >>> s = BitStream('0xccee') >>> s.insert('0xd', 8) >>> s BitStream('0xccdee') >>> s.insert('0x00') >>> s BitStream('0xccd00ee') .. method:: BitArray.invert(pos: int | Iterable[int] | None = None) -> None Inverts one or many bits from ``1`` to ``0`` or vice versa. *pos* can be either a single bit position or an iterable of bit positions. Negative numbers are treated in the same way as slice indices and it will raise :exc:`IndexError` if ``pos < -len(s)`` or ``pos > len(s)``. The default is to invert the entire :class:`BitArray`. :: >>> s = BitArray('0b111001') >>> s.invert(0) >>> s.bin '011001' >>> s.invert([-2, -1]) >>> s.bin '011010' >>> s.invert() >>> s.bin '100101' .. method:: BitArray.overwrite(bs: BitsType, pos: int) -> None Replaces the contents of the current :class:`BitArray` with *bs* at *pos*. When used with the :class:`BitStream` class the *pos* is optional, and if not present the current bit position will be used. After insertion the property :attr:`~ConstBitStream.pos` will be immediately after the overwritten bitstring. :: >>> s = BitArray(length=10) >>> s.overwrite('0b111', 3) >>> s BitArray('0b0001110000') >>> s.pos 6 .. method:: BitArray.prepend(bs: BitsType) -> None Inserts *bs* at the beginning of the current :class:`BitArray`. :: >>> s = BitArray('0b0') >>> s.prepend('0xf') >>> s BitArray('0b11110') .. method:: BitArray.replace(old: BitsType, new: BitsType, start: int | None = None, end: int | None = None, count: int | None = None, bytealigned: bool | None = None) -> int Finds occurrences of *old* and replaces them with *new*. Returns the number of replacements made. If *bytealigned* is ``True`` then replacements will only be made on byte boundaries. *start* and *end* give the search range and default to ``0`` and :attr:`~Bits.len` respectively. If *count* is specified then no more than this many replacements will be made. :: >>> s = BitArray('0b0011001') >>> s.replace('0b1', '0xf') 3 >>> print(s.bin) 0011111111001111 >>> s.replace('0b1', '', count=6) 6 >>> print(s.bin) 0011001111 .. method:: BitArray.reverse(start: int | None = None, end: int | None = None) -> None Reverses bits in the :class:`BitArray` in-place. *start* and *end* give the range of bits to reverse and default to ``0`` and :attr:`~Bits.len` respectively. :: >>> a = BitArray('0b000001101') >>> a.reverse() >>> a.bin '101100000' >>> a.reverse(0, 4) >>> a.bin '110100000' .. method:: BitArray.rol(bits: int, start: int | None = None, end: int | None = None) -> None Rotates the contents of the :class:`BitArray` in-place by *bits* bits to the left. *start* and *end* define the slice to use and default to ``0`` and :attr:`~Bits.len` respectively. Raises :exc:`ValueError` if ``bits < 0``. :: >>> s = BitArray('0b01000001') >>> s.rol(2) >>> s.bin '00000101' .. method:: BitArray.ror(bits: int, start: int | None = None, end: int | None = None) -> None Rotates the contents of the :class:`BitArray` in-place by *bits* bits to the right. *start* and *end* define the slice to use and default to ``0`` and :attr:`~Bits.len` respectively. Raises :exc:`ValueError` if ``bits < 0``. .. method:: BitArray.set(value: bool, pos: int | Iterable[int] | None = None) -> None Sets one or many bits to either ``1`` (if *value* is ``True``) or ``0`` (if *value* isn't ``True``). *pos* can be either a single bit position or an iterable of bit positions. Negative numbers are treated in the same way as slice indices and it will raise :exc:`IndexError` if ``pos < -len(s)`` or ``pos > len(s)``. The default is to set every bit in the :class:`BitArray`. Using ``s.set(True, x)`` can be more efficient than other equivalent methods such as ``s[x] = 1``, ``s[x] = "0b1"`` or ``s.overwrite('0b1', x)``, especially if many bits are being set. In particular using a ``range`` object as an iterable is treated as a special case and is done efficiently. :: >>> s = BitArray('0x0000') >>> s.set(True, -1) >>> print(s) 0x0001 >>> s.set(1, (0, 4, 5, 7, 9)) >>> s.bin '1000110101000001' >>> s.set(0) >>> s.bin '0000000000000000' >>> s.set(1, range(0, len(s), 2)) >>> s.bin '1010101010101010' Properties ---------- Note that the ``bin``, ``oct``, ``hex``, ``int``, ``uint`` and ``float`` properties can all be shortened to their initial letter. Properties can also have a length in bits appended to them to make properties such as ``u8`` or ``floatle64`` (with the exception of the ``bytes`` property which uses a unit of bytes instead of bits, so ``bytes4`` is 32 bits long). These properties with lengths can be used to quickly create a new bitstring. :: >>> a = BitArray() >>> a.f32 = 17.6 >>> a.h '418ccccd' >>> a.i7 = -1 >>> a.b '1111111' .. attribute:: BitArray.bin :type: str :noindex: .. attribute:: BitArray.b :type: str :noindex: Writable version of :attr:`Bits.bin`. .. attribute:: BitArray.bfloat :type: float :noindex: .. attribute:: BitArray.bfloatbe :type: float :noindex: .. attribute:: BitArray.bfloatle :type: float :noindex: .. attribute:: BitArray.bfloatne :type: float :noindex: Writable versions of :attr:`Bits.bfloat` / :attr:`Bits.bfloatbe` / :attr:`Bits.bfloatle` / :attr:`Bits.bfloatne`. .. attribute:: BitArray.bool :type: bool :noindex: Writable version of :attr:`Bits.bool`. .. attribute:: BitArray.bytes :type: bytes :noindex: Writable version of :attr:`Bits.bytes`. .. attribute:: BitArray.hex :type: str :noindex: .. attribute:: BitArray.h :type: str :noindex: Writable version of :attr:`Bits.hex`. .. attribute:: BitArray.int :type: int :noindex: .. attribute:: BitArray.i :type: int :noindex: Writable version of :attr:`Bits.int`. The properties can have a bit length appended to it such as ``i32`` or ``int5`` to specify the new length of the bitstring. Using a length too small to contain the value given will raise a :exc:`CreationError`. When used as a setter without a new length the value must fit into the current length of the :class:`BitArray`, else a :exc:`ValueError` will be raised. :: >>> s = BitArray('0xf3') >>> s.int -13 >>> s.int = 1232 ValueError: int 1232 is too large for a BitArray of length 8. .. attribute:: BitArray.intbe :type: int :noindex: Writable version of :attr:`Bits.intbe`. When used as a setter the value must fit into the current length of the :class:`BitArray`, else a :exc:`ValueError` will be raised. .. attribute:: BitArray.intle :type: int :noindex: Writable version of :attr:`Bits.intle`. When used as a setter the value must fit into the current length of the :class:`BitArray`, else a :exc:`ValueError` will be raised. .. attribute:: BitArray.intne :type: int :noindex: Writable version of :attr:`Bits.intne`. When used as a setter the value must fit into the current length of the :class:`BitArray`, else a :exc:`ValueError` will be raised. .. attribute:: BitArray.float :type: float :noindex: .. attribute:: BitArray.floatbe :type: float :noindex: .. attribute:: BitArray.f :type: float :noindex: Writable version of :attr:`Bits.float`. The standard ``float``, the big-endian ``floatbe`` and the shortened ``f`` are all equivalent. The properties can have a bit length appended to them such as ``f16`` or ``floatle64`` to specify the new length of the bitstring. Using a length that doesn't support any floating point types will raise a :exc:`CreationError`. .. attribute:: BitArray.floatle :type: float :noindex: Writable version of :attr:`Bits.floatle`. .. attribute:: BitArray.floatne :type: float :noindex: Writable version of :attr:`Bits.floatne`. .. attribute:: BitArray.e4m3float :type: float :noindex: Writable version of :attr:`Bits.e4m3float`. .. attribute:: BitArray.e5m2float :type: float :noindex: Writable version of :attr:`Bits.e5m2float`. .. attribute:: BitArray.oct :type: str :noindex: .. attribute:: BitArray.o :type: str :noindex: Writable version of :attr:`Bits.oct`. .. attribute:: BitArray.se :type: int :noindex: Writable version of :attr:`Bits.se`. .. attribute:: BitArray.ue :type: int :noindex: Writable version of :attr:`Bits.uie`. .. attribute:: BitArray.sie :type: int :noindex: Writable version of :attr:`Bits.sie`. .. attribute:: BitArray.uie :type: int :noindex: Writable version of :attr:`Bits.ue`. .. attribute:: BitArray.uint :type: int :noindex: .. attribute:: BitArray.u :type: int :noindex: Writable version of :attr:`Bits.uint`. When used as a setter the value must fit into the current length of the :class:`BitArray`, else a :exc:`ValueError` will be raised. .. attribute:: BitArray.uintbe :type: int :noindex: Writable version of :attr:`Bits.uintbe`. When used as a setter the value must fit into the current length of the :class:`BitArray`, else a :exc:`ValueError` will be raised. .. attribute:: BitArray.uintle :type: int :noindex: Writable version of :attr:`Bits.uintle`. When used as a setter the value must fit into the current length of the :class:`BitArray`, else a :exc:`ValueError` will be raised. .. attribute:: BitArray.uintne :type: int :noindex: Writable version of :attr:`Bits.uintne`. When used as a setter the value must fit into the current length of the :class:`BitArray`, else a :exc:`ValueError` will be raised. Special Methods --------------- .. method:: BitArray.__delitem__(key) ``del s[start:end:step]`` Deletes the slice specified. .. method:: BitArray.__iadd__(bs) ``s1 += s2`` Appends *bs* to the current bitstring. Note that for :class:`BitArray` objects this will be an in-place change, whereas for :class:`Bits` objects using ``+=`` will not call this method - instead a new object will be created (it is equivalent to a copy and an :meth:`~Bits.__add__`). :: >>> s = BitArray(ue=423) >>> s += BitArray(ue=12) >>> s.read('ue') 423 >>> s.read('ue') 12 .. method:: BitArray.__iand__(bs) ``s &= bs`` In-place bit-wise AND between two bitstrings. If the two bitstrings are not the same length then a :exc:`ValueError` is raised. .. method:: BitArray.__ilshift__(n) ``s <<= n`` Shifts the bits in-place *n* bits to the left. The *n* right-most bits will become zeros and bits shifted off the left will be lost. .. method:: BitArray.__imul__(n) ``s *= n`` In-place concatenation of *n* copies of the current bitstring. >>> s = BitArray('0xbad') >>> s *= 3 >>> s.hex 'badbadbad' .. method:: BitArray.__ior__(bs) ``s |= bs`` In-place bit-wise OR between two bitstrings. If the two bitstrings are not the same length then a :exc:`ValueError` is raised. .. method:: BitArray.__irshift__(n) ``s >>= n`` Shifts the bits in-place *n* bits to the right. The *n* left-most bits will become zeros and bits shifted off the right will be lost. .. method:: BitArray.__ixor__(bs) ``s ^= bs`` In-place bit-wise XOR between two bitstrings. If the two bitstrings are not the same length then a :exc:`ValueError` is raised. .. method:: BitArray.__setitem__(key, value) ``s1[start:end:step] = s2`` Replaces the slice specified with a new value. :: >>> s = BitArray('0x00000000') >>> s[::8] = '0xf' >>> print(s) 0x80808080 >>> s[-12:] = '0xf' >>> print(s) 0x80808f bitstring-bitstring-4.1.4/doc/bits.rst000066400000000000000000000677461453167633600200320ustar00rootroot00000000000000.. currentmodule:: bitstring Bits ==== The ``Bits`` class is the simplest type in the bitstring module, and represents an immutable sequence of bits. This is the best class to use if you will not need to modify the data after creation and don't need streaming methods. .. class:: Bits(__auto: BitsType | int | None, length: int | None = None, offset: int | None = None, **kwargs) Creates a new bitstring. You must specify either no initialiser, just an 'auto' value as the first parameter, or one of the keyword arguments ``bytes``, ``bin``, ``hex``, ``oct``, ``uint``, ``int``, ``uintbe``, ``intbe``, ``uintle``, ``intle``, ``uintne``, ``intne``, ``se``, ``ue``, ``sie``, ``uie``, ``float``, ``floatbe``, ``floatle``, ``floatne``, ``e4m3float``, ``e5m2float``, ``bfloat``, ``bfloatbe``, ``bfloatle``, ``bfloatne``, ``bool`` or ``filename``. If no initialiser is given then a zeroed bitstring of ``length`` bits is created. The initialiser for the :class:`Bits` class is precisely the same as for :class:`BitArray`, :class:`BitStream` and :class:`ConstBitStream`. ``offset`` is available when using the ``bytes`` or ``filename`` initialisers. It gives a number of bits to ignore at the start of the bitstring. Specifying ``length`` is mandatory when using the various integer initialisers. It must be large enough that a bitstring can contain the integer in ``length`` bits. It must also be specified for the float initialisers (the only valid values are 16, 32 and 64). It is optional for the ``bytes`` and ``filename`` initialisers and can be used to truncate data from the end of the input value. :: >>> s1 = Bits(hex='0x934') >>> s2 = Bits(oct='0o4464') >>> s3 = Bits(bin='0b001000110100') >>> s4 = Bits(int=-1740, length=12) >>> s5 = Bits(uint=2356, length=12) >>> s6 = Bits(bytes=b'\x93@', length=12) >>> s1 == s2 == s3 == s4 == s5 == s6 True See also :ref:`auto_init`, which allows many different types to be used to initialise a bitstring. :: >>> s = Bits('uint12=32, 0b110') >>> t = Bits('0o755, ue=12, int:3=-1') In the methods below we use ``BitsType`` to indicate that any of the types that can auto initialise can be used. Methods ------- .. method:: Bits.all(value: bool, pos: Iterable[int] | None = None) -> bool Returns ``True`` if all of the specified bits are all set to *value*, otherwise returns ``False``. If *value* is ``True`` then ``1`` bits are checked for, otherwise ``0`` bits are checked for. *pos* should be an iterable of bit positions. Negative numbers are treated in the same way as slice indices and it will raise an :exc:`IndexError` if ``pos < -len(s)`` or ``pos > len(s)``. It defaults to the whole bitstring. >>> s = Bits('int15=-1') >>> s.all(True, [3, 4, 12, 13]) True >>> s.all(1) True .. method:: Bits.any(value: bool, pos: Iterable[int] | None = None) -> bool Returns ``True`` if any of the specified bits are set to *value*, otherwise returns ``False``. If *value* is ``True`` then ``1`` bits are checked for, otherwise ``0`` bits are checked for. *pos* should be an iterable of bit positions. Negative numbers are treated in the same way as slice indices and it will raise an :exc:`IndexError` if ``pos < -len(s)`` or ``pos > len(s)``. It defaults to the whole bitstring. >>> s = Bits('0b11011100') >>> s.any(False, range(6)) True >>> s.any(1) True .. method:: Bits.copy() -> Bits Returns a copy of the bitstring. ``s.copy()`` is equivalent to the shallow copy ``s[:]`` and creates a new copy of the bitstring in memory. .. method:: Bits.count(value: bool) -> int Returns the number of bits set to *value*. *value* can be ``True`` or ``False`` or anything that can be cast to a bool, so you could equally use ``1`` or ``0``. >>> s = BitArray(1000000) >>> s.set(1, [4, 44, 444444]) >>> s.count(1) 3 >>> s.count(False) 999997 If you need to count more than just single bits you can use :meth:`~Bits.findall`, for example ``len(list(s.findall('0xabc')))``. Note that if the bitstring is very sparse, as in the example here, it could be quicker to find and count all the set bits with something like ``len(list(s.findall('0b1')))``. For bitstrings with more entropy the ``count`` method will be much quicker than finding. .. method:: Bits.cut(bits: int, start: int | None = None, end: int | None = None, count: int | None = None) -> Iterator[Bits] Returns a generator for slices of the bitstring of length *bits*. At most *count* items are returned and the range is given by the slice *[start:end]*, which defaults to the whole bitstring. :: >>> s = BitArray('0x1234') >>> for nibble in s.cut(4): ... s.prepend(nibble) >>> print(s) 0x43211234 .. method:: Bits.endswith(bs: BitsType, start: int | None = None, end: int | None = None) -> bool Returns ``True`` if the bitstring ends with the sub-string *bs*, otherwise returns ``False``. A slice can be given using the *start* and *end* bit positions and defaults to the whole bitstring. :: >>> s = Bits('0x35e22') >>> s.endswith('0b10, 0x22') True >>> s.endswith('0x22', start=13) False .. method:: Bits.find(bs: BitsType, start: int | None = None, end: int | None = None, bytealigned: bool | None = None) -> Tuple[int] | Tuple[()] Searches for *bs* in the current bitstring and sets :attr:`~ConstBitStream.pos` to the start of *bs* and returns it in a tuple if found, otherwise it returns an empty tuple. The reason for returning the bit position in a tuple is so that it evaluates as True even if the bit position is zero. This allows constructs such as ``if s.find('0xb3'):`` to work as expected. If *bytealigned* is ``True`` then it will look for *bs* only at byte aligned positions (which is generally much faster than searching for it in every possible bit position). *start* and *end* give the search range and default to the whole bitstring. :: >>> s = Bits('0x0023122') >>> s.find('0b000100', bytealigned=True) (16,) .. method:: Bits.findall(bs: BitsType, start: int | None = None, end: int | None = None, count: int | None = None, bytealigned: bool | None = None) -> Iterable[int] Searches for all occurrences of *bs* (even overlapping ones) and returns a generator of their bit positions. If *bytealigned* is ``True`` then *bs* will only be looked for at byte aligned positions. *start* and *end* optionally define a search range and default to the whole bitstring. The *count* parameter limits the number of items that will be found - the default is to find all occurrences. :: >>> s = Bits('0xab220101')*5 >>> list(s.findall('0x22', bytealigned=True)) [8, 40, 72, 104, 136] .. method:: Bits.join(sequence: Iterable) -> Bits Returns the concatenation of the bitstrings in the iterable *sequence* joined with ``self`` as a separator. :: >>> s = Bits().join(['0x0001ee', 'uint:24=13', '0b0111']) >>> print(s) 0x0001ee00000d7 >>> s = Bits('0b1').join(['0b0']*5) >>> print(s.bin) 010101010 .. method:: Bits.pp(fmt: str | None = None, width: int = 120, sep: str = ' ', show_offset: bool = True, stream: TextIO = sys.stdout) -> None Pretty print the bitstring's value according to the *fmt*. Either a single, or two comma separated formats can be specified, together with options for setting the maximum display *width*, the number of bits to display in each group, and the separator to print between groups. >>> s = Bits(int=-98987987293452, length=200) >>> s.pp(width=80) 0: 11111111 11111111 11111111 11111111 11111111 11111111 ff ff ff ff ff ff 48: 11111111 11111111 11111111 11111111 11111111 11111111 ff ff ff ff ff ff 96: 11111111 11111111 11111111 11111111 11111111 11111111 ff ff ff ff ff ff 144: 11111111 10100101 11111000 10010000 00101110 00101010 ff a5 f8 90 2e 2a 192: 11110100 f4 >>> s.pp('h16, b', width=80, show_offset=False, sep=' / ') ffff / ffff / ffff 1111111111111111 / 1111111111111111 / 1111111111111111 ffff / ffff / ffff 1111111111111111 / 1111111111111111 / 1111111111111111 ffff / ffff / ffff 1111111111111111 / 1111111111111111 / 1111111111111111 ffa5 / f890 / 2e2a 1111111110100101 / 1111100010010000 / 0010111000101010 f4 11110100 The available formats are ``'bin'``, ``'oct'``, ``'hex'`` and ``'bytes'``. A bit length can be specified after the format (with an optional `:`) to give the number of bits represented by each group, otherwise the default is based on the format or formats selected. Using a length of zero removes all separators and displays one block of characters per line for each format in *fmt* (e.g. ``'hex0'``). The ``'hex'``, ``'oct'`` and ``'bin'`` format string can be replaced with just their initial letter. For the ``'bytes'`` format, characters from the 'Latin Extended-A' unicode block are used for non-ASCII and unprintable characters. If the bitstring cannot be represented in a format due to it's length not being a multiple of the number of bits represented by each character then an :exc:`InterpretError` will be raised. An output *stream* can be specified. This should be an object with a ``write`` method and the default is ``sys.stdout``. .. method:: Bits.rfind(bs: BitsType, start: int | None = None, end: int | None = None, bytealigned: bool | None = None) -> Tuple[int] | Tuple[()] Searches backwards for *bs* in the current bitstring and sets :attr:`~ConstBitStream.pos` to the start of *bs* and returns it in a tuple if found, otherwise it returns an empty tuple. The reason for returning the bit position in a tuple is so that it evaluates as True even if the bit position is zero. This allows constructs such as ``if s.rfind('0xb3'):`` to work as expected. If *bytealigned* is ``True`` then it will look for *bs* only at byte aligned positions. *start* and *end* give the search range and default to ``0`` and :attr:`len` respectively. Note that as it's a reverse search it will start at *end* and finish at *start*. :: >>> s = Bits('0o031544') >>> s.rfind('0b100') (15,) >>> s.rfind('0b100', end=17) (12,) .. method:: Bits.split(delimiter: BitsType, start: int | None = None, end: int | None = None, count: int | None = None, bytealigned: bool | None = None) -> Iterable[Bits] Splits the bitstring into sections that start with *delimiter*. Returns a generator for bitstring objects. The first item generated is always the bits before the first occurrence of delimiter (even if empty). A slice can be optionally specified with *start* and *end*, while *count* specifies the maximum number of items generated. If *bytealigned* is ``True`` then the delimiter will only be found if it starts at a byte aligned position. :: >>> s = Bits('0x42423') >>> [bs.bin for bs in s.split('0x4')] ['', '01000', '01001000', '0100011'] .. method:: Bits.startswith(bs: BitsType, start: int | None = None, end: int | None = None) -> bool Returns ``True`` if the bitstring starts with the sub-string *bs*, otherwise returns ``False``. A slice can be given using the *start* and *end* bit positions and defaults to the whole bitstring. :: >>> s = BitArray('0xef133') >>> s.startswith('0b111011') True .. method:: Bits.tobitarray() -> bitarray.bitarray Returns the bitstring as a ``bitarray`` object. Converts the bitstring to an equivalent ``bitarray`` object from the ``bitarray`` package. This shouldn't be confused with the ``BitArray`` type provided in the ``bitstring`` package - the ``bitarray`` package is a separate third-party way of representing binary objects. Note that ``BitStream`` and ``ConstBitStream`` types that have a bit position do support this method but the bit position information will be lost. .. method:: Bits.tobytes() -> bytes Returns the bitstring as a ``bytes`` object. The returned value will be padded at the end with between zero and seven ``0`` bits to make it byte aligned. This differs from using the plain :attr:`~Bits.bytes` property which will not pad with zero bits and instead raises an exception if the bitstring is not a whole number of bytes long. This method can also be used to output your bitstring to a file - just open a file in binary write mode and write the function's output. :: >>> s = Bits(bytes=b'hello') >>> s += '0b01' >>> s.tobytes() b'hello@' This is equivalent to casting to a bytes object directly: :: >>> bytes(s) b'hello@' .. method:: Bits.tofile(f: BinaryIO) -> None Writes the bitstring to the file object *f*, which should have been opened in binary write mode. The data written will be padded at the end with between zero and seven ``0`` bits to make it byte aligned. :: >>> f = open('newfile', 'wb') >>> Bits('0x1234').tofile(f) .. method:: Bits.unpack(fmt: str | list[str | int], **kwargs) -> list[float | int | str | None | Bits] Interprets the whole bitstring according to the *fmt* string or iterable and returns a list of bitstring objects. A dictionary or keyword arguments can also be provided. These will replace length identifiers in the format string. *fmt* is an iterable or a string with comma separated tokens that describe how to interpret the next bits in the bitstring. See the :ref:`format_tokens` for details. :: >>> s = Bits('int4=-1, 0b1110') >>> i, b = s.unpack('int:4, bin') If a token doesn't supply a length (as with ``bin`` above) then it will try to consume the rest of the bitstring. Only one such token is allowed. The ``unpack`` method is a natural complement of the :func:`pack` function. :: s = bitstring.pack('uint10, hex, int13, 0b11', 130, '3d', -23) a, b, c, d = s.unpack('uint10, hex, int13, bin2') Properties ---------- Note that the ``bin``, ``oct``, ``hex``, ``int``, ``uint`` and ``float`` properties can all be shortened to their initial letter. Properties can also have a length in bits appended to them to such as ``u8`` or ``f64`` (for the ``bytes`` property the length is interpreted in bytes instead of bits). These properties with lengths will cause an :exc:`InterpretError` to be raised if the bitstring is not of the specified length. .. attribute:: Bits.bin :type: str .. attribute:: Bits.b :type: str :noindex: Property for the representation of the bitstring as a binary string. .. attribute:: Bits.bfloat :type: float .. attribute:: Bits.bfloatbe :type: float Property for the 2 byte bfloat floating point representation of the bitstring. The bitstring must be 16 bits long to support this floating point interpretation, otherwise an :exc:`InterpretError` will be raised. The :attr:`bfloat` property is bit-wise big-endian, which as all floats must be whole-byte is exactly equivalent to the byte-wise big-endian :attr:`bfloatbe`. The ``bfloat`` properties are specialised representations mainly used in machine learning. They are essentially the first half of the IEEE 32-bit floats, so have the same range but with less accuracy. If you don't know what a bfloat is then you almost certainly want to use the ``float`` properties instead. See :ref:`Exotic floats` for more information. .. attribute:: Bits.bfloatle :type: float Property for the byte-wise little-endian 2 byte bfloat floating point representation of the bitstring. .. attribute:: Bits.bfloatne :type: float Property for the byte-wise native-endian 2 byte bfloat floating point representation of the bitstring. .. attribute:: Bits.bool :type: bool Property for representing the bitstring as a boolean (``True`` or ``False``). If the bitstring is not a single bit then the getter will raise an :exc:`InterpretError`. .. attribute:: Bits.bytes :type: bytes Property representing the underlying byte data that contains the bitstring. When used as a getter the bitstring must be a whole number of byte long or a :exc:`InterpretError` will be raised. An alternative is to use the :meth:`tobytes` method, which will pad with between zero and seven ``0`` bits to make it byte aligned if needed. :: >>> s = Bits('0x12345678') >>> s.bytes b'\x124Vx' .. attribute:: Bits.hex :type: str .. attribute:: Bits.h :type: str :noindex: Property representing the hexadecimal value of the bitstring. If the bitstring is not a multiple of four bits long then getting its hex value will raise an :exc:`InterpretError`. :: >>> s = Bits(bin='1111 0000') >>> s.hex 'f0' .. attribute:: Bits.int :type: int .. attribute:: Bits.i :type: int :noindex: Property for the signed two’s complement integer representation of the bitstring. .. attribute:: Bits.intbe :type: int Property for the byte-wise big-endian signed two's complement integer representation of the bitstring. Only valid for whole-byte bitstrings, in which case it is equal to ``s.int``, otherwise an :exc:`InterpretError` is raised. .. attribute:: Bits.intle :type: int Property for the byte-wise little-endian signed two's complement integer representation of the bitstring. Only valid for whole-byte bitstring, in which case it is equal to ``s[::-8].int``, i.e. the integer representation of the byte-reversed bitstring. .. attribute:: Bits.intne :type: int Property for the byte-wise native-endian signed two's complement integer representation of the bitstring. Only valid for whole-byte bitstrings, and will equal either the big-endian or the little-endian integer representation depending on the platform being used. .. attribute:: Bits.float :type: float .. attribute:: Bits.floatbe :type: float .. attribute:: Bits.f :type: float :noindex: Property for the floating point representation of the bitstring. The bitstring must be 16, 32 or 64 bits long to support the floating point interpretations, otherwise an :exc:`InterpretError` will be raised. If the underlying floating point methods on your machine are not IEEE 754 compliant then using the float interpretations is undefined (this is unlikely unless you're on some very unusual hardware). The :attr:`float` property is bit-wise big-endian, which as all floats must be whole-byte is exactly equivalent to the byte-wise big-endian :attr:`floatbe`. .. attribute:: Bits.floatle :type: float Property for the byte-wise little-endian floating point representation of the bitstring. .. attribute:: Bits.floatne :type: float Property for the byte-wise native-endian floating point representation of the bitstring. .. attribute:: Bits.e4m3float :type: float Property for an 8 bit floating point representation with 4 exponent bits and 3 mantissa bits. See :ref:`Exotic floats` for more information. .. attribute:: Bits.e5m2float :type: float Property for an 8 bit floating point representation with 5 exponent bits and 2 mantissa bits. See :ref:`Exotic floats` for more information. .. attribute:: Bits.len :type: int .. attribute:: Bits.length :type: int :noindex: Read-only property that give the length of the bitstring in bits (:attr:`len` and ``length`` are equivalent). Using the ``len()`` built-in function is preferred in almost all cases, but these properties are available for backward compatibility. The only occasion where the properties are needed is if a 32-bit build of Python is being used and you have a bitstring whose length doesn't fit in a 32-bit unsigned integer. In that case ``len(s)`` may fail with an :exc:`OverflowError`, whereas ``s.len`` will still work. With 64-bit Python the problem shouldn't occur unless you have more than a couple of exabytes of data! .. attribute:: Bits.oct :type: str .. attribute:: Bits.o :type: str :noindex: Property for the octal representation of the bitstring. If the bitstring is not a multiple of three bits long then getting its octal value will raise a :exc:`InterpretError`. :: >>> s = Bits('0b111101101') >>> s.oct '755' >>> s.oct = '01234567' >>> s.oct '01234567' .. attribute:: Bits.se :type: int Property for the signed exponential-Golomb code representation of the bitstring. When used as a getter an :exc:`InterpretError` will be raised if the bitstring is not a single code. :: >>> s = BitArray(se=-40) >>> s.bin 0000001010001 >>> s += '0b1' >>> s.se Error: BitString is not a single exponential-Golomb code. .. attribute:: Bits.ue :type: int Property for the unsigned exponential-Golomb code representation of the bitstring. When used as a getter an :exc:`InterpretError` will be raised if the bitstring is not a single code. .. attribute:: Bits.sie :type: int Property for the signed interleaved exponential-Golomb code representation of the bitstring. When used as a getter an :exc:`InterpretError` will be raised if the bitstring is not a single code. .. attribute:: Bits.uie :type: int Property for the unsigned interleaved exponential-Golomb code representation of the bitstring. When used as a getter an :exc:`InterpretError` will be raised if the bitstring is not a single code. .. attribute:: Bits.uint :type: int .. attribute:: Bits.u :type: int :noindex: Property for the unsigned base-2 integer representation of the bitstring. .. attribute:: Bits.uintbe :type: int Property for the byte-wise big-endian unsigned base-2 integer representation of the bitstring. .. attribute:: Bits.uintle :type: int Property for the byte-wise little-endian unsigned base-2 integer representation of the bitstring. .. attribute:: Bits.uintne :type: int Property for the byte-wise native-endian unsigned base-2 integer representation of the bitstring. Special Methods --------------- .. method:: Bits.__add__(bs) .. method:: Bits.__radd__(bs) ``s1 + s2`` Concatenate two bitstring objects and return the result. Either bitstring can be 'auto' initialised. :: s = Bits(ue=132) + '0xff' s2 = '0b101' + s .. method:: Bits.__and__(bs) .. method:: Bits.__rand__(bs) ``s1 & s2`` Returns the bit-wise AND between two bitstrings, which must have the same length otherwise a :exc:`ValueError` is raised. :: >>> print(Bits('0x33') & '0x0f') 0x03 .. method:: Bits.__bool__() ``if s:`` Returns ``False`` if the bitstring is empty (has zero length), otherwise returns ``True``. >>> bool(Bits()) False >>> bool(Bits('0b0000010000')) True >>> bool(Bits('0b0000000000')) True .. method:: Bits.__contains__(bs) ``bs in s`` Returns ``True`` if *bs* can be found in the bitstring, otherwise returns ``False``. Similar to using :meth:`~Bits.find`, except that you are only told if it is found, and not where it was found. :: >>> '0b11' in Bits('0x06') True >>> '0b111' in Bits('0x06') False .. method:: Bits.__copy__() ``s2 = copy.copy(s1)`` This allows the ``copy`` module to correctly copy bitstrings. Other equivalent methods are to initialise a new bitstring with the old one or to take a complete slice. :: >>> import copy >>> s = Bits('0o775') >>> s_copy1 = copy.copy(s) >>> s_copy2 = Bits(s) >>> s_copy3 = s[:] >>> s == s_copy1 == s_copy2 == s_copy3 True .. method:: Bits.__eq__(bs) ``s1 == s2`` Compares two bitstring objects for equality, returning ``True`` if they have the same binary representation, otherwise returning ``False``. :: >>> Bits('0o7777') == '0xfff' True >>> a = Bits(uint=13, length=8) >>> b = Bits(uint=13, length=10) >>> a == b False If you have a different criterion you wish to use then code it explicitly, for example ``a.int == b.int`` could be true even if ``a == b`` wasn't (as they could be different lengths). .. method:: Bits.__getitem__(key) ``s[start:end:step]`` Returns a slice of the bitstring. The usual slice behaviour applies. :: >>> s = Bits('0x0123456') >>> s[4:8] Bits('0x1') >>> s[1::8] # 1st, 9th, 17th and 25th bits Bits('0x3') If a single element is asked for then either ``True`` or ``False`` will be returned. :: >>> s[0] False >>> s[-1] True .. method:: Bits.__hash__() ``hash(s)`` Returns an integer hash of the :class:`Bits`. This method is not available for the :class:`BitArray` or :class:`BitStream` classes, as only immutable objects should be hashed. You typically won't need to call it directly, instead it is used for dictionary keys and in sets. .. method:: Bits.__invert__() ``~s`` Returns the bitstring with every bit inverted, that is all zeros replaced with ones, and all ones replaced with zeros. If the bitstring is empty then an :exc:`Error` will be raised. :: >>> s = ConstBitStream(‘0b1110010’) >>> print(~s) 0b0001101 >>> print(~s & s) 0b0000000 >>> ~~s == s True .. method:: Bits.__len__() ``len(s)`` Returns the length of the bitstring in bits. If you are using a 32-bit Python build (which is quite unlikely these days) it's recommended that you use the :attr:`len` property rather than the :func:`len` function because of the function will raise a :exc:`OverflowError` if the length is greater than ``sys.maxsize``. .. method:: Bits.__lshift__(n) ``s << n`` Returns the bitstring with its bits shifted *n* places to the left. The *n* right-most bits will become zeros. :: >>> s = Bits('0xff') >>> s << 4 Bits('0xf0') .. method:: Bits.__mul__(n) .. method:: Bits.__rmul__(n) ``s * n / n * s`` Return bitstring consisting of *n* concatenations of another. :: >>> a = Bits('0x34') >>> b = a*5 >>> print(b) 0x3434343434 .. method:: Bits.__ne__(bs) ``s1 != s2`` Compares two bitstring objects for inequality, returning ``False`` if they have the same binary representation, otherwise returning ``True``. .. method:: Bits.__nonzero__() See :meth:`__bool__`. .. method:: Bits.__or__(bs) .. method:: Bits.__ror__(bs) ``s1 | s2`` Returns the bit-wise OR between two bitstring, which must have the same length otherwise a :exc:`ValueError` is raised. :: >>> print(Bits('0x33') | '0x0f') 0x3f .. method:: Bits.__repr__() ``repr(s)`` A representation of the bitstring that could be used to create it (which will often not be the form used to create it). If the result is too long then it will be truncated with ``...`` and the length of the whole will be given. :: >>> Bits(‘0b11100011’) Bits(‘0xe3’) .. method:: Bits.__rshift__(n) ``s >> n`` Returns the bitstring with its bits shifted *n* places to the right. The *n* left-most bits will become zeros. :: >>> s = Bits(‘0xff’) >>> s >> 4 Bits(‘0x0f’) .. method:: Bits.__str__() ``print(s)`` Used to print a representation of the bitstring, trying to be as brief as possible. If the bitstring is a multiple of 4 bits long then hex will be used, otherwise either binary or a mix of hex and binary will be used. Very long strings will be truncated with ``...``. :: >>> s = Bits('0b1')*7 >>> print(s) 0b1111111 >>> print(s + '0b1') 0xff See also the :meth:`pp` method for ways to pretty-print the bitstring. .. method:: Bits.__xor__(bs) .. method:: Bits.__rxor__(bs) ``s1 ^ s2`` Returns the bit-wise XOR between two bitstrings, which must have the same length otherwise a :exc:`ValueError` is raised. :: >>> print(Bits('0x33') ^ '0x0f') 0x3c bitstring-bitstring-4.1.4/doc/bitstream.rst000066400000000000000000000024071453167633600210420ustar00rootroot00000000000000.. currentmodule:: bitstring BitStream ========= .. class:: BitStream(__auto: BitsType | int | None, length: int | None = None, offset: int | None = None, pos: int = 0, **kwargs) Both the :class:`BitArray` and the :class:`ConstBitStream` classes are base classes for :class:`BitStream` and so all of their methods are also available for :class:`BitStream` objects. The initialiser is the same as for :class:`ConstBitStream`. A :class:`BitStream` is a mutable container of bits with methods and properties that allow it to be parsed as a stream of bits. There are no additional methods or properties in this class - see its base classes (:class:`Bits`, :class:`BitArray` and :class:`ConstBitStream`) for details. The ``pos`` will also used as a default for the :meth:`BitArray.overwrite` and :meth:`BitArray.insert` methods. The bit position is modifed by methods that read bits, as described in :attr:`~ConstBitStream.pos`, but for the mutable ``BitStream`` it is also modified by other methods: * If a methods extends the bitstring (``+=``, ``append``) the ``pos`` will move to the end of the bitstring. * If a method otherwise changes the length of the bitstring (``prepend``, ``insert``, sometimes ``replace``) the ``pos`` becomes invalid and will be reset to ``0``. bitstring-bitstring-4.1.4/doc/bitstring_logo.png000066400000000000000000000754141453167633600220610ustar00rootroot00000000000000PNG  IHDR|>zTXtRaw profile type exifxڭiv#9s{}9|%jSO"E#ws[_].W// t7~_^w+F^_>Yt_`ؿ}E}_׶|>oa2.l$ܨ.\'xRH1K'!U,ZUkl .:8݃Ƙqgu٧ͱʫn;]w}'t)v3.P[nkwZpw-|t->ҁWxkkѱo!:4JdEAXnջwK\osNotΩuC׶fi UT?P-;ҷ61N`)B#rǓO$vW{[BBJhkjv>nur2TSRsS6wuyO]=5q :vZ[O۟ڙ4;xf`ۺ9!1oH$c,?74z:oKiW cMkt vM3xrg41Upjҗg,4Xd̳&**@qb9gվCa\w4pYJn'L ;vcQe5qzJZFdk07cmvW9 jqԼEKNSdOh+2]&„:z[qRsWmmp.8~oJ]ﮫ3Ga|lyڞBW(=^i::\`Hhmrk1wtcc cs2bА2ӈ\FީGu\9vl`y5UŦ `Y^mQ.p¤ksŶ uR 3v 6Tl^gCAI1X8iՓF‹rlml bmǂ2&Rس՞\i(2zt.P_+~c\m9Zq^\^dPCN l9l ӳƂTy2iJÞQE݋ھ.VyogY+;#*u zt\21TR԰C e4x%vA93e0ZQN-K5α2pt49oN |^UI[&N.s4%PLrgAI~fpEg8Eyb/Ƥܡg+eĮA=Nfݹ"P ܬL:' X8SfLJ[@iEM1L+<J3z>9GNͬ2$ځL)UȜ hh˜pJN}໲$xD4oɃGas7a3 2u:p4+·g mp F@1&DUR[m*g"*)ˉ5Ol2F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P 'Lz$cӼ3`Dk\9C zoUjS0a|I{4atP+0c̄$ >ni.5yIc0'>`6NA2A3a{$UB.s> L/jMY$/_^IQ'YnpNvobϡjW j=>D4!&%QRfd9w㻝0s݆^HS'H9 ',&XF"8Ai kQpar/wY"Q,jժ?H [.D]"OB!q \bv+[H/KS:_V[FfnS @yn nc| =yIc*Z:mC+OrK\}Ek)(dXk<ǔL\=ڝ8 Ω{^B$q.SCv3Rz)'oر h#o'˜7G9 =zl6ݟyiBimzs!S2?`u실.s;( >f,LoM~BW,B/&`< %PȔu@BEd$Cxn[L !TM ${N``Aj_#b{0 P5pwV4S9p[pb*& vO:OV,_3 s1 PK\lެ6!VJ riV g#PK|aMy anHmwoOCB- ϖ\û]8BA`{+-[ gƀ-ǟXI{~O ;tx< !{[=w@+oT-⮝/%֫2dk4w OXwBU/G~^1M[.ғi<BՔ-pv%U~L !T ufWSڔT6CtFB;[j,Z1mBa7'L:`&L !"(wq2q]t0m& ( Z]Krfuv=jpn-X-BU>+7 %Gtsnwo2k!B!B!B!B!B!B!B!B!B!B!B!B!B!B!B!B!B!B!P+iMVdtIENDB`bitstring-bitstring-4.1.4/doc/bitstring_logo_small_white.png000066400000000000000000000336541453167633600244510ustar00rootroot00000000000000PNG  IHDRHF.zTXtRaw profile type exifxڭiv8sq77`I-mV$dFFDe}̿j&Rs'|Mϟ~;gs?~nGoλa:_ƏZ|_? QЌFr;Ab\#SS؁b;qCq˪*ľ[d1V3n[J0_"d{^?pm-e#$Ώzߣ9~sN6xlj{s") NϽbۥrt`[;te uh kiNs Q@[mсv$w=E)ugL0M>Éx|g22@?'1k$lGGO(Sp^NĻ)xHSbBSOsBC;D*S69xz_hr Ry2g-j SC`!G)̒#M?==BCW/u#<H"cIvsTvJ#1%m 72XC2 ɳ[3ycEò/] *sYv:Xljƌlw@sUQ5]i?لfo6VHH'۔ER +gFO)nţyPq|uh [ 42+UK\GTjnC#u @Ɯ 4 XDc<(! '!L!sbPfft N,{c);7W e808@G|W.D/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ation builder. # import os import time import datetime year = datetime.datetime.utcfromtimestamp( int(os.environ.get('SOURCE_DATE_EPOCH', time.time())) ).year project = 'bitstring' copyright = f'2006 - {year}, Scott Griffiths' author = 'Scott Griffiths' release = '4.1' extensions = [] templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] root_doc = 'index' add_function_parentheses = False add_module_names = False html_show_sphinx = False html_static_path = ['_static'] html_css_files = ["custom.css"] html_theme = 'piccolo_theme' html_theme_options = { # "banner_text": "New major version released. Requires Python 3.7 or later - see release notes for full details.", # "banner_hiding": "permanent", "show_theme_credit": False, "globaltoc_maxdepth": 2, "source_url": 'https://github.com/scott-griffiths/bitstring/', } html_logo = './bitstring_logo_small_white.png' bitstring-bitstring-4.1.4/doc/constbitstream.rst000066400000000000000000000235411453167633600221130ustar00rootroot00000000000000.. currentmodule:: bitstring ConstBitStream ============== .. class:: ConstBitStream(__auto: BitsType | int | None, length: int | None = None, offset: int | None = None, pos: int = 0, **kwargs) The :class:`Bits` class is the base class for :class:`ConstBitStream` and so all of its methods are also available for :class:`ConstBitStream` objects. The initialiser is the same as for :class:`Bits` except that an initial bit position :attr:`pos` can be given (defaults to 0). A :class:`ConstBitStream` is a :class:`Bits` with added methods and properties that allow it to be parsed as a stream of bits. Reading and parsing --------------------- The :class:`BitStream` and :class:`ConstBitStream` classes contain number of methods for reading the bitstring as if it were a file or stream. Depending on how it was constructed the bitstream might actually be contained in a file rather than stored in memory, but these methods work for either case. In order to behave like a file or stream, every bitstream has a property :attr:`~ConstBitStream.pos` which is the current position from which reads occur. :attr:`~ConstBitStream.pos` can range from zero (its default value on construction) to the length of the bitstream, a position from which all reads will fail as it is past the last bit. Note that the :attr:`~ConstBitStream.pos` property isn't considered a part of the bitstream's identity; this allows it to vary for immutable :class:`ConstBitStream` objects and means that it doesn't affect equality or hash values. The property :attr:`~ConstBitStream.bytepos` is also available, and is useful if you are only dealing with byte data and don't want to always have to divide the bit position by eight. Note that if you try to use :attr:`~ConstBitStream.bytepos` and the bitstring isn't byte aligned (i.e. :attr:`~ConstBitStream.pos` isn't a multiple of 8) then a :exc:`ByteAlignError` exception will be raised. Reading using format strings ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The :meth:`~ConstBitStream.read` / :meth:`~ConstBitStream.readlist` methods can also take a format string similar to that used in the auto initialiser. Only one token should be provided to :meth:`~ConstBitStream.read` and a single value is returned. To read multiple tokens use :meth:`~ConstBitStream.readlist`, which unsurprisingly returns a list. The format string consists of comma separated tokens that describe how to interpret the next bits in the bitstring. The tokens are given in :ref:`format_tokens`. For example we can read and interpret three quantities from a bitstream with:: start_code = s.read('hex32') width = s.read('uint12') height = s.read('uint12') and we also could have combined the three reads as:: start_code, width, height = s.readlist('hex32, 2*uint12') where here we are also using a multiplier to combine the format of the second and third tokens. You are allowed to use one 'stretchy' token in a :meth:`~ConstBitStream.readlist`. This is a token without a length specified, which will stretch to fill encompass as many bits as possible. This is often useful when you just want to assign something to 'the rest' of the bitstring:: a, b, everything_else = s.readlist('intle16, intle24, bits') In this example the ``bits`` token will consist of everything left after the first two tokens are read, and could be empty. It is an error to use more than one stretchy token, or to use a ``ue``, ``se``, ``uie`` or ``se`` token after a stretchy token (the reason you can't use exponential-Golomb codes after a stretchy token is that the codes can only be read forwards; that is you can't ask "if this code ends here, where did it begin?" as there could be many possible answers). The ``pad`` token is a special case in that it just causes bits to be skipped over without anything being returned. This can be useful for example if parts of a binary format are uninteresting:: a, b = s.readlist('pad12, uint4, pad4, uint8') Peeking ^^^^^^^^ In addition to the read methods there are matching peek methods. These are identical to the read except that they do not advance the position in the bitstring to after the read elements. :: s = ConstBitStream('0x4732aa34') if s.peek(8) == '0x47': t = s.read(16) # t is first 2 bytes '0x4732' else: s.find('0x47') Methods ------- .. method:: ConstBitStream.bytealign() -> int Aligns to the start of the next byte (so that :attr:`pos` is a multiple of 8) and returns the number of bits skipped. If the current position is already byte aligned then it is unchanged. :: >>> s = ConstBitStream('0xabcdef') >>> s.pos += 3 >>> s.bytealign() 5 >>> s.pos 8 .. method:: ConstBitStream.peek(fmt: str | int) -> int | float | str | Bits | bool | bytes | None Reads from the current bit position :attr:`pos` in the bitstring according to the *fmt* string or integer and returns the result. The bit position is unchanged. For information on the format string see the entry for the :meth:`read` method. :: >>> s = ConstBitStream('0x123456') >>> s.peek(16) ConstBitStream('0x1234') >>> s.peek('hex8') '12' .. method:: ConstBitStream.peeklist(fmt: str | list[str | int], **kwargs) -> list[int | float | str | Bits | bool | bytes | None] Reads from current bit position :attr:`pos` in the bitstring according to the *fmt* string or iterable and returns a list of results. A dictionary or keyword arguments can also be provided. These will replace length identifiers in the format string. The position is not advanced to after the read items. See the entries for :meth:`read` and :meth:`readlist` for more information. .. method:: ConstBitStream.read(fmt: str | int) -> int | float | str | Bits | bool | bytes | None Reads from current bit position :attr:`pos` in the bitstring according the format string and returns a single result. If not enough bits are available then a :exc:`ReadError` is raised. *fmt* is either a token string that describes how to interpret the next bits in the bitstring or an integer. If it's an integer then that number of bits will be read, and returned as a new bitstring. A full list of the tokens is given in :ref:`format_tokens`. For example:: >>> s = ConstBitStream('0x23ef55302') >>> s.read('hex12') '23e' >>> s.read('bin4') '1111' >>> s.read('u5') 10 >>> s.read('bits4') ConstBitStream('0xa') The :meth:`~ConstBitStream.read` method is useful for reading exponential-Golomb codes. :: >>> s = ConstBitStream('se=-9, ue=4') >>> s.read('se') -9 >>> s.read('ue') 4 The ``pad`` token is not very useful when used in :meth:`~ConstBitStream.read` as it just skips a number of bits and returns ``None``. However when used within :meth:`~ConstBitStream.readlist` or :meth:`~Bits.unpack` it allows unimportant part of the bitstring to be simply ignored. .. method:: ConstBitStream.readlist(fmt: str | list[str | int], **kwargs) -> list[int | float | str | Bits | bool | bytes | None] Reads from current bit position :attr:`pos` in the bitstring according to the *fmt* string or iterable and returns a list of results. If not enough bits are available then a :exc:`ReadError` is raised. A dictionary or keyword arguments can also be provided. These will replace length identifiers in the format string. The position is advanced to after the read items. See :ref:`format_tokens` for information on the format strings. For multiple items you can separate using commas or given multiple parameters:: >>> s = ConstBitStream('0x43fe01ff21') >>> s.readlist('hex8, uint6') ['43', 63] >>> s.readlist(['bin3', 'intle16']) ['100', -509] >>> s.pos = 0 >>> s.readlist('hex:b, uint:d', b=8, d=6) ['43', 63] .. method:: ConstBitStream.readto(bs: BitsType, bytealigned: bool | None = None) -> ConstBitStream Reads up to and including the next occurrence of the bitstring *bs* and returns the results. If *bytealigned* is `True` it will look for the bitstring starting only at whole-byte positions. Raises a :exc:`ReadError` if *bs* is not found, and :exc:`ValueError` if *bs* is empty. >>> s = ConstBitStream('0x47000102034704050647') >>> s.readto('0x47', bytealigned=True) ConstBitStream('0x47') >>> s.readto('0x47', bytealigned=True) ConstBitStream('0x0001020347') >>> s.readto('0x47', bytealigned=True) ConstBitStream('0x04050647') Properties ---------- The ``ConstBitStream`` and ``BitStream`` classes have the concept of a current bit position. This position will be set to zero by default on construction, and will be modified by many of the methods described above as the stream is being read. Using :meth:`~Bits.find` or :meth:`~Bits.rfind` will move ``pos`` to the start of the substring if it is found. Note that the ``pos`` property isn’t considered a part of the bitstring's identity; this allows it to vary for immutable ``ConstBitStream`` objects and means that it doesn’t affect equality or hash values. It also will be reset to zero if a bitstring is copied. .. attribute:: ConstBitStream.bytepos :type: int Property for setting and getting the current byte position in the bitstring. The value of ``pos`` will always be ``bytepos * 8`` as the two values are not independent. When used as a getter will raise a :exc:`ByteAlignError` if the current position in not byte aligned. .. attribute:: ConstBitStream.pos :type: int .. attribute:: ConstBitStream.bitpos :type: int Read and write property for setting and getting the current bit position in the bitstring. Can be set to any value from ``0`` to ``len(s)``. The :attr:`pos` and :attr:`bitpos` properties are exactly equivalent - you can use whichever you prefer. :: if s.pos < 100: s.pos += 10 bitstring-bitstring-4.1.4/doc/exp-golomb.rst000066400000000000000000000064021453167633600211200ustar00rootroot00000000000000.. currentmodule:: bitstring .. _exp-golomb: Exponential-Golomb Codes ======================== As this type of representation of integers isn't as well known as the standard base-2 representation I thought that a short explanation of them might be welcome. This section can be safely skipped if you're not interested. Exponential-Golomb codes represent integers using bit patterns that get longer for larger numbers. For unsigned and signed numbers (the bitstring properties :attr:`~Bits.ue` and :attr:`~Bits.se` respectively) the patterns start like this: ============= =========== =========== Bit pattern Unsigned Signed ============= =========== =========== ``1`` 0 0 ``010`` 1 1 ``011`` 2 -1 ``00100`` 3 2 ``00101`` 4 -2 ``00110`` 5 3 ``00111`` 6 -3 ``0001000`` 7 4 ``0001001`` 8 -4 ``0001010`` 9 5 ``0001011`` 10 -5 ``0001100`` 11 6 ``...`` ... ... ============= =========== =========== They consist of a sequence of n '0' bits, followed by a '1' bit, followed by n more bits. The bits after the first '1' bit count upwards as ordinary base-2 binary numbers until they run out of space and an extra '0' bit needs to get included at the start. The advantage of this method of representing integers over many other methods is that it can be quite efficient at representing small numbers without imposing a limit on the maximum number that can be represented. Exercise: Using the table above decode this sequence of unsigned Exponential Golomb codes: ``001001101101101011000100100101`` The answer is that it decodes to 3, 0, 0, 2, 2, 1, 0, 0, 8, 4. Note how you don’t need to know how many bits are used for each code in advance - there’s only one way to decode it. To create this bitstring you could have written something like:: a = BitStream().join([BitArray(ue=i) for i in [3,0,0,2,2,1,0,0,8,4]]) and to read it back:: while a.pos != len(a): print(a.read('ue')) The notation ``ue`` and ``se`` for the exponential-Golomb code properties comes from the H.264 video standard, which uses these types of code a lot. There are other ways to map the bitstrings to integers: Interleaved exponential-Golomb codes ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This type of code is used in the Dirac video standard, and is represented by the attributes :attr:`~Bits.uie` and :attr:`~Bits.sie`. For the interleaved codes the pattern is very similar to before for the unsigned case: ============= =========== Bit pattern Unsigned ============= =========== ``1`` 0 ``001`` 1 ``011`` 2 ``00001`` 3 ``00011`` 4 ``01001`` 5 ``01011`` 6 ``0000001`` 7 ``0000011`` 8 ``0001001`` 9 ``...`` ... ============= =========== For the signed code it looks a little different: ============= =========== Bit pattern Signed ============= =========== ``1`` 0 ``0010`` 1 ``0011`` -1 ``0110`` 2 ``0111`` -2 ``000010`` 3 ``000011`` -3 ``000110`` 4 ``000111`` -4 ``010010`` 5 ``010011`` -5 ``...`` ... ============= =========== I'm sure you can work out the pattern yourself from here!bitstring-bitstring-4.1.4/doc/fp8.rst000066400000000000000000000216551453167633600175530ustar00rootroot00000000000000.. currentmodule:: bitstring .. _Exotic floats: Exotic Floating Point Formats ============================= Python floats are typically 64 bits long, but 32 and 16 bit sizes are also supported through the ``struct`` module. These are the well-known IEEE formats. Recently, lower precision floating points have become more widely used, largely driven by the requirements of machine learning algorithms and hardware. As well as the 'half' precision 16 bit standard, a truncated version of the 32 bit standard called 'bfloat16' is used which has the range of a 32-bit float but less precision. The #bits value in the tables below show how the available bits are split into `sign` + `exponent` + `mantissa`. There's always 1 bit to determine the sign of the floating point value. The more bits in the exponent, the larger the range that can be represented. The more bits in the mantissa, the greater the precision (~significant figures) of the values. .. list-table:: :header-rows: 1 * - Type - # bits - Standard - Range - bitstring / struct format * - Double precision - 1 + 11 + 52 - IEEE 754 - 10\ :sup:`-308` → 10\ :sup:`308` - ``'float64'`` / ``'d'`` * - Single precision - 1 + 8 + 23 - IEEE 754 - 10\ :sup:`-38` → 10\ :sup:`38` - ``'float32'`` / ``'f'`` * - Half precision - 1 + 5 + 10 - IEEE 754 - 6×10\ :sup:`-8` → 65504 - ``'float16'`` / ``'e'`` * - bfloat - 1 + 8 + 7 - ``-`` - 10\ :sup:`-38` → 10\ :sup:`38` - ``'bfloat'`` / ``-`` An example of creation and interpretation of a bfloat:: >>> a = Bits(bfloat=4.5e23) # No need to specify length as always 16 bits >>> a Bits('0x66be') >>> a.bfloat 4.486248158726163e+23 # Converted to Python float 8-bit Floating Point Types ^^^^^^^^^^^^^^^^^^^^^^^^^^ .. note:: The 8-bit float formats used here are from a proposal supported by Graphcore, AMD and Qualcomm. There is a different but similar proposal from other companies, and there is an ongoing standardisation process. I (Scott Griffiths) currently work at Graphcore, but I have not been involved in the low-precision float work. This implementation is not part of my work at Graphcore (this counts as fun for me). I have been careful to only base my work here on public sources, and any misunderstandings or errors are my own. This is an experimental feature and may be modified in future point releases. Two 8-bit floating point formats are supported as an experimental feature in bitstring 4.1. These are also mainly of use in machine learning and have very limited ranges and precision. There is no standardised format for these but there are a few candidates. The formats supported by bitstring are from the proposal by `Graphcore, AMD and Qualcomm `_ in `this paper `_, and there is some useful information `here `_ too. The 8-bit formats are named after how the byte is split between the sign-exponent-mantissa parts. So ``e4m3float`` has a single sign bit, 4 bits for the exponent and 3 bits for the mantissa. For a bit more range and less precision you can use ``e5m2float`` which has 5 bits for the exponent and only 2 for the mantissa. .. list-table:: :header-rows: 1 * - Type - # bits - Range - bitstring format * - Float8E4M3FNUZ - 1 + 4 + 3 - 10\ :sup:`-3` → 240 - ``'e4m3float'`` * - Float8E5M2FNUZ - 1 + 5 + 2 - 8×10\ :sup:`-6` → 57344 - ``'e5m2float'`` As there are just 256 possible values, both the range and precision of these formats are extremely limited. It's remarkable that any useful calculations can be performed, but both inference and training of large machine learning models can be done with these formats. You can easily examine every possible value that these formats can represent using a line like this:: >>> [Bits(uint=x, length=8).e5m2float for x in range(256)] or using the :class:`Array` type it's even more concise - we can create an Array and pretty print all the values with this line:: >>> Array('e4m3float', bytearray(range(256))).pp(width=90, show_offset=True) [ 0: 0.0 0.0009765625 0.001953125 0.0029296875 0.00390625 0.0048828125 6: 0.005859375 0.0068359375 0.0078125 0.0087890625 0.009765625 0.0107421875 12: 0.01171875 0.0126953125 0.013671875 0.0146484375 0.015625 0.017578125 18: 0.01953125 0.021484375 0.0234375 0.025390625 0.02734375 0.029296875 24: 0.03125 0.03515625 0.0390625 0.04296875 0.046875 0.05078125 30: 0.0546875 0.05859375 0.0625 0.0703125 0.078125 0.0859375 36: 0.09375 0.1015625 0.109375 0.1171875 0.125 0.140625 42: 0.15625 0.171875 0.1875 0.203125 0.21875 0.234375 48: 0.25 0.28125 0.3125 0.34375 0.375 0.40625 54: 0.4375 0.46875 0.5 0.5625 0.625 0.6875 60: 0.75 0.8125 0.875 0.9375 1.0 1.125 66: 1.25 1.375 1.5 1.625 1.75 1.875 72: 2.0 2.25 2.5 2.75 3.0 3.25 78: 3.5 3.75 4.0 4.5 5.0 5.5 84: 6.0 6.5 7.0 7.5 8.0 9.0 90: 10.0 11.0 12.0 13.0 14.0 15.0 96: 16.0 18.0 20.0 22.0 24.0 26.0 102: 28.0 30.0 32.0 36.0 40.0 44.0 108: 48.0 52.0 56.0 60.0 64.0 72.0 114: 80.0 88.0 96.0 104.0 112.0 120.0 120: 128.0 144.0 160.0 176.0 192.0 208.0 126: 224.0 240.0 nan -0.0009765625 -0.001953125 -0.0029296875 132: -0.00390625 -0.0048828125 -0.005859375 -0.0068359375 -0.0078125 -0.0087890625 138: -0.009765625 -0.0107421875 -0.01171875 -0.0126953125 -0.013671875 -0.0146484375 144: -0.015625 -0.017578125 -0.01953125 -0.021484375 -0.0234375 -0.025390625 150: -0.02734375 -0.029296875 -0.03125 -0.03515625 -0.0390625 -0.04296875 156: -0.046875 -0.05078125 -0.0546875 -0.05859375 -0.0625 -0.0703125 162: -0.078125 -0.0859375 -0.09375 -0.1015625 -0.109375 -0.1171875 168: -0.125 -0.140625 -0.15625 -0.171875 -0.1875 -0.203125 174: -0.21875 -0.234375 -0.25 -0.28125 -0.3125 -0.34375 180: -0.375 -0.40625 -0.4375 -0.46875 -0.5 -0.5625 186: -0.625 -0.6875 -0.75 -0.8125 -0.875 -0.9375 192: -1.0 -1.125 -1.25 -1.375 -1.5 -1.625 198: -1.75 -1.875 -2.0 -2.25 -2.5 -2.75 204: -3.0 -3.25 -3.5 -3.75 -4.0 -4.5 210: -5.0 -5.5 -6.0 -6.5 -7.0 -7.5 216: -8.0 -9.0 -10.0 -11.0 -12.0 -13.0 222: -14.0 -15.0 -16.0 -18.0 -20.0 -22.0 228: -24.0 -26.0 -28.0 -30.0 -32.0 -36.0 234: -40.0 -44.0 -48.0 -52.0 -56.0 -60.0 240: -64.0 -72.0 -80.0 -88.0 -96.0 -104.0 246: -112.0 -120.0 -128.0 -144.0 -160.0 -176.0 252: -192.0 -208.0 -224.0 -240.0 ] You'll see that there is only 1 zero value, no 'inf' values and only one 'nan' value. When converting from a Python float (which will typically be stored in 64-bits) unrepresentable values are rounded towards zero. The formats have no code for infinity, instead using the largest positive and negative values, so anything larger than the largest representable value (including infinity) will get rounded to it. :: >>> a = BitArray(e5m2float=70) >>> print(a.bin) 01011000 >>> print(a.e5m2float) 64.0 >>> a.e5m2float = 1000000.0 >>> print(a.e5m2float) 57344.0bitstring-bitstring-4.1.4/doc/functions.rst000066400000000000000000000230551453167633600210620ustar00rootroot00000000000000.. currentmodule:: bitstring Functions --------- pack ^^^^ .. function:: pack(format[, *values, **kwargs]) Packs the values and keyword arguments according to the *format* string and returns a new :class:`BitStream`. :param format: string with comma separated tokens :param values: extra values used to construct the :class:`BitStream` :param kwargs: a dictionary of token replacements :rtype: BitStream The format string consists of comma separated tokens, see :ref:`format_tokens` and :ref:`compact_format` for details. The tokens can be 'literals', like ``0xef``, ``0b110``, ``uint8=55``, etc. which just represent a set sequence of bits. They can also have the value missing, in which case the values contained in ``*values`` will be used. :: >>> a = pack('bin3, hex4', '001', 'f') >>> b = pack('uint10', 33) A dictionary or keyword arguments can also be provided. These will replace items in the format string. :: >>> c = pack('int:a=b', a=10, b=20) >>> d = pack('int8=a, bin=b, int4=a', a=7, b='0b110') Plain names can also be used as follows:: >>> e = pack('a, b, b, a', a='0b11', b='0o2') Tokens starting with an endianness identifier (``<``, ``>`` or ``=``) implies a struct-like compact format string (see :ref:`compact_format`). For example this packs three little-endian 16-bit integers:: >>> f = pack('<3h', 12, 3, 108) And of course you can combine the different methods in a single pack. A :exc:`ValueError` will be raised if the ``*values`` are not all used up by the format string, and if a value provided doesn't match the length specified by a token. As an example of using just the ``*values`` arguments we can say:: s = bitstring.pack('hex32, uint12, uint12', '0x000001b3', 352, 288) which is equivalent to initialising as:: s = BitStream('0x0000001b3, uint12=352, uint12=288') The advantage of the pack function is if you want to write more general code for creation. :: def foo(a, b, c, d): return bitstring.pack('uint8, 0b110, int6, bin, bits', a, b, c, d) s1 = foo(12, 5, '0b00000', '') s2 = foo(101, 3, '0b11011', s1) Note how you can use some tokens without sizes (such as ``bin`` and ``bits`` in the above example), and use values of any length to fill them. If the size had been specified then a :exc:`ValueError` would be raised if the parameter given was the wrong length. Note also how bitstring literals can be used (the ``0b110`` in the bitstring returned by ``foo``) and these don't consume any of the items in ``*values``. You can also include keyword, value pairs (or an equivalent dictionary) as the final parameter(s). The values are then packed according to the positions of the keywords in the format string. This is most easily explained with some examples. Firstly the format string needs to contain parameter names:: format = 'hex32=start_code, uint12=width, uint12=height' Then we can make a dictionary with these parameters as keys and pass it to pack:: d = {'start_code': '0x000001b3', 'width': 352, 'height': 288} s = bitstring.pack(format, **d) Another method is to pass the same information as keywords at the end of pack's parameter list:: s = bitstring.pack(format, width=352, height=288, start_code='0x000001b3') You can include constant bitstring tokens such as '0x101', '0xff', 'uint7=81' etc. and also use a keyword for the length specifier in the token, for example:: s = bitstring.pack('0xabc, int:n=-1', n=100) Finally it is also possible just to use a keyword as a token:: s = bitstring.pack('hello, world', world='0x123', hello='0b110') Module Variables ---------------- lsb0 ^^^^ .. data:: lsb0 By default bit numbering in the bitstring module is done from 'left' to 'right'. That is, from bit ``0`` at the start of the data to bit ``n - 1`` at the end. This allows bitstrings to be treated like an ordinary Python container that is only allowed to contain single bits. The ``lsb0`` module variable allows bitstrings to use Least Significant Bit Zero (LSB0) bit numbering; that is the right-most bit in the bitstring will be bit 0, and the left-most bit will be bit (n-1), rather than the other way around. LSB0 is a more natural numbering system in many fields, but is the opposite to Most Significant Bit Zero (MSB0) numbering which is the natural option when thinking of bitstrings as standard Python containers. For example, if you set a bitstring to be the binary ``010001111`` it will be stored in the same way for MSB0 and LSB0 but slicing, reading, unpacking etc. will all behave differently. .. list-table:: MSB0 → :header-rows: 1 * - bit index - 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 * - value - ``0`` - ``1`` - ``0`` - ``0`` - ``0`` - ``1`` - ``1`` - ``1`` - ``1`` In MSB0 everything behaves like an ordinary Python container. Bit zero is the left-most bit and reads/slices happen from left to right. .. list-table:: ← LSB0 :header-rows: 1 * - bit index - 8 - 7 - 6 - 5 - 4 - 3 - 2 - 1 - 0 * - value - ``0`` - ``1`` - ``0`` - ``0`` - ``0`` - ``1`` - ``1`` - ``1`` - ``1`` In LSB0 the final, right-most bit is labelled as bit zero. Reads and slices happen from right to left. When bitstrings (or slices of bitstrings) are interpreted as integers and other types the left-most bit is considered as the most significant bit. It's important to note that this is the case irrespective of whether the first or last bit is considered the bit zero, so for example if you were to interpret a whole bitstring as an integer, its value would be the same with and without `lsb0` being set to `True`. To illustrate this, for the example above this means that the bin and int representations would be ``010001111`` and ``143`` respectively for both MSB0 and LSB0 bit numbering. To switch from the default MSB0, use the module level attribute ``bitstring.lsb0``. This defaults to ``False`` and unless explicitly stated all examples and documentation related to the bitstring module use the default MSB0 indexing. >>> bitstring.lsb0 = True Slicing is still done with the start bit smaller than the end bit. For example: >>> s = Bits('0b010001111') >>> s[0:5] # LSB0 so this is the right-most five bits Bits('0b01111') >>> s[0] True .. note:: In some standards and documents using LSB0 notation the slice of the final five bits would be shown as ``s[5:0]``, which is reasonable as bit 5 comes before bit 0 when reading left to right, but this notation isn't used in this module as it clashes too much with the usual Python notation. Negative indices work as you'd expect, with the first stored bit being ``s[-1]`` and the final stored bit being ``s[-n]``. Reading, peeking and unpacking of bitstrings are also affected by the ``lsb0`` flag, so reading always increments the bit position, and will move from right to left if ``lsb0`` is ``True``. Because of the way that exponential-Golomb codes are read (with the left-most bits determining the length of the code) these interpretations are not available in LSB0 mode, and using them will raise an exception. For ``BitStream`` and ``ConstBitStream`` objects changing the value of ``bitstring.lsb0`` invalidates the current position in the bitstring, unless that value is ``0``, and future results are undefined. Basically don't perform reads or change the current bit position before switching the bit numbering system! bytealigned ^^^^^^^^^^^ .. data:: bytealigned A number of methods take a bytealigned parameter to indicate that they should only work on byte boundaries (e.g. :meth:`~Bits.find`, :meth:`~Bits.findall`, :meth:`~Bits.split` and :meth:`~BitArray.replace`). This parameter defaults to ``bitstring.bytealigned``, which itself defaults to ``False``, but can be changed to modify the default behaviour of the methods. For example:: >>> a = BitArray('0x00 ff 0f ff') >>> a.find('0x0f') (4,) # found first not on a byte boundary >>> a.find('0x0f', bytealigned=True) (16,) # forced looking only on byte boundaries >>> bitstring.bytealigned = True # Change default behaviour >>> a.find('0x0f') (16,) >>> a.find('0x0f', bytealigned=False) (4,) If you’re only working with bytes then this can help avoid some errors and save some typing. Command Line Usage ------------------ The bitstring module can be called from the command line to perform simple operations. For example:: $ python -m bitstring int16=-400 0xfe70 $ python -m bitstring float32=0.2 bin 00111110010011001100110011001101 $ python -m bitstring 0xff "3*0b01,0b11" uint 65367 $ python -m bitstring hex=01, uint12=352.hex 01160 Command-line parameters are concatenated and a bitstring created from them. If the final parameter is either an interpretation string or ends with a ``.`` followed by an interpretation string then that interpretation of the bitstring will be used when printing it. If no interpretation is given then the bitstring is just printed. Exceptions ---------- .. exception:: Error(Exception) Base class for all module exceptions. .. exception:: InterpretError(Error, ValueError) Inappropriate interpretation of binary data. For example using the 'bytes' property on a bitstring that isn't a whole number of bytes long. .. exception:: ByteAlignError(Error) Whole-byte position or length needed. .. exception:: CreationError(Error, ValueError) Inappropriate argument during bitstring creation. .. exception:: ReadError(Error, IndexError) Reading or peeking past the end of a bitstring. bitstring-bitstring-4.1.4/doc/index.rst000066400000000000000000000146071453167633600201640ustar00rootroot00000000000000 .. currentmodule:: bitstring .. image:: bitstring_logo.png :width: 400px `bitstring `_ is a Python module that makes the creation and analysis of binary data as simple and efficient as possible. It has been maintained since 2006 and now has many millions of downloads per year. You can try out an interactive walkthrough notebook on `binder `_ (or the non-interactive version `here `_). .. image:: https://github.com/scott-griffiths/bitstring/actions/workflows/.github/workflows/ci.yml/badge.svg :target: https://github.com/scott-griffiths/bitstring/actions/workflows/ci.yml .. image:: https://img.shields.io/readthedocs/bitstring .. image:: https://img.shields.io/pypi/dm/bitstring?color=blue :target: https://pypistats.org/packages/bitstring .. image:: https://mybinder.org/badge_logo.svg :target: https://mybinder.org/v2/gh/scott-griffiths/bitstring/main?labpath=doc%2Fwalkthrough.ipynb ------ Overview ======== * Create bitstrings from hex, octal, binary, files, formatted strings, bytes, integers and floats of different endiannesses. * Powerful binary packing and unpacking functions. * Bit level slicing, joining, searching, replacing and more. * Read from and interpret bitstrings as streams of binary data. * Create arrays of any fixed-length format. * Rich API - chances are that whatever you want to do there's a simple and elegant way of doing it. * Supports Python 3.7 and later. Use bitstring version 3 for Python 2.7 and 3.x support. * Open source software, released under the MIT licence. It is not difficult to manipulate binary data in Python, for example using the ``struct`` and ``array`` modules, but it can be quite fiddly and time consuming even for quite small tasks, especially if you are not dealing with whole-byte data. The bitstring module provides support many different bit formats, allowing easy and efficient storage, interpretation and construction. Documentation ^^^^^^^^^^^^^ The :ref:`quick_reference` provides a basic list of the classes and their methods. The :ref:`reference` section has a complete list of all the classes, methods, properties and functions of the bitstring module, together with short examples for many items. .. toctree:: :hidden: self .. toctree:: :hidden: quick_reference reference appendices Mixed format bitstrings ^^^^^^^^^^^^^^^^^^^^^^^ If you have binary data (or want to construct it) from multiple types then you could use the :class:`BitArray` class. The example below constructs a 28 bit bitstring from a hexadecimal string, then unpacks it into multiple bit interpretations. It also demonstrates how it can be flexibly modified and sliced using standard notation, and how properties such as ``bin`` and ``float`` can be used to interpret the data. :: >>> s = bitstring.BitArray('0x4f8e220') >>> s.unpack('uint12, hex8, bin') [1272, 'e2', '00100000'] >>> '0b11000' in s True >>> s += 'f32=0.001' >>> s.bin '010011111000111000100010000000111010100000110001001001101111' >>> s[-32:].float 0.0010000000474974513 The module also supplies the :class:`BitStream` class, which adds a bit position so that objects can also be read from, searched in, and navigated in, similar to a file or stream. Bitstrings are designed to be as lightweight as possible and can be considered to be just a list of binary digits. They are however stored efficiently - although there are a variety of ways of creating and viewing the binary data, the bitstring itself just stores the byte data, and all views are calculated as needed, and are not stored as part of the object. The different views or interpretations on the data are accessed through properties such as :attr:`~Bits.hex`, :attr:`~Bits.bin` and :attr:`~Bits.int`, and an extensive set of functions is supplied for modifying, navigating and analysing the binary data. There are also a companion classes called :class:`Bits` and :class:`ConstBitStream` which are immutable versions of :class:`BitArray` and :class:`BitStream` respectively. See the reference documentation for full details. Arrays of bitstrings ^^^^^^^^^^^^^^^^^^^^ .. note :: This class was introduced in version 4.1 of bitstring, and is a 'beta' feature that may have some small changes in future point releases. If you are dealing with just one type of data but perhaps it's not one of the dozen or so supported in the ``array`` module in the standard library, then we have you covered with the :class:`Array` class. A ``bitstring.Array`` works in a similar way to a ``array.array``, except that you can efficiently pack in any fixed-length binary format. Want an array of 5 bit unsigned integers, or of 8 or 16 bit floating point numbers? No problem. You can also easily change the data's interpretation, convert to another format, and freely modify the underlying data which is stored as a :class:`BitArray` object. :: >>> a = bitstring.Array('uint16', [0, 1, 4, 6, 11, 2, 8, 7]) >>> a.data BitArray('0x0000000100040006000b000200080007') >>> b = a.astype('uint5') >>> b.data BitArray('0x0048658907') >>> a.tolist() == b.tolist() True You can also take and set slices as you'd expect, and apply operations to each element in the ``Array``. :: >>> a[::2] *= 5 >>> a Array('uint16', [0, 1, 20, 6, 55, 2, 40, 7]) >>> a >> 2 Array('uint16', [0, 0, 5, 1, 13, 0, 10, 1]) Installation and download ^^^^^^^^^^^^^^^^^^^^^^^^^ To install just ``pip install bitstring``. To download the module, as well as for defect reports, enhancement requests and Git repository browsing go to `the project's home on GitHub. `_ Release Notes ^^^^^^^^^^^^^ To see what been added, improved or fixed, and possibly also to see what's coming in the next version, see the `release notes `_ on GitHub. Credits ^^^^^^^ Created by Scott Griffiths in 2006 to help with ad hoc parsing and creation of compressed video files. Maintained and expanded ever since as it became unexpectedly popular. Thanks to all those who have contributed ideas, code and bug reports over the years. These docs are styled using the `Piccolo theme `_. bitstring-bitstring-4.1.4/doc/interpretation.rst000066400000000000000000000177441453167633600221310ustar00rootroot00000000000000.. currentmodule:: bitstring Interpreting Bitstrings ======================= Bitstrings don't know or care how they were created; they are just collections of bits. This means that you are quite free to interpret them in any way that makes sense. Several Python properties are used to create interpretations for the bitstring. These properties call private functions which will calculate and return the appropriate interpretation. These don’t change the bitstring in any way and it remains just a collection of bits. If you use the property again then the calculation will be repeated. Note that these properties can potentially be very expensive in terms of both computation and memory requirements. For example if you have initialised a bitstring from a 10 GiB file object and ask for its binary string representation then that string will be around 80 GiB in size! If you're in an interactive session then the pretty-print method :meth:`~Bits.pp` can be useful as it will only convert the bitstring one chunk at a time for display. Short Interpretations --------------------- Many of the more commonly used interpretations have single letter equivalents. The ``hex``, ``bin``, ``oct``, ``int``, ``uint`` and ``float`` properties can be shortened to ``h``, ``b``, ``o``, ``i``, ``u`` and ``f`` respectively. Properties can have bit lengths appended to them to make properties such as ``f64``, ``u32`` or ``floatle32``. When used as a getter these just add an extra check on the bitstring's length - if the bitstring is not the stated length then an :exc:`InterpretError` is raised. When used as a setter they define the new length of the bitstring. :: s = BitArray() # Empty bitstring s.f32 = 101.5 # New length is 32 bits, representing a float Properties ---------- For the properties described below we will use these:: >>> a = BitArray('0x123') >>> b = BitArray('0b111') bin / b ^^^^^^^ The most fundamental interpretation is perhaps as a binary string (a ‘bitstring’). The :attr:`~Bits.bin` property returns a string of the binary representation of the bitstring. All bitstrings can use this property and it is used to test equality between bitstrings. :: >>> a.bin '000100100011' >>> b.b '111' Note that the initial zeros are significant; for bitstrings the zeros are just as important as the ones! hex / h ^^^^^^^ For whole-byte bitstrings the most natural interpretation is often as hexadecimal, with each byte represented by two hex digits. If the bitstring does not have a length that is a multiple of four bits then an :exc:`InterpretError` exception will be raised. This is done in preference to truncating or padding the value, which could hide errors in user code. :: >>> a.hex '123' >>> b.h ValueError: Cannot convert to hex unambiguously - not multiple of 4 bits. oct / o ^^^^^^^ For an octal interpretation use the :attr:`~Bits.oct` property. If the bitstring does not have a length that is a multiple of three then an :exc:`InterpretError` exception will be raised. :: >>> a.oct '0443' >>> b.o '7' >>> (b + '0b0').oct ValueError: Cannot convert to octal unambiguously - not multiple of 3 bits. uint / u / uintbe / uintle / uintne ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To interpret the bitstring as a binary (base-2) bit-wise big-endian unsigned integer (i.e. a non-negative integer) use the :attr:`~Bits.uint` property. >>> a.uint 283 >>> b.u 7 For byte-wise big-endian, little-endian and native-endian interpretations use :attr:`~Bits.uintbe`, :attr:`~Bits.uintle` and :attr:`~Bits.uintne` respectively. These will raise a :exc:`ValueError` if the bitstring is not a whole number of bytes long. :: >>> s = BitArray('0x000001') >>> s.uint # bit-wise big-endian 1 >>> s.uintbe # byte-wise big-endian 1 >>> s.uintle # byte-wise little-endian 65536 >>> s.uintne # byte-wise native-endian (will be 1 on a big-endian platform!) 65536 int / i / intbe / intle / intne ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ For a two's complement interpretation as a base-2 signed integer use the :attr:`~Bits.int` property. If the first bit of the bitstring is zero then the :attr:`~Bits.int` and :attr:`~Bits.uint` interpretations will be equal, otherwise the :attr:`~Bits.int` will represent a negative number. :: >>> a.int 283 >>> b.i -1 For byte-wise big, little and native endian signed integer interpretations use :attr:`~Bits.intbe`, :attr:`~Bits.intle` and :attr:`~Bits.intne` respectively. These work in the same manner as their unsigned counterparts described above. float / f / floatbe / floatle / floatne ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ For a floating point interpretation use the :attr:`~Bits.float` property. This uses the IEEE 754 floating point representation and will only work if the bitstring is 16, 32 or 64 bits long. Different endiannesses are provided via :attr:`~Bits.floatle` and :attr:`~Bits.floatne`. Note that as floating point interpretations are only valid on whole-byte bitstrings there is no difference between the bit-wise big-endian :attr:`~Bits.float` and the byte-wise big-endian :attr:`~Bits.floatbe`. Note also that standard floating point numbers in Python are stored in 64 bits, so use this size if you wish to avoid rounding errors. bfloat / bfloatbe / bfloatle / bfloatne ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This is a specialised 16-bit floating point format that is essentially a truncated version of the 32-bit IEEE float. It is used mainly in machine learning. As only one length is permitted it doesn't need to be specified on creation or interpretation. See :ref:`Exotic floats` for more information. e4m3float / e5m2float ^^^^^^^^^^^^^^^^^^^^^^^ Specialised 8-bit floating point formats. See :ref:`Exotic floats` for more information. bytes ^^^^^ A common need is to retrieve the raw bytes from a bitstring for further processing or for writing to a file. For this use the :py:attr:`~Bits.bytes` interpretation, which returns a ``bytes`` object. If the length of the bitstring isn't a multiple of eight then a :exc:`ValueError` will be raised. This is because there isn't an unequivocal representation as ``bytes``. You may prefer to use the method :meth:`~Bits.tobytes` as this will be pad with between one and seven zero bits up to a byte boundary if necessary. :: >>> open('somefile', 'wb').write(a.tobytes()) >>> open('anotherfile', 'wb').write(('0x0'+a).bytes) >>> a1 = BitArray(filename='somefile') >>> a1.hex '1230' >>> a2 = BitArray(filename='anotherfile') >>> a2.hex '0123' Note that the :meth:`~Bits.tobytes` method automatically padded with four zero bits at the end, whereas for the other example we explicitly padded at the start to byte align before using the :attr:`~Bits.bytes` property. ue ^^ The :attr:`~Bits.ue` property interprets the bitstring as a single unsigned exponential-Golomb code and returns an integer. If the bitstring is not exactly one code then an :exc:`InterpretError` is raised instead. If you instead wish to read the next bits in the stream and interpret them as a code use the read function or unpack with a ``ue`` format string. See :ref:`exp-golomb` for a short explanation of this type of integer representation. :: >>> s = BitStream(ue=12) >>> s.bin '0001101' >>> s.append('ue=3') >>> print(s.unpack('2*ue')) [12, 3] se ^^ The :attr:`~Bits.se` property does much the same as ``ue`` and the provisos there all apply. The obvious difference is that it interprets the bitstring as a signed exponential-Golomb rather than unsigned - see :ref:`exp-golomb` for more information. :: >>> s = BitStream('0x164b') >>> s.se InterpretError: Bitstring is not a single exponential-Golomb code. >>> while s.pos < len(s): ... print(s.read('se')) -5 2 0 -1 uie / sie ^^^^^^^^^ A slightly different type, interleaved exponential-Golomb codes are also supported. The principles are the same as with ``ue`` and ``se`` - see :ref:`exp-golomb` for detail of the differences. bitstring-bitstring-4.1.4/doc/introduction.rst000066400000000000000000000377601453167633600216030ustar00rootroot00000000000000 **************** Introduction **************** .. module:: bitstring .. moduleauthor:: Scott Griffiths The bitstring classes --------------------- Five classes are provided by the bitstring module, four are simple containers of bits: * ``Bits``: This is the most basic class. It is immutable and so its contents can't be changed after creation. * ``BitArray(Bits)``: This adds mutating methods to its base class. * ``ConstBitStream(Bits)``: This adds methods and properties to allow the bits to be treated as a stream of bits, with a bit position and reading/parsing methods. * ``BitStream(BitArray, ConstBitStream)``: This is the most versatile class, having both the bitstream methods and the mutating methods. The fifth class is :class:`Array` which is a container of fixed-length bitstrings. The rest of this introduction mostly concerns the more basic types - for more details on :class:`Array` you can go directly to the reference documentation, but understanding how bit format strings are specified will be helpful. :class:`Bits` and :class:`BitArray` are intended to loosely mirror the ``bytes`` and ``bytearray`` types in Python. The term 'bitstring' is used in this documentation to refer generically to any of these four classes. To summarise when to use each class: * If you need to change the contents of the bitstring then you must use :class:`BitArray` or :class:`BitStream`. Truncating, replacing, inserting, appending etc. are not available for the const classes. * If you need to use a bitstring as the key in a dictionary or as a member of a ``set`` then you must use :class:`Bits` or a :class:`ConstBitStream`. As :class:`BitArray` and :class:`BitStream` objects are mutable they do not support hashing and so cannot be used in these ways. * If you are creating directly from a file then a :class:`BitArray` or :class:`BitStream` will read the whole file into memory whereas a :class:`Bits` or :class:`ConstBitStream` will not, so using the const classes allows extremely large files to be examined. * If you don't need the extra functionality of a particular class then the simpler ones might be faster and more memory efficient. The fastest and most memory efficient class is :class:`Bits`. The :class:`Bits` class is the base class of the other three class. This means that ``isinstance(s, Bits)`` will be true if ``s`` is an instance of any of the four classes. Creating bitstrings ------------------- ``Bits(__auto, length: Optional[int], offset: Optional[int], **kwargs)`` When initialising a bitstring you need to specify at most one initialiser. This can either be the first parameter in the constructor ('auto' initialisation, described below), or using one of the following keywords: * ``bytes`` : A ``bytes`` object, for example read from a binary file. * ``hex``, ``oct``, ``bin``: Hexadecimal, octal or binary strings. * ``int``, ``uint``: Signed or unsigned bit-wise big-endian binary integers. * ``intle``, ``uintle``: Signed or unsigned byte-wise little-endian binary integers. * ``intbe``, ``uintbe``: Signed or unsigned byte-wise big-endian binary integers. * ``intne``, ``uintne``: Signed or unsigned byte-wise native-endian binary integers. * ``float`` / ``floatbe``, ``floatle``, ``floatne``: Big, little and native endian floating point numbers. * ``bfloat`` / ``bfloatbe``, ``bfloatle``, ``bfloatne``: Big, little and native endian 16 bit 'bfloat' numbers. * ``e4m3float``, ``e5m2float``: Two formats of 8-bit floating point numbers. * ``se``, ``ue`` : Signed or unsigned exponential-Golomb coded integers. * ``sie``, ``uie`` : Signed or unsigned interleaved exponential-Golomb coded integers. * ``bool`` : A boolean (i.e. True or False). * ``filename`` : Directly from a file, without reading into memory if using :class:`Bits` or :class:`ConstBitStream`. For example:: a = Bits(hex='deadbeef') b = BitArray(float=100.25, length=32) c = ConstBitStream(filename='a_big_file') Note that some types need a length to be specified and others can infer the length. Another way to create a bitstring is via the ``pack`` function, which packs multiple values accoring to a given format. See the entry on :func:`pack` for more information. .. _auto_init: The auto initialiser ^^^^^^^^^^^^^^^^^^^^ The first parameter when creating a bitstring is a positional only parameter, referred to as 'auto', that can be a variety of types: * An iterable, whose elements will be evaluated as booleans (imagine calling ``bool()`` on each item) and the bits set to ``1`` for ``True`` items and ``0`` for ``False`` items. * A positive integer, used to create a bitstring of that many zero bits. * A file object, opened in binary mode, from which the bitstring will be formed. * A ``bytearray`` or ``bytes`` object. * An ``array`` object from the built-in ``array`` module. This is used after being converted to it's constituent byte data via its ``tobytes`` method. * A ``bitarray`` or ``frozenbitarray`` object from the 3rd party ``bitarray`` package. If it is a string then that string will be parsed into tokens to construct the binary data: * Starting with ``'0x'`` or ``'hex='`` implies hexadecimal. e.g. ``'0x013ff'``, ``'hex=013ff'`` * Starting with ``'0o'`` or ``'oct='`` implies octal. e.g. ``'0o755'``, ``'oct=755'`` * Starting with ``'0b'`` or ``'bin='`` implies binary. e.g. ``'0b0011010'``, ``'bin=0011010'`` * Starting with ``'int'`` or ``'uint'`` followed by a length in bits and ``'='`` gives base-2 integers. e.g. ``'uint8=255'``, ``'int4=-7'`` * To get big, little and native-endian whole-byte integers append ``'be'``, ``'le'`` or ``'ne'`` respectively to the ``'uint'`` or ``'int'`` identifier. e.g. ``'uintle32=1'``, ``'intne16=-23'`` * For floating point numbers use ``'float'`` followed by the length in bits and ``'='`` and the number. The default is big-endian, but you can also append ``'be'``, ``'le'`` or ``'ne'`` as with integers. e.g. ``'float64=0.2'``, ``'floatle32=-0.3e12'`` * Starting with ``'ue='``, ``'uie='``, ``'se='`` or ``'sie='`` implies an exponential-Golomb coded integer. e.g. ``'ue=12'``, ``'sie=-4'`` Multiples tokens can be joined by separating them with commas, so for example ``'uint4=4, 0b1, se=-1'`` represents the concatenation of three elements. Parentheses and multiplicative factors can also be used, for example ``'2*(0b10, 0xf)'`` is equivalent to ``'0b10, 0xf, 0b10, 0xf'``. The multiplying factor must come before the thing it is being used to repeat. Promotion to bitstrings """"""""""""""""""""""" Almost anywhere that a bitstring is expected you can substitute something that will get 'auto' promoted to a bitstring. For example:: >>> BitArray('0xf') == '0b1111' True Here the equals operator is expecting another bitstring so creates one from the string. The right hand side gets promoted to ``Bits('0b1111')``. Methods that need another bitstring as a parameter will also 'auto' promote, for example:: for bs in s.split('0x40'): if bs.endswith('0b111'): bs.append([1, 0]) ... if 'u8=42' in bs: bs.prepend(b'\x01') which illustrates a variety of methods promoting strings, iterables and a bytes object to bitstrings. Anything that can be used as the first parameter of the ``Bits`` constructor can be auto promoted to a bitstring where one is expected, with the exception of integers. Integers won't be auto promoted, but instead will raise a ``TypeError``:: >>> a = BitArray(100) # Create bitstring with 100 zeroed bits. >>> a += 0xff # TypeError - 0xff is the same as the integer 255. >>> a += '0xff' # Probably what was meant - append eight '1' bits. >>> a += Bits(255) # If you really want to do it then code it explicitly. ``BitsType`` """""""""""" .. class:: BitsType(Bits | str | Iterable[Any] | bool | BinaryIO | bytearray | bytes | memoryview | bitarray.bitarray) The ``BitsType`` type is used in the documentation in a number of places where an object of any type that can be promoted to a bitstring is acceptable. It's just a union of types rather than an actual class (though it's documented here as a class as I could find no alternative). It's not user accessible, but is just a shorthand way of saying any of the above types. Keyword initialisers ^^^^^^^^^^^^^^^^^^^^ If the 'auto' initialiser isn't used then at most one keyword initialiser can be used. From a hexadecimal string """"""""""""""""""""""""" >>> c = BitArray(hex='0x000001b3') >>> c.hex '000001b3' The initial ``0x`` or ``0X`` is optional. Whitespace is also allowed and is ignored. Note that the leading zeros are significant, so the length of ``c`` will be 32. If you include the initial ``0x`` then you can use the 'auto' initialiser instead. As it is the first parameter in :class:`__init__` this will work equally well:: c = BitArray('0x000001b3') From a binary string """""""""""""""""""" >>> d = BitArray(bin='0011 00') >>> d.bin '001100' An initial ``0b`` or ``0B`` is optional and whitespace will be ignored. As with ``hex``, the 'auto' initialiser will work if the binary string is prefixed by ``0b``:: >>> d = BitArray('0b001100') From an octal string """""""""""""""""""" >>> o = BitArray(oct='34100') >>> o.oct '34100' An initial ``0o`` or ``0O`` is optional, but ``0o`` (a zero and lower-case 'o') is preferred as it is slightly more readable. As with ``hex`` and ``bin``, the 'auto' initialiser will work if the octal string is prefixed by ``0o``:: >>> o = BitArray('0o34100') From an integer """"""""""""""" >>> e = BitArray(uint=45, length=12) >>> f = BitArray(int=-1, length=7) >>> e.bin '000000101101' >>> f.bin '1111111' For initialisation with signed and unsigned binary integers (``int`` and ``uint`` respectively) the ``length`` parameter is mandatory, and must be large enough to contain the integer. So for example if ``length`` is 8 then ``uint`` can be in the range 0 to 255, while ``int`` can range from -128 to 127. Two's complement is used to represent negative numbers. The 'auto' initialiser can be used by giving the length in bits immediately after the ``int`` or ``uint`` token, followed by an equals sign then the value:: >>> e = BitArray('uint12=45') >>> f = BitArray('int7=-1') The ``uint`` and ``int`` names can be shortened to just ``u`` and ``i`` respectively. For mutable bitstrings you can change value by assigning to a property with a length:: >>> e = BitArray() >>> e.u12 = 45 >>> f = BitArray() >>> f.i7 = -1 The plain ``int`` and ``uint`` initialisers are bit-wise big-endian. That is to say that the most significant bit comes first and the least significant bit comes last, so the unsigned number one will have a ``1`` as its final bit with all other bits set to ``0``. These can be any number of bits long. For whole-byte bitstring objects there are more options available with different endiannesses. Big and little-endian integers """""""""""""""""""""""""""""" >>> big_endian = BitArray(uintbe=1, length=16) >>> little_endian = BitArray(uintle=1, length=16) >>> native_endian = BitArray(uintne=1, length=16) There are unsigned and signed versions of three additional 'endian' types. The unsigned versions are used above to create three bitstrings. The first of these, ``big_endian``, is equivalent to just using the plain bit-wise big-endian ``uint`` initialiser, except that all ``intbe`` or ``uintbe`` interpretations must be of whole-byte bitstrings, otherwise a :exc:`ValueError` is raised. The second, ``little_endian``, is interpreted as least significant byte first, i.e. it is a byte reversal of ``big_endian``. So we have:: >>> big_endian.hex '0001' >>> little_endian.hex '0100' Finally we have ``native_endian``, which will equal either ``big_endian`` or ``little_endian``, depending on whether you are running on a big or little-endian machine (if you really need to check then use ``import sys; sys.byteorder``). From a floating point number """""""""""""""""""""""""""" >>> f1 = BitArray(float=10.3, length=32) >>> f2 = BitArray('float64=5.4e31') Floating point numbers can be used for initialisation provided that the bitstring is 16, 32 or 64 bits long. Standard Python floating point numbers are 64 bits long, so if you use 32 bits then some accuracy could be lost. The 16 bit version has very limited range and is used mainly in specialised areas such as machine learning. The exact bits used to represent the floating point number will conform to the IEEE 754 standard, even if the machine being used does not use that standard internally. Similar to the situation with integers there are big and little endian versions. The plain ``float`` is big endian and so ``floatbe`` is just an alias. As with other initialisers you can also 'auto' initialise, as demonstrated with the second example below:: >>> little_endian = BitArray(floatle=0.0, length=64) >>> native_endian = BitArray('floatne:32=-6.3') See also :ref:`Exotic floats` for information on non IEEE 754 floating point representations that are supported (bfloat and different 8-bit float formats). From exponential-Golomb codes """"""""""""""""""""""""""""" Initialisation with integers represented by exponential-Golomb codes is also possible. ``ue`` is an unsigned code while ``se`` is a signed code. Interleaved exponential-Golomb codes are also supported via ``uie`` and ``sie``:: >>> g = BitArray(ue=12) >>> h = BitArray(se=-402) >>> g.bin '0001101' >>> h.bin '0000000001100100101' For these initialisers the length of the bitstring is fixed by the value it is initialised with, so the length parameter must not be supplied and it is an error to do so. If you don't know what exponential-Golomb codes are then you are in good company, but they are quite interesting, so I’ve included a section on them (see :ref:`exp-golomb`). The 'auto' initialiser may also be used by giving an equals sign and the value immediately after a ``ue`` or ``se`` token:: >>> g = BitArray('ue=12') >>> h = BitArray('se=-402') You may wonder why you would bother doing this in this case as the syntax is slightly longer. Hopefully all will become clear in the next section. From raw byte data """""""""""""""""" Using the length and offset parameters to specify the length in bits and an offset at the start to be ignored is particularly useful when initialising from raw data or from a file. :: a = BitArray(bytes=b'\x00\x01\x02\xff', length=28, offset=1) b = BitArray(bytes=open("somefile", 'rb').read()) The ``length`` parameter is optional; it defaults to the length of the data in bits (and so will be a multiple of 8). You can use it to truncate some bits from the end of the bitstring. The ``offset`` parameter is also optional and is used to truncate bits at the start of the data. You can also use a ``bytearray`` or a ``bytes`` object, either explicitly with a ``bytes=some_bytearray`` keyword or via the 'auto' initialiser:: c = BitArray(a_bytearray_object) d = BitArray(b'\x23g$5') From a file """"""""""" Using the ``filename`` initialiser allows a file to be analysed without the need to read it all into memory. The way to create a file-based bitstring is:: p = Bits(filename="my200GBfile") This will open the file in binary read-only mode. The file will only be read as and when other operations require it, and the contents of the file will not be changed by any operations. If only a portion of the file is needed then the ``offset`` and ``length`` parameters (specified in bits) can be used. Note that we created a :class:`Bits` here rather than a :class:`BitArray`, as they have quite different behaviour in this case. The immutable :class:`Bits` will never read the file into memory (except as needed by other operations), whereas if we had created a :class:`BitArray` then the whole of the file would immediately have been read into memory. This is because in creating a :class:`BitArray` you are implicitly saying that you want to modify it, and so it needs to be in memory. It's also possible to use the 'auto' initialiser for file objects. It's as simple as:: f = open('my200GBfile', 'rb') p = Bits(f) bitstring-bitstring-4.1.4/doc/optimisation.rst000066400000000000000000000077701453167633600215770ustar00rootroot00000000000000.. currentmodule:: bitstring Optimisation Techniques ======================= The :mod:`bitstring` module aims to be as fast as reasonably possible, and since version 4.1 has used the ``bitarray`` C extension to power its core. There are however some pointers you should follow to make your code efficient, so if you need things to run faster then this is the section for you. Use combined read and interpretation ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When parsing a bitstring one way to write code is in the following style:: width = s.read(12).uint height = s.read(12).uint flags = s.read(4).bin This works fine, but is not very quick. The problem is that the call to :meth:`~ConstBitStream.read` constructs and returns a new bitstring, which then has to be interpreted. The new bitstring isn't used for anything else and so creating it is wasted effort. Instead it is better to use a string parameter that does the read and interpretation together:: width = s.read('uint12') height = s.read('uint12') flags = s.read('bin4') This is much faster, although probably not as fast as the combined call:: width, height, flags = s.readlist('uint12, uint12, bin4') Choose the simplest class you can ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you don't need to modify your bitstring after creation then prefer the immutable :class:`Bits` over the mutable :class:`BitArray`. This is typically the case when parsing, or when creating directly from files. The speed difference between the classes is noticeable, and there are also memory usage optimisations that are made if objects are known to be immutable. You should also prefer :class:`ConstBitStream` to :class:`BitStream` if you won't need to modify any bits. One anti-pattern to watch out for is using ``+=`` on a :class:`Bits` object. For example, don't do this:: s = Bits() for i in range(1000): s += '0xab' Now this is inefficient for a few reasons, but the one I'm highlighting is that as the immutable bitstring doesn't have an ``__iadd__`` special method the ordinary ``__add__`` gets used instead. In other words ``s += '0xab'`` gets converted to ``s = s + '0xab'``, which creates a new :class:`Bits` from the old on every iteration. This isn't what you'd want or possibly expect. If ``s`` had been a :class:`BitArray` then the addition would have been done in-place, and have been much more efficient. Another problem is that the string ``0xab`` needs to be converted to a bitstring on every iteration. There are cacheing mechanisms that will make this faster after the first time, but if there is a constant conversion happening in a loop like this it is better to hoist it out of the loop by declaring ``ab = Bits('0xab')`` first and then adding this object instead of the string. Use dedicated functions for bit setting and checking ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you need to set or check individual bits then there are special functions for this. For example one way to set bits would be:: s = BitArray(1000) for p in [14, 34, 501]: s[p] = '0b1' This creates a 1000 bit bitstring and sets three of the bits to '1'. Unfortunately the crucial line spends most of its time creating a new bitstring from the '0b1' string. You could make it slightly quicker by using ``s[p] = True``, but it is much faster (and I mean at least an order of magnitude) to use the :meth:`~BitArray.set` method:: s = BitArray(1000) s.set(True, [14, 34, 501]) As well as :meth:`~BitArray.set` and :meth:`~BitArray.invert` there are also checking methods :meth:`~Bits.all` and :meth:`~Bits.any`. So rather than using :: if s[100] and s[200]: do_something() it's better to say :: if s.all(True, (100, 200)): do_something() If the pattern of setting or getting can be expressed as a ``range`` then it is much faster to pass in the range object so that it can be used to optimize the pattern. For example, instead of :: for i in range(0, len(s), 2): s.set(True, i) you should just write :: s.set(True, range(0, len(s), 2))bitstring-bitstring-4.1.4/doc/python-logo.png000066400000000000000000002431541453167633600213110ustar00rootroot00000000000000PNG  IHDRY]Ɇ&sBIT|d pHYs B4tEXtCreation Time06/05/04Mq%tEXtSoftwareMacromedia Fireworks MX 2004vprVWx헿o@ǟ\'9`Ab1 lLH "2  ?`r1ld@:Vwq\EBc9ۯ}|v6Z+ s]T,tc J+GUcQ̕ʋ2/TP( #COϿ?#8={pK޴} k<%3}D ZT&Gr"϶׿uX:$DF%~閟$ )y7H& 6SaSbA:DyɃ`B; G/s|F5.`1R/pM svQ33SO3_p) 'G,rqe^r o-'ˑ"ӊyFYpFƵHt\1#}")ԧDZ3^Mv$}T1o yX?cK<{Էaߍ%O<O5jNv FW,"sѥ[IX6xW>+ 6qx1=y|n݅|ΎY8=nɛZϓ@](ꃾ*dOSwVt19>@c&pôgǙh# gO&|{atWƫYgx[˛9\;f+Mhd&Qxhg3T*d=bO6N}} \C8co4נ\Zt;’T7MMGӆ˵N$񰰿ձ_hnI{+qnA^oͯjYкGCw$<\89G"Y:~ҎԦCp.Oz;.fiPCb!{a>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$L ەnH4\ٷ""u0meH Eaƍ;g-gg=52Y_־ՅP-DDDyXn&['Hyk30Ctn޼7m$ZEDD1cȊ}n>#\nCc%r{+dg"nXN܆:q\ XDD3(m)t9.{ydkn[{3ݼySx|,ׄ\ r:'<'G~5!M~>n/ r5aW.jC% CVLhrԂ^~R'\57lʼn!+N^-^nHYc Y}HpsCV? !l}Ͷ(ϞNm;!"">;0n><dRp Vm"""CqV.c ? ~=FWs,|w aTNk?C߷8Aʸ$ġ@""J$X)+nx""Aǐ5 DÓyaM OhHqaa0Ah1d'f"""" !( YDDDD`""""CQ"EDDD,"""0dE!( YDDDD`""""CQ"EDDD,"""0dE!( YDDDD`""""CQ"EDDD,"""0dE!( YDDDD`""""CQ"ŅwIIENDB`bitstring-bitstring-4.1.4/doc/quick_reference.rst000066400000000000000000000550541453167633600222100ustar00rootroot00000000000000.. currentmodule:: bitstring .. _quick_reference: ############### Quick Reference ############### This section gives a summary of the bitstring module's classes, functions and attributes. There are four classes that are bit containers, so that each element is a single bit. They differ based on whether they can be modified after creation and on whether they have the concept of a current bit position. .. |nbsp| unicode:: 0xa0 :trim: .. list-table:: :widths: 20 15 15 50 :header-rows: 1 * - Class - Mutable? - Streaming methods? - * - :ref:`bits_quick_reference` - |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| ✘ - |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| ✘ - An efficient, immutable container of bits. * - :ref:`bitarray_quick_reference` - |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| ✔ - |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| ✘ - Like ``Bits`` but it can be changed after creation. * - :ref:`constbitstream_quick_reference` - |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| ✘ - |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| ✔ - Immutable like ``Bits`` but with a bit position and reading methods. * - :ref:`bitstream_quick_reference` - |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| ✔ - |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| ✔ - Mutable like ``BitArray`` but with a bit position and reading methods. The final class is a flexible container whose elements are fixed-length bitstrings. .. list-table:: :widths: 20 15 15 50 * - :ref:`array_quick_reference` - |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| ✔ - |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| |nbsp| ✘ - An efficient list-like container where each item has a fixed-length binary format. ---- .. _bits_quick_reference: Bits ---- :class:`Bits` is the most basic class and is just a container of bits. It is immutable, so once created its value cannot change. ``Bits(__auto, length: Optional[int], offset: Optional[int], **kwargs)`` The first parameter (usually referred to as `auto`) can be many different types, including parsable strings, a file handle, a bytes or bytearray object, an integer or an iterable. A single initialiser from `kwargs` can be used instead of `auto`, including ``bin``, ``hex``, ``oct``, ``bool``, ``uint``, ``int``, ``float``, ``bytes`` and ``filename``. Examples:: Bits('0xef') Bits(float=-50.5, length=32) Bits('uint10=99') Bits(uint=99, length=10) Methods ^^^^^^^ * :meth:`~Bits.all` -- Check if all specified bits are set to 1 or 0. * :meth:`~Bits.any` -- Check if any of specified bits are set to 1 or 0. * :meth:`~Bits.copy` -- Return a copy of the bitstring. * :meth:`~Bits.count` -- Count the number of bits set to 1 or 0. * :meth:`~Bits.cut` -- Create generator of constant sized chunks. * :meth:`~Bits.endswith` -- Return whether the bitstring ends with a sub-bitstring. * :meth:`~Bits.find` -- Find a sub-bitstring in the current bitstring. * :meth:`~Bits.findall` -- Find all occurrences of a sub-bitstring in the current bitstring. * :meth:`~Bits.join` -- Join bitstrings together using current bitstring. * :meth:`~Bits.pp` -- Pretty print the bitstring. * :meth:`~Bits.rfind` -- Seek backwards to find a sub-bitstring. * :meth:`~Bits.split` -- Create generator of chunks split by a delimiter. * :meth:`~Bits.startswith` -- Return whether the bitstring starts with a sub-bitstring. * :meth:`~Bits.tobitarray` -- Return bitstring as a ``bitarray`` object from the `bitarray `_ package. * :meth:`~Bits.tobytes` -- Return bitstring as bytes, padding if needed. * :meth:`~Bits.tofile` -- Write bitstring to file, padding if needed. * :meth:`~Bits.unpack` -- Interpret bits using format string. Special methods ^^^^^^^^^^^^^^^ Also available are operators that will return a new bitstring (or check for equality): * :meth:`== ` / :meth:`\!= ` -- Equality tests. * :meth:`[] ` -- Get an element or slice. * :meth:`+ ` -- Concatenate with another bitstring. * :meth:`* ` -- Concatenate multiple copies of the current bitstring. * :meth:`~ ` -- Invert every bit of the bitstring. * :meth:`\<\< ` -- Shift bits to the left. * :meth:`>> ` -- Shift bits to the right. * :meth:`& ` -- Bit-wise AND between two bitstrings. * :meth:`| ` -- Bit-wise OR between two bitstrings. * :meth:`^ ` -- Bit-wise XOR between two bitstrings. Properties ^^^^^^^^^^ These read-only properties of the ``Bits`` object are interpretations of the binary data and are calculated as required. Many require the bitstring to be specific lengths. * :attr:`~Bits.bin` / ``b`` -- The bitstring as a binary string. * :attr:`~Bits.bool` -- For single bit bitstrings, interpret as True or False. * :attr:`~Bits.bytes` -- The bitstring as a bytes object. * :attr:`~Bits.float` / ``floatbe`` / ``f`` -- Interpret as a big-endian floating point number. * :attr:`~Bits.floatle` -- Interpret as a little-endian floating point number. * :attr:`~Bits.floatne` -- Interpret as a native-endian floating point number. * :attr:`~Bits.e4m3float` -- Interpret as an 8 bit float with 1:4:3 format. * :attr:`~Bits.e5m2float` -- Interpret as an 8 bit float with 1:5:2 format. * :attr:`~Bits.bfloat` / ``bfloatbe`` -- Interpret as a big-endian bfloat floating point number. * :attr:`~Bits.bfloatle` -- Interpret as a little-endian bfloat floating point number. * :attr:`~Bits.bfloatne` -- Interpret as a native-endian bfloat floating point number. * :attr:`~Bits.hex` / ``h`` -- The bitstring as a hexadecimal string. * :attr:`~Bits.int` / ``i`` -- Interpret as a two's complement signed integer. * :attr:`~Bits.intbe` -- Interpret as a big-endian signed integer. * :attr:`~Bits.intle` -- Interpret as a little-endian signed integer. * :attr:`~Bits.intne` -- Interpret as a native-endian signed integer. * :attr:`~Bits.len` -- Length of the bitstring in bits. * :attr:`~Bits.oct` / ``o`` -- The bitstring as an octal string. * :attr:`~Bits.se` -- Interpret as a signed exponential-Golomb code. * :attr:`~Bits.ue` -- Interpret as an unsigned exponential-Golomb code. * :attr:`~Bits.sie` -- Interpret as a signed interleaved exponential-Golomb code. * :attr:`~Bits.uie` -- Interpret as an unsigned interleaved exponential-Golomb code. * :attr:`~Bits.uint` / ``u`` -- Interpret as a two's complement unsigned integer. * :attr:`~Bits.uintbe` -- Interpret as a big-endian unsigned integer. * :attr:`~Bits.uintle` -- Interpret as a little-endian unsigned integer. * :attr:`~Bits.uintne` -- Interpret as a native-endian unsigned integer. ---- .. _bitarray_quick_reference: BitArray -------- ``Bits`` ⟶ ``BitArray`` :class:`BitArray` adds mutating methods to ``Bits``. The constructor is the same as for ``Bits``. Additional methods ^^^^^^^^^^^^^^^^^^ All of the methods listed above for the ``Bits`` class are available, plus: * :meth:`~BitArray.append` -- Append a bitstring. * :meth:`~BitArray.byteswap` -- Change byte endianness in-place. * :meth:`~BitArray.clear` -- Remove all bits from the bitstring. * :meth:`~BitArray.insert` -- Insert a bitstring. * :meth:`~BitArray.invert` -- Flip bit(s) between one and zero. * :meth:`~BitArray.overwrite` -- Overwrite a section with a new bitstring. * :meth:`~BitArray.prepend` -- Prepend a bitstring. * :meth:`~BitArray.replace` -- Replace occurrences of one bitstring with another. * :meth:`~BitArray.reverse` -- Reverse bits in-place. * :meth:`~BitArray.rol` -- Rotate bits to the left. * :meth:`~BitArray.ror` -- Rotate bits to the right. * :meth:`~BitArray.set` -- Set bit(s) to 1 or 0. Additional special methods ^^^^^^^^^^^^^^^^^^^^^^^^^^ The special methods available for the ``Bits`` class are all available, plus some which will modify the bitstring: * :meth:`[] ` -- Set an element or slice. * :meth:`del ` -- Delete an element or slice. * :meth:`+= ` -- Append bitstring to the current bitstring. * :meth:`*= ` -- Concatenate multiple copies of the current bitstring. * :meth:`\<\<= ` -- Shift bits in-place to the left. * :meth:`>>= ` -- Shift bits in-place to the right. * :meth:`&= ` -- In-place bit-wise AND between two bitstrings. * :meth:`|= ` -- In-place bit-wise OR between two bitstrings. * :meth:`^= ` -- In-place bit-wise XOR between two bitstrings. ``BitArray`` objects have the same properties as ``Bits``, except that they are all (with the exception of ``len``) writable as well as readable. ---- .. _constbitstream_quick_reference: ConstBitStream -------------- ``Bits`` ⟶ ``ConstBitStream`` :class:`ConstBitStream` adds a bit position and methods to read and navigate in an immutable bitstream. If you wish to use streaming methods on a large file without changing it then this is often the best class to use. The constructor is the same as for ``Bits`` / ``BitArray`` but with an optional current bit position. ``ConstBitStream(auto, length: Optional[int], offset: Optional[int], pos: int = 0, **kwargs)`` All of the methods, special methods and properties listed above for the ``Bits`` class are available, plus: Additional methods ^^^^^^^^^^^^^^^^^^ * :meth:`~ConstBitStream.bytealign` -- Align to next byte boundary. * :meth:`~ConstBitStream.peek` -- Peek at and interpret next bits as a single item. * :meth:`~ConstBitStream.peeklist` -- Peek at and interpret next bits as a list of items. * :meth:`~ConstBitStream.read` -- Read and interpret next bits as a single item. * :meth:`~ConstBitStream.readlist` -- Read and interpret next bits as a list of items. * :meth:`~ConstBitStream.readto` -- Read up to and including next occurrence of a bitstring. Additional properties ^^^^^^^^^^^^^^^^^^^^^ * :attr:`~ConstBitStream.bytepos` -- The current byte position in the bitstring. * :attr:`~ConstBitStream.pos` -- The current bit position in the bitstring. ---- .. _bitstream_quick_reference: BitStream --------- ``Bits`` ⟶ ``BitArray / ConstBitStream`` ⟶ ``BitStream`` :class:`BitStream` contains all of the 'stream' elements of ``ConstBitStream`` and adds all of the mutating methods of ``BitArray``. The constructor is the same as for ``ConstBitStream``. It has all the methods, special methods and properties of the ``Bits``, ``BitArray`` and ``ConstBitArray`` classes. It is the most general of the four classes, but it is usually best to choose the simplest class for your use case. ---- .. _array_quick_reference: Array ----- A bitstring :class:`Array` is a contiguously allocated sequence of bitstrings of the same type. It is similar to the ``array`` type in the `array `_ module, except that it is far more flexible. ``Array(dtype: str, initializer, trailing_bits)`` The `dtype` can any single fixed-length token as described in :ref:`format_tokens` and :ref:`compact_format`. The `inititalizer` will typically be an iterable such as a list, but can also be many other things including an open binary file, a bytes or bytearray object, another ``bitstring.Array`` or an ``array.array``. The `trailing_bits` typically isn't used in construction, and specifies bits left over after interpreting the stored binary data according to the data type `dtype`. Both the dtype and the underlying bit data (stored as a :class:`BitArray`) can be freely modified after creation, and element-wise operations can be used on the ``Array``. Modifying the data or format after creation may cause the :attr:`~Array.trailing_bits` to not be empty. Initialization examples:: Array('>H', [1, 10, 20]) Array('float16', a_file_object) Array('int4', stored_bytes) Methods ^^^^^^^ * :meth:`~Array.append` -- Append a single item to the end of the Array. * :meth:`~Array.astype` -- Cast the Array to a new dtype. * :meth:`~Array.byteswap` -- Change byte endianness of all items. * :meth:`~Array.count` -- Count the number of occurences of a value. * :meth:`~Array.equals` -- Compare with another Array for exact equality. * :meth:`~Array.extend` -- Append multiple items to the end of the Array from an iterable. * :meth:`~Array.fromfile` -- Append items read from a file object. * :meth:`~Array.insert` -- Insert an item at a given position. * :meth:`~Array.pop` -- Return and remove an item. * :meth:`~Array.pp` -- Pretty print the Array. * :meth:`~Array.reverse` -- Reverse the order of all items. * :meth:`~Array.tobytes` -- Return Array data as bytes object, padding with zero bits at the end if needed. * :meth:`~Array.tofile` -- Write Array data to a file, padding with zero bits at the end if needed. * :meth:`~Array.tolist` -- Return Array items as a list. Special methods ^^^^^^^^^^^^^^^ These non-mutating special methods are available. Where appropriate they return a new ``Array``. * :meth:`[] ` -- Get an element or slice. * :meth:`+ ` -- Add value to each element. * :meth:`- ` -- Subtract value from each element. * :meth:`* ` -- Multiply each element by a value. * :meth:`/ ` -- Divide each element by a value. * :meth:`// ` -- Floor divide each element by a value. * :meth:`% ` -- Take modulus of each element with a value. * :meth:`\<\< ` -- Shift value of each element to the left. * :meth:`>> ` -- Shift value of each element to the right. * :meth:`& ` -- Bit-wise AND of each element. * :meth:`| ` -- Bit-wise OR of each element. * :meth:`^ ` -- Bit-wise XOR of each element. * :meth:`- ` -- Unary minus of each element. * :meth:`abs() ` -- Absolute value of each element. For example:: >>> b = Array('i6', [30, -10, 1, 0]) >>> b >> 2 Array('i6', [7, -3, 0, 0]) >>> b + 1 Array('i6', [31, -9, 2, 1]) >>> b + b Array('i6', [30, -10, 1, 0, 30, -10, 1, 0]) Comparison operators will output an ``Array`` with a ``dtype`` of ``'bool'``. * :meth:`== ` / :meth:`\!= ` -- Equality tests. * :meth:`\< ` -- Less than comparison. * :meth:`\<= ` -- Less than or equal comparison. * :meth:`> ` -- Greater than comparison. * :meth:`>= ` -- Greater than or equal comparison. Mutating versions of many of the methods are also available. * :meth:`[] ` -- Set an element or slice. * :meth:`del ` -- Delete an element or slice. * :meth:`+= ` -- Add value to each element in-place. * :meth:`-= ` -- Subtract value from each element in-place. * :meth:`*= ` -- Multiply each element by a value in-place. * :meth:`/= ` -- Divide each element by a value in-place. * :meth:`//= ` -- Floor divide each element by a value in-place. * :meth:`%= ` -- Take modulus of each element with a value in-place. * :meth:`\<\<= ` -- Shift bits of each element to the left in-place. * :meth:`>>= ` -- Shift bits of each element to the right in-place. * :meth:`&= ` -- In-place bit-wise AND of each element. * :meth:`|= ` -- In-place bit-wise OR of each element. * :meth:`^= ` -- In-place bit-wise XOR of each element. Example:: >>> a = Array('float16', [1.5, 2.5, 7, 1000]) >>> a[::2] *= 3.0 # Multiply every other float16 value in-place >>> a Array('float16', [4.5, 2.5, 21.0, 1000.0]) The bit-wise logical operations (``&``, ``|``, ``^``) are performed on each element with a ``Bits`` object, which must have the same length as the ``Array`` elements. The other element-wise operations are performed on the interpreted data, not on the bit-data. For example this means that the shift operations won't work on floating point formats. Properties ^^^^^^^^^^ * :attr:`~Array.data` -- The complete binary data in a ``BitArray`` object. Can be freely modified. * :attr:`~Array.dtype` -- The data type or typecode. Can be freely modified. * :attr:`~Array.itemsize` -- The length *in bits* of a single item. Read only. * :attr:`~Array.trailing_bits` -- If the data length is not a multiple of the `dtype` length, this ``BitArray`` gives the leftovers at the end of the data. ---- General Information ------------------- .. _format_tokens: Format tokens ^^^^^^^^^^^^^ Format strings are used when constructing bitstrings, as well as reading, packing and unpacking them, as well as giving the format for :class:`Array` objects. They can also be auto promoted to bitstring when appropriate - see :ref:`auto_init`. =================== =============================================================================== ``'int:n'`` ``n`` bits as a signed integer. ``'uint:n'`` ``n`` bits as an unsigned integer. ``'intbe:n'`` ``n`` bits as a byte-wise big-endian signed integer. ``'uintbe:n'`` ``n`` bits as a byte-wise big-endian unsigned integer. ``'intle:n'`` ``n`` bits as a byte-wise little-endian signed integer. ``'uintle:n'`` ``n`` bits as a byte-wise little-endian unsigned integer. ``'intne:n'`` ``n`` bits as a byte-wise native-endian signed integer. ``'uintne:n'`` ``n`` bits as a byte-wise native-endian unsigned integer. ``'float:n'`` ``n`` bits as a big-endian floating point number (same as ``floatbe``). ``'floatbe:n'`` ``n`` bits as a big-endian floating point number (same as ``float``). ``'floatle:n'`` ``n`` bits as a little-endian floating point number. ``'floatne:n'`` ``n`` bits as a native-endian floating point number. ``'bfloat[:16]'`` 16 bits as a big-endian bfloat floating point number (same as ``bfloatbe``). ``'bfloatbe[:16]'`` 16 bits as a big-endian bfloat floating point number (same as ``bfloat``). ``'bfloatle[:16]'`` 16 bits as a little-endian floating point number. ``'bfloatne[:16]'`` 16 bits as a native-endian floating point number. ``'e4m3float'`` 8 bits as a 1:4:3 format floating point number. ``'e5m2float'`` 8 bits as a 1:5:2 format floating point number. ``'hex:n'`` ``n`` bits as a hexadecimal string. ``'oct:n'`` ``n`` bits as an octal string. ``'bin:n'`` ``n`` bits as a binary string. ``'bits:n'`` ``n`` bits as a new bitstring. ``'bytes:n'`` ``n`` bytes as a ``bytes`` object. ``'ue'`` next bits as an unsigned exponential-Golomb code. ``'se'`` next bits as a signed exponential-Golomb code. ``'uie'`` next bits as an interleaved unsigned exponential-Golomb code. ``'sie'`` next bits as an interleaved signed exponential-Golomb code. ``'bool[:1]'`` next bit as a boolean (True or False). ``'pad:n'`` next ``n`` bits will be ignored (padding). Only applicable when reading, not creating. =================== =============================================================================== The ``':'`` before the length is optional, and is mostly omitted in the documentation, except where it improves readability. The ``hex``, ``bin``, ``oct``, ``int``, ``uint`` and ``float`` properties can all be shortened to just their initial letter. Bitstring literals ^^^^^^^^^^^^^^^^^^ To make a literal quantity (one that directly represents a sequence of bits) you can use any of the format tokens above followed by an ``'='`` and a value to initialise with. For example:: s = BitArray('float32=10.125, int7=-9') s.append('hex:abc') You can also create binary, octal and hexadecimal literals by starting a string with ``'0b'``, ``'0o'`` and ``'0ox'`` respectively:: t = BitArray('0b101') t += '0x001f' .. _compact_format: Compact format strings ^^^^^^^^^^^^^^^^^^^^^^ Another option is to use a format specifier similar to those used in the ``struct`` and ``array`` modules. These consist of a character to give the endianness, followed by more single characters to give the format. The endianness character must start the format string: ======= ============= ``'>'`` Big-endian ``'<'`` Little-endian ``'='`` Native-endian ======= ============= .. note:: * For native-endian ``'@'`` and ``'='`` can both be used and are equivalent. The ``'@'`` character was required for native-endianness prior to version 4.1 of bitstring. * For 'network' endianness use ``'>'`` as network and big-endian are equivalent. This is followed by at least one of these format characters: ======= =============================== ``'b'`` 8 bit signed integer ``'B'`` 8 bit unsigned integer ``'h'`` 16 bit signed integer ``'H'`` 16 bit unsigned integer ``'l'`` 32 bit signed integer ``'L'`` 32 bit unsigned integer ``'q'`` 64 bit signed integer ``'Q'`` 64 bit unsigned integer ``'e'`` 16 bit floating point number ``'f'`` 32 bit floating point number ``'d'`` 64 bit floating point number ======= =============================== The exact type is determined by combining the endianness character with the format character, but rather than give an exhaustive list a single example should explain: ======== ====================================== =========== ``'>h'`` Big-endian 16 bit signed integer ``intbe16`` ``'h'`` on big-endian systems, and equal the little-endian ``'\n", "Note:\n", "\n", "Be sure to remember the quotes around the hex and binary strings.\n", "If you forget them you would just have an ordinary Python integer, which would instead create a bitstring of that many '0' bits.\n", "For example `0xff01` is the same as the base-10 number 65281, so `BitArray(0xff01)` would consist of 65281 zero bits!\n", "\n", "\n", "There are lots of things we can do with our new bitstrings, the simplest of which is just to print them:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0xff01\n", "0b110\n" ] } ], "source": [ "print(a)\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now you would be forgiven for thinking that the strings that we used to create the two bitstrings had just been stored to be given back when printed, but that's not the case.\n", "Every bitstring should be considered just as a sequence of bits.\n", "As we'll see there are lots of ways to create and manipulate them, but they have no memory of how they were created.\n", "When they are printed they just pick the simplest hex or binary representation of themselves.\n", "If you prefer you can pick the representation that you want:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1111111100000001\n", "6\n", "-2\n", "b'\\xff\\x01'\n" ] } ], "source": [ "print(a.bin)\n", "print(b.oct)\n", "print(b.int)\n", "print(a.bytes)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "There are a few things to note here:\n", "\n", "* To get the different interpretations of the binary data we use properties such as `bin`, `hex`, `oct`, `int` and `bytes`. You can probably guess what these all mean, but you don't need to know quite yet. The properties are calculated when you ask for them rather than being stored as part of the object itself.\n", "* Many of the interpretations have single letter aliases, and interpretations can also have bit lengths appended to them. This allows expressions such as `a.u32 = 900` which will set `a` to the 32 bit representation of the unsigned integer `900`. You're not restricted to the usual bit lengths, so something like `a.i5 = -8` will work as well.\n", "\n", "Great - let's try some more:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Cannot convert to hex unambiguously - not a multiple of 4 bits long.\n" ] } ], "source": [ "try:\n", " b.hex\n", "except bitstring.InterpretError as e:\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Oh dear - this throws a `bitstring.InterpretError` error.\n", "The problem we have here is that `b` is 3 bits long, whereas each hex digit represents 4 bits.\n", "This means that there is no unambiguous way to represent it in hexadecimal.\n", "There are similar restrictions on other interpretations (octal must be a multiple of 3 bits, bytes a multiple of 8 bits etc.)\n", "\n", "An exception is raised rather than trying to guess the best hex representation as there are a multitude of ways to convert to hex.\n", "I occasionally get asked why it doesn't just do the 'obvious' conversion, which is invariably what that person expects from his own field of work.\n", "This could be truncating bits at the start or end, or padding at the start or end with either zeros or ones.\n", "Rather than try to guess what is meant we just raise an exception - if you want a particular behaviour then write it explicitly:\n" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "c\n", "6\n" ] } ], "source": [ "print((b + [0]).hex)\n", "print(([0] + b).hex)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Here we've added a zero bit first to the end and then to the start.\n", "Don't worry too much about how it all works, but just to give you a taster the zero bit `[0]` could also have been written as `BitArray([0])`, `BitArray('0b0')`, `BitArray(bin='0')`, `'0b0'` or just `1` (this final option isn't a typo, it means construct a bitstring of length one, with all the bits initialised to zero - it does look a bit confusing though which is why I prefer `[0]` and `[1]` to represent single bits).\n", "Take a look at [the auto initialiser](https://bitstring.readthedocs.io/en/stable/creation.html#the-auto-initialiser) for more details." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Modifying bitstrings\n", "\n", "A `BitArray` can be treated just like a list of bits. You can slice it, delete sections, insert new bits and more using standard index notation:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0b111110\n", "0b1111111100\n" ] } ], "source": [ "print(a[3:9])\n", "del a[-6:]\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "The slicing works just as it does for other containers, so the deletion above removes the final six bits.\n", "\n", "If you ask for a single item, rather than a slice, a boolean is returned. Naturally enough `1` bits are `True` whereas `0` bits are `False`." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n" ] } ], "source": [ "print(a[0])\n", "print(a[-1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "To join together bitstrings you can use a variety of methods, including `append`, `prepend`, `insert`, and plain `+` or `+=` operations::" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "a.prepend('0b01')\n", "a.append('0o7')\n", "a += '0x06'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Here we first put two bits at the start of `a`, then three bits on the end (a single octal digit) and finally another byte (two hex digits) on the end.\n", "\n", "Note how we are just using ordinary strings to specify the new bitstrings we are adding.\n", "These get converted automatically to the right sequence of bits.\n", "\n", "
\n", "Note:\n", " The length in bits of bitstrings specified with strings depends on the number of characters, including leading zeros.\n", " So each hex character is four bits, each octal character three bits and each binary character one bit.\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Finding and replacing\n", "\n", "A `find` is provided to search for bit patterns within a bitstring.\n", "You can choose whether to search only on byte boundaries or at any bit position:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": "(3,)" }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = BitArray('0xa9f')\n", "a.find('0x4f')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we have found the `0x4f` byte in our bitstring, though it wasn't obvious from the hexadecimal as it was at bit position 3.\n", "To see this clearer consider this equality:\n" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": "True" }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a == '0b101, 0x4f, 0b1'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "in which we've broken the bitstring into three parts to show the found byte.\n", "This also illustrates using commas to join bitstring sections." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Constructing a bitstring\n", "\n", "Let's say you have a specification for a binary file type (or maybe a packet specification etc.) and you want to create a bitstring quickly and easily in Python.\n", "For this example I'm going to use a header from the MPEG-2 video standard.\n", "Here's how the header is described in the standard:\n", "\n", "|sequence_header() | No. of bits | Mnemonic|\n", "|-----------------------------------|--------------|----------|\n", "|sequence_header_code | 32 | bslbf |\n", "|horizontal_size_value | 12 | uimsbf |\n", "|vertical_size_value | 12 | uimsbf |\n", "|aspect_ratio_information | 4 | uimsbf |\n", "|frame_rate_code | 4 | uimsbf |\n", "|bit_rate_value | 18 | uimsbf |\n", "|marker_bit | 1 | bslbf |\n", "|vbv_buffer_size_value | 10 | uimsbf |\n", "|constrained_parameters_flag | 1 | bslbf |\n", "|load_intra_quantiser_matrix | 1 | uimsbf |\n", "|if (load_intra_quantiser_matrix) |\n", "|{ intra_quantiser_matrix[64] } | 8*64 | uimsbf |\n", "|load_non_intra_quantiser_matrix | 1 | uimsbf |\n", "|if (load_non_intra_quantiser_matrix) |\n", "|{ non_intra_quantiser_matrix[64] } | 8*64 | uimsbf |\n", "|next_start_code() | | |\n", "\n", "The mnemonics mean things like uimsbf = 'Unsigned integer, most significant bit first'.\n", "\n", "So to create a sequence_header for your particular stream with width of 352 and height of 288 you could start like this:\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "000001b3160120\n" ] } ], "source": [ "s = BitArray()\n", "s.append('0x000001b3') # the sequence_header_code\n", "s.append('uint12=352') # 12 bit unsigned integer\n", "s.append('uint12=288')\n", "print(s.hex)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which is fine, but if you wanted to be a bit more concise you could just write" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "s = BitArray('0x000001b3, uint12=352, uint12=288')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is better, but it might not be a good idea to have the width and height hard-wired in like that.\n", "We can make it more flexible by using a format string and the `pack` function:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "width, height = 352, 288\n", "s = bitstring.pack('0x000001b3, 2*u12', width, height)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have also used `2*u12` as shorthand for `uint12, uint12`.\n", "\n", "The [`pack`](https://bitstring.readthedocs.io/en/stable/functions.html#bitstring.pack) function can also take a dictionary as a parameter which can replace the tokens in the format string.\n", "For example:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": "\"BitStream('0x000001b31601201')\"" }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fmt = 'sequence_header_code, \\\n", " uint12=horizontal_size_value, \\\n", " uint12=vertical_size_value, \\\n", " uint4=aspect_ratio_information, '\n", " # ...\n", "d = {'sequence_header_code': '0x000001b3',\n", " 'horizontal_size_value': 352,\n", " 'vertical_size_value': 288,\n", " 'aspect_ratio_information': 1,\n", " # ...\n", " }\n", "\n", "s = bitstring.pack(fmt, **d)\n", "repr(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Parsing bitstreams\n", "\n", "You might have noticed that `pack` returned a `BitStream` rather than a `BitArray`.\n", "This isn't a problem as the `BitStream` class just adds a few stream-like qualities to `BitArray` which we'll take a quick look at here.\n", "\n", "The stream-ness of this object is via its bit position, and various reading and peeking methods.\n", "First let's try a read or two, and see how this affects the bit position:\n" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "BitStream('0x000001')\n", "24\n", "b3\n", "32\n" ] } ], "source": [ "print(s.pos)\n", "print(repr(s.read(24)))\n", "print(s.pos)\n", "print(s.read('hex8'))\n", "print(s.pos)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First we read 24 bits, which returned a new `BitStream` object, then we used a format string to read 8 bits interpreted as a hexadecimal string.\n", "We know that the next two sets of 12 bits were created from integers, so to read them back we can say" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": "[352, 288]" }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.readlist('2*u12')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "If you don't want to use a bitstream then you can always use [`unpack`](https://bitstring.readthedocs.io/en/stable/bits.html#bitstring.Bits.unpack).\n", "This takes much the same form as [`readlist`](https://bitstring.readthedocs.io/en/stable/constbitstream.html#bitstring.ConstBitStream.readlist) except it just unpacks from the start of the bitstring.\n", "For example:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": "[b'\\x00\\x00\\x01\\xb3', 352, 288, 1]" }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.unpack('bytes4, 2*u12, uint4')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Worked Examples\n", "\n", "Below are a few examples of using the bitstring module, as I always find that a good example can help more than a lengthy reference manual." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Hamming distance\n", "\n", "The Hamming distance between two bitstrings is the number of bit positions in which the two bitstrings differ.\n", "So for example the distance between `0b00110` and `0b01100` is 2 as the second and fourth bits are different.\n", "\n", "Let's write a function that calculates the Hamming weight of two bitstrings.\n" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": "2" }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def hamming_weight(a, b):\n", " return (BitArray(a)^b).count(True)\n", "\n", "hamming_weight('0b00110', '0b01100')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Er, that's it. The `^` is a bit-wise exclusive or, which means that the bits in `a^b` are only set if they differ in `a` and `b`.\n", "The `count` method just counts the number of 1 (or True) bits." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Sieve of Eratosthenes\n", "\n", "The sieve of Eratosthenes is an ancient (and _very_ inefficient) method of finding prime numbers.\n", "The algorithm starts with the number 2 (which is prime) and marks all of its multiples as not prime, it then continues with the next unmarked integer (which will also be prime) and marks all of its multiples as not prime.\n", "\n", "[![Sieve animation](https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif)](https://commons.wikimedia.org/wiki/File:Sieve_of_Eratosthenes_animation.svg)\n", "\n", "So to find all primes under a hundred million you could write:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "There are 5761455 primes less than 100000000,\n", "the largest one of which is 99999989\n", "and there are 440312 twin primes.\n" ] } ], "source": [ "# Create a BitArray with a hundred million 'one' bits\n", "limit = 100_000_000\n", "is_prime = BitArray(limit)\n", "is_prime.set(True)\n", "# Manually set 0 and 1 to be not prime.\n", "is_prime.set(False, [0, 1])\n", "# For every other integer, if it's set as prime then unset all of its multiples\n", "for i in range(2, math.ceil(math.sqrt(limit))):\n", " if is_prime[i]:\n", " is_prime.set(False, range(i*i, limit, i))\n", "\n", "print(f\"There are {is_prime.count(True)} primes less than {limit},\")\n", "print(f\"the largest one of which is {is_prime.rfind('0b1')[0]}\")\n", "print(f\"and there are {len(list(is_prime.findall('0b101')))} twin primes.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We find the largest prime with a reverse find ([`rfind`](https://bitstring.readthedocs.io/en/stable/bits.html#bitstring.Bits.rfind)) looking for a single set bit.\n", "For twin primes (primes which differ by 2) we use [`findall`](https://bitstring.readthedocs.io/en/stable/bits.html#bitstring.Bits.findall) to look for the binary sequence `101` which returns a generator for the bit positions.\n", "\n", "To see the pattern of the primes we could use the [pretty print](https://bitstring.readthedocs.io/en/stable/bits.html#bitstring.Bits.pp) method:" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 0: 00110101 00010100 01010001 00000101 00000100 01010001 35 14 51 05 04 51\n", " 48: 00000100 00010100 00010001 01000001 00010000 01000000 04 14 11 41 10 40\n", " 96: 01000101 00010100 01000000 00000001 00010000 01010000 45 14 40 01 10 50\n", " 144: 00000101 00000100 00010001 00000100 00010100 00000001 05 04 11 04 14 01\n", " 192: 01000101 00000000 00010000 00000001 00010100 01000001 45 00 10 01 14 41\n", " 240: 01000000 00010000 01000001 00000101 00000100 01010000 40 10 41 05 04 50\n", " 288: 00000100 00000000 00010001 01000100 00000000 00010000 04 00 11 44 00 10\n", " 336: 01000000 00010100 01000001 00000001 00000100 00010001 40 14 41 01 04 11\n", " 384: 00000100 00000100 01000000 01000000 00010100 00000001 04 04 40 40 14 01\n", " 432: 01000001 00010000 01000000 01000101 00010000 00000001 41 10 40 45 10 01\n", " 480: 00000001 00010000 00010001 00000100 00000000 01010000 01 10 11 04 00 50\n", " 528: 00000000 00000100 00010000 00000100 00010000 01010000 00 04 10 04 10 50\n", " 576: 01000000 00010000 01000001 01000001 00000100 01010000 40 10 41 41 04 50\n", " 624: 00000001 00000000 01010001 00000100 00010100 00000000 01 00 51 04 14 00\n", " 672: 01000100 00010000 00010000 00000100 00000100 00000001 44 10 10 04 04 01\n", " 720: 00000001 00000100 00010001 00000001 00000100 01000000 01 04 11 01 04 40\n", " 768: 01000100 00000000 00010000 00000100 00000000 01010000 44 00 10 04 00 50\n", " 816: 00000101 00010100 00000001 00000000 00000100 01010001 05 14 01 00 04 51\n", " 864: 00000000 00000100 01010001 00000000 00000000 00010001 00 04 51 00 00 11\n", " 912: 00000001 00000000 01000000 01000100 00010000 01000000 01 00 40 44 10 40\n", " 960: 00000001 00010000 01000001 00000001 00000100 01 10 41 01 04 \n" ] } ], "source": [ "is_prime[0:1000].pp('bin, hex', width=88)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "I'll leave optimising the algorithm as an exercise for the reader, but it illustrates both bit checking and setting.\n", "One reason you might want to use a bitstring for this purpose (instead of a plain list for example) is that the million bits only take up a million bits in memory, whereas for a list of integers it would be much more." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Next Steps\n", "\n", "There is fairly extensive [documentation](https://bitstring.readthedocs.io/en/stable/) available.\n", "The [Quick Reference](https://bitstring.readthedocs.io/en/stable/quick_ref.html) is a good place to quickly see what's available.\n", "\n", "For any discussions / bug reports / feature requests see the homepage on [GitHub](https://github.com/scott-griffiths/bitstring/)." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.0" } }, "nbformat": 4, "nbformat_minor": 1 } bitstring-bitstring-4.1.4/pyproject.toml000066400000000000000000000022021453167633600204560ustar00rootroot00000000000000[build-system] requires = ["setuptools>=61"] build-backend = "setuptools.build_meta" [project] name = "bitstring" version = "4.1.4" authors = [ { name="Scott Griffiths", email="dr.scottgriffiths@gmail.com" }, ] description = "Simple construction, analysis and modification of binary data." readme = "README.md" requires-python = ">=3.7" classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "License :: OSI Approved :: MIT License", "Topic :: Software Development :: Libraries :: Python Modules", ] keywords = ["binary", "bitarray", "bitvector", "bitfield"] dependencies = [ "bitarray >= 2.8.0, < 3.0.0", ] [project.urls] homepage = "https://github.com/scott-griffiths/bitstring" documentation = "https://bitstring.readthedocs.io/" [tool.setuptools] packages = ["bitstring"] bitstring-bitstring-4.1.4/release_notes.txt000066400000000000000000001771671453167633600211620ustar00rootroot00000000000000-------------------------------- bitstring module version history -------------------------------- ---------------------------- November 2023: version 4.1.4 ---------------------------- Fixing a regression introduced in 4.1.3 * 'bytes' token can't be used without explicit length. Bug #303. ---------------------------- November 2023: version 4.1.3 ---------------------------- A maintenance release, with some changes to the beta features introduced in 4.1. * Removed a couple of files that accidentally got included in the previous release. Bug #293. * The 8-bit float formats have been renamed 'e4m3float' and 'e5m2float'. * Some refactoring and performance optimizations. -------------------------------------- September 2023: version 4.1.2 released -------------------------------------- Another maintenance release. Once again some small changes to the 'beta' Array class, plus new Array functionality. * Fix for the module command-line usage. Bug #290. * Fix for when creating bitstrings from memoryview objects. * Renamed the 'fmt' parameter for Arrays to 'dtype'. * More Array operator coverage. * Added operators that act on two Arrays of the same size. * Added comparison operators for Arrays that return an Array of bools. * Added Array.equals method as == will now return an Array (see above item). * Added astype() method for Arrays to easily cast to a new dtype. ----------------------------------- August 2023: version 4.1.1 released ----------------------------------- A maintenance release, with some changes to the Array class which is still in 'beta'. * bitarray dependency now pinned to ">=2.8.0, <3.0.0" rather than a specific version. Bug #283. * Fix for using numpy integers as integer parameters. Bug #286. * Removed ability to extend an Array with the '+' operator. Use the 'extend' method instead. * Improvements when pretty-printing the Array. * Array.count() can now count 'nan' values for floating point types. ----------------------------------- August 2023: version 4.1.0 released ----------------------------------- This has turned into a suprisingly big release, with a major refactor and a brand new class (the first for 12 years!) There are also a couple of small possibly breaking changes detailed below, in particular 'auto' initialising bitstrings from integers is now disallowed. * Speed increased with bitarray dependency. The major weakness of bitstring has been its poor performance for computationally intensive tasks relative to lower level alternatives. This was principally due to relying on pure Python code to achieve things that the base language often didn't have fast ways of doing. This release starts to address that problem with a fairly extensive rewrite to replace much of the pure Python low-level bit operations with methods from the bitarray package. This is a package that does many of the same things as bitstring, and the two packages have co-existed for a long time. While bitarray doesn't have all of the options and facilities of bitstring it has the advantage of being very fast as it is implemented in C. By replacing the internal datatypes I can speed up bitstring's operations while keeping the same API. Huge kudos to Ilan Schnell for all his work on bitarray. * New Array class for homogeneous data (beta) If your data is all of the same type you can make use of the new Array class, which mirrors much of the functionality of the standard array.array type, but doesn't restrict you to just a dozen formats. >>> from bitstring import Array >>> a = Array('uint7', [9, 100, 3, 1]) >>> a.data BitArray('0x1390181') >>> b = Array('float16', a.tolist()) >>> b.append(0.25) >>> b.tobytes() b'H\x80V@B\x00<\x004\x00' >>> b.tolist() [9.0, 100.0, 3.0, 1.0, 0.25] The data is stored efficiently in a BitArray object, and you can manipulate both the data and the Array format freely. See the main documentation for more details. Note that this feature carries the 'beta' flag so may change in future point versions. Other changes: * Added two new floating point interpretations: float8_143 and float8_152. These are 8-bit floating point formats, with very limited range and precision, but useful in some fields, particularly machine learning. This is an experimental feature - the formats haven't even been standardised yet. >>> a = Bits(float8_143=16.5) >>> a.bin '01100000' >>> a.float8_143 16.0 * Auto initialistion from ints has been removed and now raises a TypeError. Creating a bitstring from an int still creates a zeroed bitstring of that length but ints won't be promoted to bitstrings as that has been a constant source of errors and confusion. >>> a = BitArray(100) # Fine - create with 100 zeroed bits >>> a += 0xff # TypeError - previously this would have appended 0xff (=255) zero bits. >>> a += '0xff' # Probably what was meant - append eight '1' bits. >>> a += Bits(255) # Fine, append 255 zero bits. This is a breaking change, but it breaks loudly with an exception, it is easily recoded, and it removes a confusing wrinkle. * Explicitly specifying the 'auto' parameter is now disallowed rather than discouraged. It was always meant to be a positional-only parameter (and will be once I can drop Python 3.7 support) but for now it's renamed to '__auto'. In the unlikely event this breaks code, the fix should be just to delete the 'auto=' if it's already the first parameter. >>> s = Bits(auto='0xff') # Now raises a CreationError >>> s = Bits('0xff') # Fine, as always * Deleting, replacing or inserting into a bitstring resets the bit position to 0 if the bitstring's length has been changed. Previously the bit position was adjusted but this was not well defined. * Only empty bitstring are now considered False in a boolean sense. Previously s was False is no bits in s were set to 1, but this goes against what it means to be a container in Python so I consider this to be a bug, even if it was documented. I'm guessing it's related to __nonzero__ in Python 2 becoming __bool__ in Python 3, and it's never been fixed before now. * Casting to bytes now behaves as expected, so that bytes(s) gives the same result as s.tobytes(). Previously it created a byte per bit. * Pretty printing with the 'bytes' format now uses characters from the 'Latin Extended-A' unicode block for non-ASCII and unprintable characters instead of replacing them with '.' * When using struct-like codes you can now use '=' instead of '@' to signify native- endianness. They behave identically, but the new '=' is now preferred. * More fixes for LSB0 mode. There are now no known issues with this feature. ---------------------------------- April 2023: version 4.0.2 released ---------------------------------- A maintenance release. * Added py.typed file and converted the module to a package to let mypy find type annotations. Bug 248. * Fix to shifting operations when using LSB0 mode. Bug 251. * A few more fixes for LSB0 mode. * Improved LSB0 documentation. * Added build-system section to pyproject.toml. Bug 243. * Rewrote the walkthrough documentation as a jupyter notebook. * Updated the project's logo. ------------------------------------- November 2022: version 4.0.1 released ------------------------------------- This is a major release which drops support for Python 2.7 and has a new minimum requirement of Python 3.7. Around 95% of downloads satisfy this - users of older versions can continue to use bitstring 3.1, which will still be supported with fixes, but no new features. Other breaking changes are minimal, and there are a few cool features added. Breaking changes: * Minimum supported Python version is now Python 3.7. * Removed ConstBitArray and BitString class aliases. Use Bits and BitStream instead. * The cut() method will now also yield the final bits of a bitstring, even if they are shorter than the requested cut size. * Removed default uint interpretation. This wasn't being applied uniformly - default is now always to return a bitstring object of the given length and not to interpret it as a uint. Bug 220. * If an overwrite goes beyond the end of the bitstring it will now extend the bitstring rather than raise an exception. Bug 148. New features and improvements: * Type hints added throughout the code. * Underscores are now allowed in strings representing number literals. * The copy() method now works on Bits as well as BitArray objects. * The experimental command-line feature is now official. Command-line parameters are concatenated and a bitstring created from them. If the final parameter is either an interpretation string or ends with a '.' followed by an interpretation string then that interpretation of the bitstring will be used when printing it. $ python -m bitstring int:16=-400 0xfe70 $ python -m bitstring float:32=0.2 bin 00111110010011001100110011001101 * New pp() method that pretty-prints the bitstring in various formats - useful especially in interactive sessions. Thanks to Omer Barak for the suggestion and discussion. >>> s.pp() 0: 10001000 01110110 10001110 01110110 11111000 01110110 10000111 00101000 64: 01110010 11111001 10000111 10011000 11110111 10011110 10000111 11111101 128: 11111001 10001100 01111111 10111100 10111111 11011011 11101011 11111011 192: 1100 >>> s.pp('bin, hex') 0: 10001000 01110110 10001110 01110110 11111000 01110110 88 76 8e 76 f8 76 48: 10000111 00101000 01110010 11111001 10000111 10011000 87 28 72 f9 87 98 96: 11110111 10011110 10000111 11111101 11111001 10001100 f7 9e 87 fd f9 8c 144: 01111111 10111100 10111111 11011011 11101011 11111011 7f bc bf db eb fb 192: 1100 c * Shorter and more versatile properties. The bin, oct, hex, float, uint and int properties can now be shortened to just their first letter. They can also have a length in bits after them - allowing Rust-like data types. :: >>> s = BitArray('0x44961000') >>> s.h '44961000' >>> s.f32 1200.5 >>> s.u 1150685184 >>> s.i7 = -60 >>> s.b '1000100' >>> t = Bits('u12=160, u12=120, b=100') * Other types with bit lengths can also be used as properties :: >>> s.floatle64 = 10.511 * A colon is no longer required in format strings before a bit length. So for example `Bits('int:15=-101')` could be written as `Bits('int15=-101')`. This is now the preferred usage in the documentation except where the colon improves readability. * Support for IEEE 16 bit floats. Floating point types can now be 16 bits long as well as 32 and 64 bits. This is using the 'e' format from the struct module. * Support for bfloats. This is a specialised 16-bit floating point format mostly used in machine learning. It's essentially a truncated IEEE 32-bit format that keeps its range but only has a couple of signficant figures of accuracy. --------------------------------------- July 20th 2021: version 3.1.9 released --------------------------------------- (version 3.1.8 was pulled due to serious issues) Another maintenance release. * Fixed a couple of outdated results in the readme (Issue 214). * Some more documentation tidying. * Turned off some debug code by default. * Fixed a couple of failing tests in different Python versions. * Fix for consistent pos initialisation semantics for different types. * Change to allow wheels to be uploaded to PyPI. * More work for LSB0 mode, but still not finished or documented (sorry). --------------------------------------- May 5th 2020: version 3.1.7 released --------------------------------------- This is a maintenance release with a few bug fixes plus an experimental feature to allow bits to be indexed in the opposite direction. * Fixing del not working correctly when stop value negative (Issue 201) * Removed deprecated direct import of ABC from collections module (Issue 196) * Tested and added explicit support for Python 3.7 and 3.8. (Issue 193) * Fixing a few stale links to documentation. (Issue 194) * Allowing initialisation with an io.BytesIO object. (Issue 189) Experimental LSB0 mode ---------------------- This feature allows bitstring to use Least Significant Bit Zero (LSB0) bit numbering; that is the final bit in the bitstring will be bit 0, and the first bit will be bit (n-1), rather than the other way around. LSB0 is a more natural numbering system in many fields, but is the opposite to Most Significant Bit Zero (MSB0) numbering which is the natural option when thinking of bitstrings as standard Python containers. To switch from the default MSB0, use the module level function >>> bitstring.set_lsb0(True) Getting and setting bits should work in this release, as will some other methods. Many other methods are not tested yet and might not work as expected. This is mostly a release to get feedback before finalising the interface. Slicing is still done with the start bit smaller than the end bit. For example: >>> s = Bits('0b000000111') >>> s[0:5] Bits('0b00111') >>> s[0] True Negative indices work as (hopefully) you'd expect, with the first stored bit being `s[-1]` and the final stored bit being `s[-n]`. See https://github.com/scott-griffiths/bitstring/issues/156 for discussions and to add any further comments. --------------------------------------- July 9th 2019: version 3.1.6 released --------------------------------------- A long overdue maintenance release with some fixes. * Fixed immutability bug. Bug 176. * Fixed failure of `__contains__` in some circumstances. Bug 180. * Better handling of open files. Bug 186. * Better Python 2/3 check. * Making unit tests easier to run. * Allowing length of 1 to be specified for bools. (Thanks to LemonPi) --------------------------------------- May 17th 2016: version 3.1.5 released --------------------------------------- * Support initialisation from an array. * Added a separate LICENSE file. --------------------------------------- March 19th 2016: version 3.1.4 released --------------------------------------- This is another bug fix release. * Fix for bitstring types when created directly from other bitstring types. * Updating contact, website details. --------------------------------------- March 4th 2014: version 3.1.3 released --------------------------------------- This is another bug fix release. * Fix for problem with prepend for bitstrings with byte offsets in their data store. --------------------------------------- April 18th 2013: version 3.1.2 released --------------------------------------- This is another bug fix release. * Fix for problem where unpacking bytes would by eight times too long --------------------------------------- March 21st 2013: version 3.1.1 released --------------------------------------- This is a bug fix release. * Fix for problem where concatenating bitstrings sometimes modified method's arguments ------------------------------------------ February 26th 2013: version 3.1.0 released ------------------------------------------ This is a minor release with a couple of new features and some bug fixes. New 'pad' token --------------- This token can be used in reads and when packing/unpacking to indicate that you don't care about the contents of these bits. Any padding bits will just be skipped over when reading/unpacking or zero-filled when packing. >>> a, b = s.readlist('pad:5, uint:3, pad:1, uint:3') Here only two items are returned in the list - the padding bits are ignored. New clear and copy convenience methods -------------------------------------- These methods have been introduced in Python 3.3 for lists and bytearrays, as more obvious ways of clearing and copying, and we mirror that change here. t = s.copy() is equivalent to t = s[:], and s.clear() is equivalent to del s[:]. Other changes ------------- * Some bug fixes. ----------------------------------------- February 7th 2012: version 3.0.2 released ----------------------------------------- This is a minor update that fixes a few bugs. * Fix for subclasses of bitstring classes behaving strangely (Issue 121). * Fix for excessive memory usage in rare cases (Issue 120). * Fixes for slicing edge cases. There has also been a reorganisation of the code to return it to a single 'bitstring.py' file rather than the package that has been used for the past several releases. This change shouldn't affect users directly. ------------------------------------------ November 21st 2011: version 3.0.1 released ------------------------------------------ This release fixed a small but very visible bug in bitstring printing. ------------------------------------------ November 21st 2011: version 3.0.0 released ------------------------------------------ This is a major release which breaks backward compatibility in a few places. Backwardly incompatible changes =============================== Hex, oct and bin properties don't have leading 0x, 0o and 0b ------------------------------------------------------------ If you ask for the hex, octal or binary representations of a bitstring then they will no longer be prefixed with '0x', 0o' or '0b'. This was done as it was noticed that the first thing a lot of user code does after getting these representations was to cut off the first two characters before further processing. >>> a = BitArray('0x123') >>> a.hex, a.oct, a.bin ('123', '0443', '000100100011') Previously this would have returned ('0x123', '0o0443', '0b000100100011') This change might require some recoding, but it should all be simplifications. ConstBitArray renamed to Bits ----------------------------- Previously Bits was an alias for ConstBitStream (for backward compatibility). This has now changed so that Bits and BitArray loosely correspond to the built-in types bytes and bytearray. If you were using streaming/reading methods on a Bits object then you will have to change it to a ConstBitStream. The ConstBitArray name is kept as an alias for Bits. Stepping in slices has conventional meaning ------------------------------------------- The step parameter in __getitem__, __setitem__ and __delitem__ used to act as a multiplier for the start and stop parameters. No one seemed to use it though and so it has now reverted to the conventional meaning for containers. If you are using step then recoding is simple: s[a:b:c] becomes s[a*c:b*c]. Some examples of the new usage: >>> s = BitArray('0x0000') s[::4] = [1, 1, 1, 1] >>> s.hex '8888' >>> del s[8::2] >>> s.hex '880' New features ============ New readto method ----------------- This method is a mix between a find and a read - it searches for a bitstring and then reads up to and including it. For example: >>> s = ConstBitStream('0x47000102034704050647') >>> s.readto('0x47', bytealigned=True) BitStream('0x47') >>> s.readto('0x47', bytealigned=True) BitStream('0x0001020347') >>> s.readto('0x47', bytealigned=True) BitStream('0x04050647') pack function accepts an iterable as its format ----------------------------------------------- Previously only a string was accepted as the format in the pack function. This was an oversight as it broke the symmetry between pack and unpack. Now you can use formats like this: fmt = ['hex:8', 'bin:3'] a = pack(fmt, '47', '001') a.unpack(fmt) -------------------------------------- June 18th 2011: version 2.2.0 released -------------------------------------- This is a minor upgrade with a couple of new features. New interleaved exponential-Golomb interpretations -------------------------------------------------- New bit interpretations for interleaved exponential-Golomb (as used in the Dirac video codec) are supplied via 'uie' and 'sie': >>> s = BitArray(uie=41) >>> s.uie 41 >>> s.bin '0b00010001001' These are pretty similar to the non-interleaved versions - see the manual for more details. Credit goes to Paul Sargent for the patch. New package-level bytealigned variable -------------------------------------- A number of methods take a 'bytealigned' parameter to indicate that they should only work on byte boundaries (e.g. find, replace, split). Previously this parameter defaulted to 'False'. Instead it now defaults to 'bitstring.bytealigned', which itself defaults to 'False', but can be changed to modify the default behaviour of the methods. For example: >>> a = BitArray('0x00 ff 0f ff') >>> a.find('0x0f') (4,) # found first not on a byte boundary >>> a.find('0x0f', bytealigned=True) (16,) # forced looking only on byte boundaries >>> bitstring.bytealigned = True # Change default behaviour >>> a.find('0x0f') (16,) >>> a.find('0x0f', bytealigned=False) (4,) If you're only working with bytes then this can help avoid some errors and save some typing! Other changes ------------- * Fix for Python 3.2, correcting for a change to the binascii module. * Fix for bool initialisation from 0 or 1. * Efficiency improvements, including interning strategy. ------------------------------------------ February 23rd 2011: version 2.1.1 released ------------------------------------------ This is a release to fix a couple of bugs that were introduced in 2.1.0. * Bug fix: Reading using the 'bytes' token had been broken (Issue 102). * Fixed problem using some methods on ConstBitArrays. * Better exception handling for tokens missing values. * Some performance improvements. ----------------------------------------- January 23rd 2011: version 2.1.0 released ----------------------------------------- New class hierarchy introduced with simpler classes --------------------------------------------------- Previously there were just two classes, the immutable Bits which was the base class for the mutable BitString class. Both of these classes have the concept of a bit position, from which reads etc. take place so that the bitstring could be treated as if it were a file or stream. Two simpler classes have now been added which are purely bit containers and don't have a bit position. These are called ConstBitArray and BitArray. As you can guess the former is an immutable version of the latter. The other classes have also been renamed to better reflect their capabilities. Instead of BitString you can use BitStream, and instead of Bits you can use ConstBitStream. The old names are kept as aliases for backward compatibility. The classes hierarchy is: ConstBitArray / \ / \ BitArray ConstBitStream (formerly Bits) \ / \ / BitStream (formerly BitString) Other changes ------------- A lot of internal reorganisation has taken place since the previous version, most of which won't be noticed by the end user. Some things you might see are: * New package structure. Previous versions have been a single file for the module and another for the unit tests. The module is now split into many more files so it can't be used just by copying bitstring.py any more. * To run the unit tests there is now a script called runtests.py in the test directory. * File based bitstring are now implemented in terms of an mmap. This should be just an implementation detail, but unfortunately for 32-bit versions of Python this creates a limit of 4GB on the files that can be used. The work around is either to get a 64-bit Python, or just stick with version 2.0. * The ConstBitArray and ConstBitStream classes no longer copy byte data when a slice or a read takes place, they just take a reference. This is mostly a very nice optimisation, but there are occasions where it could have an adverse effect. For example if a very large bitstring is created, a small slice taken and the original deleted. The byte data from the large bitstring would still be retained in memory. * Optimisations. Once again this version should be faster than the last. The module is still pure Python but some of the reorganisation was to make it more feasible to put some of the code into Cython or similar, so hopefully more speed will be on the way. -------------------------------------- July 26th 2010: version 2.0.3 released -------------------------------------- * Bug fix: Using peek and read for a single bit now returns a new bitstring as was intended, rather than the old behaviour of returning a bool. * Removed HTML docs from source archive - better to use the online version. -------------------------------------- July 25th 2010: version 2.0.2 released -------------------------------------- This is a major release, with a number of backwardly incompatible changes. The main change is the removal of many methods, all of which have simple alternatives. Other changes are quite minor but may need some recoding. There are a few new features, most of which have been made to help the stream-lining of the API. As always there are performance improvements and some API changes were made purely with future performance in mind. The backwardly incompatible changes are: ----------------------------------------- * Methods removed. About half of the class methods have been removed from the API. They all have simple alternatives, so what remains is more powerful and easier to remember. The removed methods are listed here on the left, with their equivalent replacements on the right: s.advancebit() -> s.pos += 1 s.advancebits(bits) -> s.pos += bits s.advancebyte() -> s.pos += 8 s.advancebytes(bytes) -> s.pos += 8*bytes s.allunset([a, b]) -> s.all(False, [a, b]) s.anyunset([a, b]) -> s.any(False, [a, b]) s.delete(bits, pos) -> del s[pos:pos+bits] s.peekbit() -> s.peek(1) s.peekbitlist(a, b) -> s.peeklist([a, b]) s.peekbits(bits) -> s.peek(bits) s.peekbyte() -> s.peek(8) s.peekbytelist(a, b) -> s.peeklist([8*a, 8*b]) s.peekbytes(bytes) -> s.peek(8*bytes) s.readbit() -> s.read(1) s.readbitlist(a, b) -> s.readlist([a, b]) s.readbits(bits) -> s.read(bits) s.readbyte() -> s.read(8) s.readbytelist(a, b) -> s.readlist([8*a, 8*b]) s.readbytes(bytes) -> s.read(8*bytes) s.retreatbit() -> s.pos -= 1 s.retreatbits(bits) -> s.pos -= bits s.retreatbyte() -> s.pos -= 8 s.retreatbytes(bytes) -> s.pos -= 8*bytes s.reversebytes(start, end) -> s.byteswap(0, start, end) s.seek(pos) -> s.pos = pos s.seekbyte(bytepos) -> s.bytepos = bytepos s.slice(start, end, step) -> s[start:end:step] s.tell() -> s.pos s.tellbyte() -> s.bytepos s.truncateend(bits) -> del s[-bits:] s.truncatestart(bits) -> del s[:bits] s.unset([a, b]) -> s.set(False, [a, b]) Many of these methods have been deprecated for the last few releases, but there are some new removals too. Any recoding needed should be quite straightforward, so while I apologise for the hassle, I had to take the opportunity to streamline and rationalise what was becoming a bit of an overblown API. * set / unset methods combined. The set/unset methods have been combined in a single method, which now takes a boolean as its first argument: s.set([a, b]) -> s.set(1, [a, b]) s.unset([a, b]) -> s.set(0, [a, b]) s.allset([a, b]) -> s.all(1, [a, b]) s.allunset([a, b]) -> s.all(0, [a, b]) s.anyset([a, b]) -> s.any(1, [a, b]) s.anyunset([a, b]) -> s.any(0, [a, b]) * all / any only accept iterables. The all and any methods (previously called allset, allunset, anyset and anyunset) no longer accept a single bit position. The recommended way of testing a single bit is just to index it, for example instead of: >>> if s.all(True, i): just use >>> if s[i]: If you really want to you can of course use an iterable with a single element, such as 's.any(False, [i])', but it's clearer just to write 'not s[i]'. * Exception raised on reading off end of bitstring. If a read or peek goes beyond the end of the bitstring then a ReadError will be raised. The previous behaviour was that the rest of the bitstring would be returned and no exception raised. * BitStringError renamed to Error. The base class for errors in the bitstring module is now just Error, so it will likely appears in your code as bitstring.Error instead of the rather repetitive bitstring.BitStringError. * Single bit slices and reads return a bool. A single index slice (such as s[5]) will now return a bool (i.e. True or False) rather than a single bit bitstring. This is partly to reflect the style of the bytearray type, which returns an integer for single items, but mostly to avoid common errors like: >>> if s[0]: ... do_something() While the intent of this code snippet is quite clear (i.e. do_something if the first bit of s is set) under the old rules s[0] would be true as long as s wasn't empty. That's because any one-bit bitstring was true as it was a non-empty container. Under the new rule s[0] is True if s starts with a '1' bit and False if s starts with a '0' bit. The change does not affect reads and peeks, so s.peek(1) will still return a single bit bitstring, which leads on to the next item... * Empty bitstrings or bitstrings with only zero bits are considered False. Previously a bitstring was False if it had no elements, otherwise it was True. This is standard behaviour for containers, but wasn't very useful for a container of just 0s and 1s. The new behaviour means that the bitstring is False if it has no 1 bits. This means that code like this: >>> if s.peek(1): ... do_something() should work as you'd expect. It also means that Bits(1000), Bits(0x00) and Bits('uint:12=0') are all also False. If you need to check for the emptiness of a bitstring then instead check the len property: if s -> if s.len if not s -> if not s.len * Length and offset disallowed for some initialisers. Previously you could create bitstring using expressions like: >>> s = Bits(hex='0xabcde', offset=4, length=13) This has now been disallowed, and the offset and length parameters may only be used when initialising with bytes or a file. To replace the old behaviour you could instead use >>> s = Bits(hex='0xabcde')[4:17] * Renamed 'format' parameter 'fmt'. Methods with a 'format' parameter have had it renamed to 'fmt', to prevent hiding the built-in 'format'. Affects methods unpack, read, peek, readlist, peeklist and byteswap and the pack function. * Iterables instead of *format accepted for some methods. This means that for the affected methods (unpack, readlist and peeklist) you will need to use an iterable to specify multiple items. This is easier to show than to describe, so instead of >>> a, b, c, d = s.readlist('uint:12', 'hex:4', 'bin:7') you would instead write >>> a, b, c, d = s.readlist(['uint:12', 'hex:4', 'bin:7']) Note that you could still use the single string 'uint:12, hex:4, bin:7' if you preferred. * Bool auto-initialisation removed. You can no longer use True and False to initialise single bit bitstrings. The reasoning behind this is that as bool is a subclass of int, it really is bad practice to have Bits(False) be different to Bits(0) and to have Bits(True) different to Bits(1). If you have used bool auto-initialisation then you will have to be careful to replace it as the bools will now be interpreted as ints, so Bits(False) will be empty (a bitstring of length 0), and Bits(True) will be a single zero bit (a bitstring of length 1). Sorry for the confusion, but I think this will prevent bigger problems in the future. There are a few alternatives for creating a single bit bitstring. My favourite it to use a list with a single item: Bits(False) -> Bits([0]) Bits(True) -> Bits([1]) * New creation from file strategy Previously if you created a bitstring from a file, either by auto-initialising with a file object or using the filename parameter, the file would not be read into memory unless you tried to modify it, at which point the whole file would be read. The new behaviour depends on whether you create a Bits or a BitString from the file. If you create a Bits (which is immutable) then the file will never be read into memory. This allows very large files to be opened for examination even if they could never fit in memory. If however you create a BitString, the whole of the referenced file will be read to store in memory. If the file is very big this could take a long time, or fail, but the idea is that in saying you want the mutable BitString you are implicitly saying that you want to make changes and so (for now) we need to load it into memory. The new strategy is a bit more predictable in terms of performance than the old. The main point to remember is that if you want to open a file and don't plan to alter the bitstring then use the Bits class rather than BitString. Just to be clear, in neither case will the contents of the file ever be changed - if you want to output the modified BitString then use the tofile method, for example. * find and rfind return a tuple instead of a bool. If a find is unsuccessful then an empty tuple is returned (which is False in a boolean sense) otherwise a single item tuple with the bit position is returned (which is True in a boolean sense). You shouldn't need to recode unless you explicitly compared the result of a find to True or False, for example this snippet doesn't need to be altered: >>> if s.find('0x23'): ... print(s.bitpos) but you could now instead use >>> found = s.find('0x23') >>> if found: ... print(found[0]) The reason for returning the bit position in a tuple is so that finding at position zero can still be True - it's the tuple (0,) - whereas not found can be False - the empty tuple (). The new features in this release are: ------------------------------------- * New count method. This method just counts the number of 1 or 0 bits in the bitstring. >>> s = Bits('0x31fff4') >>> s.count(1) 16 * read and peek methods accept integers. The read, readlist, peek and peeklist methods now accept integers as parameters to mean "read this many bits and return a bitstring". This has allowed a number of methods to be removed from this release, so for example instead of: >>> a, b, c = s.readbits(5, 6, 7) >>> if s.peekbit(): ... do_something() you should write: >>> a, b, c = s.readlist([5, 6, 7]) >>> if s.peek(1): ... do_something() * byteswap used to reverse all bytes. The byteswap method now allows a format specifier of 0 (the default) to signify that all of the whole bytes should be reversed. This means that calling just byteswap() is almost equivalent to the now removed bytereverse() method (a small difference is that byteswap won't raise an exception if the bitstring isn't a whole number of bytes long). * Auto initialise with bytearray or (for Python 3 only) bytes. So rather than writing: >>> a = Bits(bytes=some_bytearray) you can just write >>> a = Bits(some_bytearray) This also works for the bytes type, but only if you're using Python 3. For Python 2 it's not possible to distinguish between a bytes object and a str. For this reason this method should be used with some caution as it will make you code behave differently with the different major Python versions. >>> b = Bits(b'abcd\x23\x00') # Only Python 3! * set, invert, all and any default to whole bitstring. This means that you can for example write: >>> a = BitString(100) # 100 zero bits >>> a.set(1) # set all bits to 1 >>> a.all(1) # are all bits set to 1? True >>> a.any(0) # are any set to 0? False >>> a.invert() # invert every bit * New exception types. As well as renaming BitStringError to just Error there are also new exceptions which use Error as a base class. These can be caught in preference to Error if you need finer control. The new exceptions sometimes also derive from built-in exceptions: ByteAlignError(Error) - whole byte position or length needed. ReadError(Error, IndexError) - reading or peeking off the end of the bitstring. CreationError(Error, ValueError) - inappropriate argument during bitstring creation. InterpretError(Error, ValueError) - inappropriate interpretation of binary data. -------------------------------------------------------------- March 18th 2010: version 1.3.0 for Python 2.6 and 3.x released -------------------------------------------------------------- New features: * byteswap method for changing endianness. Changes the endianness in-place according to a format string or integer(s) giving the byte pattern. See the manual for details. >>> s = BitString('0x00112233445566') >>> s.byteswap(2) 3 >>> s BitString('0x11003322554466') >>> s.byteswap('h') 3 >>> s BitString('0x00112233445566') >>> s.byteswap([2, 5]) 1 >>> s BitString('0x11006655443322') * Multiplicative factors in bitstring creation and reading. For example: >>> s = Bits('100*0x123') * Token grouping using parenthesis. For example: >>> s = Bits('3*(uint:6=3, 0b1)') * Negative slice indices allowed. The start and end parameters of many methods may now be negative, with the same meaning as for negative slice indices. Affects all methods with these parameters. * Sequence ABCs used. The Bits class now derives from collections.Sequence, while the BitString class derives from collections.MutableSequence. * Keywords allowed in readlist, peeklist and unpack. Keywords for token lengths are now permitted when reading. So for example, you can write >>> s = bitstring.pack('4*(uint:n)', 2, 3, 4, 5, n=7) >>> s.unpack('4*(uint:n)', n=7) [2, 3, 4, 5] * start and end parameters added to rol and ror. * join function accepts other iterables. Also its parameter has changed from 'bitstringlist' to 'sequence'. This is technically a backward incompatibility in the unlikely event that you are referring to the parameter by name. * __init__ method accepts keywords. Rather than a long list of initialisers the __init__ methods now use a **kwargs dictionary for all initialisers except 'auto'. This should have no effect, except that this is a small backward incompatibility if you use positional arguments when initialising with anything other than auto (which would be rather unusual). * More optimisations. * Bug fixed in replace method (it could fail if start != 0). ---------------------------------------------------------------- January 19th 2010: version 1.2.0 for Python 2.6 and 3.x released ---------------------------------------------------------------- * New 'Bits' class. Introducing a brand new class, Bits, representing an immutable sequence of bits. The Bits class is the base class for the mutable BitString. The differences between Bits and BitStrings are: 1) Bits are immutable, so once they have been created their value cannot change. This of course means that mutating methods (append, replace, del etc.) are not available for Bits. 2) Bits are hashable, so they can be used in sets and as keys in dictionaries. 3) Bits are potentially more efficient than BitStrings, both in terms of computation and memory. The current implementation is only marginally more efficient though - this should improve in future versions. You can switch from Bits to a BitString or vice versa by constructing a new object from the old. >>> s = Bits('0xabcd') >>> t = BitString(s) >>> t.append('0xe') >>> u = Bits(t) The relationship between Bits and BitString is supposed to loosely mirror that between bytes and bytearray in Python 3. * Deprecation messages turned on. A number of methods have been flagged for removal in version 2. Deprecation warnings will now be given, which include an alternative way to do the same thing. All of the deprecated methods have simpler equivalent alternatives. >>> t = s.slice(0, 2) __main__:1: DeprecationWarning: Call to deprecated function slice. Instead of 's.slice(a, b, c)' use 's[a:b:c]'. The deprecated methods are: advancebit, advancebits, advancebyte, advancebytes, retreatbit, retreatbits, retreatbyte, retreatbytes, tell, seek, slice, delete, tellbyte, seekbyte, truncatestart and truncateend. * Initialise from bool. Booleans have been added to the list of types that can 'auto' initialise a bitstring. >>> zerobit = BitString(False) >>> onebit = BitString(True) * Improved efficiency. More methods have been speeded up, in particular some deletions and insertions. * Bug fixes. A rare problem with truncating the start of bitstrings was fixed. A possible problem outputting the final byte in tofile() was fixed. ----------------------------------------------------------------- December 22nd 2009: version 1.1.3 for Python 2.6 and 3.x released ----------------------------------------------------------------- This version hopefully fixes an installation problem for platforms with case-sensitive file systems. There are no new features or other bug fixes. ----------------------------------------------------------------- December 18th 2009: version 1.1.2 for Python 2.6 and 3.x released ----------------------------------------------------------------- This is a minor update with (almost) no new features. * Improved efficiency. The speed of many typical operations has been increased, some substantially. * Initialise from integer. A BitString of '0' bits can be created using just an integer to give the length in bits. So instead of >>> s = BitString(length=100) you can write just >>> s = BitString(100) This matches the behaviour of bytearrays and (in Python 3) bytes. * A defect related to using the set / unset functions on BitStrings initialised from a file has been fixed. ----------------------------------------------------------------- November 24th 2009: version 1.1.0 for Python 2.6 and 3.x released ----------------------------------------------------------------- Note that this version will not work for Python 2.4 or 2.5. There may be an update for these Python versions some time next year, but it's not a priority quite yet. Also note that only one version is now provided, which works for Python 2.6 and 3.x (done with the minimum of hackery!) * Improved efficiency. A fair number of functions have improved efficiency, some quite dramatically. * New bit setting and checking functions. Although these functions don't do anything that couldn't be done before, they do make some common use cases much more efficient. If you need to set or check single bits then these are the functions you need. set / unset : Set bit(s) to 1 or 0 respectively. allset / allunset : Check if all bits are 1 or all 0. anyset / anyunset : Check if any bits are 1 or any 0. >>> s = BitString(length=1000) >>> s.set((10, 100, 44, 12, 1)) >>> s.allunset((2, 22, 222)) True >>> s.anyset(range(7, 77)) True * New rotate functions. ror / rol : Rotate bits to the right or left respectively. >>> s = BitString('0b100000000') >>> s.ror(2) >>> s.bin '0b001000000' >>> s.rol(5) >>> s.bin '0b000000100' * Floating point interpretations. New float initialisations and interpretations are available. These only work for BitStrings of length 32 or 64 bits. >>> s = BitString(float=0.2, length=64) >>> s.float 0.200000000000000001 >>> t = bitstring.pack('<3f', -0.4, 1e34, 17.0) >>> t.hex '0xcdccccbedf84f67700008841' * 'bytes' token reintroduced. This token returns a bytes object (equivalent to a str in Python 2.6). >>> s = BitString('0x010203') >>> s.unpack('bytes:2, bytes:1') ['\x01\x02', '\x03'] * 'uint' is now the default token type. So for example these are equivalent: a, b = s.readlist('uint:12, uint:12') a, b = s.readlist('12, 12') -------------------------------------------------------- October 10th 2009: version 1.0.1 for Python 3.x released -------------------------------------------------------- This is a straight port of version 1.0.0 to Python 3. For changes since the last Python 3 release read all the way down in this document to version 0.4.3. This version will also work for Python 2.6, but there's no advantage to using it over the 1.0.0 release. It won't work for anything before 2.6. ------------------------------------------------------- October 9th 2009: version 1.0.0 for Python 2.x released ------------------------------------------------------- Version 1 is here! This is the first release not to carry the 'beta' tag. It contains a couple of minor new features but is principally a release to fix the API. If you've been using an older version then you almost certainly will have to recode a bit. If you're not ready to do that then you may wish to delay updating. So the bad news is that there are lots of small changes to the API. The good news is that all the changes are pretty trivial, the new API is cleaner and more 'Pythonic', and that by making it version 1.0 I'm promising not to tweak it again for some time. ** API Changes ** * New read / peek functions for returning multiple items. The functions read, readbits, readbytes, peek, peekbits and peekbytes now only ever return a single item, never a list. The new functions readlist, readbitlist, readbytelist, peeklist, peekbitlist and peekbytelist can be used to read multiple items and will always return a list. So a line like: >>> a, b = s.read('uint:12, hex:32') becomes >>> a, b = s.readlist('uint:12, hex:32') * Renaming / removing functions. Functions have been renamed as follows: seekbit -> seek tellbit -> tell reversebits -> reverse deletebits -> delete tostring -> tobytes and a couple have been removed altogether: deletebytes - use delete instead. empty - use 'not s' rather than 's.empty()'. * Renaming parameters. The parameters 'startbit' and 'endbit' have been renamed 'start' and 'end'. This affects the functions slice, find, findall, rfind, reverse, cut and split. The parameter 'bitpos' has been renamed to 'pos'. The affects the functions seek, tell, insert, overwrite and delete. * Mutating methods return None rather than self. This means that you can't chain functions together so >>> s.append('0x00').prepend('0xff') >>> t = s.reverse() Needs to be rewritten >>> s.append('0x00') >>> s.prepend('0xff) >>> s.reverse() >>> t = s Affects truncatestart, truncateend, insert, overwrite, delete, append, prepend, reverse and reversebytes. * Properties renamed. The 'data' property has been renamed to 'bytes'. Also if the BitString is not a whole number of bytes then a ValueError exception will be raised when using 'bytes' as a 'getter'. Properties 'len' and 'pos' have been added to replace 'length' and 'bitpos', although the longer names have not been removed so you can continue to use them if you prefer. * Other changes. The unpack function now always returns a list, never a single item. BitStrings are now 'unhashable', so calling hash on one or making a set will fail. The colon separating the token name from its length is now mandatory. So for example BitString('uint12=100') becomes BitString('uint:12=100'). Removed support for the 'bytes' token in format strings. Instead of s.read('bytes:4') use s.read('bits:32'). ** New features ** * Added endswith and startswith functions. These do much as you'd expect; they return True or False depending on whether the BitString starts or ends with the parameter. >>> BitString('0xef342').startswith('0b11101') True ---------------------------------------------------------- September 11th 2009: version 0.5.2 for Python 2.x released ---------------------------------------------------------- Finally some tools for dealing with endianness! * New interpretations are now available for whole-byte BitStrings that treat them as big, little, or native-endian. >>> big = BitString(intbe=1, length=16) # or BitString('intbe:16=1') if you prefer. >>> little = BitString(intle=1, length=16) >>> print big.hex, little.hex 0x0001 0x0100 >>> print big.intbe, little.intle 1 1 * 'Struct'-like compact format codes To save some typing when using pack, unpack, read and peek, compact format codes based on those used in the struct and array modules have been added. These must start with a character indicating the endianness (>, < or @ for big, little and native-endian), followed by characters giving the format: b 1-byte signed int B 1-byte unsigned int h 2-byte signed int H 2-byte unsigned int l 4-byte signed int L 4-byte unsigned int q 8-byte signed int Q 8-byte unsigned int For example: >>> s = bitstring.pack('<4h', 0, 1, 2, 3) creates a BitString with four little-endian 2-byte integers. While >>> x, y, z = s.read('>hhl') reads them back as two big-endian two-byte integers and one four-byte big endian integer. Of course you can combine this new format with the old ones however you like: >>> s.unpack('>> from bitstring import BitString, pack >>> a = pack('0b11, 0xff, 0o77, int:5=-1, se=33') You can also leave placeholders in the format, which will be filled in by the values provided. >>> b = pack('uint:10, hex:4', 33, 'f') Finally you can use a dictionary or keywords. >>> c = pack('bin=a, hex=b, bin=a', a='010', b='ef') The unpack function is similar to the read function except that it always unpacks from the start of the BitString. >>> x, y = b.unpack('uint:10, hex') If a token is given without a length (as above) then it will expand to fill the remaining bits in the BitString. This also now works with read() and peek(). * New tostring() and tofile() functions. The tostring() function just returns the data as a string, with up to seven zero bits appended to byte align. The tofile() function does the same except writes to a file object. >>> f = open('myfile', 'wb') >>> BitString('0x1234ff').tofile(f) * Other changes. The use of '=' is now mandatory in 'auto' initialisers. Tokens like 'uint12 100' will no longer work. Also the use of a ':' before the length is encouraged, but not yet mandated. So the previous example should be written as 'uint:12=100'. The 'auto' initialiser will now take a file object. >>> f = open('myfile', 'rb') >>> s = BitString(f) ----------------------------------------------------- July 19th 2009: version 0.5.0 for Python 2.x released ----------------------------------------------------- This update breaks backward compatibility in a couple of areas. The only one you probably need to be concerned about is the change to the default for bytealigned in find, replace, split, etc. See the user manual for more details on each of these items. * Expanded abilities of 'auto' initialiser. More types can be initialised through the 'auto' initialiser. For example instead of >>> a = BitString(uint=44, length=16) you can write >>> a = BitString('uint16=44') Also, different comma-separated tokens will be joined together, e.g. >>> b = BitString('0xff') + 'int8=-5' can be written >>> b = BitString('0xff, int8=-5') * New formatted read() and peek() functions. These takes a format string similar to that used in the auto initialiser. If only one token is provided then a single value is returned, otherwise a list of values is returned. >>> start_code, width, height = s.read('hex32, uint12, uint12') is equivalent to >>> start_code = s.readbits(32).hex >>> width = s.readbits(12).uint >>> height = s.readbits(12).uint The tokens are: int n : n bits as an unsigned integer. uint n : n bits as a signed integer. hex n : n bits as a hexadecimal string. oct n : n bits as an octal string. bin n : n bits as a binary string. ue : next bits as an unsigned exp-Golomb. se : next bits as a signed exp-Golomb. bits n : n bits as a new BitString. bytes n : n bytes as a new BitString. See the user manual for more details. * hex() and oct() functions removed. The special functions for hex() and oct() have been removed. Please use the hex and oct properties instead. >>> hex(s) becomes >>> s.hex * join made a member function. The join function must now be called on a BitString object, which will be used to join the list together. You may need to recode slightly: >>> s = bitstring.join('0x34', '0b1001', '0b1') becomes >>> s = BitString().join('0x34', '0b1001', '0b1') * More than one value allowed in readbits, readbytes, peekbits and peekbytes If you specify more than one bit or byte length then a list of BitStrings will be returned. >>> a, b, c = s.readbits(10, 5, 5) is equivalent to >>> a = readbits(10) >>> b = readbits(5) >>> c = readbits(5) * bytealigned defaults to False, and is at the end of the parameter list Functions that have a bytealigned parameter have changed so that it now defaults to False rather than True. Also its position in the parameter list has changed to be at the end. You may need to recode slightly (sorry!) * readue and readse functions have been removed Instead you should use the new read function with a 'ue' or 'se' token: >>> i = s.readue() becomes >>> i = s.read('ue') This is more flexible as you can read multiple items in one go, plus you can now also use the peek function with ue and se. * Minor bugs fixed. See the issue tracker for more details. ----------------------------------------------------- June 15th 2009: version 0.4.3 for Python 2.x released ----------------------------------------------------- This is a minor update. This release is the first to bundle the bitstring manual. This is a PDF and you can find it in the docs directory. Changes in version 0.4.3 * New 'cut' function This function returns a generator for constant sized chunks of a BitString. >>> for byte in s.cut(8): ... do_something_with(byte) You can also specify a startbit and endbit, as well as a count, which limits the number of items generated: >>> first100TSPackets = list(s.cut(188*8, count=100)) * 'slice' function now equivalent to __getitem__. This means that a step can also be given to the slice function so that the following are now the same thing, and it's just a personal preference which to use: >>> s1 = s[a:b:c] >>> s2 = s.slice(a, b, c) * findall gets a 'count' parameter. So now >>> list(a.findall(s, count=n)) is equivalent to >>> list(a.findall(s))[:n] except that it won't need to generate the whole list and so is much more efficient. * Changes to 'split'. The split function now has a 'count' parameter rather than 'maxsplit'. This makes the interface closer to that for cut, replace and findall. The final item generated is now no longer the whole of the rest of the BitString. * A couple of minor bugs were fixed. See the issue tracker for details. ---------------------------------------------------- May 25th 2009: version 0.4.2 for Python 2.x released ---------------------------------------------------- This is a minor update, and almost doesn't break compatibility with version 0.4.0, but with the slight exception of findall() returning a generator, detailed below. Changes in version 0.4.2 * Stepping in slices The use of the step parameter (also known as the stride) in slices has been added. Its use is a little non-standard as it effectively gives a multiplicative factor to apply to the start and stop parameters, rather than skipping over bits. For example this makes it much more convenient if you want to give slices in terms of bytes instead of bits. Instead of writing s[a*8:b*8] you can use s[a:b:8]. When using a step the BitString is effectively truncated to a multiple of the step, so s[::8] is equal to s if s is an integer number of bytes, otherwise it is truncated by up to 7 bits. So the final seven complete 16-bit words could be written as s[-7::16] Negative slices are also allowed, and should do what you'd expect. So for example s[::-1] returns a bit-reversed copy of s (which is similar to s.reversebits(), which does the same operation on s in-place). As another example, to get the first 10 bytes in reverse byte order you could use s_bytereversed = s[0:10:-8]. * Removed restrictions on offset You can now specify an offset of greater than 7 bits when creating a BitString, and the use of offset is also now permitted when using the filename initialiser. This is useful when you want to create a BitString from the middle of a file without having to read the file into memory. >>> f = BitString(filename='reallybigfile', offset=8000000, length=32) * Integers can be assigned to slices You can now assign an integer to a slice of a BitString. If the integer doesn't fit in the size of slice given then a ValueError exception is raised. So this is now allowed and works as expected: >>> s[8:16] = 106 and is equivalent to >>> s[8:16] = BitString(uint=106, length=8) * Less exceptions raised Some changes have been made to slicing so that less exceptions are raised, bringing the interface closer to that for lists. So for example trying to delete past the end of the BitString will now just delete to the end, rather than raising a ValueError. * Initialisation from lists and tuples A new option for the auto initialiser is to pass it a list or tuple. The items in the list or tuple are evaluated as booleans and the bits in the BitString are set to 1 for True items and 0 for False items. This can be used anywhere the auto initialiser can currently be used. For example: >>> a = BitString([True, 7, False, 0, ()]) # 0b11000 >>> b = a + ['Yes', ''] # Adds '0b10' >>> (True, True, False) in a True * Miscellany reversebits() now has optional startbit and endbit parameters. As an optimisation findall() will return a generator, rather than a list. If you still want the whole list then of course you can just call list() on the generator. Improved efficiency of rfind(). A couple of minor bugs were fixed. See the issue tracker for details. ----------------------------------------------------- April 23rd 2009: Python 3 only version 0.4.1 released ----------------------------------------------------- This version is just a port of version 0.4.0 to Python 3. All the unit tests pass, but beyond that only limited ad hoc testing has been done and so it should be considered an experimental release. That said, the unit test coverage is very good - I'm just not sure if anyone even wants a Python 3 version! --------------------------------------- April 11th 2009: version 0.4.0 released --------------------------------------- Changes in version 0.4.0 * New functions Added rfind(), findall(), replace(). These do pretty much what you'd expect - see the docstrings or the wiki for more information. * More special functions Some missing functions were added: __repr__, __contains__, __rand__, __ror__, _rxor__ and __delitem__. * Miscellany A couple of small bugs were fixed (see the issue tracker). ---- There are some small backward incompatibilities relative to version 0.3.2: * Combined find() and findbytealigned() findbytealigned() has been removed, and becomes part of find(). The default start position has changed on both find() and split() to be the start of the BitString. You may need to recode: >>> s1.find(bs) >>> s2.findbytealigned(bs) >>> s2.split(bs) becomes >>> s1.find(bs, bytealigned=False, startbit=s1.bitpos) >>> s2.find(bs, startbit=s1.bitpos) # bytealigned defaults to True >>> s2.split(bs, startbit=s2.bitpos) * Reading off end of BitString no longer raises exception. Previously a read or peek function that encountered the end of the BitString would raise a ValueError. It will now instead return the remainder of the BitString, which could be an empty BitString. This is closer to the file object interface. * Removed visibility of offset. The offset property was previously read-only, and has now been removed from public view altogether. As it is used internally for efficiency reasons you shouldn't really have needed to use it. If you do then use the _offset parameter instead (with caution). --------------------------------------- March 11th 2009: version 0.3.2 released --------------------------------------- Changes in version 0.3.2 * Better performance A number of functions (especially find() and findbytealigned()) have been sped up considerably. * Bit-wise operations Added support for bit-wise AND (&), OR (|) and XOR (^). For example: >>> a = BitString('0b00111') >>> print a & '0b10101' 0b00101 * Miscellany Added seekbit() and seekbyte() functions. These complement the 'advance' and 'retreat' functions, although you can still just use bitpos and bytepos properties directly. >>> a.seekbit(100) # Equivalent to a.bitpos = 100 Allowed comparisons between BitString objects and strings. For example this will now work: >>> a = BitString('0b00001111') >>> a == '0x0f' True ------------------------------------------ February 26th 2009: version 0.3.1 released ------------------------------------------ Changes in version 0.3.1 This version only adds features and fixes bugs relative to 0.3.0, and doesn't break backwards compatibility. * Octal interpretation and initialisation The oct property now joins bin and hex. Just prefix octal numbers with '0o'. >>> a = BitString('0o755') >>> print a.bin 0b111101101 * Simpler copying Rather than using b = copy.copy(a) to create a copy of a BitString, now you can just use b = BitString(a). * More special methods Lots of new special methods added, for example bit-shifting via << and >>, equality testing via == and !=, bit inversion (~) and concatenation using *. Also __setitem__ is now supported so BitString objects can be modified using standard index notation. * Proper installer Finally got round to writing the distutils script. To install just python setup.py install. ------------------------------------------ February 15th 2009: version 0.3.0 released ------------------------------------------ Changes in version 0.3.0 * Simpler initialisation from binary and hexadecimal The first argument in the BitString constructor is now called auto and will attempt to interpret the type of a string. Prefix binary numbers with '0b' and hexadecimals with '0x'. >>> a = BitString('0b0') # single zero bit >>> b = BitString('0xffff') # two bytes Previously the first argument was data, so if you relied on this then you will need to recode: >>> a = BitString('\x00\x00\x01\xb3') # Don't do this any more! becomes >>> a = BitString(data='\x00\x00\x01\xb3') or just >>> a = BitString('0x000001b3') This new notation can also be used in functions that take a BitString as an argument. For example: >>> a = BitString('0x0011') + '0xff' >>> a.insert('0b001', 6) >>> a.find('0b1111') * BitString made more mutable The functions append, deletebits, insert, overwrite, truncatestart and truncateend now modify the BitString that they act upon. This allows for cleaner and more efficient code, but you may need to rewrite slightly if you depended upon the old behaviour: >>> a = BitString(hex='0xffff') >>> a = a.append(BitString(hex='0x00')) >>> b = a.deletebits(10, 10) becomes: >>> a = BitString('0xffff') >>> a.append('0x00') >>> b = copy.copy(a) >>> b.deletebits(10, 10) Thanks to Frank Aune for suggestions in this and other areas. * Changes to printing The binary interpretation of a BitString is now prepended with '0b'. This is in keeping with the Python 2.6 (and 3.0) bin function. The prefix is optional when initialising using 'bin='. Also, if you just print a BitString with no interpretation it will pick something appropriate - hex if it is an integer number of bytes, otherwise binary. If the BitString representation is very long it will be truncated by '...' so it is only an approximate interpretation. >>> a = BitString('0b0011111') >>> print a 0b0011111 >>> a += '0b0' >>> print a 0x3e * More convenience functions Some missing functions such as advancebit and deletebytes have been added. Also a number of peek functions make an appearance as have prepend and reversebits. See the Tutorial for more details. ----------------------------------------- January 13th 2009: version 0.2.0 released ----------------------------------------- Some fairly minor updates, not really deserving of a whole version point update. ------------------------------------------ December 29th 2008: version 0.1.0 released ------------------------------------------ First release! bitstring-bitstring-4.1.4/tests/000077500000000000000000000000001453167633600167105ustar00rootroot00000000000000bitstring-bitstring-4.1.4/tests/__init__.py000066400000000000000000000000001453167633600210070ustar00rootroot00000000000000bitstring-bitstring-4.1.4/tests/smalltestfile000066400000000000000000000000101453167633600214720ustar00rootroot00000000000000#Egbitstring-bitstring-4.1.4/tests/stress_test.py000066400000000000000000000053431453167633600216510ustar00rootroot00000000000000#!/usr/bin/env python import sys sys.path.insert(0, '..') from bitstring import Bits, BitStream import bitstring import time import random import cProfile import pstats import math # Some performance tests. Each is a task - it is permissible to rewrite # to do it in a different way. # TEST 1: Create a bitstring, read every 3 bits and count how many equal '001'. def perf1(): s = bitstring.Bits('0xef1356a6200b3, 0b0') s *= 6000 c = 0 for triplet in s.cut(3): if triplet == '0b001': c += 1 assert c == 12000, c def perf2(): s = bitstring.BitArray(100000000) s.set(1, [10, 100, 1000, 100000]) count = s.count(1) assert count == 4 def perf3(): s = bitstring.BitArray() for i in range(10000): s += 'uint:12=244, float:32=0.4' s += '0x3e44f, 0b11011, 0o75523' s += [0, 1, 2, 0, 0, 1, 2, 0, -1, 0, 'hello'] s += bitstring.BitArray(104) def perf4(): random.seed(999) i = random.randrange(0, 2**20000000) s = bitstring.BitArray(uint=i, length=20000000) for ss in ['0b11010010101', '0xabcdef1234, 0b000101111010101010011010100100101010101', '0x4321']: x = len(list(s.findall(ss))) assert x == 289 def perf5(): s = set() s2 = set() random.seed(12) for _ in range(20000): v = random.randint(0, 2**10) s.add(bitstring.ConstBitStream(uint=v, length=1001, pos=v % 1000)) s2.add(v) assert len(s) == len(s2) def perf6(): random.seed(1414) i = random.randrange(0, 2 ** 800000) s = bitstring.ConstBitStream(uint=i, length=800000) for _ in range(800000 // 40): _ = s.readlist('uint:4, float:32, bool, bool, bool, bool') def perf7(): limit = 1000000 is_prime = bitstring.BitArray(limit) is_prime.set(True) # Manually set 0 and 1 to be not prime. is_prime.set(False, [0, 1]) # For every other integer, if it's set as prime then unset all of its multiples for i in range(2, math.ceil(math.sqrt(limit))): if is_prime[i]: is_prime.set(False, range(i*i, limit, i)) twin_primes = len(list(is_prime.findall('0b101'))) assert twin_primes == 8169 def run(f): start_time = time.perf_counter() print("Running {0}".format(str(f))) f() print("Took {0} s".format(time.perf_counter() - start_time)) def main(): start_time = time.perf_counter() run(perf1) run(perf2) run(perf3) run(perf4) run(perf5) run(perf6) run(perf7) print("Total time {0} s".format(time.perf_counter() - start_time)) if __name__ == '__main__': print(f"bitstring version {bitstring.__version__}") cProfile.run('main()', 'stats') p = pstats.Stats('stats') p.sort_stats('time').print_stats(10) bitstring-bitstring-4.1.4/tests/test.m1v000066400000000000000000003645641453167633600203360ustar00rootroot00000000000000  MPEG-1 Test Sequence, 25 frames/sec @ R".RJR")H".RJR")H".RH"&J֓B'bER)JD\)rER)JD\)rD+})H".RJR")H"*9JR")H".RJR")H".R#P?")HZ"4JR")H".RJR"})H".R)H".RJR")H".RJR")HퟝPt!,`r@ ,v!,7!,m ZH~x[<poF延= VI珼 RVJv6@B!JŠ%" 1wQ(w)J)H%  U K3 1L ,\m)z H] A khBcPBprxؓs)[JǾ (i4 { Gr !H``o ,q480P i`0,f7'QsHx 8 `}3@3I`T5`Mbssn%|$V{\co, ,40(J6.@#w-8@/BƣiD G#R_m@"C6mbn! <5$vOR.RORt".RJR")H })H".RJR")H".RJV5bPGK>~B9!XhiDt`vA)@0g-߾GL: P(b2#_K @2XeywT1vT%t:z @70) 9?s% @ 1_H@aܚ`T ߧ4 0)()@b [bM`*YO23 eGaaۮbhb{0 v@V^l7-` Y=|C @>XK))+"h0!ВGh_z3"hHCwI홗HBfC,5oaRo 4<5+ZRQ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yz3]D@;+ ,.^0?JC -;v ;]@|› }|wFa5 @5 +0XC0\Mԉ4Ԩ65 Dx2ih) &V %)W?C!FHx~g'r}& RM +!17 %\01 {l`j@j0{ b_f!^a0‰b6(+l ?jۘ=oZKuH7``S% 30)B)M 3e'p%{H5@[܃r >橘,lo?j" 6"~u^ΥŨ"OªdN88sGn!!AhxuL8Ň0ZB Uug 尐XS#d :rYl@ݸ\%n=}D"q "gs \Dvr'\DNsO>j[8֣NvQ>ptp ~G`#2v{гΩ.X( eKkjT8MU-4 {wbt=EcaNQ'g~-SQQ,852AN &cH#CJUٰBk? z=vZg>@ #ޒj.8]rg=<;<\um@BqEvUL z4k]suTuh QmmTQ::iP {B}DydHML:'[<mlR oojY@> rmzr| 6"YUL-.HQm`-pbitstring-bitstring-4.1.4/tests/test_array.py000066400000000000000000000672261453167633600214540ustar00rootroot00000000000000#!/usr/bin/env python import unittest import sys import bitstring import array import os from bitstring import Array, Bits, BitArray import copy import itertools import io sys.path.insert(0, '..') THIS_DIR = os.path.dirname(os.path.abspath(__file__)) class Creation(unittest.TestCase): def testCreationFromInt(self): a = Array('u12', 20) self.assertEqual(len(a), 20) self.assertEqual(a[19], 0) with self.assertRaises(IndexError): _ = a[20] def testCreationFromIntList(self): a = Array('i4', [-3, -2, -1, 0, 7]) self.assertEqual(len(a), 5) self.assertEqual(a[2], -1) self.assertEqual(a[-1], 7) def testCreationFromBytesExplicit(self): a = Array('hex:8') a.data.bytes = b'ABCD' self.assertEqual(a[0], '41') self.assertEqual(a[1], '42') self.assertEqual(a[2], '43') self.assertEqual(a[3], '44') def testCreationFromBitsFormat(self): a = Bits('0x000102030405') b = Array('bits:8', a) c = Array('bits:8', [Bits('0x00'), Bits('0x01'), Bits('0x02'), Bits('0x03'), Bits('0x04'), Bits('0x05')]) self.assertTrue(b.equals(c)) def testCreationFromFloat8(self): a = Array('e4m3float') a.data.bytes = b'\x7f\x00' self.assertEqual(a[0], 240.0) self.assertEqual(a[1], 0.0) b = Array('e4m3float', [100000, -0.0]) self.assertTrue(a.equals(b)) def testCreationFromMultiple(self): with self.assertRaises(ValueError): _ = Array('2*float16') def testChangingFmt(self): a = Array('uint8', [255]*100) self.assertEqual(len(a), 100) a.dtype = 'int4' self.assertEqual(len(a), 200) self.assertEqual(a.count(-1), 200) a.append(5) self.assertEqual(len(a), 201) self.assertEqual(a.count(-1), 200) a = Array('>d', [0, 0, 1]) with self.assertRaises(ValueError): a.dtype = 'se' self.assertEqual(a[-1], 1.0) self.assertEqual(a.dtype, '>d') def testChangingFormatWithTrailingBits(self): a = Array('bool', 803) self.assertEqual(len(a), 803) a.dtype = '>e' self.assertEqual(len(a), 803 // 16) b = Array('>f', [0]) b.dtype = 'i3' self.assertEqual(b.tolist(), [0]*10) def testCreationWithTrailingBits(self): a = Array('bool', trailing_bits='0xf') self.assertEqual(a.data, '0b1111') self.assertEqual(len(a), 4) b = Array('bin:3', ['111', '000', '111']) self.assertEqual(len(b), 3) self.assertEqual(b.data, '0b111000111') b.dtype = 'h4' self.assertEqual(len(b), 2) with self.assertRaises(ValueError): b.append('f') del b.data[0] b.append('f') self.assertEqual(len(b), 3) c = Array('>e', trailing_bits='0x0000, 0b1') self.assertEqual(c[0], 0.0) self.assertEqual(c.tolist(), [0.0]) def testCreationWithArrayCode(self): a = Array('H', [10, 20]) self.assertEqual(a.data.unpack('2*uint16'), a.tolist()) a = Array('\n" "[\n" "c040 3f80 4000\n" "]\n") a.data += '0b110' a.dtype='hex16' s = io.StringIO() a.pp(stream=s) self.assertEqual(s.getvalue(), """ [ c040 3f80 4000 ] + trailing_bits = 0b110\n""") def testPpUint(self): a = Array('uint32', [12, 100, 99]) s = io.StringIO() a.pp(stream=s) self.assertEqual(s.getvalue(), """ [ 12 100 99 ]\n""") def testPpBits(self): a = Array('bits2', b'89') s = io.StringIO() a.pp(stream=s, width=0, show_offset=True) self.assertEqual(s.getvalue(), """ [ 0: 0b00 1: 0b11 2: 0b10 3: 0b00 4: 0b00 5: 0b11 6: 0b10 7: 0b01 ]\n""") def testPpTwoFormats(self): a = Array('float16', bytearray(20)) s = io.StringIO() a.pp(stream=s, fmt='e5m2float, bin') self.assertEqual(s.getvalue(), """ [ 0.0 0.0 0.0 0.0 : 00000000 00000000 00000000 00000000 0.0 0.0 0.0 0.0 : 00000000 00000000 00000000 00000000 0.0 0.0 0.0 0.0 : 00000000 00000000 00000000 00000000 0.0 0.0 0.0 0.0 : 00000000 00000000 00000000 00000000 0.0 0.0 0.0 0.0 : 00000000 00000000 00000000 00000000 ]\n""") def testPpTwoFormatsNoLength(self): a = Array('float16', bytearray(range(50, 56))) s = io.StringIO() a.pp(stream=s, fmt='u, b') self.assertEqual(s.getvalue(), """ [ 12851 13365 13879 : 0011001000110011 0011010000110101 0011011000110111 ]\n""") class ArrayOperations(unittest.TestCase): def testInPlaceAdd(self): a = Array('i7', [-9, 4, 0]) a += 9 self.assertEqual(a.tolist(), [0, 13, 9]) self.assertEqual(len(a.data), 21) def testAdd(self): a = Array('>d') a.extend([1.0, -2.0, 100.5]) b = a + 2 self.assertTrue(a.equals(Array('>d', [1.0, -2.0, 100.5]))) self.assertTrue(b.equals(Array('>d', [3.0, 0.0, 102.5]))) def testSub(self): a = Array('uint44', [3, 7, 10]) b = a - 3 self.assertTrue(b.equals(Array('u44', [0, 4, 7]))) with self.assertRaises(ValueError): _ = a - 4 def testInPlaceSub(self): a = Array('float16', [-9, -10.5]) a -= -1.5 self.assertEqual(a.tolist(), [-7.5, -9.0]) def testMul(self): a = Array('i21', [-5, -4, 0, 2, 100]) b = a * 2 self.assertEqual(b.tolist(), [-10, -8, 0, 4, 200]) a = Array('int9', [-1, 0, 3]) b = a * 2 self.assertEqual(a.tolist(), [-1, 0, 3]) self.assertEqual(b.tolist(), [-2, 0, 6]) c = a * 2.5 self.assertEqual(c.tolist(), [-2, 0, 7]) def testInPlaceMul(self): a = Array('i21', [-5, -4, 0, 2, 100]) a *= 0.5 self.assertEqual(a.tolist(), [-2, -2, 0, 1, 50]) def testDiv(self): a = Array('i32', [-2, -1, 0, 1, 2]) b = a // 2 self.assertEqual(a.tolist(), [-2, -1, 0, 1, 2]) self.assertEqual(b.tolist(), [-1, -1, 0, 0, 1]) def testInPlaceDiv(self): a = Array('i10', [-4, -3, -2, -1, 0, 1, 2]) a //= 2 self.assertTrue(a.equals(Array('i10', [-2, -2, -1, -1, 0, 0, 1]))) def testTrueDiv(self): a = Array('float16', [5, 10, -6]) b = a / 4 self.assertTrue(a.equals(Array('float16', [5.0, 10.0, -6.0]))) self.assertTrue(b.equals(Array('float16', [1.25, 2.5, -1.5]))) def testInPlaceTrueDiv(self): a = Array('int71', [-4, -3, -2, -1, 0, 1, 2]) a /= 2 self.assertTrue(a.equals(Array('int71', [-2, -1, -1, 0, 0, 0, 1]))) def testAnd(self): a = Array('int16', [-1, 100, 9]) with self.assertRaises(TypeError): _ = a & 0 b = a & '0x0001' self.assertEqual(b.tolist(), [1, 0, 1]) b = a & '0xffff' self.assertEqual(b.dtype, 'int16') self.assertEqual(b.tolist(), [-1, 100, 9]) def testInPlaceAnd(self): a = Array('bool', [True, False, True]) with self.assertRaises(TypeError): a &= 0b1 a = Array('uint10', a.tolist()) a <<= 3 self.assertEqual(a.tolist(), [8, 0, 8]) a += 1 self.assertEqual(a.tolist(), [9, 1, 9]) with self.assertRaises(ValueError): a &= '0b111' a &= '0b0000000111' self.assertEqual(a.data, '0b 0000000001 0000000001 0000000001') def testOr(self): a = Array('e4m3float', [-4, 2.5, -9, 0.25]) b = a | '0b10000000' self.assertEqual(a.tolist(), [-4, 2.5, -9, 0.25]) self.assertEqual(b.tolist(), [-4, -2.5, -9, -0.25]) def testInPlaceOr(self): a = Array('hex:12') a.append('f0f') a.extend(['000', '111']) a |= '0x00f' self.assertEqual(a.tolist(), ['f0f', '00f', '11f']) with self.assertRaises(TypeError): a |= 12 def testXor(self): a = Array('hex8', ['00', 'ff', 'aa']) b = a ^ '0xff' self.assertEqual(a.tolist(), ['00', 'ff', 'aa']) self.assertEqual(b.tolist(), ['ff', '00', '55']) def testInPlaceXor(self): a = Array('u10', [0, 0xf, 0x1f]) a ^= '0b00, 0x0f' def testRshift(self): a = Array(dtype='u8') a.data = Bits('0x00010206') b = a >> 1 self.assertEqual(a.tolist(), [0, 1, 2, 6]) self.assertEqual(b.tolist(), [0, 0, 1, 3]) a = Array('i10', [-1, 0, -20, 10]) b = a >> 1 self.assertEqual(b.tolist(), [-1, 0, -10, 5]) c = a >> 0 self.assertEqual(c.tolist(), [-1, 0, -20, 10]) with self.assertRaises(ValueError): _ = a >> -1 def testInPlaceRshift(self): a = Array('i8', [-8, -1, 0, 1, 100]) a >>= 1 self.assertEqual(a.tolist(), [-4, -1, 0, 0, 50]) a >>= 100000 self.assertEqual(a.tolist(), [-1, -1, 0, 0, 0]) def testLshift(self): a = Array('e5m2float', [0.3, 1.2]) with self.assertRaises(TypeError): _ = a << 3 a = Array('int16', [-2, -1, 0, 128]) b = a << 4 self.assertEqual(a.tolist(), [-2, -1, 0, 128]) self.assertEqual(b.tolist(), [-32, -16, 0, 2048]) with self.assertRaises(ValueError): _ = a << 1000 def testInPlaceLshift(self): a = Array('u11', [0, 5, 10, 1, 2, 3]) a <<= 2 self.assertEqual(a.tolist(), [0, 20, 40, 4, 8, 12]) a <<= 0 self.assertEqual(a.tolist(), [0, 20, 40, 4, 8, 12]) with self.assertRaises(ValueError): a <<= -1 def testNeg(self): a = Array('i92', [-1, 1, 0, 100, -100]) b = -a self.assertEqual(b.tolist(), [1, -1, 0, -100, 100]) self.assertEqual(b.dtype, 'int92') def testAbs(self): a = Array('float16', [-2.0, 0, -0, 100, -5.5]) b = abs(a) self.assertTrue(b.equals(Array('float16', [2.0, 0, 0, 100, 5.5]))) class CreationFromBits(unittest.TestCase): def testAppendingAuto(self): a = Array('bits8') a.append('0xff') self.assertEqual(len(a), 1) self.assertEqual(a[0], Bits('0xff')) with self.assertRaises(TypeError): a += 8 a.append(Bits(8)) self.assertTrue(a[:].equals(Array('bits:8', ['0b1111 1111', Bits('0x00')]))) a.extend(['0b10101011']) self.assertEqual(a[-1].hex, 'ab') class SameSizeArrayOperations(unittest.TestCase): def testAddingSameTypes(self): a = Array('u8', [1, 2, 3, 4]) b = Array('u8', [5, 5, 5, 4]) c = a + b self.assertEqual(c.tolist(), [6, 7, 8, 8]) self.assertEqual(c.dtype, 'uint8') def testAddingDifferentTypes(self): a = Array('u8', [1, 2, 3, 4]) b = Array('i6', [5, 5, 5, 4]) c = a + b self.assertEqual(c.tolist(), [6, 7, 8, 8]) self.assertEqual(c.dtype, 'int6') d = Array('float16', [-10, 0, 5, 2]) e = d + a self.assertEqual(e.tolist(), [-9.0, 2.0, 8.0, 6.0]) self.assertEqual(e.dtype, 'float16') e = a + d self.assertEqual(e.tolist(), [-9.0, 2.0, 8.0, 6.0]) self.assertEqual(e.dtype, 'float16') x1 = a[:] x2 = a[:] x1.dtype = 'e5m2float' x2.dtype = 'e4m3float' y = x1 + x2 self.assertEqual(y.dtype, x1.dtype) def testAddingErrors(self): a = Array('float16', [10, 100, 1000]) b = Array('i3', [-1, 2]) with self.assertRaises(ValueError): _ = a + b b.append(0) c = a + b self.assertEqual(c.tolist(), [9, 102, 1000]) a.dtype='hex16' with self.assertRaises(ValueError): _ = a + b class ComparisonOperators(unittest.TestCase): def testLessThanWithScalar(self): a = Array('u16', [14, 16, 100, 2, 100]) b = a < 80 self.assertEqual(b.tolist(), [True, True, False, True, False]) self.assertEqual(b.dtype, 'bool') def testLessThanWithArray(self): a = Array('u16', [14, 16, 100, 2, 100]) b = Array('bfloat', [1000, -54, 0.2, 55, 9]) c = a < b self.assertEqual(c.tolist(), [True, False, False, True, False]) self.assertEqual(c.dtype, 'bool') def testArrayEquals(self): a = Array('i12', [1, 2, -3, 4, -5, 6]) b = Array('i12', [6, 5, 4, 3, 2, 1]) self.assertEqual(abs(a), b[::-1]) self.assertNotEqual(a, b) class AsType(unittest.TestCase): def testSwitchingIntTypes(self): a = Array('u8', [15, 42, 1]) b = a.astype('i8') self.assertEqual(a.tolist(), b.tolist()) self.assertEqual(b.dtype, 'i8') def testSwitchingFloatTypes(self): a = Array('float64', [-990, 34, 1, 0.25]) b = a.astype('float16') self.assertEqual(a.tolist(), b.tolist()) self.assertEqual(b.dtype, 'float16') class ReverseMethods(unittest.TestCase): def testRadd(self): a = Array('u6', [1,2,3]) b = 5 + a self.assertTrue(b.equals(Array('uint:6', [6, 7, 8]))) def testRmul(self): a = Array('bfloat', [4, 2, 8]) b = 0.5 * a self.assertTrue(b.equals(Array('bfloat16', [2.0, 1.0, 4.0]))) def testRsub(self): a = Array('i90', [-1, -10, -100]) b = 100 - a self.assertTrue(b.equals(Array('int90', [101, 110, 200]))) def testRmod(self): a = Array('i8', [1, 2, 4, 8, 10]) with self.assertRaises(TypeError): _ = 15 % a def testRfloordiv(self): a = Array('>H', [1, 2, 3, 4, 5]) with self.assertRaises(TypeError): _ = 100 // a def testRtruediv(self): a = Array('>H', [1, 2, 3, 4, 5]) with self.assertRaises(TypeError): _ = 100 / a def testRand(self): a = Array('u8', [255, 8, 4, 2, 1, 0]) b = '0x0f' & a self.assertEqual(b.tolist(), [15, 8, 4, 2, 1, 0]) def testRor(self): a = Array('u8', [255, 8, 4, 2, 1, 0]) b = '0x0f' | a self.assertEqual(b.tolist(), [255, 15, 15, 15, 15, 15]) def testRxor(self): a = Array('u8', [255, 8, 4, 2, 1, 0]) b = '0x01' ^ a self.assertEqual(b.tolist(), [254, 9, 5, 3, 0, 1]) bitstring-bitstring-4.1.4/tests/test_bitarray.py000066400000000000000000000712211453167633600221410ustar00rootroot00000000000000#!/usr/bin/env python """ Unit tests for the bitarray module. """ import unittest import sys import os import bitarray import bitstring from bitstring import BitArray, Bits sys.path.insert(0, '..') class All(unittest.TestCase): def testCreationFromUint(self): s = BitArray(uint=15, length=6) self.assertEqual(s.bin, '001111') s = BitArray(uint=0, length=1) self.assertEqual(s.bin, '0') s.u = 1 self.assertEqual(s.uint, 1) s = BitArray(length=8) s.uint = 0 self.assertEqual(s.uint, 0) s.u8 = 255 self.assertEqual(s.uint, 255) self.assertEqual(s.len, 8) with self.assertRaises(bitstring.CreationError): s.uint = 256 with self.assertRaises(bitstring.CreationError): s.uint = -1 def testCreationFromOct(self): s = BitArray(oct='7') self.assertEqual(s.oct, '7') self.assertEqual(s.bin, '111') s.append('0o1') self.assertEqual(s.bin, '111001') s.oct = '12345670' self.assertEqual(s.length, 24) self.assertEqual(s.bin, '001010011100101110111000') s = BitArray('0o123') self.assertEqual(s.oct, '123') class NoPosAttribute(unittest.TestCase): def testReplace(self): s = BitArray('0b01') s.replace('0b1', '0b11') self.assertEqual(s, '0b011') def testDelete(self): s = BitArray('0b000000001') del s[-1:] self.assertEqual(s, '0b00000000') def testInsert(self): s = BitArray('0b00') s.insert('0xf', 1) self.assertEqual(s, '0b011110') def testInsertSelf(self): b = BitArray('0b10') b.insert(b, 0) self.assertEqual(b, '0b1010') c = BitArray('0x00ff') c.insert(c, 8) self.assertEqual(c, '0x0000ffff') a = BitArray('0b11100') a.insert(a, 3) self.assertEqual(a, '0b1111110000') def testNoBitPosForInsert(self): s = BitArray(100) with self.assertRaises(TypeError): s.insert('0xabc') def testInsertParameters(self): s = BitArray('0b111') with self.assertRaises(TypeError): s.insert('0x4') def testOverwrite(self): s = BitArray('0b01110') s.overwrite('0b000', 1) self.assertEqual(s, '0b00000') def testOverwriteNoPos(self): s = BitArray('0x01234') with self.assertRaises(TypeError): s.overwrite('0xf') def testOverwriteParameters(self): s = BitArray('0b0000') with self.assertRaises(TypeError): s.overwrite('0b111') def testPrepend(self): s = BitArray('0b0') s.prepend([1]) self.assertEqual(s, [1, 0]) def testRol(self): s = BitArray('0b0001') s.rol(1) self.assertEqual(s, '0b0010') def testRor(self): s = BitArray('0b1000') s.ror(1) self.assertEqual(s, '0b0100') def testSetItem(self): s = BitArray('0b000100') s[4:5] = '0xf' self.assertEqual(s, '0b000111110') s[0:1] = [1] self.assertEqual(s, '0b100111110') s[5:5] = BitArray() self.assertEqual(s, '0b100111110') class Bugs(unittest.TestCase): def testAddingNonsense(self): a = BitArray([0]) a += '0' # a uint of length 0 - so nothing gets added. self.assertEqual(a, [0]) with self.assertRaises(ValueError): a += '3' with self.assertRaises(ValueError): a += 'se' with self.assertRaises(ValueError): a += 'float:32' def testPrependAfterCreationFromDataWithOffset(self): s1 = BitArray(bytes=b'\x00\x00\x07\xff\xf0\x00', offset=21, length=15) self.assertFalse(s1.any(0)) b = s1.tobytes() self.assertEqual(b, b'\xff\xfe') s1.prepend('0b0') self.assertEqual(s1.bin, '0111111111111111') s1.prepend('0b0') self.assertEqual(s1.bin, '00111111111111111') class ByteAligned(unittest.TestCase): def testChangingIt(self): bitstring.bytealigned = True self.assertTrue(bitstring.bytealigned) bitstring.bytealigned = False self.assertFalse(bitstring.bytealigned) def testNotByteAligned(self): a = BitArray('0x00 ff 0f f') li = list(a.findall('0xff')) self.assertEqual(li, [8, 20]) p = a.find('0x0f')[0] self.assertEqual(p, 4) p = a.rfind('0xff')[0] self.assertEqual(p, 20) s = list(a.split('0xff')) self.assertEqual(s, ['0x00', '0xff0', '0xff']) a.replace('0xff', '') self.assertEqual(a, '0x000') def testByteAligned(self): bitstring.bytealigned = True a = BitArray('0x00 ff 0f f') li = list(a.findall('0xff')) self.assertEqual(li, [8]) p = a.find('0x0f')[0] self.assertEqual(p, 16) p = a.rfind('0xff')[0] self.assertEqual(p, 8) s = list(a.split('0xff')) self.assertEqual(s, ['0x00', '0xff0ff']) a.replace('0xff', '') self.assertEqual(a, '0x000ff') bitstring.bytealigned = False class SliceAssignment(unittest.TestCase): def testSliceAssignmentSingleBit(self): a = BitArray('0b000') a[2] = '0b1' self.assertEqual(a.bin, '001') a[0] = BitArray(bin='1') self.assertEqual(a.bin, '101') a[-1] = '0b0' self.assertEqual(a.bin, '100') a[-3] = '0b0' self.assertEqual(a.bin, '000') def testSliceAssignmentSingleBitErrors(self): a = BitArray('0b000') with self.assertRaises(IndexError): a[-4] = '0b1' with self.assertRaises(IndexError): a[3] = '0b1' with self.assertRaises(TypeError): a[1] = 1.3 def testSliceAssignmentMulipleBits(self): a = BitArray('0b0') a[0] = '0b110' self.assertEqual(a.bin3, '110') a[0] = '0b000' self.assertEqual(a.bin5, '00010') a[0:3] = '0b111' self.assertEqual(a.b5, '11110') a[-2:] = '0b011' self.assertEqual(a.bin, '111011') a[:] = '0x12345' self.assertEqual(a.hex, '12345') a[:] = '' self.assertFalse(a) def testSliceAssignmentMultipleBitsErrors(self): a = BitArray() with self.assertRaises(IndexError): a[0] = '0b00' a += '0b1' a[0:2] = '0b11' self.assertEqual(a, '0b11') def testDelSliceStep(self): a = BitArray(bin='100111101001001110110100101') del a[::2] self.assertEqual(a.bin, '0110010101100') del a[3:9:3] self.assertEqual(a.bin, '01101101100') del a[2:7:1] self.assertEqual(a.bin, '011100') del a[::99] self.assertEqual(a.bin, '11100') del a[::1] self.assertEqual(a.bin, '') def testDelSliceNegativeStep(self): a = BitArray('0b0001011101101100100110000001') del a[5:23:-3] self.assertEqual(a.bin, '0001011101101100100110000001') del a[25:3:-3] self.assertEqual(a.bin, '00011101010000100001') del a[:6:-7] self.assertEqual(a.bin, '000111010100010000') del a[15::-2] self.assertEqual(a.bin, '0010000000') del a[::-1] self.assertEqual(a.bin, '') def testDelSliceNegativeEnd(self): a = BitArray('0b01001000100001') del a[:-5] self.assertEqual(a, '0b00001') a = BitArray('0b01001000100001') del a[-11:-5] self.assertEqual(a, '0b01000001') def testDelSliceErrors(self): a = BitArray(10) del a[5:3] self.assertEqual(a, Bits(10)) del a[3:5:-1] self.assertEqual(a, Bits(10)) def testDelSingleElement(self): a = BitArray('0b0010011') del a[-1] self.assertEqual(a.bin, '001001') del a[2] self.assertEqual(a.bin, '00001') with self.assertRaises(IndexError): del a[5] def testSetSliceStep(self): a = BitArray(bin='0000000000') a[::2] = '0b11111' self.assertEqual(a.bin, '1010101010') a[4:9:3] = [0, 0] self.assertEqual(a.bin, '1010001010') a[7:3:-1] = [1, 1, 1, 0] self.assertEqual(a.bin, '1010011110') a[7:1:-2] = [0, 0, 1] self.assertEqual(a.b, '1011001010') a[::-5] = [1, 1] self.assertEqual(a.bin, '1011101011') a[::-1] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1] self.assertEqual(a.bin, '1000000000') def testSetSliceStepWithInt(self): a = BitArray(9) a[5:8] = -1 self.assertEqual(a.bin, '000001110') a[:] = 10 self.assertEqual(a.bin, '000001010') a[::-1] = 10 self.assertEqual(a.bin, '010100000') a[::2] = True self.assertEqual(a.bin, '111110101') def testSetSliceErrors(self): a = BitArray(8) with self.assertRaises(ValueError): a[::3] = [1] class A(object): pass with self.assertRaises(TypeError): a[1:2] = A() with self.assertRaises(ValueError): a[1:4:-1] = [1, 2] class Subclassing(unittest.TestCase): def testIsInstance(self): class SubBits(BitArray): pass a = SubBits() self.assertTrue(isinstance(a, SubBits)) def testClassType(self): class SubBits(BitArray): pass self.assertEqual(SubBits().__class__, SubBits) class Clear(unittest.TestCase): def testClear(self): s = BitArray('0xfff') s.clear() self.assertEqual(s.len, 0) class Copy(unittest.TestCase): def testCopyMethod(self): s = BitArray(9) t = s.copy() self.assertEqual(s, t) t[0] = True self.assertEqual(t.bin, '100000000') self.assertEqual(s.bin, '000000000') class ModifiedByAddingBug(unittest.TestCase): def testAdding(self): a = BitArray('0b0') b = BitArray('0b11') c = a + b self.assertEqual(c, '0b011') self.assertEqual(a, '0b0') self.assertEqual(b, '0b11') class Lsb0Setting(unittest.TestCase): @classmethod def setUpClass(cls): bitstring.lsb0 = True @classmethod def tearDownClass(cls): bitstring.lsb0 = False def testSetSingleBit(self): a = BitArray(10) a[0] = True self.assertEqual(a, '0b0000000001') a[1] = True self.assertEqual(a, '0b0000000011') a[0] = False self.assertEqual(a, '0b0000000010') a[9] = True self.assertEqual(a, '0b1000000010') with self.assertRaises(IndexError): a[10] = True def testSetSingleNegativeBit(self): a = BitArray('0o000') a[-1] = True self.assertEqual(a, '0b100000000') a[-2] = True self.assertEqual(a, '0o600') a[-9] = True self.assertEqual(a, '0o601') with self.assertRaises(IndexError): a[-10] = True def testInvertBit(self): a = BitArray('0b11110000') a.invert() self.assertEqual(a, '0x0f') a.invert(0) self.assertEqual(a, '0b00001110') a.invert(-1) self.assertEqual(a, '0b10001110') def testDeletingBits(self): a = BitArray('0b11110') del a[0] self.assertEqual(a, '0xf') def testDeletingRange(self): a = BitArray('0b101111000') del a[0:1] self.assertEqual(a, '0b10111100') del a[2:6] self.assertEqual(a, '0b1000') a = BitArray('0xabcdef') del a[:8] self.assertEqual(a, '0xabcd') del a[-4:] self.assertEqual(a, '0xbcd') del a[:-4] self.assertEqual(a, '0xb') def testAppendingBits(self): a = BitArray('0b111') a.append('0b000') self.assertEqual(a.bin, '000111') a += '0xabc' self.assertEqual(a, '0xabc, 0b000111') def testSettingSlice(self): a = BitArray('0x012345678') a[4:12] = '0xfe' self.assertEqual(a, '0x012345fe8') a[0:4] = '0xbeef' self.assertEqual(a, '0x012345febeef') def testTruncatingStart(self): a = BitArray('0b1110000') a = a[4:] self.assertEqual(a, '0b111') def testTruncatingEnd(self): a = BitArray('0x123456') a = a[:16] self.assertEqual(a, '0x3456') def testAll(self): a = BitArray('0b0000101') self.assertTrue(a.all(1, [0, 2])) self.assertTrue(a.all(False, [-1, -2, -3, -4])) b = Bits(bytes=b'\x00\xff\xff', offset=7) self.assertTrue(b.all(1, [1, 2, 3, 4, 5, 6, 7])) self.assertTrue(b.all(1, [-2, -3, -4, -5, -6, -7, -8])) def testAny(self): a = BitArray('0b0001') self.assertTrue(a.any(1, [0, 1, 2])) def testEndswith(self): a = BitArray('0xdeadbeef') self.assertTrue(a.endswith('0xdead')) def testStartswith(self): a = BitArray('0xdeadbeef') self.assertTrue(a.startswith('0xbeef')) def testCut(self): a = BitArray('0xff00ff1111ff2222') li = list(a.cut(16)) self.assertEqual(li, ['0x2222', '0x11ff', '0xff11', '0xff00']) def testFind(self): t = BitArray('0b10') p, = t.find('0b1') self.assertEqual(p, 1) t = BitArray('0b1010') p, = t.find('0b1') self.assertEqual(p, 1) a = BitArray('0b10101010, 0xabcd, 0b10101010, 0x0') p, = a.find('0b10101010', bytealigned=False) self.assertEqual(p, 4) p, = a.find('0b10101010', start=4, bytealigned=False) self.assertEqual(p, 4) p, = a.find('0b10101010', start=5, bytealigned=False) self.assertEqual(p, 22) def testFindFailing(self): a = BitArray() p = a.find('0b1') self.assertEqual(p, ()) a = BitArray('0b11111111111011') p = a.find('0b100') self.assertFalse(p) def testFindFailing2(self): s = BitArray('0b101') p, = s.find('0b1', start=2) self.assertEqual(p, 2) def testRfind(self): a = BitArray('0b1000000') p = a.rfind('0b1') self.assertEqual(p, (6,)) p = a.rfind('0b000') self.assertEqual(p, (3,)) def testRfindWithStartAndEnd(self): a = BitArray('0b11 0000 11 00') p = a.rfind('0b11', start=8) self.assertEqual(p[0], 8) p = a.rfind('0b110', start=8) self.assertEqual(p, ()) p = a.rfind('0b11', end=-1) self.assertEqual(p[0], 2) def testFindall(self): a = BitArray('0b001000100001') b = list(a.findall('0b1')) self.assertEqual(b, [0, 5, 9]) c = list(a.findall('0b0001')) self.assertEqual(c, [0, 5]) d = list(a.findall('0b10')) self.assertEqual(d, [4, 8]) e = list(a.findall('0x198273641234')) self.assertEqual(e, []) def testFindAllWithStartAndEnd(self): a = BitArray('0xaabbccaabbccccbb') b = list(a.findall('0xbb', start=0, end=8)) self.assertEqual(b, [0]) b = list(a.findall('0xbb', start=1, end=8)) self.assertEqual(b, []) b = list(a.findall('0xbb', start=0, end=7)) self.assertEqual(b, []) b = list(a.findall('0xbb', start=48)) self.assertEqual(b, [48]) b = list(a.findall('0xbb', start=47)) self.assertEqual(b, [48]) b = list(a.findall('0xbb', start=49)) self.assertEqual(b, []) def testFindAllByteAligned(self): a = BitArray('0x0550550') b = list(a.findall('0x55', bytealigned=True)) self.assertEqual(b, [16]) def testFindAllWithCount(self): a = BitArray('0b0001111101') b = list(a.findall([1], start=1, count=1)) self.assertEqual(b, [2]) def testSplit(self): a = BitArray('0x4700004711472222') li = list(a.split('0x47', bytealigned=True)) self.assertEqual(li, ['', '0x472222', '0x4711', '0x470000']) def testByteSwap(self): a = BitArray('0xaa00ff00ff00') n = a.byteswap(2, end=32, repeat=True) self.assertEqual(n, 2) self.assertEqual(a, '0xaa0000ff00ff') def testInsert(self): a = BitArray('0x0123456') a.insert('0xf', 4) self.assertEqual(a, '0x012345f6') def testOverwrite(self): a = BitArray('0x00000000') a.overwrite('0xdead', 4) self.assertEqual(a, '0x000dead0') def testReplace(self): a = BitArray('0x5551100') n = a.replace('0x1', '0xabc') self.assertEqual(n, 2) self.assertEqual(a, '0x555abcabc00') n = a.replace([1], [0], end=12) self.assertEqual(n, 2) self.assertEqual(a, '0x555abcab000') def testReverse(self): a = BitArray('0x0011223344') a.reverse() self.assertEqual(a, '0x22cc448800') a.reverse(0, 16) self.assertEqual(a, '0x22cc440011') def testRor(self): a = BitArray('0b111000') a.ror(1) self.assertEqual(a, '0b011100') a = BitArray('0b111000') a.ror(1, start=2, end=6) self.assertEqual(a, '0b011100') def testRol(self): a = BitArray('0b1') a.rol(12) self.assertEqual(a, '0b1') b = BitArray('0b000010') b.rol(3) self.assertEqual(b, '0b010000') def testSet(self): a = BitArray(100) a.set(1, [0, 2, 4]) self.assertTrue(a[0]) self.assertTrue(a.startswith('0b000010101')) a = BitArray('0b111') a.set(False, 0) self.assertEqual(a, '0b110') def testFailingRepr(self): a = BitArray('0b010') a.find('0b1') self.assertEqual(repr(a), "BitArray('0b010')") def testLeftShift(self): a = BitArray('0b11001') self.assertEqual((a << 1).b, '10010') self.assertEqual((a << 5).b, '00000') self.assertEqual((a << 0).b, '11001') def testRightShift(self): a = BitArray('0b11001') self.assertEqual((a >> 1).b, '01100') self.assertEqual((a >> 5).b, '00000') self.assertEqual((a >> 0).b, '11001') # def testConstFileBased(self): # filename = os.path.join(THIS_DIR, 'test.m1v') # a = Bits(filename=filename, offset=8) # self.assertTrue(a[-8]) # self.assertTrue(a.endswith('0x01b3')) class Repr(unittest.TestCase): def testStandardRepr(self): a = BitArray('0o12345') self.assertEqual(repr(a), "BitArray('0b001010011100101')") class NewProperties(unittest.TestCase): def testAliases(self): a = BitArray('0x1234567890ab') self.assertEqual(a.oct, a.o) self.assertEqual(a.hex, a.h) self.assertEqual(a.bin, a.b) self.assertEqual(a[:32].float, a[:32].f) self.assertEqual(a.int, a.i) self.assertEqual(a.uint, a.u) def testAliasesWithLengths(self): a = BitArray('0x123') h = a.h12 self.assertEqual(h, '123') b = a.b12 self.assertEqual(b, '000100100011') o = a.o12 self.assertEqual(o, '0443') u = a.u12 self.assertEqual(u, a.u) i = a.i12 self.assertEqual(i, a.i) x = BitArray('0x12345678') f = x.f32 self.assertEqual(f, x.f) def testAssignments(self): a = BitArray() a.f64 = 0.5 self.assertEqual(a.f64, 0.5) a.u88 = 1244322 self.assertEqual(a.u88, 1244322) a.i3 = -3 self.assertEqual(a.i3, -3) a.h16 = '0x1234' self.assertEqual(a.h16, '1234') a.o9 = '0o765' self.assertEqual(a.o9, '765') a.b7 = '0b0001110' self.assertEqual(a.b7, '0001110') def testAssignmentsWithoutLength(self): a = BitArray(64) a.f = 1234.5 self.assertEqual(a.float, 1234.5) self.assertEqual(a.len, 64) a.u = 99 self.assertEqual(a.uint, 99) self.assertEqual(a.len, 64) a.i = -999 self.assertEqual(a.int, -999) self.assertEqual(a.len, 64) a.h = 'feedbeef' self.assertEqual(a.hex, 'feedbeef') a.o = '1234567' self.assertEqual(a.oct, '1234567') a.b = '001' self.assertEqual(a.bin, '001') def testGetterLengthErrors(self): a = BitArray('0x123') with self.assertRaises(bitstring.InterpretError): _ = a.h16 with self.assertRaises(bitstring.InterpretError): _ = a.b331123112313 with self.assertRaises(bitstring.InterpretError): _ = a.o2 with self.assertRaises(bitstring.InterpretError): _ = a.f with self.assertRaises(bitstring.InterpretError): _ = a.f32 with self.assertRaises(bitstring.InterpretError): _ = a.u13 with self.assertRaises(bitstring.InterpretError): _ = a.i1 b = BitArray() with self.assertRaises(bitstring.InterpretError): _ = b.u0 def testSetterLengthErrors(self): a = BitArray() a.u8 = 255 self.assertEqual(a.len, 8) with self.assertRaises(ValueError): a.u8 = 256 a.f32 = 10 a.f64 = 10 with self.assertRaises(ValueError): a.f256 = 10 with self.assertRaises(bitstring.CreationError): a.u0 = 2 with self.assertRaises(bitstring.CreationError): a.hex4 = '0xab' self.assertEqual(len(a), 64) with self.assertRaises(bitstring.CreationError): a.o3 = '0xab' with self.assertRaises(bitstring.CreationError): a.b4 = '0xab' a.h0 = '' self.assertEqual(a.len, 0) a.i8 = 127 a.i8 = -128 with self.assertRaises(ValueError): a.i8 = 128 with self.assertRaises(ValueError): a.i8 = -129 with self.assertRaises(bitstring.CreationError): a.froggy16 = '0xabc' def testUnpack(self): a = BitArray('0xff160120') b = a.unpack('h8,2*u12') self.assertEqual(b, ['ff', 352, 288]) def testReading(self): a = bitstring.BitStream('0x01ff') b = a.read('u8') self.assertEqual(b, 1) self.assertEqual(a.pos, 8) self.assertEqual(a.read('i'), -1) def testLongerMoreGeneralNames(self): a = BitArray() a.f64 = 0.0 self.assertEqual(a.float64, 0.0) a.float32 = 10.5 self.assertEqual(a.f32, 10.5) def testBytesProperties(self): a = BitArray() a.bytes = b'hello' self.assertEqual(a.bytes5, b'hello') a.bytes3 = b'123' self.assertEqual(a.bytes, b'123') with self.assertRaises(bitstring.CreationError): a.bytes5 = b'123456789' with self.assertRaises(bitstring.CreationError): a.bytes5 = b'123' def testConversionToBytes(self): a = BitArray(bytes=b'1234') b = bytes(a) self.assertEqual(b, b'1234') a += [1] self.assertEqual(bytes(a), b'1234\x80') a = BitArray() self.assertEqual(bytes(a), b'') class BFloats(unittest.TestCase): def testCreation(self): a = BitArray('bfloat=100.5') self.assertEqual(a.unpack('bfloat')[0], 100.5) b = BitArray(bfloat=20.25) self.assertEqual(b.bfloat, 20.25) b.bfloat = -30.5 self.assertEqual(b.bfloat, -30.5) self.assertEqual(len(b), 16) fs = [0.0, -6.1, 1.52e35, 0.000001] a = bitstring.pack('4*bfloat', *fs) fsp = a.unpack('4*bfloat') self.assertEqual(len(a), len(fs)*16) for f, fp in zip(fs, fsp): self.assertAlmostEqual(f, fp, delta=max(f/100, -f/100)) a = BitArray(bfloat=13) self.assertEqual(a.bfloat, 13) def testCreationErrors(self): a = BitArray(bfloat=-0.25, length=16) self.assertEqual(len(a), 16) with self.assertRaises(bitstring.CreationError): _ = BitArray(bfloat=10, length=15) with self.assertRaises(bitstring.CreationError): _ = BitArray('bfloat:1=0.5') def testLittleEndian(self): a = BitArray('f32=1000') b = BitArray(bfloat=a.f) self.assertEqual(a[0:16], b[0:16]) a = BitArray('floatle:32=1000') b = BitArray(bfloatle=1000) self.assertEqual(a[16:32], b) self.assertEqual(b.bfloatle, 1000.0) b.byteswap() self.assertEqual(b.bfloat, 1000.0) self.assertEqual(b.bfloatbe, 1000.0) with self.assertRaises(bitstring.CreationError): _ = BitArray(bfloatle=-5, length=15) def testMoreCreation(self): a = BitArray('bfloat:16=1.0, bfloat16=2.0, bfloat=3.0') x, y, z = a.unpack('3*bfloat16') self.assertEqual((x, y, z), (1.0, 2.0, 3.0)) def testInterpretBug(self): a = BitArray(100) with self.assertRaises(bitstring.InterpretError): v = a.bfloat def testOverflows(self): s = BitArray() inf16 = BitArray(float=float('inf'), length=16) inf32 = BitArray(float=float('inf'), length=32) inf64 = BitArray(float=float('inf'), length=64) infbfloat = BitArray(bfloat=float('inf')) s.f64 = 1e400 self.assertEqual(s, inf64) s.f32 = 1e60 self.assertEqual(s, inf32) s.f16 = 100000 self.assertEqual(s, inf16) s.bfloat = 1e60 self.assertEqual(s, infbfloat) ninf16 = BitArray(float=float('-inf'), length=16) ninf32 = BitArray(float=float('-inf'), length=32) ninf64 = BitArray(float=float('-inf'), length=64) ninfbfloat = BitArray(bfloat=float('-inf')) s.f64 = -1e400 self.assertEqual(s, ninf64) s.f32 = -1e60 self.assertEqual(s, ninf32) s.f16 = -100000 self.assertEqual(s, ninf16) s.bfloat = -1e60 self.assertEqual(s, ninfbfloat) def testBigEndianStringInitialisers(self): a = BitArray('bfloatbe=4.5') b = BitArray('bfloatbe:16=-2.25') self.assertEqual(a.bfloatbe, 4.5) self.assertEqual(b.bfloatbe, -2.25) def testLilleEndianStringInitialisers(self): a = BitArray('bfloatle=4.5') b = BitArray('bfloatle:16=-2.25') self.assertEqual(a.bfloatle, 4.5) self.assertEqual(b.bfloatle, -2.25) def testNativeEndianStringInitialisers(self): a = BitArray('bfloatne=4.5') b = BitArray('bfloatne:16=-2.25') self.assertEqual(a.bfloatne, 4.5) self.assertEqual(b.bfloatne, -2.25) THIS_DIR = os.path.dirname(os.path.abspath(__file__)) class BitarrayTests(unittest.TestCase): def tearDown(self) -> None: bitstring.lsb0 = False def testToBitarray(self): a = BitArray('0xff, 0b0') b = a.tobitarray() self.assertEqual(type(b), bitarray.bitarray) self.assertEqual(b, bitarray.bitarray('111111110')) def testToBitarrayLSB0(self): bitstring.lsb0 = True a = bitstring.Bits('0xff, 0b0') b = a.tobitarray() self.assertEqual(type(b), bitarray.bitarray) self.assertEqual(b, bitarray.bitarray('111111110')) def testFromFile(self): a = bitstring.ConstBitStream(filename=os.path.join(THIS_DIR, 'smalltestfile')) b = a.tobitarray() self.assertEqual(a.bin, b.to01()) def testWithOffset(self): a = bitstring.ConstBitStream(filename=os.path.join(THIS_DIR, 'smalltestfile')) b = bitstring.ConstBitStream(filename=os.path.join(THIS_DIR, 'smalltestfile'), offset=11) self.assertEqual(len(a), len(b) + 11) self.assertEqual(a[11:].tobitarray(), b.tobitarray()) def testWithLength(self): a = bitstring.ConstBitStream(filename=os.path.join(THIS_DIR, 'smalltestfile')) b = bitstring.ConstBitStream(filename=os.path.join(THIS_DIR, 'smalltestfile'), length=11) self.assertEqual(len(b), 11) self.assertEqual(a[:11].tobitarray(), b.tobitarray()) def testWithOffsetAndLength(self): a = bitstring.ConstBitStream(filename=os.path.join(THIS_DIR, 'smalltestfile')) b = bitstring.ConstBitStream(filename=os.path.join(THIS_DIR, 'smalltestfile'), offset=17, length=7) self.assertEqual(len(b), 7) self.assertEqual(a[17:24].tobitarray(), b.tobitarray()) try: import numpy as np numpy_installed = True except ImportError: numpy_installed = False class Numpy(unittest.TestCase): @unittest.skipIf(not numpy_installed, "numpy not installed.") def testGetting(self): a = BitArray('0b110') p = np.int_(1) self.assertEqual(a[p], True) p = np.short(0) self.assertEqual(a[p], True) @unittest.skipIf(not numpy_installed, "numpy not installed.") def testSetting(self): a = BitArray('0b110') p = np.int_(1) a[p] = '0b1111' self.assertEqual(a, '0b111110') @unittest.skipIf(not numpy_installed, "numpy not installed.") def testCreation(self): a = BitArray(np.longlong(12)) self.assertEqual(a.hex, '000')bitstring-bitstring-4.1.4/tests/test_bits.py000066400000000000000000000655651453167633600213030ustar00rootroot00000000000000#!/usr/bin/env python import io import unittest import sys import bitarray import bitstring import array import os from bitstring import InterpretError, Bits, BitArray sys.path.insert(0, '..') THIS_DIR = os.path.dirname(os.path.abspath(__file__)) class Creation(unittest.TestCase): def testCreationFromBytes(self): s = Bits(bytes=b'\xa0\xff') self.assertEqual((s.len, s.hex), (16, 'a0ff')) s = Bits(bytes=b'abc', length=0) self.assertEqual(s, '') def testCreationFromBytesErrors(self): with self.assertRaises(bitstring.CreationError): Bits(bytes=b'abc', length=25) def testCreationFromDataWithOffset(self): s1 = Bits(bytes=b'\x0b\x1c\x2f', offset=0, length=20) s2 = Bits(bytes=b'\xa0\xb1\xC2', offset=4) self.assertEqual((s2.len, s2.hex), (20, '0b1c2')) self.assertEqual((s1.len, s1.hex), (20, '0b1c2')) self.assertTrue(s1 == s2) def testCreationFromHex(self): s = Bits(hex='0xA0ff') self.assertEqual((s.len, s.hex), (16, 'a0ff')) s = Bits(hex='0x0x0X') self.assertEqual((s.length, s.hex), (0, '')) def testCreationFromHexWithWhitespace(self): s = Bits(hex=' \n0 X a 4e \r3 \n') self.assertEqual(s.hex, 'a4e3') def testCreationFromHexErrors(self): with self.assertRaises(bitstring.CreationError): Bits(hex='0xx0') with self.assertRaises(bitstring.CreationError): Bits(hex='0xX0') with self.assertRaises(bitstring.CreationError): Bits(hex='0Xx0') with self.assertRaises(bitstring.CreationError): Bits(hex='-2e') with self.assertRaises(bitstring.CreationError): Bits('0x2', length=2) with self.assertRaises(bitstring.CreationError): Bits('0x3', offset=1) def testCreationFromBin(self): s = Bits(bin='1010000011111111') self.assertEqual((s.length, s.hex), (16, 'a0ff')) s = Bits(bin='00')[:1] self.assertEqual(s.bin, '0') s = Bits(bin=' 0000 \n 0001\r ') self.assertEqual(s.bin, '00000001') def testCreationFromBinWithWhitespace(self): s = Bits(bin=' \r\r\n0 B 00 1 1 \t0 ') self.assertEqual(s.bin, '00110') def testCreationFromOctErrors(self): s = Bits('0b00011') with self.assertRaises(bitstring.InterpretError): _ = s.oct with self.assertRaises(bitstring.CreationError): _ = Bits('oct=8') def testCreationFromUintWithOffset(self): with self.assertRaises(bitstring.CreationError): Bits(uint=12, length=8, offset=1) def testCreationFromUintErrors(self): with self.assertRaises(bitstring.CreationError): Bits(uint=-1, length=10) with self.assertRaises(bitstring.CreationError): Bits(uint=12) with self.assertRaises(bitstring.CreationError): Bits(uint=4, length=2) with self.assertRaises(bitstring.CreationError): Bits(uint=0, length=0) with self.assertRaises(bitstring.CreationError): Bits(uint=12, length=-12) def testCreationFromInt(self): s = Bits(int=0, length=4) temp = s.hex self.assertEqual(s.bin, '0000') s = Bits(int=1, length=2) self.assertEqual(s.bin, '01') s = Bits(int=-1, length=11) self.assertEqual(s.bin, '11111111111') s = Bits(int=12, length=7) self.assertEqual(s.int, 12) s = Bits(int=-243, length=108) self.assertEqual((s.int, s.length), (-243, 108)) for length in range(6, 10): for value in range(-17, 17): s = Bits(int=value, length=length) self.assertEqual((s.int, s.length), (value, length)) _ = Bits(int=10, length=8) def testCreationFromIntErrors(self): with self.assertRaises(bitstring.CreationError): _ = Bits(int=-1, length=0) with self.assertRaises(bitstring.CreationError): _ = Bits(int=12) with self.assertRaises(bitstring.CreationError): _ = Bits(int=4, length=3) with self.assertRaises(bitstring.CreationError): _ = Bits(int=-5, length=3) def testCreationFromSe(self): for i in range(-100, 10): s = Bits(se=i) self.assertEqual(s.se, i) def testCreationFromSeWithOffset(self): with self.assertRaises(bitstring.CreationError): Bits(se=-13, offset=1) def testCreationFromSeErrors(self): with self.assertRaises(bitstring.CreationError): Bits(se=-5, length=33) with self.assertRaises(bitstring.CreationError): Bits('se2=0') s = Bits(bin='001000') with self.assertRaises(bitstring.InterpretError): _ = s.se def testCreationFromUe(self): [self.assertEqual(Bits(ue=i).ue, i) for i in range(0, 20)] def testCreationFromUeWithOffset(self): with self.assertRaises(bitstring.CreationError): Bits(ue=104, offset=2) def testCreationFromUeErrors(self): with self.assertRaises(bitstring.CreationError): Bits(ue=-1) with self.assertRaises(bitstring.CreationError): Bits(ue=1, length=12) s = Bits(bin='10') with self.assertRaises(bitstring.InterpretError): _ = s.ue def testCreationFromBool(self): a = Bits('bool=1') self.assertEqual(a, 'bool=1') b = Bits('bool:1=0') self.assertEqual(b, [0]) c = bitstring.pack('bool=1, 2*bool', 0, 1) self.assertEqual(c, '0b101') d = bitstring.pack('bool:1=1, 2*bool1', 1, 0) self.assertEqual(d, '0b110') def testCreationFromBoolErrors(self): with self.assertRaises(ValueError): _ = Bits('bool=3') with self.assertRaises(bitstring.CreationError): _ = Bits(bool=0, length=2) def testCreationKeywordError(self): with self.assertRaises(bitstring.CreationError): Bits(squirrel=5) def testCreationFromBitarray(self): ba = bitarray.bitarray('0010') bs = Bits(ba) self.assertEqual(bs.bin, '0010') bs = Bits(ba, length=2) self.assertEqual(bs.bin, '00') bs2 = Bits(bitarray=ba) self.assertEqual(bs2.bin, '0010') def testCreationFromFrozenBitarray(self): fba = bitarray.frozenbitarray('111100001') ba = Bits(fba) self.assertEqual(ba.bin, '111100001') bs2 = Bits(bitarray=fba) self.assertEqual(bs2.bin, '111100001') bs3 = Bits(bitarray=fba, offset=4) self.assertEqual(bs3.bin, '00001') bs3 = Bits(bitarray=fba, offset=4, length=4) self.assertEqual(bs3.bin, '0000') def testCreationFromBitarrayErrors(self): ba = bitarray.bitarray('0101') with self.assertRaises(bitstring.CreationError): _ = Bits(bitarray=ba, length=5) with self.assertRaises(bitstring.CreationError): _ = Bits(bitarray=ba, offset=5) with self.assertRaises(bitstring.CreationError): _ = Bits(ba, length=-1) def testCreationFromMemoryview(self): x = bytes(bytearray(range(20))) m = memoryview(x[10:15]) b = Bits(m) self.assertEqual(b.unpack('5*u8'), [10, 11, 12, 13, 14]) class Initialisation(unittest.TestCase): def testEmptyInit(self): a = Bits() self.assertEqual(a, '') def testNoPos(self): a = Bits('0xabcdef') with self.assertRaises(AttributeError): _ = a.pos def testFind(self): a = Bits('0xabcd') r = a.find('0xbc') self.assertEqual(r[0], 4) r = a.find('0x23462346246', bytealigned=True) self.assertFalse(r) def testRfind(self): a = Bits('0b11101010010010') b = a.rfind('0b010') self.assertEqual(b[0], 11) def testFindAll(self): a = Bits('0b0010011') b = list(a.findall([1])) self.assertEqual(b, [2, 5, 6]) t = BitArray('0b10') tp = list(t.findall('0b1')) self.assertEqual(tp, [0]) class Cut(unittest.TestCase): def testCut(self): s = Bits('0b000111'*10) for t in s.cut(6): self.assertEqual(t.bin, '000111') class InterleavedExpGolomb(unittest.TestCase): def testCreation(self): s1 = Bits(uie=0) s2 = Bits(uie=1) self.assertEqual(s1, [1]) self.assertEqual(s2, [0, 0, 1]) s1 = Bits(sie=0) s2 = Bits(sie=-1) s3 = Bits(sie=1) self.assertEqual(s1, [1]) self.assertEqual(s2, [0, 0, 1, 1]) self.assertEqual(s3, [0, 0, 1, 0]) def testCreationFromProperty(self): s = BitArray() s.uie = 45 self.assertEqual(s.uie, 45) s.sie = -45 self.assertEqual(s.sie, -45) def testInterpretation(self): for x in range(101): self.assertEqual(Bits(uie=x).uie, x) for x in range(-100, 100): self.assertEqual(Bits(sie=x).sie, x) def testErrors(self): for f in ['sie=100, 0b1001', '0b00', 'uie=100, 0b1001']: s = Bits(f) with self.assertRaises(bitstring.InterpretError): _ = s.sie with self.assertRaises(bitstring.InterpretError): _ = s.uie with self.assertRaises(ValueError): Bits(uie=-10) class FileBased(unittest.TestCase): def setUp(self): filename = os.path.join(THIS_DIR, 'smalltestfile') self.a = Bits(filename=filename) self.b = Bits(filename=filename, offset=16) self.c = Bits(filename=filename, offset=20, length=16) self.d = Bits(filename=filename, offset=20, length=4) def testCreationWithOffset(self): self.assertEqual(str(self.a), '0x0123456789abcdef') self.assertEqual(str(self.b), '0x456789abcdef') self.assertEqual(str(self.c), '0x5678') def testBitOperators(self): x = self.b[4:20] self.assertEqual(x, '0x5678') self.assertEqual((x & self.c).hex, self.c.hex) self.assertEqual(self.c ^ self.b[4:20], Bits(16)) self.assertEqual(self.a[23:36] | self.c[3:], self.c[3:]) def testAddition(self): _ = self.d + '0x1' x = self.a[20:24] + self.c[-4:] + self.c[8:12] self.assertEqual(x, '0x587') x = self.b + x self.assertEqual(x.h, '456789abcdef587') x = BitArray(x) del x[12:24] self.assertEqual(x, '0x456abcdef587') class Comparisons(unittest.TestCase): def testUnorderable(self): a = Bits(5) b = Bits(5) with self.assertRaises(TypeError): _ = a < b with self.assertRaises(TypeError): _ = a > b with self.assertRaises(TypeError): _ = a <= b with self.assertRaises(TypeError): _ = a >= b class Subclassing(unittest.TestCase): def testIsInstance(self): class SubBits(bitstring.Bits): pass a = SubBits() self.assertTrue(isinstance(a, SubBits)) def testClassType(self): class SubBits(bitstring.Bits): pass self.assertEqual(SubBits().__class__, SubBits) class LongBoolConversion(unittest.TestCase): def testLongBool(self): a = Bits(1000) b = bool(a) self.assertTrue(b is True) class PadToken(unittest.TestCase): def testCreation(self): a = Bits('pad:10') self.assertEqual(a, Bits(10)) b = Bits('pad:0') self.assertEqual(b, Bits()) c = Bits('0b11, pad:1, 0b111') self.assertEqual(c, Bits('0b110111')) def testPack(self): s = bitstring.pack('0b11, pad:3=5, 0b1') self.assertEqual(s.bin, '110001') d = bitstring.pack('pad:c', c=12) self.assertEqual(d, Bits(12)) e = bitstring.pack('0xf, uint12, pad:1, bin, pad4, 0b10', 0, '111') self.assertEqual(e.bin, '11110000000000000111000010') def testUnpack(self): s = Bits('0b111000111') x, y = s.unpack('3, pad:3, 3') self.assertEqual((x, y.u), ('0b111', 7)) x, y = s.unpack('2, pad2, bin') self.assertEqual((x.u2, y), (3, '00111')) x = s.unpack('pad:1, pad:2, pad:3') self.assertEqual(x, []) def testUnpackBug(self): t = Bits('0o755, ue=12, int3=-1') a, b = t.unpack('pad:9, ue, int3') self.assertEqual((a, b), (12, -1)) class ModifiedByAddingBug(unittest.TestCase): def testAdding(self): a = Bits('0b0') b = Bits('0b11') c = a + b self.assertEqual(c, '0b011') self.assertEqual(a, '0b0') self.assertEqual(b, '0b11') def testAdding2(self): a = Bits(100) b = Bits(101) c = a + b self.assertEqual(a, Bits(100)) self.assertEqual(b, Bits(101)) self.assertEqual(c, Bits(201)) class WrongTypeBug(unittest.TestCase): def testAppendToBits(self): a = Bits(BitArray()) with self.assertRaises(AttributeError): a.append('0b1') self.assertEqual(type(a), Bits) b = bitstring.ConstBitStream(bitstring.BitStream()) self.assertEqual(type(b), bitstring.ConstBitStream) class InitFromArray(unittest.TestCase): def testEmptyArray(self): a = array.array('B') b = Bits(a) self.assertEqual(b.length, 0) def testSingleByte(self): a = array.array('B', b'\xff') b = Bits(a) self.assertEqual(b.length, 8) self.assertEqual(b.hex, 'ff') def testSignedShort(self): a = array.array('h') a.append(10) a.append(-1) b = Bits(a) self.assertEqual(b.length, 32) self.assertEqual(b.bytes, a.tobytes()) def testDouble(self): a = array.array('d', [0.0, 1.0, 2.5]) b = Bits(a) self.assertEqual(b.length, 192) c, d, e = b.unpack('3*floatne:64') self.assertEqual((c, d, e), (0.0, 1.0, 2.5)) class Iteration(unittest.TestCase): def testIterateEmptyBits(self): self.assertEqual(list(Bits([])), []) self.assertEqual(list(Bits([1, 0])[1:1]), []) def testIterateNonEmptyBits(self): self.assertEqual(list(Bits([1, 0])), [True, False]) self.assertEqual(list(Bits([1, 0, 0, 1])[1:3]), [False, False]) def testIterateLongBits(self): self.assertEqual( list(Bits([1, 0]) * 1024), [True, False] * 1024 ) class ContainsBug(unittest.TestCase): def testContains(self): a = Bits('0b1, 0x0001dead0001') self.assertTrue('0xdead' in a) self.assertFalse('0xfeed' in a) self.assertTrue('0b1' in Bits('0xf')) self.assertFalse('0b0' in Bits('0xf')) class ByteStoreImmutablity(unittest.TestCase): # def testBitsDataStoreType(self): # a = Bits('0b1') # b = Bits('0b111') # c = a + b # self.assertEqual(type(a._datastore), ByteStore) # self.assertEqual(type(b._datastore), ByteStore) # self.assertEqual(type(c._datastore), ByteStore) def testImmutabilityBugAppend(self): a = Bits('0b111') b = a + '0b000' c = BitArray(b) c[1] = 0 self.assertEqual(c.bin, '101000') self.assertEqual(a.b3, '111') self.assertEqual(b.bin, '111000') # self.assertEqual(type(b._datastore), ByteStore) def testImmutabilityBugPrepend(self): a = Bits('0b111') b = '0b000' + a c = BitArray(b) c[1] = 1 self.assertEqual(b.bin, '000111') self.assertEqual(c.bin, '010111') def testImmutabilityBugCreation(self): a = Bits() # self.assertEqual(type(a._datastore), ByteStore) class Lsb0Indexing(unittest.TestCase): @classmethod def setUpClass(cls): bitstring.lsb0 = True @classmethod def tearDownClass(cls): bitstring.lsb0 = False def testGetSingleBit(self): a = Bits('0b000001111') self.assertEqual(a[0], True) self.assertEqual(a[3], True) self.assertEqual(a[4], False) self.assertEqual(a[8], False) with self.assertRaises(IndexError): _ = a[9] self.assertEqual(a[-1], False) self.assertEqual(a[-5], False) self.assertEqual(a[-6], True) self.assertEqual(a[-9], True) with self.assertRaises(IndexError): _ = a[-10] def testSimpleSlicing(self): a = Bits('0xabcdef') self.assertEqual(a[0:4], '0xf') self.assertEqual(a[4:8], '0xe') self.assertEqual(a[:], '0xabcdef') self.assertEqual(a[4:], '0xabcde') self.assertEqual(a[-4:], '0xa') self.assertEqual(a[-8:-4], '0xb') self.assertEqual(a[:-8], '0xcdef') def testExtendedSlicing(self): a = Bits('0b100000100100100') self.assertEqual(a[2::3], '0b10111') def testAll(self): a = Bits('0b000111') self.assertTrue(a.all(1, [0, 1, 2])) self.assertTrue(a.all(0, [3, 4, 5])) def testAny(self): a = Bits('0b00000110') self.assertTrue(a.any(1, [0, 1])) self.assertTrue(a.any(0, [5, 6])) def testStartswith(self): a = Bits('0b0000000111') self.assertTrue(a.startswith('0b111')) self.assertFalse(a.startswith('0b0')) self.assertTrue(a.startswith('0b011', start=1)) self.assertFalse(a.startswith('0b0111', end=3)) self.assertTrue(a.startswith('0b0111', end=4)) def testEndsWith(self): a = Bits('0x1234abcd') self.assertTrue(a.endswith('0x123')) self.assertFalse(a.endswith('0xabcd')) class Lsb0Interpretations(unittest.TestCase): @classmethod def setUpClass(cls): bitstring.lsb0 = True @classmethod def tearDownClass(cls): bitstring.lsb0 = False def testUint(self): a = Bits('0x01') self.assertEqual(a, '0b00000001') self.assertEqual(a.uint, 1) self.assertEqual(a[0], True) def testFloat(self): a = Bits(float=0.25, length=32) try: bitstring.lsb0 = False b = Bits(float=0.25, length=32) finally: bitstring.lsb0 = True self.assertEqual(a.float, 0.25) self.assertEqual(b.float, 0.25) self.assertEqual(a.bin, b.bin) def testGolomb(self): with self.assertRaises(bitstring.CreationError): _ = Bits(ue=2) with self.assertRaises(bitstring.CreationError): _ = Bits(se=2) with self.assertRaises(bitstring.CreationError): _ = Bits(uie=2) with self.assertRaises(bitstring.CreationError): _ = Bits(sie=2) def testBytes(self): a = Bits('0xabcdef') b = a.bytes self.assertEqual(b, b'\xab\xcd\xef') b = a.bytes3 self.assertEqual(b, b'\xab\xcd\xef') class UnderscoresInLiterals(unittest.TestCase): def testHexCreation(self): a = Bits(hex='ab_cd__ef') self.assertEqual(a.hex, 'abcdef') b = Bits('0x0102_0304') self.assertEqual(b.uint, 0x0102_0304) def testBinaryCreation(self): a = Bits(bin='0000_0001_0010') self.assertEqual(a.bin, '000000010010') b = Bits('0b0011_1100_1111_0000') self.assertEqual(b.bin, '0011110011110000') v = 0b1010_0000 c = Bits(uint=0b1010_0000, length=8) self.assertEqual(c.uint, v) def testOctalCreation(self): a = Bits(oct='0011_2233_4455_6677') self.assertEqual(a.uint, 0o001122334455_6677) b = Bits('0o123_321_123_321') self.assertEqual(b.uint, 0o123_321_123321) class PrettyPrinting(unittest.TestCase): def testSimplestCases(self): a = Bits('0b101011110000') s = io.StringIO() a.pp(stream=s) self.assertEqual(s.getvalue(), ' 0: 10101111 0000 af 0\n') s = io.StringIO() a.pp('hex', stream=s) self.assertEqual(s.getvalue(), ' 0: af 0\n') s = io.StringIO() a.pp('oct', stream=s) self.assertEqual(s.getvalue(), ' 0: 5360\n') def testSmallWidth(self): a = Bits(20) s = io.StringIO() a.pp(fmt='b', stream=s, width=5) self.assertEqual(s.getvalue(), ' 0: 00000000\n' ' 8: 00000000\n' '16: 0000 \n') def testSeparator(self): a = Bits('0x0f0f')*9 s = io.StringIO() a.pp('hex:32', sep='!-!', stream=s) self.assertEqual(s.getvalue(), ' 0: 0f0f0f0f!-!0f0f0f0f!-!0f0f0f0f!-!0f0f0f0f!-!0f0f\n') def testMultiLine(self): a = Bits(100) s = io.StringIO() a.pp('bin', sep='', stream=s, width=80) self.assertEqual(s.getvalue(), ' 0: 000000000000000000000000000000000000000000000000000000000000000000000000\n' ' 72: 0000000000000000000000000000 \n') def testMultiformat(self): a = Bits('0b1111000011110000') s = io.StringIO() a.pp(stream=s, fmt='bin, hex') self.assertEqual(s.getvalue(), ' 0: 11110000 11110000 f0 f0\n') s = io.StringIO() a.pp(stream=s, fmt='hex, bin:12') self.assertEqual(s.getvalue(), ' 0: f0f 0 111100001111 0000\n') def testMultiLineMultiFormat(self): a = Bits(int=-1, length=112) s = io.StringIO() a.pp(stream=s, fmt='bin:8, hex:8', width=42) self.assertEqual(s.getvalue(), ' 0: 11111111 11111111 11111111 ff ff ff\n' ' 24: 11111111 11111111 11111111 ff ff ff\n' ' 48: 11111111 11111111 11111111 ff ff ff\n' ' 72: 11111111 11111111 11111111 ff ff ff\n' ' 96: 11111111 11111111 ff ff \n') s = io.StringIO() a.pp(stream=s, fmt='bin, hex', width=41) self.assertEqual(s.getvalue(), ' 0: 11111111 11111111 ff ff\n' ' 16: 11111111 11111111 ff ff\n' ' 32: 11111111 11111111 ff ff\n' ' 48: 11111111 11111111 ff ff\n' ' 64: 11111111 11111111 ff ff\n' ' 80: 11111111 11111111 ff ff\n' ' 96: 11111111 11111111 ff ff\n') a = bytearray(range(0, 256)) b = Bits(bytes=a) s = io.StringIO() b.pp(stream=s, fmt='bytes') self.assertEqual(s.getvalue(), """ 0: ĀāĂă ĄąĆć ĈĉĊċ ČčĎď ĐđĒē ĔĕĖė ĘęĚě ĜĝĞğ !"# $%&' ()*+ ,-./ 0123 4567 89:; <=>? @ABC DEFG HIJK LMNO PQRS TUVW XYZ[ 736: \]^_ `abc defg hijk lmno pqrs tuvw xyz{ |}~ſ ƀƁƂƃ ƄƅƆƇ ƈƉƊƋ ƌƍƎƏ ƐƑƒƓ ƔƕƖƗ Ƙƙƚƛ ƜƝƞƟ ƠơƢƣ ƤƥƦƧ ƨƩƪƫ ƬƭƮƯ ưƱƲƳ ƴƵƶƷ 1472: Ƹƹƺƻ Ƽƽƾƿ ǀǁǂǃ DŽDždžLJ LjljNJNj njǍǎǏ ǐǑǒǓ ǔǕǖǗ ǘǙǚǛ ǜǝǞǟ ǠǡǢǣ ǤǥǦǧ ǨǩǪǫ ǬǭǮǯ ǰDZDzdz ǴǵǶǷ ǸǹǺǻ ǼǽǾÿ \n""") def testGroupSizeErrors(self): a = Bits(120) with self.assertRaises(ValueError): a.pp('hex:3') with self.assertRaises(ValueError): a.pp('hex:4, oct') def testZeroGroupSize(self): a = Bits(600) s = io.StringIO() a.pp('b0', stream=s, show_offset=False) expected_output = ('0' * 120 + '\n') * 5 self.assertEqual(s.getvalue(), expected_output) a = Bits(400) s = io.StringIO() a.pp(stream=s, fmt='hex:0', show_offset=False, width=80) expected_output = ('0' * 80 + '\n') + ('0' * 20 + ' ' * 60 + '\n') self.assertEqual(s.getvalue(), expected_output) s = io.StringIO() a = Bits(uint=10, length=48) a.pp(stream=s, width=20, fmt='hex:0, oct:0', show_offset=False) expected_output = ("000000 00000000\n" "00000a 00000012\n") self.assertEqual(s.getvalue(), expected_output) def testOct(self): a = Bits('0o01234567'*20) s = io.StringIO() a.pp(stream=s, fmt='o', show_offset=False, width=20) expected_output = "0123 4567 0123 4567\n" * 10 self.assertEqual(s.getvalue(), expected_output) t = io.StringIO() a.pp('h, oct:0', width=1, show_offset=False, stream=t) expected_output = "053977 01234567\n" * 20 self.assertEqual(t.getvalue(), expected_output) def testBytes(self): a = Bits(bytes=b'helloworld!!'*5) s = io.StringIO() a.pp(stream=s, fmt='bytes', show_offset=False, width=48) expected_output = ("hell owor ld!! hell owor ld!! hell owor ld!!\n" "hell owor ld!! hell owor ld!! \n") self.assertEqual(s.getvalue(), expected_output) s = io.StringIO() a.pp(stream=s, fmt='bytes0', show_offset=False, width=40) expected_output = ("helloworld!!helloworld!!helloworld!!hell\n" "oworld!!helloworld!! \n") self.assertEqual(s.getvalue(), expected_output) class PrettyPrintingErrors(unittest.TestCase): def testWrongFormats(self): a = Bits('0x12341234') with self.assertRaises(ValueError): a.pp('binary') with self.assertRaises(ValueError): a.pp('bin, bin, bin') def testInterpretProblems(self): a = Bits(7) with self.assertRaises(InterpretError): a.pp('oct') with self.assertRaises(InterpretError): a.pp('hex') with self.assertRaises(InterpretError): a.pp('bin, bytes') class PrettyPrinting_LSB0(unittest.TestCase): def setUp(self) -> None: bitstring.lsb0 = True def tearDown(self) -> None: bitstring.lsb0 = False def test_bin(self): a = Bits(bin='1111 0000 0000 1111 1010') s = io.StringIO() a.pp('bin', stream=s, width=5) self.assertEqual(s.getvalue(), '11111010 : 0\n' '00000000 : 8\n' ' 1111 :16\n') class Copy(unittest.TestCase): def testCopyMethod(self): s = Bits('0xc00dee') t = s.copy() self.assertEqual(s, t) class NativeEndianIntegers(unittest.TestCase): def testUintne(self): s = Bits(uintne=454, length=160) t = Bits('uintne160=454') self.assertEqual(s, t) def testIntne(self): s = Bits(intne=-1000, length=64) t = Bits('intne:64=-1000') self.assertEqual(s, t) class NonNativeEndianIntegers(unittest.TestCase): def setUp(self) -> None: bitstring.bits.byteorder = 'little' if bitstring.bits.byteorder == 'big' else 'little' def tearDown(self) -> None: self.setUp() def testUintne(self): s = Bits(uintne=454, length=160) t = Bits('uintne160=454') self.assertEqual(s, t) def testIntne(self): s = Bits(intne=-1000, length=64) t = Bits('intne:64=-1000') self.assertEqual(s, t) bitstring-bitstring-4.1.4/tests/test_bitstore.py000066400000000000000000000061351453167633600221610ustar00rootroot00000000000000#!/usr/bin/env python import unittest import sys sys.path.insert(0, '..') import bitstring from bitstring.bitstore import BitStore, offset_slice_indices_lsb0 import sys sys.path.insert(0, '..') class BasicFunctionality(unittest.TestCase): def testGettingInt(self): a = BitStore('001') self.assertEqual(a.getindex(0), 0) self.assertEqual(a.getindex(1), 0) self.assertEqual(a.getindex(2), 1) self.assertEqual(a.getindex(-1), 1) self.assertEqual(a.getindex(-2), 0) self.assertEqual(a.getindex(-3), 0) with self.assertRaises(IndexError): _ = a.getindex(3) with self.assertRaises(IndexError): _ = a.getindex(-4) class BasicLSB0Functionality(unittest.TestCase): @classmethod def setUpClass(cls): bitstring.lsb0 = True @classmethod def tearDownClass(cls): bitstring.lsb0 = False def testGettingInt(self): a = BitStore('001') self.assertEqual(a.getindex(0), 1) self.assertEqual(a.getindex(1), 0) self.assertEqual(a.getindex(2), 0) self.assertEqual(a.getindex(-1), 0) self.assertEqual(a.getindex(-2), 0) self.assertEqual(a.getindex(-3), 1) with self.assertRaises(IndexError): _ = a.getindex(3) with self.assertRaises(IndexError): _ = a.getindex(-4) def testGettingSlice(self): a = BitStore(buffer=b'12345678') self.assertEqual(a.getslice(slice(None, None, None)).tobytes(), b'12345678') self.assertEqual(a.getslice(slice(None, -8, None)).tobytes(), b'2345678') self.assertEqual(a.getslice(slice(8, None, None)).tobytes(), b'1234567') self.assertEqual(a.getslice(slice(16, 24, None)).tobytes(), b'6') def testSettingInt(self): a = BitStore('00000') a[0] = 1 self.assertEqual(a.to01(), '00001') a[-1] = 1 self.assertEqual(a.to01(), '10001') with self.assertRaises(IndexError): a[5] = 1 with self.assertRaises(IndexError): a[-6] = 0 class GettingSlices(unittest.TestCase): def tearDown(self) -> None: bitstring.lsb0 = False def testEverything(self): a = BitStore('010010001000110111001111101101001111') # Try combination of start and stop for msb0 and get the result. # Convert to start and stop needed for lsb0 options = [5, 2, -2, 1, 7, -3, -9, 0, -1, -len(a), len(a), len(a) - 1, -len(a) - 1, -100, 100, None] for start_option in options: for end_option in options: bitstring.lsb0 = True lsb0 = a.getslice(slice(start_option, end_option, None)) bitstring.lsb0 = False msb0 = a.getslice(slice(start_option, end_option, None)) new_slice = offset_slice_indices_lsb0(slice(start_option, end_option, None), len(a), 0) new_start, new_end = new_slice.start, new_slice.stop self.assertEqual(len(msb0), len(lsb0), f"[{start_option}: {end_option}] -> [{new_start}: {new_end}] len(msb0)={len(msb0)}, len(lsb0)={len(lsb0)}")bitstring-bitstring-4.1.4/tests/test_bitstream.py000066400000000000000000004313531453167633600223240ustar00rootroot00000000000000#!/usr/bin/env python import unittest import sys sys.path.insert(0, '..') import bitstring import copy import os import collections from bitstring import Bits, BitStream, ConstBitStream, pack THIS_DIR = os.path.dirname(os.path.abspath(__file__)) class FlexibleInitialisation(unittest.TestCase): def testFlexibleInitialisation(self): a = BitStream('uint:8=12') c = BitStream(' uint : 8 = 12') self.assertTrue(a == c == BitStream(uint=12, length=8)) self.assertEqual(a.uint, 12) a = BitStream(' int:2= -1') b = BitStream('int :2 = -1') c = BitStream(' int: 2 =-1 ') self.assertTrue(a == b == c == BitStream(int=-1, length=2)) def testFlexibleInitialisation2(self): h = BitStream('hex=12') o = BitStream('oct=33') b = BitStream('bin=10') self.assertEqual(h, '0x12') self.assertEqual(o, '0o33') self.assertEqual(b, '0b10') def testFlexibleInitialisation3(self): for s in ['se=-1', ' se = -1 ', 'se = -1']: a = BitStream(s) self.assertEqual(a.se, -1) for s in ['ue=23', 'ue =23', 'ue = 23']: a = BitStream(s) self.assertEqual(a.ue, 23) def testMultipleStringInitialisation(self): a = BitStream('0b1 , 0x1') self.assertEqual(a, '0b10001') a = BitStream('ue=5, ue=1, se=-2') self.assertEqual(a.read('ue'), 5) self.assertEqual(a.read('ue'), 1) self.assertEqual(a.read('se'), -2) b = BitStream('uint:32 = 12, 0b11') + 'int:100=-100, 0o44' self.assertEqual(b.read(32).uint, 12) self.assertEqual(b.read(2).bin, '11') self.assertEqual(b.read(100).int, -100) class Reading(unittest.TestCase): def testReadBits(self): s = BitStream(bytes=b'\x4d\x55') self.assertEqual(s.read(4).hex, '4') self.assertEqual(s.read(8).hex, 'd5') self.assertEqual(s.read(1), [0]) self.assertEqual(s.read(3).bin, '101') self.assertFalse(s.read(0)) def testReadByte(self): s = BitStream(hex='4d55') self.assertEqual(s.read(8).hex, '4d') self.assertEqual(s.read(8).hex, '55') def testReadBytes(self): s = BitStream(hex='0x112233448811') self.assertEqual(s.read(3 * 8).hex, '112233') with self.assertRaises(ValueError): s.read(-16) s.bitpos += 1 self.assertEqual(s.read(2 * 8).bin, '1000100100010000') def testReadUE(self): with self.assertRaises(bitstring.InterpretError): _ = BitStream('').ue # The numbers 0 to 8 as unsigned Exponential-Golomb codes s = BitStream(bin='1 010 011 00100 00101 00110 00111 0001000 0001001') self.assertEqual(s.pos, 0) for i in range(9): self.assertEqual(s.read('ue'), i) with self.assertRaises(bitstring.ReadError): s.read('ue') def testReadSE(self): s = BitStream(bin='010 00110 0001010 0001000 00111') self.assertEqual(s.read('se'), 1) self.assertEqual(s.read('se'), 3) self.assertEqual(s.readlist(3 * ['se']), [5, 4, -3]) class Find(unittest.TestCase): def testFind1(self): s = ConstBitStream(bin='0b0000110110000') self.assertTrue(s.find(BitStream(bin='11011'))) self.assertEqual(s.bitpos, 4) self.assertEqual(s.read(5).bin, '11011') s.bitpos = 0 self.assertFalse(s.find('0b11001', False)) def testFind2(self): s = BitStream(bin='0') self.assertTrue(s.find(s, False)) self.assertEqual(s.pos, 0) self.assertFalse(s.find('0b00', False)) with self.assertRaises(ValueError): s.find(BitStream()) def testFindWithOffset(self): s = BitStream(hex='0x112233')[4:] self.assertTrue(s.find('0x23', False)) self.assertEqual(s.pos, 8) def testFindCornerCases(self): s = BitStream(bin='000111000111') self.assertTrue(s.find('0b000')) self.assertEqual(s.pos, 0) self.assertTrue(s.find('0b000')) self.assertEqual(s.pos, 0) self.assertTrue(s.find('0b0111000111')) self.assertEqual(s.pos, 2) self.assertTrue(s.find('0b000', start=2)) self.assertEqual(s.pos, 6) self.assertTrue(s.find('0b111', start=6)) self.assertEqual(s.pos, 9) s.pos += 2 self.assertTrue(s.find('0b1', start=s.pos)) def testFindBytes(self): s = BitStream('0x010203040102ff') self.assertFalse(s.find('0x05', bytealigned=True)) self.assertTrue(s.find('0x02', bytealigned=True)) self.assertEqual(s.read(16).hex, '0203') self.assertTrue(s.find('0x02', start=s.bitpos, bytealigned=True)) s.read(1) self.assertFalse(s.find('0x02', start=s.bitpos, bytealigned=True)) def testFindBytesAlignedCornerCases(self): s = BitStream('0xff') self.assertTrue(s.find(s)) self.assertFalse(s.find(BitStream(hex='0x12'))) self.assertFalse(s.find(BitStream(hex='0xffff'))) def testFindBytesBitpos(self): s = BitStream(hex='0x1122334455') s.pos = 2 s.find('0x66', bytealigned=True) self.assertEqual(s.pos, 2) s.pos = 38 s.find('0x66', bytealigned=True) self.assertEqual(s.pos, 38) def testFindByteAligned(self): s = BitStream(hex='0x12345678') self.assertTrue(s.find(BitStream(hex='0x56'), bytealigned=True)) self.assertEqual(s.bytepos, 2) s.pos = 0 self.assertFalse(s.find(BitStream(hex='0x45'), bytealigned=True)) s = BitStream('0x1234') s.find('0x1234') self.assertTrue(s.find('0x1234')) s += '0b111' s.pos = 3 s.find('0b1', start=17, bytealigned=True) self.assertFalse(s.find('0b1', start=17, bytealigned=True)) self.assertEqual(s.pos, 3) def testFindByteAlignedWithOffset(self): s = BitStream(hex='0x112233')[4:] self.assertTrue(s.find(BitStream(hex='0x23'))) def testFindByteAlignedErrors(self): s = BitStream(hex='0xffff') with self.assertRaises(ValueError): s.find('') with self.assertRaises(ValueError): s.find(BitStream()) class Rfind(unittest.TestCase): def testRfind(self): a = BitStream('0b001001001') b = a.rfind('0b001') self.assertEqual(b, (6,)) self.assertEqual(a.pos, 6) big = BitStream(length=100000) + '0x12' + BitStream(length=10000) found = big.rfind('0x12', bytealigned=True) self.assertEqual(found, (100000,)) self.assertEqual(big.pos, 100000) def testRfindByteAligned(self): a = BitStream('0x8888') b = a.rfind('0b1', bytealigned=True) self.assertEqual(b, (8,)) self.assertEqual(a.pos, 8) def testRfindStartbit(self): a = BitStream('0x0000ffffff') b = a.rfind('0x0000', start=1, bytealigned=True) self.assertEqual(b, ()) self.assertEqual(a.pos, 0) b = a.rfind('0x00', start=1, bytealigned=True) self.assertEqual(b, (8,)) self.assertEqual(a.pos, 8) def testRfindEndbit(self): a = BitStream('0x000fff') b = a.rfind('0b011', start=0, end=14, bytealigned=False) self.assertEqual(bool(b), True) b = a.rfind('0b011', 0, 13, False) self.assertEqual(b, ()) def testRfindErrors(self): a = BitStream('0x43234234') with self.assertRaises(ValueError): a.rfind('', bytealigned=True) with self.assertRaises(ValueError): a.rfind('0b1', start=-99, bytealigned=True) with self.assertRaises(ValueError): a.rfind('0b1', end=33, bytealigned=True) with self.assertRaises(ValueError): a.rfind('0b1', start=10, end=9, bytealigned=True) class Shift(unittest.TestCase): def testShiftLeft(self): s = BitStream('0b1010') t = s << 1 self.assertEqual(s.bin, '1010') self.assertEqual(t.bin, '0100') s = t << 0 self.assertEqual(s, '0b0100') t = s << 100 self.assertEqual(t.bin, '0000') def testShiftLeftErrors(self): s = BitStream() with self.assertRaises(ValueError): s << 1 s = BitStream('0xf') with self.assertRaises(ValueError): s << -1 def testShiftRight(self): s = BitStream('0b1010') t = s >> 1 self.assertEqual(s.bin, '1010') self.assertEqual(t.bin, '0101') q = s >> 0 self.assertEqual(q, '0b1010') q.replace('0b1010', '') t = s >> 100 self.assertEqual(t.bin, '0000') def testShiftRightErrors(self): s = BitStream() with self.assertRaises(ValueError): s >> 1 s = BitStream('0xf') with self.assertRaises(ValueError): s >> -1 def testShiftRightInPlace(self): s = BitStream('0xffff')[4:12] s >>= 1 self.assertEqual(s, '0b01111111') s = BitStream('0b11011') s >>= 2 self.assertEqual(s.bin, '00110') s >>= 100000000000000 self.assertEqual(s.bin, '00000') s = BitStream('0xff') s >>= 1 self.assertEqual(s, '0x7f') s >>= 0 self.assertEqual(s, '0x7f') def testShiftInPlaceWholeBitstring(self): s = BitStream('0xabcd') s >>= len(s) self.assertEqual(s, '0x0000') def testShiftRightInPlaceErrors(self): s = BitStream() with self.assertRaises(ValueError): s >>= 1 s += '0b11' with self.assertRaises(ValueError): s >>= -1 def testShiftLeftInPlace(self): s = BitStream('0xffff') t = s[4:12] t <<= 2 self.assertEqual(t, '0b11111100') s = BitStream('0b11011') s <<= 2 self.assertEqual(s.bin, '01100') s <<= 100000000000000000000 self.assertEqual(s.bin, '00000') s = BitStream('0xff') s <<= 1 self.assertEqual(s, '0xfe') s <<= 0 self.assertEqual(s, '0xfe') def testShiftLeftInPlaceErrors(self): s = BitStream() with self.assertRaises(ValueError): s <<= 1 s += '0b11' with self.assertRaises(ValueError): s <<= -1 class Replace(unittest.TestCase): def testReplace1(self): a = BitStream('0b1') n = a.replace('0b1', '0b0', bytealigned=True) self.assertEqual(a.bin, '0') self.assertEqual(n, 1) n = a.replace('0b1', '0b0', bytealigned=True) self.assertEqual(n, 0) def testReplace2(self): a = BitStream('0b00001111111') n = a.replace('0b1', '0b0', bytealigned=True) self.assertEqual(a.bin, '00001111011') self.assertEqual(n, 1) n = a.replace('0b1', '0b0', bytealigned=False) self.assertEqual(a.bin, '00000000000') self.assertEqual(n, 6) def testReplace3(self): a = BitStream('0b0') n = a.replace('0b0', '0b110011111', bytealigned=True) self.assertEqual(n, 1) self.assertEqual(a.bin, '110011111') n = a.replace('0b11', '', bytealigned=False) self.assertEqual(n, 3) self.assertEqual(a.bin, '001') def testReplace4(self): a = BitStream('0x00114723ef4732344700') n = a.replace('0x47', '0x00', bytealigned=True) self.assertEqual(n, 3) self.assertEqual(a.hex, '00110023ef0032340000') a.replace('0x00', '', bytealigned=True) self.assertEqual(a.hex, '1123ef3234') a.replace('0x11', '', start=1, bytealigned=True) self.assertEqual(a.hex, '1123ef3234') a.replace('0x11', '0xfff', end=7, bytealigned=True) self.assertEqual(a.hex, '1123ef3234') a.replace('0x11', '0xfff', end=8, bytealigned=True) self.assertEqual(a.hex, 'fff23ef3234') def testReplace5(self): a = BitStream('0xab') b = BitStream('0xcd') c = BitStream('0xabef') c.replace(a, b) self.assertEqual(c, '0xcdef') self.assertEqual(a, '0xab') self.assertEqual(b, '0xcd') a = BitStream('0x0011223344') a.pos = 12 a.replace('0x11', '0xfff', bytealigned=True) self.assertEqual(a.pos, 0) self.assertEqual(a, '0x00fff223344') def testReplaceWithSelf(self): a = BitStream('0b11') a.replace('0b1', a) self.assertEqual(a, '0xf') a.replace(a, a) self.assertEqual(a, '0xf') def testReplaceCount(self): a = BitStream('0x223344223344223344') n = a.replace('0x2', '0x0', count=0, bytealigned=True) self.assertEqual(n, 0) self.assertEqual(a.hex, '223344223344223344') n = a.replace('0x2', '0x0', count=1, bytealigned=True) self.assertEqual(n, 1) self.assertEqual(a.hex, '023344223344223344') n = a.replace('0x33', '', count=2, bytealigned=True) self.assertEqual(n, 2) self.assertEqual(a.hex, '02442244223344') n = a.replace('0x44', '0x4444', count=1435, bytealigned=True) self.assertEqual(n, 3) self.assertEqual(a.hex, '02444422444422334444') def testReplaceBitpos(self): a = BitStream('0xff') a.bitpos = 8 a.replace('0xff', '', bytealigned=True) self.assertEqual(a.bitpos, 0) a = BitStream('0b0011110001') a.bitpos = 4 a.replace('0b1', '0b000') self.assertEqual(a.bitpos, 0) a = BitStream('0b1') a.bitpos = 1 a.replace('0b1', '0b11111', bytealigned=True) self.assertEqual(a.bitpos, 0) a.replace('0b11', '0b0', False) self.assertEqual(a.bitpos, 0) a.append('0b00') a.pos = 5 a.replace('0b00', '0b11') self.assertEqual(a.bitpos, 5) def testReplaceErrors(self): a = BitStream('0o123415') with self.assertRaises(ValueError): a.replace('', Bits(0o7), bytealigned=True) with self.assertRaises(ValueError): a.replace('0b1', '0b1', start=-100, bytealigned=True) with self.assertRaises(ValueError): a.replace('0b1', '0b1', end=19, bytealigned=True) class SliceAssignment(unittest.TestCase): def testSetSlice(self): a = BitStream() a[0:0] = '0xabcdef' self.assertEqual(a.bytepos, 0) a[4:16] = '' self.assertEqual(a, '0xaef') self.assertEqual(a.bitpos, 0) a.pos = 4 a[8:] = '0x00' self.assertEqual(a, '0xae00') self.assertEqual(a.bitpos, 0) a += '0xf' self.assertEqual(a.bitpos, 20) a[8:] = '0xe' self.assertEqual(a, '0xaee') self.assertEqual(a.bitpos, 0) b = BitStream() b[0:800] = '0xffee' self.assertEqual(b, '0xffee') b[4:48] = '0xeed123' self.assertEqual(b, '0xfeed123') b[-800:8] = '0x0000' self.assertEqual(b, '0x0000ed123') a = BitStream('0xabcde') self.assertEqual(a[-100:-90], '') self.assertEqual(a[-100:-16], '0xa') a[-100:-16] = '0x0' self.assertEqual(a, '0x0bcde') def testInsertingUsingSetItem(self): a = BitStream() a[0:0] = '0xdeadbeef' self.assertEqual(a, '0xdeadbeef') self.assertEqual(a.bytepos, 0) a[16:16] = '0xfeed' self.assertEqual(a, '0xdeadfeedbeef') self.assertEqual(a.bytepos, 0) a[0:0] = '0xa' self.assertEqual(a, '0xadeadfeedbeef') self.assertEqual(a.bitpos, 0) a.bytepos = 6 a[0:8] = '0xff' self.assertEqual(a.bytepos, 6) a[8:0] = '0x000' self.assertTrue(a.startswith('0xff000ead')) def testSliceAssignmentBitPos(self): a = BitStream('int:64=-1') a.pos = 64 a[0:8] = '' self.assertEqual(a.pos, 0) a.pos = 52 a[-16:] = '0x0000' self.assertEqual(a.pos, 52) class Pack(unittest.TestCase): def testPack1(self): s = bitstring.pack('uint:6, bin, hex, int:6, se, ue, oct', 10, '0b110', 'ff', -1, -6, 6, '54') t = BitStream('uint:6=10, 0b110, 0xff, int:6=-1, se=-6, ue=6, oct=54') self.assertEqual(s, t) with self.assertRaises(ValueError): pack('tomato', '0') with self.assertRaises(ValueError): pack('uint', 12) with self.assertRaises(ValueError): pack('int', 12) with self.assertRaises(ValueError): pack('hex', 'penguin') with self.assertRaises(ValueError): pack('hex12', '0x12') def testPackWithLiterals(self): s = bitstring.pack('0xf') self.assertEqual(s, '0xf') self.assertTrue(type(s), BitStream) s = pack('0b1') self.assertEqual(s, '0b1') s = pack('0o7') self.assertEqual(s, '0o7') s = pack('int:10=-1') self.assertEqual(s, '0b1111111111') s = pack('uint:10=1') self.assertEqual(s, '0b0000000001') s = pack('ue=12') self.assertEqual(s.ue, 12) s = pack('se=-12') self.assertEqual(s.se, -12) s = pack('bin=01') self.assertEqual(s.bin, '01') s = pack('hex=01') self.assertEqual(s.hex, '01') s = pack('oct=01') self.assertEqual(s.oct, '01') def testPackWithDict(self): a = pack('uint:6=width, se=height', height=100, width=12) w, h = a.unpack('uint:6, se') self.assertEqual(w, 12) self.assertEqual(h, 100) d = {'w': '0xf', '300': 423, 'e': '0b1101'} a = pack('int:100=300, bin=e, uint:12=300', **d) x, y, z = a.unpack('int:100, bin, uint:12') self.assertEqual(x, 423) self.assertEqual(y, '1101') self.assertEqual(z, 423) def testPackWithDict2(self): a = pack('int:5, bin:3=b, 0x3, bin=c, se=12', 10, b='0b111', c='0b1') b = BitStream('int:5=10, 0b111, 0x3, 0b1, se=12') self.assertEqual(a, b) a = pack('bits:3=b', b=BitStream('0b101')) self.assertEqual(a, '0b101') a = pack('bits:24=b', b=BitStream('0x001122')) self.assertEqual(a, '0x001122') def testPackWithDict3(self): s = pack('hex:4=e, hex:4=0xe, hex:4=e', e='f') self.assertEqual(s, '0xfef') s = pack('sep', sep='0b00') self.assertEqual(s, '0b00') def testPackWithDict4(self): s = pack('hello', hello='0xf') self.assertEqual(s, '0xf') s = pack('x, y, x, y, x', x='0b10', y='uint:12=100') t = BitStream('0b10, uint:12=100, 0b10, uint:12=100, 0b10') self.assertEqual(s, t) a = [1, 2, 3, 4, 5] s = pack('int:8, div,' * 5, *a, **{'div': '0b1'}) t = BitStream('int:8=1, 0b1, int:8=2, 0b1, int:8=3, 0b1, int:8=4, 0b1, int:8=5, 0b1') self.assertEqual(s, t) def testPackWithLocals(self): width = 352 height = 288 s = pack('uint:12=width, uint:12=height', **locals()) self.assertEqual(s, '0x160120') def testPackWithLengthRestriction(self): _ = pack('bin:3', '0b000') with self.assertRaises(bitstring.CreationError): _ = pack('bin:3', '0b0011') with self.assertRaises(bitstring.CreationError): _ = pack('bin:3', '0b11') with self.assertRaises(bitstring.CreationError): _ = pack('bin:3=0b0011') with self.assertRaises(bitstring.CreationError): _ = pack('bin:3=0b11') _ = pack('hex:4', '0xf') with self.assertRaises(bitstring.CreationError): _ = pack('hex:4', '0b111') with self.assertRaises(bitstring.CreationError): _ = pack('hex:4', '0b11111') with self.assertRaises(bitstring.CreationError): _ = pack('hex:8=0xf') _ = pack('oct:6', '0o77') with self.assertRaises(bitstring.CreationError): _ = pack('oct:6', '0o1') with self.assertRaises(bitstring.CreationError): _ = pack('oct:6', '0o111') with self.assertRaises(bitstring.CreationError): _ = pack('oct:3', '0b1') with self.assertRaises(bitstring.CreationError): _ = pack('oct:3=hello', hello='0o12') _ = pack('bits:3', BitStream('0b111')) with self.assertRaises(bitstring.CreationError): _ = pack('bits:3', BitStream('0b11')) with self.assertRaises(bitstring.CreationError): _ = pack('bits:3', BitStream('0b1111')) with self.assertRaises(bitstring.CreationError): _ = pack('bits:12=b', b=BitStream('0b11')) def testPackNull(self): s = pack('') self.assertFalse(s) s = pack(',') self.assertFalse(s) s = pack(',,,,,0b1,,,,,,,,,,,,,0b1,,,,,,,,,,') self.assertEqual(s, '0b11') s = pack(',,uint:12,,bin:3,', 100, '100') a, b = s.unpack(',,,uint:12,,,,bin:3,,,') self.assertEqual(a, 100) self.assertEqual(b, '100') def testPackUint(self): s = pack('uint:10, uint:5', 1, 2) a, b = s.unpack('10, 5') self.assertEqual((a.uint, b.uint), (1, 2)) s = pack('uint:10=150, uint:12=qee', qee=3) self.assertEqual(s, 'uint:10=150, uint:12=3') t = BitStream('uint:100=5') self.assertEqual(t, 'uint:100=5') def testPackDefualtUintErrors(self): with self.assertRaises(bitstring.CreationError): _ = BitStream('5=-1') def testPackingLongKeywordBitstring(self): s = pack('bits=b', b=BitStream(128000)) self.assertEqual(s, BitStream(128000)) def testPackingWithListFormat(self): f = ['bin', 'hex', 'uint:10'] a = pack(','.join(f), '00', '234', 100) b = pack(f, '00', '234', 100) self.assertEqual(a, b) class Unpack(unittest.TestCase): def testUnpack1(self): s = BitStream('uint:13=23, hex=e, bin=010, int:41=-554, 0o44332, se=-12, ue=4') s.pos = 11 a, b, c, d, e, f, g = s.unpack('uint:13, hex:4, bin:3, int:41, oct:15, se, ue') self.assertEqual(a, 23) self.assertEqual(b, 'e') self.assertEqual(c, '010') self.assertEqual(d, -554) self.assertEqual(e, '44332') self.assertEqual(f, -12) self.assertEqual(g, 4) self.assertEqual(s.pos, 11) def testUnpack2(self): s = BitStream('0xff, 0b000, uint:12=100') a, b, c = s.unpack('bits:8, bits, uint:12') self.assertEqual(type(s), BitStream) self.assertEqual(a, '0xff') self.assertEqual(type(s), BitStream) self.assertEqual(b, '0b000') self.assertEqual(c, 100) a, b = s.unpack(['bits:11', 'uint']) self.assertEqual(a, '0xff, 0b000') self.assertEqual(b, 100) def testUnpackNull(self): s = pack('0b1, , , 0xf,') a, b = s.unpack('bin:1,,,hex:4,') self.assertEqual(a, '1') self.assertEqual(b, 'f') class FromFile(unittest.TestCase): def testCreationFromFileOperations(self): filename = os.path.join(THIS_DIR, 'smalltestfile') s = BitStream(filename=filename) s.append('0xff') self.assertEqual(s.hex, '0123456789abcdefff') s = ConstBitStream(filename=filename) t = BitStream('0xff') + s self.assertEqual(t.hex, 'ff0123456789abcdef') s = BitStream(filename=filename) del s[:1] self.assertEqual((BitStream('0b0') + s).hex, '0123456789abcdef') s = BitStream(filename=filename) del s[:7 * 8] self.assertEqual(s.hex, 'ef') s = BitStream(filename=filename) s.insert('0xc', 4) self.assertEqual(s.hex, '0c123456789abcdef') s = BitStream(filename=filename) s.prepend('0xf') self.assertEqual(s.hex, 'f0123456789abcdef') s = BitStream(filename=filename) s.overwrite('0xaaa', 12) self.assertEqual(s.hex, '012aaa6789abcdef') s = BitStream(filename=filename) s.reverse() self.assertEqual(s.hex, 'f7b3d591e6a2c480') s = BitStream(filename=filename) del s[-60:] self.assertEqual(s.hex, '0') s = BitStream(filename=filename) del s[:60] self.assertEqual(s.hex, 'f') def testFileProperties(self): s = ConstBitStream(filename=os.path.join(THIS_DIR, 'smalltestfile')) self.assertEqual(s.hex, '0123456789abcdef') self.assertEqual(s.uint, 81985529216486895) self.assertEqual(s.int, 81985529216486895) self.assertEqual(s.bin, '0000000100100011010001010110011110001001101010111100110111101111') self.assertEqual(s[:-1].oct, '002215053170465363367') s.bitpos = 0 self.assertEqual(s.read('se'), -72) s.bitpos = 0 self.assertEqual(s.read('ue'), 144) self.assertEqual(s.bytes, b'\x01\x23\x45\x67\x89\xab\xcd\xef') self.assertEqual(s.tobytes(), b'\x01\x23\x45\x67\x89\xab\xcd\xef') def testCreationFromFileWithLength(self): test_filename = os.path.join(THIS_DIR, 'test.m1v') s = ConstBitStream(filename=test_filename, length=32) self.assertEqual(s.length, 32) self.assertEqual(s.hex, '000001b3') s = ConstBitStream(filename=test_filename, length=0) self.assertFalse(s) small_test_filename = os.path.join(THIS_DIR, 'smalltestfile') with self.assertRaises(bitstring.CreationError): _ = BitStream(filename=small_test_filename, length=65) with self.assertRaises(bitstring.CreationError): _ = ConstBitStream(filename=small_test_filename, length=64, offset=1) with self.assertRaises(bitstring.CreationError): _ = ConstBitStream(filename=small_test_filename, offset=65) with open(small_test_filename, 'rb') as f: with self.assertRaises(bitstring.CreationError): _ = ConstBitStream(f, offset=65) with self.assertRaises(bitstring.CreationError): _ = ConstBitStream(f, length=65) with self.assertRaises(bitstring.CreationError): _ = ConstBitStream(f, offset=60, length=5) def testCreationFromFileWithOffset(self): filename = os.path.join(THIS_DIR, 'test.m1v') a = BitStream(filename=filename, offset=4) self.assertEqual(a.peek(4 * 8).hex, '00001b31') b = BitStream(filename=filename, offset=28) self.assertEqual(b.peek(8).hex, '31') def testFileSlices(self): s = BitStream(filename=os.path.join(THIS_DIR, 'smalltestfile')) self.assertEqual(s[-16:].hex, 'cdef') def testCreataionFromFileErrors(self): with self.assertRaises(IOError): _ = BitStream(filename='Idonotexist') def testFindInFile(self): s = BitStream(filename=os.path.join(THIS_DIR, 'test.m1v')) self.assertTrue(s.find('0x160120')) self.assertEqual(s.bytepos, 4) s3 = s.read(24) self.assertEqual(s3.hex, '160120') s.bytepos = 0 self.assertTrue(s._pos == 0) self.assertTrue(s.find('0x0001b2')) self.assertEqual(s.bytepos, 13) def testHexFromFile(self): s = BitStream(filename=os.path.join(THIS_DIR, 'test.m1v')) self.assertEqual(s[0:32].hex, '000001b3') self.assertEqual(s[-32:].hex, '000001b7') s.hex = '0x11' self.assertEqual(s.hex, '11') def testFileOperations(self): filename = os.path.join(THIS_DIR, 'test.m1v') s1 = BitStream(filename=filename) s2 = BitStream(filename=filename) self.assertEqual(s1.read(32).hex, '000001b3') self.assertEqual(s2.read(32).hex, '000001b3') s1.bytepos += 4 self.assertEqual(s1.read(8).hex, '02') self.assertEqual(s2.read(5 * 8).hex, '1601208302') s1.pos = s1.len with self.assertRaises(ValueError): s1.pos += 1 def testFileBitGetting(self): s = ConstBitStream(filename=os.path.join(THIS_DIR, 'smalltestfile'), offset=16, length=8) b = s[1] self.assertTrue(b) b = s.any(0, [-1, -2, -3]) self.assertTrue(b) b = s.all(0, [0, 1, 2]) self.assertFalse(b) class CreationErrors(unittest.TestCase): def testIncorrectBinAssignment(self): s = BitStream() with self.assertRaises(bitstring.CreationError): s._setbin_safe('0010020') def testIncorrectHexAssignment(self): s = BitStream() with self.assertRaises(bitstring.CreationError): s.hex = '0xabcdefg' class Length(unittest.TestCase): def testLengthZero(self): self.assertEqual(BitStream('').len, 0) def testLength(self): self.assertEqual(BitStream('0x80').len, 8) def testOffsetLengthError(self): with self.assertRaises(bitstring.CreationError): BitStream(hex='0xffff', offset=-1) class SimpleConversions(unittest.TestCase): def testConvertToUint(self): self.assertEqual(BitStream('0x10').uint, 16) self.assertEqual(BitStream('0b000111').uint, 7) def testConvertToInt(self): self.assertEqual(BitStream('0x10').int, 16) self.assertEqual(BitStream('0b11110').int, -2) def testConvertToHex(self): self.assertEqual(BitStream(bytes=b'\x00\x12\x23\xff').hex, '001223ff') s = BitStream('0b11111') with self.assertRaises(bitstring.InterpretError): _ = s.hex class Empty(unittest.TestCase): def testEmptyBitstring(self): s = BitStream() with self.assertRaises(bitstring.ReadError): s.read(1) self.assertEqual(s.bin, '') self.assertEqual(s.hex, '') with self.assertRaises(bitstring.InterpretError): _ = s.int with self.assertRaises(bitstring.InterpretError): _ = s.uint self.assertFalse(s) def testNonEmptyBitStream(self): s = BitStream(bin='0') self.assertFalse(not s.len) class Position(unittest.TestCase): def testBitPosition(self): s = BitStream(bytes=b'\x00\x00\x00') self.assertEqual(s.bitpos, 0) s.read(5) self.assertEqual(s.pos, 5) s.pos = s.len with self.assertRaises(bitstring.ReadError): s.read(1) def testBytePosition(self): s = BitStream(bytes=b'\x00\x00\x00') self.assertEqual(s.bytepos, 0) s.read(10) with self.assertRaises(bitstring.ByteAlignError): _ = s.bytepos s.read(6) self.assertEqual(s.bytepos, 2) def testSeekToBit(self): s = BitStream(bytes=b'\x00\x00\x00\x00\x00\x00') s.bitpos = 0 self.assertEqual(s.bitpos, 0) with self.assertRaises(ValueError): s.pos = -1 with self.assertRaises(ValueError): s.bitpos = 6 * 8 + 1 s.bitpos = 6 * 8 self.assertEqual(s.bitpos, 6 * 8) def testSeekToByte(self): s = BitStream(bytes=b'\x00\x00\x00\x00\x00\xab') s.bytepos = 5 self.assertEqual(s.read(8).hex, 'ab') def testAdvanceBitsAndBytes(self): s = BitStream(bytes=b'\x00\x00\x00\x00\x00\x00\x00\x00') s.pos += 5 self.assertEqual(s.pos, 5) s.bitpos += 16 self.assertEqual(s.pos, 2 * 8 + 5) s.pos -= 8 self.assertEqual(s.pos, 8 + 5) def testRetreatBitsAndBytes(self): a = BitStream(length=100) a.pos = 80 a.bytepos -= 5 self.assertEqual(a.bytepos, 5) a.pos -= 5 self.assertEqual(a.pos, 35) class Append(unittest.TestCase): def testAppend(self): s1 = BitStream('0b00000') s1.append(BitStream(bool=True)) self.assertEqual(s1.bin, '000001') self.assertEqual((BitStream('0x0102') + BitStream('0x0304')).hex, '01020304') def testAppendSameBitstring(self): s1 = BitStream('0xf0')[:6] s1.append(s1) self.assertEqual(s1.bin, '111100111100') def testAppendWithOffset(self): s = BitStream(bytes=b'\x28\x28', offset=1) s.append('0b0') self.assertEqual(s.hex, '5050') class ByteAlign(unittest.TestCase): def testByteAlign(self): s = BitStream(hex='0001ff23') s.bytealign() self.assertEqual(s.bytepos, 0) s.pos += 11 s.bytealign() self.assertEqual(s.bytepos, 2) s.pos -= 10 s.bytealign() self.assertEqual(s.bytepos, 1) def testInsertByteAligned(self): s = BitStream('0x0011') s.insert(BitStream('0x22'), 8) self.assertEqual(s.hex, '002211') s = BitStream(0) s.insert(BitStream(bin='101'), 0) self.assertEqual(s.bin, '101') class Truncate(unittest.TestCase): def testTruncateStart(self): s = BitStream('0b1') del s[0] self.assertFalse(s) s = BitStream(hex='1234') self.assertEqual(s.hex, '1234') del s[:4] self.assertEqual(s.hex, '234') del s[:9] self.assertEqual(s.bin, '100') del s[:2] self.assertEqual(s.bin, '0') self.assertEqual(s.len, 1) del s[:1] self.assertFalse(s) def testTruncateEnd(self): s = BitStream('0b1') del s[-1:] self.assertFalse(s) s = BitStream(bytes=b'\x12\x34') self.assertEqual(s.hex, '1234') del s[-4:] self.assertEqual(s.hex, '123') del s[-9:] self.assertEqual(s.bin, '000') del s[-3:] self.assertFalse(s) s = BitStream('0b001') del s[:2] del s[-1:] self.assertFalse(s) class Slice(unittest.TestCase): def testByteAlignedSlice(self): s = BitStream(hex='0x123456') self.assertEqual(s[8:16].hex, '34') s = s[8:24] self.assertEqual(s.len, 16) self.assertEqual(s.hex, '3456') s = s[0:8] self.assertEqual(s.hex, '34') s.hex = '0x123456' self.assertEqual(s[8:24][0:8].hex, '34') def testSlice(self): s = BitStream(bin='000001111100000') s1 = s[0:5] s2 = s[5:10] s3 = s[10:15] self.assertEqual(s1.bin, '00000') self.assertEqual(s2.bin, '11111') self.assertEqual(s3.bin, '00000') class Insert(unittest.TestCase): def testInsert(self): s1 = BitStream(hex='0x123456') s2 = BitStream(hex='0xff') s1.bytepos = 1 s1.insert(s2) self.assertEqual(s1.bytepos, 2) self.assertEqual(s1.hex, '12ff3456') s1.insert('0xee', 24) self.assertEqual(s1.hex, '12ff34ee56') self.assertEqual(s1.bitpos, 32) with self.assertRaises(ValueError): s1.insert('0b1', -1000) with self.assertRaises(ValueError): s1.insert('0b1', 1000) def testInsertNull(self): s = BitStream(hex='0x123') s.insert(BitStream(), 3) self.assertEqual(s.hex, '123') def testInsertBits(self): one = BitStream(bin='1') zero = BitStream(bin='0') s = BitStream(bin='00') s.insert(one, 0) self.assertEqual(s.bin, '100') s.insert(zero, 0) self.assertEqual(s.bin, '0100') s.insert(one, s.len) self.assertEqual(s.bin, '01001') s.insert(s, 2) self.assertEqual(s.bin, '0101001001') class Resetting(unittest.TestCase): def testSetHex(self): s = BitStream() s.hex = '0' self.assertEqual(s.hex, '0') s.hex = '0x010203045' self.assertEqual(s.hex, '010203045') with self.assertRaises(bitstring.CreationError): s.hex = '0x002g' def testSetBin(self): s = BitStream(bin="000101101") self.assertEqual(s.bin, '000101101') self.assertEqual(s.len, 9) s.bin = '0' self.assertEqual(s.bin, '0') self.assertEqual(s.len, 1) def testSetEmptyBin(self): s = BitStream(hex='0x000001b3') s.bin = '' self.assertEqual(s.len, 0) self.assertEqual(s.bin, '') def testSetInvalidBin(self): s = BitStream() with self.assertRaises(bitstring.CreationError): s.bin = '00102' class Overwriting(unittest.TestCase): def testOverwriteBit(self): s = BitStream(bin='0') s.overwrite(BitStream(bin='1'), 0) self.assertEqual(s.bin, '1') def testOverwriteLimits(self): s = BitStream(bin='0b11111') s.overwrite(BitStream(bin='000'), 0) self.assertEqual(s.bin, '00011') s.overwrite('0b000', 2) self.assertEqual(s.bin, '00000') def testOverwriteNull(self): s = BitStream(hex='342563fedec') s2 = BitStream(s) s.overwrite(BitStream(bin=''), 23) self.assertEqual(s.bin, s2.bin) def testOverwritePosition(self): s1 = BitStream(hex='0123456') s2 = BitStream(hex='ff') s1.bytepos = 1 s1.overwrite(s2) self.assertEqual((s1.hex, s1.bytepos), ('01ff456', 2)) s1.overwrite('0xff', 0) self.assertEqual((s1.hex, s1.bytepos), ('ffff456', 1)) def testOverwriteWithSelf(self): s = BitStream('0x123') s.overwrite(s) self.assertEqual(s, '0x123') class Split(unittest.TestCase): def testSplitByteAlignedCornerCases(self): s = BitStream() bsl = s.split(BitStream(hex='0xff')) self.assertEqual(next(bsl).hex, '') with self.assertRaises(StopIteration): _ = next(bsl) s = BitStream(hex='aabbcceeddff') delimiter = BitStream() bsl = s.split(delimiter) with self.assertRaises(ValueError): _ = next(bsl) delimiter = BitStream(hex='11') bsl = s.split(delimiter) self.assertEqual(next(bsl).hex, s.hex) def testSplitByteAligned(self): s = BitStream(hex='0x1234aa1234bbcc1234ffff') delimiter = BitStream(hex='1234') bsl = s.split(delimiter) self.assertEqual([b.hex for b in bsl], ['', '1234aa', '1234bbcc', '1234ffff']) self.assertEqual(s.pos, 0) def testSplitByteAlignedWithIntialBytes(self): s = BitStream(hex='aa471234fedc43 47112233 47 4723 472314') delimiter = BitStream(hex='47') s.find(delimiter) self.assertEqual(s.bytepos, 1) bsl = s.split(delimiter, start=0) self.assertEqual([b.hex for b in bsl], ['aa', '471234fedc43', '47112233', '47', '4723', '472314']) self.assertEqual(s.bytepos, 1) def testSplitByteAlignedWithOverlappingDelimiter(self): s = BitStream(hex='aaffaaffaaffaaffaaff') bsl = s.split(BitStream(hex='aaffaa')) self.assertEqual([b.hex for b in bsl], ['', 'aaffaaff', 'aaffaaffaaff']) class Adding(unittest.TestCase): def testAdding(self): s1 = BitStream(hex='0x0102') s2 = BitStream(hex='0x0304') s3 = s1 + s2 self.assertEqual(s1.hex, '0102') self.assertEqual(s2.hex, '0304') self.assertEqual(s3.hex, '01020304') s3 += s1 self.assertEqual(s3.hex, '010203040102') self.assertEqual(s2[9:16].bin, '0000100') self.assertEqual(s1[0:9].bin, '000000010') s4 = BitStream(bin='000000010') + BitStream(bin='0000100') self.assertEqual(s4.bin, '0000000100000100') s5 = s1[0:9] + s2[9:16] self.assertEqual(s5.bin, '0000000100000100') def testMoreAdding(self): s = BitStream(bin='00') + BitStream(bin='') + BitStream(bin='11') self.assertEqual(s.bin, '0011') s = '0b01' s += BitStream('0b11') self.assertEqual(s.bin, '0111') s = BitStream('0x00') t = BitStream('0x11') s += t self.assertEqual(s.hex, '0011') self.assertEqual(t.hex, '11') s += s self.assertEqual(s.hex, '00110011') def testRadd(self): s = '0xff' + BitStream('0xee') self.assertEqual(s.hex, 'ffee') def testTruncateAsserts(self): s = BitStream('0x001122') s.bytepos = 2 del s[-s.len:] # self.assertEqual(s.bytepos, 0) s.append('0x00') s.append('0x1122') s.bytepos = 2 del s[:s.len] # self.assertEqual(s.bytepos, 0) s.append('0x00') def testOverwriteErrors(self): s = BitStream(bin='11111') with self.assertRaises(ValueError): s.overwrite(BitStream(bin='1'), -10) with self.assertRaises(ValueError): s.overwrite(BitStream(bin='1'), 6) s.overwrite('bin=0', 5) self.assertEqual(s.b, '111110') s.overwrite(BitStream(hex='0x00'), 1) self.assertEqual(s.b, '100000000') def testDeleteBits(self): s = BitStream(bin='000111100000') s.bitpos = 4 del s[4:8] self.assertEqual(s.bin, '00010000') del s[4:1004] self.assertTrue(s.bin, '0001') def testDeleteBitsWithPosition(self): s = BitStream(bin='000111100000') del s[4:8] self.assertEqual(s.bin, '00010000') def testDeleteBytes(self): s = BitStream('0x00112233') del s[8:8] self.assertEqual(s.hex, '00112233') self.assertEqual(s.pos, 0) del s[8:16] self.assertEqual(s.hex, '002233') self.assertEqual(s.bytepos, 0) del s[:24] self.assertFalse(s) self.assertEqual(s.pos, 0) def testGetItemWithPositivePosition(self): s = BitStream(bin='0b1011') self.assertEqual(s[0], True) self.assertEqual(s[1], False) self.assertEqual(s[2], True) self.assertEqual(s[3], True) with self.assertRaises(IndexError): _ = s[4] def testGetItemWithNegativePosition(self): s = BitStream(bin='1011') self.assertEqual(s[-1], True) self.assertEqual(s[-2], True) self.assertEqual(s[-3], False) self.assertEqual(s[-4], True) with self.assertRaises(IndexError): _ = s[-5] def testSlicing(self): s = ConstBitStream(hex='0123456789') self.assertEqual(s[0:8].hex, '01') self.assertFalse(s[0:0]) self.assertFalse(s[23:20]) self.assertEqual(s[8:12].bin, '0010') self.assertEqual(s[32:80], '0x89') def testNegativeSlicing(self): s = ConstBitStream(hex='012345678') self.assertEqual(s[:-8].hex, '0123456') self.assertEqual(s[-16:-8].hex, '56') self.assertEqual(s[-24:].hex, '345678') self.assertEqual(s[-1000:-24], '0x012') def testLen(self): s = BitStream() self.assertEqual(len(s), 0) s.append(BitStream(bin='001')) self.assertEqual(len(s), 3) def testJoin(self): s1 = BitStream(bin='0') s2 = BitStream(bin='1') s3 = BitStream(bin='000') s4 = BitStream(bin='111') strings = [s1, s2, s1, s3, s4] s = BitStream().join(strings) self.assertEqual(s.bin, '010000111') def testJoin2(self): s1 = BitStream(hex='00112233445566778899aabbccddeeff') s2 = BitStream(bin='0b000011') bsl = [s1[0:32], s1[4:12], s2, s2, s2, s2] s = ConstBitStream().join(bsl) self.assertEqual(s.hex, '00112233010c30c3') bsl = [BitStream(uint=j, length=12) for j in range(10) for _ in range(10)] s = BitStream().join(bsl) self.assertEqual(s.length, 1200) def testJoinWithInts(self): with self.assertRaises(TypeError): s = BitStream().join([1, 2]) def testPos(self): s = BitStream(bin='1') self.assertEqual(s.bitpos, 0) s.read(1) self.assertEqual(s.bitpos, 1) def testWritingData(self): strings = [BitStream(bin=x) for x in ['0', '001', '0011010010', '010010', '1011']] s = BitStream().join(strings) s2 = BitStream(bytes=s.bytes) self.assertEqual(s2.bin, '000100110100100100101011') s2.append(BitStream(bin='1')) s3 = BitStream(bytes=s2.tobytes()) self.assertEqual(s3.bin, '00010011010010010010101110000000') def testWritingDataWithOffsets(self): s1 = BitStream(bytes=b'\x10') s2 = BitStream(bytes=b'\x08\x00', length=8, offset=1) s3 = BitStream(bytes=b'\x04\x00', length=8, offset=2) self.assertTrue(s1 == s2) self.assertTrue(s2 == s3) self.assertTrue(s1.bytes == s2.bytes) self.assertTrue(s2.bytes == s3.bytes) def testVariousThings1(self): hexes = ['12345678', '87654321', 'ffffffffff', 'ed', '12ec'] bins = ['001010', '1101011', '0010000100101110110110', '11', '011'] bsl = [] for (hex_, bin_) in list(zip(hexes, bins)) * 5: bsl.append(BitStream(hex=hex_)) bsl.append(BitStream(bin=bin_)) s = BitStream().join(bsl) for (hex_, bin_) in list(zip(hexes, bins)) * 5: h = s.read(4 * len(hex_)) b = s.read(len(bin_)) self.assertEqual(h.hex, hex_) self.assertEqual(b.bin, bin_) def testVariousThings2(self): s1 = BitStream(hex="0x1f08")[:13] self.assertEqual(s1.bin, '0001111100001') s2 = BitStream(bin='0101') self.assertEqual(s2.bin, '0101') s1.append(s2) self.assertEqual(s1.length, 17) self.assertEqual(s1.bin, '00011111000010101') s1 = s1[3:8] self.assertEqual(s1.bin, '11111') def testVariousThings3(self): s1 = BitStream(hex='0x012480ff')[2:27] s2 = s1 + s1 self.assertEqual(s2.length, 50) s3 = s2[0:25] s4 = s2[25:50] self.assertEqual(s3.bin, s4.bin) def testPeekBit(self): s = BitStream(bin='01') self.assertEqual(s.peek(1), [0]) self.assertEqual(s.peek(1), [0]) self.assertEqual(s.read(1), [0]) self.assertEqual(s.peek(1), [1]) self.assertEqual(s.peek(1), [1]) s = BitStream(bytes=b'\x1f', offset=3) self.assertEqual(s.len, 5) self.assertEqual(s.peek(5).bin, '11111') self.assertEqual(s.peek(5).bin, '11111') s.pos += 1 with self.assertRaises(bitstring.ReadError): _ = s.peek(5) s = BitStream(hex='001122334455') self.assertEqual(s.peek(8).hex, '00') self.assertEqual(s.read(8).hex, '00') s.pos += 33 with self.assertRaises(bitstring.ReadError): _ = s.peek(8) s = BitStream(hex='001122334455') self.assertEqual(s.peek(8 * 2).hex, '0011') self.assertEqual(s.read(8 * 3).hex, '001122') self.assertEqual(s.peek(8 * 3).hex, '334455') with self.assertRaises(bitstring.ReadError): _ = s.peek(25) def testAdvanceBit(self): s = BitStream(hex='0xff') s.bitpos = 6 s.pos += 1 self.assertEqual(s.bitpos, 7) s.bitpos += 1 with self.assertRaises(ValueError): s.pos += 1 def testAdvanceByte(self): s = BitStream(hex='0x010203') s.bytepos += 1 self.assertEqual(s.bytepos, 1) s.bytepos += 1 self.assertEqual(s.bytepos, 2) s.bytepos += 1 with self.assertRaises(ValueError): s.bytepos += 1 def testRetreatBit(self): s = BitStream(hex='0xff') with self.assertRaises(ValueError): s.pos -= 1 s.pos = 5 s.pos -= 1 self.assertEqual(s.pos, 4) def testRetreatByte(self): s = BitStream(hex='0x010203') with self.assertRaises(ValueError): s.bytepos -= 1 s.bytepos = 3 s.bytepos -= 1 self.assertEqual(s.bytepos, 2) self.assertEqual(s.read(8).hex, '03') def testCreationByAuto(self): s = BitStream('0xff') self.assertEqual(s.hex, 'ff') s = BitStream('0b00011') self.assertEqual(s.bin, '00011') with self.assertRaises(bitstring.CreationError): _ = BitStream('hello') s1 = BitStream(bytes=b'\xf5', length=3, offset=5) s2 = BitStream(s1, length=1, offset=1) self.assertEqual(s2, '0b0') s = BitStream(bytes=b'\xff', offset=2) t = BitStream(s, offset=2) self.assertEqual(t, '0b1111') with self.assertRaises(TypeError): _ = BitStream(1.2) def testCreationByAuto2(self): s = BitStream('bin=001') self.assertEqual(s.bin, '001') s = BitStream('oct=0o007') self.assertEqual(s.oct, '007') s = BitStream('hex=123abc') self.assertEqual(s, '0x123abc') s = BitStream('bin2=01') self.assertEqual(s, '0b01') for s in ['bin:1=01', 'bits:4=0b1', 'oct3=000', 'hex4=0x1234']: with self.assertRaises(bitstring.CreationError): _ = BitStream(s) def testInsertUsingAuto(self): s = BitStream('0xff') s.insert('0x00', 4) self.assertEqual(s.hex, 'f00f') with self.assertRaises(ValueError): s.insert('ff') def testOverwriteUsingAuto(self): s = BitStream('0x0110') s.overwrite('0b1') self.assertEqual(s.hex, '8110') s.overwrite('') self.assertEqual(s.hex, '8110') with self.assertRaises(ValueError): s.overwrite('0bf') def testFindUsingAuto(self): s = BitStream('0b000000010100011000') self.assertTrue(s.find('0b101')) self.assertEqual(s.pos, 7) def testFindbytealignedUsingAuto(self): s = BitStream('0x00004700') self.assertTrue(s.find('0b01000111', bytealigned=True)) self.assertEqual(s.bytepos, 2) def testAppendUsingAuto(self): s = BitStream('0b000') s.append('0b111') self.assertEqual(s.bin, '000111') s.append('0b0') self.assertEqual(s.bin, '0001110') def testSplitByteAlignedUsingAuto(self): s = BitStream('0x000143563200015533000123') sections = s.split('0x0001') self.assertEqual(next(sections).hex, '') self.assertEqual(next(sections).hex, '0001435632') self.assertEqual(next(sections).hex, '00015533') self.assertEqual(next(sections).hex, '000123') self.assertRaises(StopIteration, next, sections) def testSplitByteAlignedWithSelf(self): s = BitStream('0x1234') sections = s.split(s) self.assertEqual(next(sections).hex, '') self.assertEqual(next(sections).hex, '1234') with self.assertRaises(StopIteration): next(sections) def testPrepend(self): s = BitStream('0b000') s.prepend('0b11') self.assertEqual(s.bin, '11000') s.prepend(s) self.assertEqual(s.bin, '1100011000') s.prepend('') self.assertEqual(s.bin, '1100011000') def testNullSlice(self): s = BitStream('0x111') t = s[1:1] self.assertEqual(len(t), 0) def testMultipleAutos(self): s = BitStream('0xa') s.prepend('0xf') s.append('0xb') self.assertEqual(s, '0xfab') s.prepend(s) s.append('0x100') s.overwrite('0x5', 4) self.assertEqual(s, '0xf5bfab100') def testReverse(self): s = BitStream('0b0011') s.reverse() self.assertEqual(s.bin, '1100') s = BitStream('0b10') s.reverse() self.assertEqual(s.bin, '01') s = BitStream() s.reverse() self.assertEqual(s.bin, '') def testInitWithConcatenatedStrings(self): s = BitStream('0xff 0Xee 0xd 0xcc') self.assertEqual(s.hex, 'ffeedcc') s = BitStream('0b0 0B111 0b001') self.assertEqual(s.bin, '0111001') s += '0b1' + '0B1' self.assertEqual(s.bin, '011100111') s = BitStream(hex='ff0xee') self.assertEqual(s.hex, 'ffee') s = BitStream(bin='000b0b11') self.assertEqual(s.bin, '0011') s = BitStream(' 0o123 0O 7 0 o1') self.assertEqual(s.oct, '12371') s += ' 0 o 332' self.assertEqual(s.oct, '12371332') def testEquals(self): s1 = BitStream('0b01010101') s2 = BitStream('0b01010101') self.assertTrue(s1 == s2) s3 = BitStream() s4 = BitStream() self.assertTrue(s3 == s4) self.assertFalse(s3 != s4) s5 = BitStream(bytes=b'\xff', offset=2, length=3) s6 = BitStream('0b111') self.assertTrue(s5 == s6) class A(object): pass self.assertFalse(s5 == A()) def testLargeEquals(self): s1 = BitStream(1000000) s2 = BitStream(1000000) s1.set(True, [-1, 55, 53214, 534211, 999999]) s2.set(True, [-1, 55, 53214, 534211, 999999]) self.assertEqual(s1, s2) s1.set(True, 800000) self.assertNotEqual(s1, s2) def testNotEquals(self): s1 = BitStream('0b0') s2 = BitStream('0b1') self.assertTrue(s1 != s2) self.assertFalse(s1 != BitStream('0b0')) def testEqualityWithAutoInitialised(self): a = BitStream('0b00110111') self.assertTrue(a == '0b00110111') self.assertTrue(a == '0x37') self.assertTrue('0b0011 0111' == a) self.assertTrue('0x3 0x7' == a) self.assertFalse(a == '0b11001000') self.assertFalse('0x3737' == a) def testInvertSpecialMethod(self): s = BitStream('0b00011001') self.assertEqual((~s).bin, '11100110') self.assertEqual((~BitStream('0b0')).bin, '1') self.assertEqual((~BitStream('0b1')).bin, '0') self.assertTrue(~~s == s) def testInvertBitPosition(self): s = ConstBitStream('0xefef') s.pos = 8 t = ~s self.assertEqual(s.pos, 8) self.assertEqual(t.pos, 0) def testInvertSpecialMethodErrors(self): s = BitStream() with self.assertRaises(bitstring.Error): _ = ~s def testJoinWithAuto(self): s = BitStream().join(['0xf', '0b00', BitStream(bin='11')]) self.assertEqual(s, '0b11110011') def testAutoBitStringCopy(self): s = BitStream('0xabcdef') t = BitStream(s) self.assertEqual(t.hex, 'abcdef') del s[-8:] self.assertEqual(t.hex, 'abcdef') class Multiplication(unittest.TestCase): def testMultiplication(self): a = BitStream('0xff') b = a * 8 self.assertEqual(b, '0xffffffffffffffff') b = 4 * a self.assertEqual(b, '0xffffffff') self.assertTrue(1 * a == a * 1 == a) c = a * 0 self.assertFalse(c) a *= 3 self.assertEqual(a, '0xffffff') a *= 0 self.assertFalse(a) one = BitStream('0b1') zero = BitStream('0b0') mix = one * 2 + 3 * zero + 2 * one * 2 self.assertEqual(mix, '0b110001111') q = BitStream() q *= 143 self.assertFalse(q) q += [True, True, False] self.assertEqual(q.bitpos, 3) q *= 0 self.assertFalse(q) self.assertEqual(q.bitpos, 0) def testMultiplicationWithFiles(self): a = BitStream(filename=os.path.join(THIS_DIR, 'test.m1v')) b = a.len a *= 3 self.assertEqual(a.len, 3 * b) def testMultiplicationErrors(self): a = BitStream('0b1') b = BitStream('0b0') with self.assertRaises(ValueError): _ = a * -1 with self.assertRaises(ValueError): a *= -1 with self.assertRaises(ValueError): _ = -1 * a with self.assertRaises(TypeError): _ = a * 1.2 with self.assertRaises(TypeError): _ = b * a with self.assertRaises(TypeError): a *= b class BitWise(unittest.TestCase): def testBitwiseAnd(self): a = BitStream('0b01101') b = BitStream('0b00110') self.assertEqual((a & b).bin, '00100') self.assertEqual((a & '0b11111'), a) with self.assertRaises(ValueError): _ = a & '0b1' with self.assertRaises(ValueError): _ = b & '0b110111111' c = BitStream('0b0011011') c.pos = 4 d = c & '0b1111000' self.assertEqual(d.pos, 0) self.assertEqual(d.bin, '0011000') d = '0b1111000' & c self.assertEqual(d.bin, '0011000') def testBitwiseOr(self): a = BitStream('0b111001001') b = BitStream('0b011100011') c = a | b self.assertEqual(c.bin, '111101011') self.assertEqual((a | '0b000000000'), a) with self.assertRaises(ValueError): _ = a | '0b0000' with self.assertRaises(ValueError): _ = b | (a + '0b1') a = '0xff00' | BitStream('0x00f0') self.assertEqual(a.hex, 'fff0') def testBitwiseXor(self): a = BitStream('0b111001001') b = BitStream('0b011100011') c = a ^ b self.assertEqual(c.bin, '100101010') self.assertEqual((a ^ '0b111100000').bin, '000101001') with self.assertRaises(ValueError): _ = a ^ '0b0000' with self.assertRaises(ValueError): _ = b ^ (a + '0b1') a = '0o707' ^ BitStream('0o777') self.assertEqual(a.oct, '070') class Split2(unittest.TestCase): def testSplit(self): a = BitStream('0b0 010100111 010100 0101 010') a.pos = 20 subs = [i.bin for i in a.split('0b010')] self.assertEqual(subs, ['0', '010100111', '010100', '0101', '010']) self.assertEqual(a.pos, 20) def testSplitCornerCases(self): a = BitStream('0b000000') bsl = a.split('0b1', False) self.assertEqual(next(bsl), a) with self.assertRaises(StopIteration): next(bsl) b = BitStream() bsl = b.split('0b001', False) self.assertFalse(next(bsl)) with self.assertRaises(StopIteration): _ = next(bsl) def testSplitErrors(self): a = BitStream('0b0') b = a.split('', False) with self.assertRaises(ValueError): _ = next(b) def testSliceWithOffset(self): a = BitStream(bytes=b'\x00\xff\x00', offset=7) b = a[7:12] self.assertEqual(b.bin, '11000') def testSplitWithMaxsplit(self): a = BitStream('0xaabbccbbccddbbccddee') self.assertEqual(len(list(a.split('0xbb', bytealigned=True))), 4) bsl = list(a.split('0xbb', count=1, bytealigned=True)) self.assertEqual((len(bsl), bsl[0]), (1, '0xaa')) bsl = list(a.split('0xbb', count=2, bytealigned=True)) self.assertEqual(len(bsl), 2) self.assertEqual(bsl[0], '0xaa') self.assertEqual(bsl[1], '0xbbcc') def testSplitMore(self): s = BitStream('0b1100011001110110') for i in range(10): a = list(s.split('0b11', False, count=i)) b = list(s.split('0b11', False))[:i] self.assertEqual(a, b) b = s.split('0b11', count=-1) with self.assertRaises(ValueError): _ = next(b) def testSplitStartbit(self): a = BitStream('0b0010101001000000001111') bsl = a.split('0b001', bytealigned=False, start=1) self.assertEqual([x.bin for x in bsl], ['010101', '001000000', '001111']) b = a.split('0b001', start=-100) with self.assertRaises(ValueError): _ = next(b) b = a.split('0b001', start=23) with self.assertRaises(ValueError): _ = next(b) b = a.split('0b1', start=10, end=9) with self.assertRaises(ValueError): _ = next(b) def testSplitStartbitByteAligned(self): a = BitStream('0x00ffffee') bsl = list(a.split('0b111', start=9, bytealigned=True)) self.assertEqual([x.bin for x in bsl], ['1111111', '11111111', '11101110']) def testSplitEndbit(self): a = BitStream('0b000010001001011') bsl = list(a.split('0b1', bytealigned=False, end=14)) self.assertEqual([x.bin for x in bsl], ['0000', '1000', '100', '10', '1']) self.assertEqual(list(a[4:12].split('0b0', False)), list(a.split('0b0', start=4, end=12))) try: list(a.split('0xffee', end=15)) except ValueError: self.fail("ValueError raised unexpectedly") # Whereas this one will when we call next() bsl = a.split('0xffee', end=16) with self.assertRaises(ValueError): _ = next(bsl) def testSplitEndbitByteAligned(self): a = BitStream('0xff00ff')[:22] bsl = list(a.split('0b 0000 0000 111', end=19)) self.assertEqual([x.bin for x in bsl], ['11111111', '00000000111']) bsl = list(a.split('0b 0000 0000 111', end=18)) self.assertEqual([x.bin for x in bsl], ['111111110000000011']) def testSplitMaxSplit(self): a = BitStream('0b1' * 20) for i in range(10): bsl = list(a.split('0b1', count=i)) self.assertEqual(len(bsl), i) ####################### def testExplicitAuto(self): with self.assertRaises(bitstring.CreationError): a = BitStream(auto='0x1') def testPositionInSlice(self): a = BitStream('0x00ffff00') a.bytepos = 2 b = a[8:24] self.assertEqual(b.bytepos, 0) def testFindByteAlignedWithBits(self): a = BitStream('0x00112233445566778899') a.find('0b0001', bytealigned=True) self.assertEqual(a.bitpos, 8) def testFindStartbitNotByteAligned(self): a = BitStream('0b0010000100') found = a.find('0b1', start=4) self.assertEqual((found, a.bitpos), ((7,), 7)) found = a.find('0b1', start=2) self.assertEqual((found, a.bitpos), ((2,), 2)) found = a.find('0b1', bytealigned=False, start=8) self.assertEqual((found, a.bitpos), ((), 2)) def testFindEndbitNotByteAligned(self): a = BitStream('0b0010010000') found = a.find('0b1', bytealigned=False, end=2) self.assertEqual((found, a.bitpos), ((), 0)) found = a.find('0b1', end=3) self.assertEqual((found, a.bitpos), ((2,), 2)) found = a.find('0b1', bytealigned=False, start=3, end=5) self.assertEqual((found, a.bitpos), ((), 2)) found = a.find('0b1', start=3, end=6) self.assertEqual((found[0], a.bitpos), (5, 5)) def testFindStartbitByteAligned(self): a = BitStream('0xff001122ff0011ff') a.pos = 40 found = a.find('0x22', start=23, bytealigned=True) self.assertEqual((found, a.bytepos), ((24,), 3)) a.bytepos = 4 found = a.find('0x22', start=24, bytealigned=True) self.assertEqual((found, a.bytepos), ((24,), 3)) found = a.find('0x22', start=25, bytealigned=True) self.assertEqual((found, a.pos), ((), 24)) found = a.find('0b111', start=40, bytealigned=True) self.assertEqual((found, a.pos), ((56,), 56)) def testFindEndbitByteAligned(self): a = BitStream('0xff001122ff0011ff') found = a.find('0x22', end=31, bytealigned=True) self.assertFalse(found) self.assertEqual(a.pos, 0) found = a.find('0x22', end=32, bytealigned=True) self.assertTrue(found) self.assertEqual(a.pos, 24) self.assertEqual(found[0], 24) def testFindStartEndbitErrors(self): a = BitStream('0b00100') with self.assertRaises(ValueError): _ = a.find('0b1', bytealigned=False, start=-100) with self.assertRaises(ValueError): _ = a.find('0b1', end=6) with self.assertRaises(ValueError): _ = a.find('0b1', start=4, end=3) b = BitStream('0x0011223344') with self.assertRaises(ValueError): _ = b.find('0x22', bytealigned=True, start=-100) with self.assertRaises(ValueError): _ = b.find('0x22', end=41, bytealigned=True) def testPrependAndAppendAgain(self): c = BitStream('0x1122334455667788') c.bitpos = 40 c.append('0b1') self.assertEqual(c.bitpos, len(c)) c = BitStream() c.prepend('0x1234') self.assertEqual(c.bytepos, 0) c = BitStream() c.append('0x1234') self.assertEqual(c.bytepos, 2) s = BitStream(bytes=b'\xff\xff', offset=2) self.assertEqual(s.length, 14) t = BitStream(bytes=b'\x80', offset=1, length=2) s.prepend(t) self.assertEqual(s, '0x3fff') def testFindAll(self): a = BitStream('0b11111') p = a.findall('0b1') self.assertEqual(list(p), [0, 1, 2, 3, 4]) p = a.findall('0b11') self.assertEqual(list(p), [0, 1, 2, 3]) p = a.findall('0b10') self.assertEqual(list(p), []) a = BitStream('0x4733eeff66554747335832434547') p = a.findall('0x47', bytealigned=True) self.assertEqual(list(p), [0, 6 * 8, 7 * 8, 13 * 8]) p = a.findall('0x4733', bytealigned=True) self.assertEqual(list(p), [0, 7 * 8]) a = BitStream('0b1001001001001001001') p = a.findall('0b1001', bytealigned=False) self.assertEqual(list(p), [0, 3, 6, 9, 12, 15]) self.assertEqual(a.pos, 0) def testFindAllGenerator(self): a = BitStream('0xff1234512345ff1234ff12ff') p = a.findall('0xff', bytealigned=True) self.assertEqual(next(p), 0) self.assertEqual(next(p), 6 * 8) self.assertEqual(next(p), 9 * 8) self.assertEqual(next(p), 11 * 8) with self.assertRaises(StopIteration): _ = next(p) def testFindAllCount(self): s = BitStream('0b1') * 100 for i in [0, 1, 23]: self.assertEqual(len(list(s.findall('0b1', count=i))), i) with self.assertRaises(ValueError): _ = s.findall('0b1', bytealigned=True, count=-1) def testContains(self): a = BitStream('0b1') + '0x0001dead0001' self.assertTrue('0xdead' in a) self.assertEqual(a.pos, 0) self.assertFalse('0xfeed' in a) def testRepr(self): max_ = bitstring.bits.MAX_CHARS bls = ['', '0b1', '0o5', '0x43412424f41', '0b00101001010101'] for bs in bls: a = BitStream(bs) b = eval(a.__repr__()) self.assertEqual(a, b) filename = os.path.join(THIS_DIR, 'test.m1v') for f in [ConstBitStream(filename=filename), ConstBitStream(filename=filename, length=17), ConstBitStream(filename=filename, length=23, offset=23102)]: f2 = eval(f.__repr__()) self.assertEqual(f._bitstore.filename, f2._bitstore.filename) self.assertEqual(f2.tobytes(), f.tobytes()) a = BitStream('0b1') self.assertEqual(repr(a), "BitStream('0b1')") a += '0b11' a.pos = 2 self.assertEqual(repr(a), "BitStream('0b111', pos=2)") a.pos = 0 a += '0b1' self.assertEqual(repr(a), "BitStream('0xf', pos=4)") a.pos = 0 a *= max_ self.assertEqual(repr(a), "BitStream('0x" + "f" * max_ + "')") a += '0xf' self.assertEqual(repr(a), "BitStream('0x" + "f" * max_ + "...', pos=1004) # length=%d" % (max_ * 4 + 4)) def testPrint(self): s = BitStream(hex='0x00') self.assertEqual('0x' + s.hex, s.__str__()) s = BitStream(filename=os.path.join(THIS_DIR, 'test.m1v')) self.assertEqual('0x' + s[0: bitstring.bits.MAX_CHARS * 4].hex + '...', s.__str__()) self.assertEqual(BitStream().__str__(), '') s = BitStream('0b11010') self.assertEqual('0b' + s.bin, s.__str__()) s = BitStream('0x12345678901234567890,0b1') self.assertEqual('0x12345678901234567890, 0b1', s.__str__()) def testIter(self): a = BitStream('0b001010') b = BitStream() for bit in a: b.append(ConstBitStream(bool=bit)) self.assertEqual(a, b) def testDelitem(self): a = BitStream('0xffee') del a[0:8] self.assertEqual(a.hex, 'ee') del a[0:8] self.assertFalse(a) del a[10:12] self.assertFalse(a) def testNonZeroBitsAtStart(self): a = BitStream(bytes=b'\xff', offset=2) b = BitStream('0b00') b += a self.assertTrue(b == '0b0011 1111') self.assertEqual(a.tobytes(), b'\xfc') def testNonZeroBitsAtEnd(self): a = BitStream(bytes=b'\xff', length=5) b = BitStream('0b00') a += b self.assertTrue(a == '0b1111100') self.assertEqual(a.tobytes(), b'\xf8') with self.assertRaises(ValueError): _ = a.bytes def testNewOffsetErrors(self): with self.assertRaises(bitstring.CreationError): _ = BitStream(hex='ff', offset=-1) with self.assertRaises(bitstring.CreationError): _ = BitStream('0xffffffff', offset=33) def testSliceStep(self): a = BitStream('0x3') b = a[::1] self.assertEqual(a, b) self.assertEqual(a[2:4:1], '0b11') self.assertEqual(a[0:2:1], '0b00') self.assertEqual(a[:3], '0o1') a = BitStream('0x0011223344556677') self.assertEqual(a[-8:], '0x77') self.assertEqual(a[:-24], '0x0011223344') self.assertEqual(a[-1000:-24], '0x0011223344') def testInterestingSliceStep(self): a = BitStream('0b0011000111') self.assertEqual(a[7:3:-1], '0b1000') self.assertEqual(a[9:2:-1], '0b1110001') self.assertEqual(a[8:2:-2], '0b100') self.assertEqual(a[100:-20:-3], '0b1010') self.assertEqual(a[100:-20:-1], '0b1110001100') self.assertEqual(a[10:2:-1], '0b1110001') self.assertEqual(a[100:2:-1], '0b1110001') def testInsertionOrderAndBitpos(self): b = BitStream() b[0:0] = '0b0' b[0:0] = '0b1' self.assertEqual(b, '0b10') self.assertEqual(b.bitpos, 0) a = BitStream() a.insert('0b0') a.insert('0b1') self.assertEqual(a, '0b01') self.assertEqual(a.bitpos, 2) def testOverwriteOrderAndBitpos(self): a = BitStream('0xff') a.overwrite('0xa') self.assertEqual(a, '0xaf') self.assertEqual(a.bitpos, 4) a.overwrite('0xb') self.assertEqual(a, '0xab') self.assertEqual(a.bitpos, 8) a.overwrite('0xa', 4) self.assertEqual(a, '0xaa') self.assertEqual(a.bitpos, 8) a.overwrite(a, 0) self.assertEqual(a, '0xaa') def testInitSliceWithInt(self): a = BitStream(length=8) a[:] = 100 self.assertEqual(a.uint, 100) a[0] = 1 self.assertEqual(a.bin, '11100100') a[1] = 0 self.assertEqual(a.bin, '10100100') a[-1] = -1 self.assertEqual(a.bin, '10100101') a[-3:] = -2 self.assertEqual(a.bin, '10100110') def testInitSliceWithIntErrors(self): a = BitStream('0b0000') with self.assertRaises(ValueError): a[0:4] = 16 with self.assertRaises(ValueError): a[0:4] = -9 with self.assertRaises(ValueError): a[0] = 2 with self.assertRaises(ValueError): a[0] = -2 def testReverseWithSlice(self): a = BitStream('0x0012ff') a.reverse() self.assertEqual(a, '0xff4800') a.reverse(8, 16) self.assertEqual(a, '0xff1200') b = a[8:16] b.reverse() a[8:16] = b self.assertEqual(a, '0xff4800') def testReverseWithSliceErrors(self): a = BitStream('0x123') with self.assertRaises(ValueError): a.reverse(-1, 4) with self.assertRaises(ValueError): a.reverse(10, 9) with self.assertRaises(ValueError): a.reverse(1, 10000) def testInitialiseFromList(self): a = BitStream([]) self.assertFalse(a) a = BitStream([True, False, [], [0], 'hello']) self.assertEqual(a, '0b10011') a += [] self.assertEqual(a, '0b10011') a += [True, False, True] self.assertEqual(a, '0b10011101') a.find([12, 23]) self.assertEqual(a.pos, 3) self.assertEqual([1, 0, False, True], BitStream('0b1001')) a = [True] + BitStream('0b1') self.assertEqual(a, '0b11') def testInitialiseFromTuple(self): a = BitStream(()) self.assertFalse(a) a = BitStream((0, 1, '0', '1')) self.assertEqual('0b0111', a) a.replace((True, True), []) self.assertEqual(a, (False, True)) def testCut(self): a = BitStream('0x00112233445') b = list(a.cut(8)) self.assertEqual(b, ['0x00', '0x11', '0x22', '0x33', '0x44', '0x5']) b = list(a.cut(4, 8, 16)) self.assertEqual(b, ['0x1', '0x1']) b = list(a.cut(4, 0, 44, 4)) self.assertEqual(b, ['0x0', '0x0', '0x1', '0x1']) a = BitStream() b = list(a.cut(10)) self.assertTrue(not b) def testCutErrors(self): a = BitStream('0b1') b = a.cut(1, 1, 2) with self.assertRaises(ValueError): _ = next(b) b = a.cut(1, -2, 1) with self.assertRaises(ValueError): _ = next(b) b = a.cut(0) with self.assertRaises(ValueError): _ = next(b) b = a.cut(1, count=-1) with self.assertRaises(ValueError): _ = next(b) def testCutProblem(self): s = BitStream('0x1234') for n in list(s.cut(4)): s.prepend(n) self.assertEqual(s, '0x43211234') def testJoinFunctions(self): a = BitStream().join(['0xa', '0xb', '0b1111']) self.assertEqual(a, '0xabf') a = BitStream('0b1').join(['0b0' for _ in range(10)]) self.assertEqual(a, '0b0101010101010101010') a = BitStream('0xff').join([]) self.assertFalse(a) a = BitStream('0xff').join([Bits(5), '0xab', '0xabc']) self.assertEqual(a, '0b00000, 0xffabffabc') def testAddingBitpos(self): a = BitStream('0xff') b = BitStream('0x00') a.bitpos = b.bitpos = 8 c = a + b self.assertEqual(c.bitpos, 0) def testIntelligentRead1(self): a = BitStream(uint=123, length=23) u = a.read('uint:23') self.assertEqual(u, 123) self.assertEqual(a.pos, a.len) b = BitStream(int=-12, length=44) i = b.read('int:44') self.assertEqual(i, -12) self.assertEqual(b.pos, b.len) u2, i2 = (a + b).readlist('uint:23, int:44') self.assertEqual((u2, i2), (123, -12)) def testIntelligentRead2(self): a = BitStream(ue=822) u = a.read('ue') self.assertEqual(u, 822) self.assertEqual(a.pos, a.len) b = BitStream(se=-1001) s = b.read('se') self.assertEqual(s, -1001) self.assertEqual(b.pos, b.len) s, u1, u2 = (b + 2 * a).readlist('se, ue, ue') self.assertEqual((s, u1, u2), (-1001, 822, 822)) def testIntelligentRead3(self): a = BitStream('0x123') + '0b11101' h = a.read('hex:12') self.assertEqual(h, '123') b = a.read('bin: 5') self.assertEqual(b, '11101') c = '0b' + b + a b, h = c.readlist('bin:5, hex:12') self.assertEqual((b, h), ('11101', '123')) def testIntelligentRead4(self): a = BitStream('0o007') o = a.read('oct:9') self.assertEqual(o, '007') self.assertEqual(a.pos, a.len) def testIntelligentRead5(self): a = BitStream('0x00112233') c0, c1, c2 = a.readlist('bits:8, bits:8, bits:16') self.assertEqual((c0, c1, c2), (BitStream('0x00'), BitStream('0x11'), BitStream('0x2233'))) a.pos = 0 c = a.read('bits:16') self.assertEqual(c, BitStream('0x0011')) def testIntelligentRead6(self): a = BitStream('0b000111000') b1, b2, b3 = a.readlist('bin :3, int: 3, int:3') self.assertEqual(b1, '000') self.assertEqual(b2, -1) self.assertEqual(b3, 0) def testIntelligentRead7(self): a = BitStream('0x1234') a1, a2, a3, a4 = a.readlist('bin:0, oct:0, hex:0, bits:0') self.assertTrue(a1 == a2 == a3 == '') self.assertFalse(a4) with self.assertRaises(ValueError): _ = a.read('int:0') with self.assertRaises(ValueError): _ = a.read('uint:0') self.assertEqual(a.pos, 0) def testIntelligentRead8(self): a = BitStream('0x123456') for t in ['hex:1', 'oct:1', '-5', 'fred', 'bin:-2', 'uint:p', 'uint:-2', 'int:u', 'int:-3', 'ses', 'uee', '-14']: with self.assertRaises(ValueError): _ = a.read(t) def testIntelligentRead9(self): a = BitStream('0xff') self.assertEqual(a.read('intle8'), -1) def testIntelligentPeek(self): a = BitStream('0b01, 0x43, 0o4, uint:23=2, se=5, ue=3') b, c, e = a.peeklist('bin:2, hex:8, oct:3') self.assertEqual((b, c, e), ('01', '43', '4')) self.assertEqual(a.pos, 0) a.pos = 13 f, g, h = a.peeklist('uint:23, se, ue') self.assertEqual((f, g, h), (2, 5, 3)) self.assertEqual(a.pos, 13) def testReadMultipleBits(self): s = BitStream('0x123456789abcdef') a, b = s.readlist([4, 4]) self.assertEqual(a, '0x1') self.assertEqual(b, '0x2') c, d, e = s.readlist([8, 16, 8]) self.assertEqual(c, '0x34') self.assertEqual(d, '0x5678') self.assertEqual(e, '0x9a') def testPeekMultipleBits(self): s = BitStream('0b1101, 0o721, 0x2234567') a, b, c, d = s.peeklist([2, 1, 1, 9]) self.assertEqual(a, '0b11') self.assertEqual(bool(b), True) self.assertEqual(bool(c), True) self.assertEqual(d, '0o721') self.assertEqual(s.pos, 0) a, b = s.peeklist([4, 9]) self.assertEqual(a, '0b1101') self.assertEqual(b, '0o721') s.pos = 13 a, b = s.peeklist([16, 8]) self.assertEqual(a, '0x2234') self.assertEqual(b, '0x56') self.assertEqual(s.pos, 13) def testDifficultPrepends(self): a = BitStream('0b1101011') b = BitStream() for i in range(10): b.prepend(a) self.assertEqual(b, a * 10) def testPackingWrongNumberOfThings(self): with self.assertRaises(bitstring.CreationError): _ = pack('bin:1') with self.assertRaises(bitstring.CreationError): _ = pack('', 100) def testPackWithVariousKeys(self): a = pack('uint10', uint10='0b1') self.assertEqual(a, '0b1') b = pack('0b110', **{'0b110': '0xfff'}) self.assertEqual(b, '0xfff') def testPackWithVariableLength(self): for i in range(1, 11): a = pack('uint:n', 0, n=i) self.assertEqual(a.bin, '0' * i) def testToBytes(self): a = BitStream(bytes=b'\xab\x00') b = a.tobytes() self.assertEqual(a.bytes, b) for i in range(7): del a[-1:] self.assertEqual(a.tobytes(), b'\xab\x00') del a[-1:] self.assertEqual(a.tobytes(), b'\xab') def testToFile(self): filename = os.path.join(THIS_DIR, 'temp_bitstring_unit_testing_file') a = BitStream('0x0000ff')[:17] with open(filename, 'wb') as f: a.tofile(f) b = BitStream(filename=filename) self.assertEqual(b, '0x000080') a = BitStream('int:1000000=-1') self.assertEqual(a.int, -1) with open(filename, 'wb') as f: a.tofile(f) b = BitStream(filename=filename) self.assertEqual(b.int, -1) self.assertEqual(b.len, 1000000) def testTokenParser(self): tp = bitstring.utils.tokenparser self.assertEqual(tp('hex'), (True, [('hex', None, None)])) self.assertEqual(tp('hex=14'), (True, [('hex', None, '14')])) self.assertEqual(tp('se'), (False, [('se', None, None)])) self.assertEqual(tp('ue=12'), (False, [('ue', None, '12')])) self.assertEqual(tp('0xef'), (False, [('0x', None, 'ef')])) self.assertEqual(tp('uint:12'), (False, [('uint', 12, None)])) self.assertEqual(tp('int:30=-1'), (False, [('int', 30, '-1')])) self.assertEqual(tp('bits10'), (False, [('bits', 10, None)])) self.assertEqual(tp('bits:10'), (False, [('bits', 10, None)])) self.assertEqual(tp('123'), (False, [('bits', 123, None)])) self.assertEqual(tp('123'), (False, [('bits', 123, None)])) self.assertEqual(tp('hex12', ('hex12',)), (False, [('hex12', None, None)])) self.assertEqual(tp('2*bits:6'), (False, [('bits', 6, None), ('bits', 6, None)])) def testTokenParserStructCodes(self): tp = bitstring.utils.tokenparser self.assertEqual(tp('>H'), (False, [('uintbe', 16, None)])) self.assertEqual(tp('b'), (False, [('int', 8, None)])) self.assertEqual(tp('b', 23), BitStream('intbe:8=23')) self.assertEqual(pack('>B', 23), BitStream('uintbe:8=23')) self.assertEqual(pack('>h', 23), BitStream('intbe:16=23')) self.assertEqual(pack('>H', 23), BitStream('uintbe:16=23')) self.assertEqual(pack('>l', 23), BitStream('intbe:32=23')) self.assertEqual(pack('>L', 23), BitStream('uintbe:32=23')) self.assertEqual(pack('>q', 23), BitStream('intbe:64=23')) self.assertEqual(pack('>Q', 23), BitStream('uintbe:64=23')) with self.assertRaises(bitstring.CreationError): _ = pack('2L', 40, 40)) def testStructTokens3(self): s = pack('>hhl', 1, 2, 3) a, b, c = s.unpack('>hhl') self.assertEqual((a, b, c), (1, 2, 3)) s = pack('Q \tL', 1001, 43, 21, 9999) self.assertEqual(s.unpack('QL'), [1001, 43, 21, 9999]) def testStructTokensMultiplicativeFactors(self): s = pack('<2h', 1, 2) a, b = s.unpack('<2h') self.assertEqual((a, b), (1, 2)) s = pack('<100q', *range(100)) self.assertEqual(s.len, 100 * 64) self.assertEqual(s[44*64:45*64].uintle, 44) s = pack('@L0B2h', 5, 5, 5) self.assertEqual(s.unpack('@Lhh'), [5, 5, 5]) def testStructTokensErrors(self): for f in ['>>q', '<>q', 'q>', '2q', 'q', '>-2q', '@a', '>int:8', '>q2']: with self.assertRaises(bitstring.CreationError): _ = pack(f, 100) def testImmutableBitStreams(self): a = ConstBitStream('0x012345') self.assertEqual(a, '0x012345') b = BitStream('0xf') + a self.assertEqual(b, '0xf012345') with self.assertRaises(AttributeError): a.append(b) with self.assertRaises(AttributeError): a.prepend(b) with self.assertRaises(TypeError): a[0] = '0b1' with self.assertRaises(TypeError): del a[5] with self.assertRaises(AttributeError): a.replace('0b1', '0b0') with self.assertRaises(AttributeError): a.insert('0b11', 4) with self.assertRaises(AttributeError): a.reverse() with self.assertRaises(AttributeError): a.reversebytes() self.assertEqual(a, '0x012345') self.assertTrue(isinstance(a, ConstBitStream)) def testReverseBytes(self): a = BitStream('0x123456') a.byteswap() self.assertEqual(a, '0x563412') b = a + '0b1' b.byteswap() self.assertEqual('0x123456, 0b1', b) a = BitStream('0x54') a.byteswap() self.assertEqual(a, '0x54') a = BitStream() a.byteswap() self.assertFalse(a) def testReverseBytes2(self): a = BitStream() a.byteswap() self.assertFalse(a) a = BitStream('0x00112233') a.byteswap(0, 0, 16) self.assertEqual(a, '0x11002233') a.byteswap(0, 4, 28) self.assertEqual(a, '0x12302103') a.byteswap(start=0, end=18) self.assertEqual(a, '0x30122103') with self.assertRaises(ValueError): a.byteswap(0, 10, 2) with self.assertRaises(ValueError): a.byteswap(0, -4, 4) with self.assertRaises(ValueError): a.byteswap(0, 24, 48) a.byteswap(0, 24) self.assertEqual(a, '0x30122103') a.byteswap(0, 11, 11) self.assertEqual(a, '0x30122103') def testCapitalsInPack(self): a = pack('A', A='0b1') self.assertEqual(a, '0b1') format_ = 'bits:4=BL_OFFT, uint:12=width, uint:12=height' d = {'BL_OFFT': '0b1011', 'width': 352, 'height': 288} s = bitstring.pack(format_, **d) self.assertEqual(s, '0b1011, uint:12=352, uint:12=288') a = pack('0X0, uint:8, hex', 45, '0XABcD') self.assertEqual(a, '0x0, uint:8=45, 0xabCD') def testOtherCapitals(self): a = ConstBitStream('0XABC, 0O0, 0B11') self.assertEqual(a, 'hex=0Xabc, oct=0, bin=0B11') def testEfficientOverwrite(self): a = BitStream(100000000) a.overwrite([1], 123456) self.assertEqual(a[123456], True) a.overwrite('0xff', 1) self.assertEqual(a[0:32:1], '0x7f800000') b = BitStream('0xffff') b.overwrite('0x0000') self.assertEqual(b, '0x0000') self.assertEqual(b.pos, 16) c = BitStream(length=1000) c.overwrite('0xaaaaaaaaaaaa', 81) self.assertEqual(c[81:81 + 6 * 8], '0xaaaaaaaaaaaa') self.assertEqual(len(list(c.findall('0b1'))), 24) s = BitStream(length=1000) s = s[5:] s.overwrite('0xffffff', 500) s.pos = 500 self.assertEqual(s.read(4 * 8), '0xffffff00') s.overwrite('0xff', 502) self.assertEqual(s[502:518], '0xffff') def testPeekAndReadListErrors(self): a = BitStream('0x123456') with self.assertRaises(ValueError): _ = a.read('hex:8, hex:8') with self.assertRaises(ValueError): _ = a.peek('hex:8, hex:8') with self.assertRaises(TypeError): _ = a.read(10, 12) with self.assertRaises(TypeError): _ = a.peek(12, 14) with self.assertRaises(TypeError): _ = a.read(8, 8) with self.assertRaises(TypeError): _ = a.peek(80, 80) def testStartswith(self): a = BitStream() self.assertTrue(a.startswith(BitStream())) self.assertFalse(a.startswith('0b0')) a = BitStream('0x12ff') self.assertTrue(a.startswith('0x1')) self.assertTrue(a.startswith('0b0001001')) self.assertTrue(a.startswith('0x12ff')) self.assertFalse(a.startswith('0x12ff, 0b1')) self.assertFalse(a.startswith('0x2')) def testStartswithStartEnd(self): s = BitStream('0x123456') self.assertTrue(s.startswith('0x234', 4)) self.assertFalse(s.startswith('0x123', end=11)) self.assertTrue(s.startswith('0x123', end=12)) self.assertTrue(s.startswith('0x34', 8, 16)) self.assertFalse(s.startswith('0x34', 7, 16)) self.assertFalse(s.startswith('0x34', 9, 16)) self.assertFalse(s.startswith('0x34', 8, 15)) def testEndswith(self): a = BitStream() self.assertTrue(a.endswith('')) self.assertFalse(a.endswith(BitStream('0b1'))) a = BitStream('0xf2341') self.assertTrue(a.endswith('0x41')) self.assertTrue(a.endswith('0b001')) self.assertTrue(a.endswith('0xf2341')) self.assertFalse(a.endswith('0x1f2341')) self.assertFalse(a.endswith('0o34')) def testEndswithStartEnd(self): s = BitStream('0x123456') self.assertTrue(s.endswith('0x234', end=16)) self.assertFalse(s.endswith('0x456', start=13)) self.assertTrue(s.endswith('0x456', start=12)) self.assertTrue(s.endswith('0x34', 8, 16)) self.assertTrue(s.endswith('0x34', 7, 16)) self.assertFalse(s.endswith('0x34', 9, 16)) self.assertFalse(s.endswith('0x34', 8, 15)) def testUnhashability(self): s = BitStream('0xf') with self.assertRaises(TypeError): _ = {s} with self.assertRaises(TypeError): _ = hash([s]) def testConstBitStreamSetCreation(self): sl = [ConstBitStream(uint=i, length=7) for i in range(15)] s = set(sl) self.assertEqual(len(s), 15) s.add(ConstBitStream('0b0000011')) self.assertEqual(len(s), 15) with self.assertRaises(TypeError): s.add(BitStream('0b0000011')) def testConstBitStreamFunctions(self): s = ConstBitStream('0xf, 0b1') self.assertEqual(type(s), ConstBitStream) t = copy.copy(s) self.assertEqual(type(t), ConstBitStream) a = s + '0o3' self.assertEqual(type(a), ConstBitStream) b = a[0:4] self.assertEqual(type(b), ConstBitStream) b = a[4:3] self.assertEqual(type(b), ConstBitStream) b = a[5:2:-1] self.assertEqual(type(b), ConstBitStream) b = ~a self.assertEqual(type(b), ConstBitStream) b = a << 2 self.assertEqual(type(b), ConstBitStream) b = a >> 2 self.assertEqual(type(b), ConstBitStream) b = a * 2 self.assertEqual(type(b), ConstBitStream) b = a * 0 self.assertEqual(type(b), ConstBitStream) b = a & ~a self.assertEqual(type(b), ConstBitStream) b = a | ~a self.assertEqual(type(b), ConstBitStream) b = a ^ ~a self.assertEqual(type(b), ConstBitStream) b = a._slice(4, 4) self.assertEqual(type(b), ConstBitStream) b = a.read(4) self.assertEqual(type(b), ConstBitStream) def testConstBitStreamProperties(self): a = ConstBitStream('0x123123') with self.assertRaises(AttributeError): a.hex = '0x234' with self.assertRaises(AttributeError): a.oct = '0o234' with self.assertRaises(AttributeError): a.bin = '0b101' with self.assertRaises(AttributeError): a.ue = 3453 with self.assertRaises(AttributeError): a.se = -123 with self.assertRaises(AttributeError): a.int = 432 with self.assertRaises(AttributeError): a.uint = 4412 with self.assertRaises(AttributeError): a.intle = 123 with self.assertRaises(AttributeError): a.uintle = 4412 with self.assertRaises(AttributeError): a.intbe = 123 with self.assertRaises(AttributeError): a.uintbe = 4412 with self.assertRaises(AttributeError): a.intne = 123 with self.assertRaises(AttributeError): a.uintne = 4412 with self.assertRaises(AttributeError): a.bytes = b'hello' def testConstBitStreamMisc(self): a = ConstBitStream('0xf') b = a a += '0xe' self.assertEqual(b, '0xf') self.assertEqual(a, '0xfe') c = BitStream(a) self.assertEqual(a, c) a = ConstBitStream('0b1') a += a self.assertEqual(a, '0b11') self.assertEqual(type(a), ConstBitStream) a._addleft(a) self.assertEqual(a, '0b1111') self.assertEqual(type(a), ConstBitStream) def testConstBitStreamHashibility(self): a = ConstBitStream('0x1') b = ConstBitStream('0x2') c = ConstBitStream('0x1') c.pos = 3 s = {a, b, c} self.assertEqual(len(s), 2) self.assertEqual(hash(a), hash(c)) def testConstHashabilityAgain(self): a = ConstBitStream(uint=1 << 300, length=10000) b = ConstBitStream(uint=2 << 300, length=10000) c = ConstBitStream(uint=3 << 300, length=10000) s = {a, b, c} self.assertEqual(len(s), 3) def testHashEdgeCases(self): a = ConstBitStream('0xabcd') b = ConstBitStream('0xabcd') c = b[1:] self.assertEqual(hash(a), hash(b)) self.assertNotEqual(hash(a), hash(c)) def testConstBitStreamCopy(self): a = ConstBitStream('0xabc') a.pos = 11 b = copy.copy(a) b.pos = 4 self.assertEqual(id(a._bitstore), id(b._bitstore)) self.assertEqual(a.pos, 11) self.assertEqual(b.pos, 4) def testPython26stuff(self): s = BitStream('0xff') self.assertTrue(isinstance(s.tobytes(), bytes)) self.assertTrue(isinstance(s.bytes, bytes)) def testReadFromBits(self): a = ConstBitStream('0xaabbccdd') b = a.read(8) self.assertEqual(b, '0xaa') self.assertEqual(a[0:8], '0xaa') self.assertEqual(a[-1], True) a.pos = 0 self.assertEqual(a.read(4).uint, 10) class Set(unittest.TestCase): def testSet(self): a = BitStream(length=16) a.set(True, 0) self.assertEqual(a, '0b10000000 00000000') a.set(1, 15) self.assertEqual(a, '0b10000000 00000001') b = a[4:12] b.set(True, 1) self.assertEqual(b, '0b01000000') b.set(True, -1) self.assertEqual(b, '0b01000001') b.set(1, -8) self.assertEqual(b, '0b11000001') with self.assertRaises(IndexError): b.set(True, -9) with self.assertRaises(IndexError): b.set(True, 8) def testSetNegativeIndex(self): a = BitStream(10) a.set(1, -1) self.assertEqual(a.bin, '0000000001') a.set(1, [-1, -10]) self.assertEqual(a.bin, '1000000001') with self.assertRaises(IndexError): a.set(1, [-11]) def testFileBasedSetUnset(self): filename = os.path.join(THIS_DIR, 'test.m1v') a = BitStream(filename=filename) a.set(True, (0, 1, 2, 3, 4)) self.assertEqual(a[0:32], '0xf80001b3') a = BitStream(filename=filename) a.set(False, (28, 29, 30, 31)) self.assertTrue(a.startswith('0x000001b0')) def testSetList(self): a = BitStream(length=18) a.set(True, range(18)) self.assertEqual(a.int, -1) a.set(False, range(18)) self.assertEqual(a.int, 0) def testUnset(self): a = BitStream(length=16, int=-1) a.set(False, 0) self.assertEqual(~a, '0b10000000 00000000') a.set(0, 15) self.assertEqual(~a, '0b10000000 00000001') b = a[4:12] b.set(False, 1) self.assertEqual(~b, '0b01000000') b.set(False, -1) self.assertEqual(~b, '0b01000001') b.set(False, -8) self.assertEqual(~b, '0b11000001') with self.assertRaises(IndexError): b.set(False, -9) with self.assertRaises(IndexError): b.set(False, 8) def testSetWholeBitStream(self): a = BitStream(10000) a.set(1) self.assertTrue(a.all(1)) a.set(0) self.assertTrue(a.all(0)) class Invert(unittest.TestCase): def testInvertBits(self): a = BitStream('0b111000') a.invert(range(a.len)) self.assertEqual(a, '0b000111') a.invert([0, 1, -1]) self.assertEqual(a, '0b110110') def testInvertWholeBitStream(self): a = BitStream('0b11011') a.invert() self.assertEqual(a, '0b00100') def testInvertSingleBit(self): a = BitStream('0b000001') a.invert(0) self.assertEqual(a.bin, '100001') a.invert(-1) self.assertEqual(a.bin, '100000') def testInvertErrors(self): a = BitStream(10) with self.assertRaises(IndexError): a.invert(10) with self.assertRaises(IndexError): a.invert(-11) with self.assertRaises(IndexError): a.invert([1, 2, 10]) def testIor(self): a = BitStream('0b1101001') a |= '0b1110000' self.assertEqual(a, '0b1111001') b = a[2:] c = a[1:-1] b |= c self.assertEqual(c, '0b11100') self.assertEqual(b, '0b11101') def testIand(self): a = BitStream('0b0101010101000') a &= '0b1111110000000' self.assertEqual(a, '0b0101010000000') s = BitStream(filename=os.path.join(THIS_DIR, 'test.m1v'), offset=26, length=24) s &= '0xff00ff' self.assertEqual(s, '0xcc0004') def testIxor(self): a = BitStream('0b11001100110011') a ^= '0b11111100000010' self.assertEqual(a, '0b00110000110001') def testLogicalInplaceErrors(self): a = BitStream(4) with self.assertRaises(ValueError): a |= '0b111' with self.assertRaises(ValueError): a &= '0b111' with self.assertRaises(ValueError): a ^= '0b111' class AllAndAny(unittest.TestCase): def testAll(self): a = BitStream('0b0111') self.assertTrue(a.all(True, (1, 3))) self.assertFalse(a.all(True, (0, 1, 2))) self.assertTrue(a.all(True, [-1])) self.assertFalse(a.all(True, [0])) def testFileBasedAll(self): filename = os.path.join(THIS_DIR, 'test.m1v') a = BitStream(filename=filename) self.assertTrue(a.all(True, [31])) a = BitStream(filename=filename) self.assertTrue(a.all(False, (0, 1, 2, 3, 4))) def testFileBasedAny(self): filename = os.path.join(THIS_DIR, 'test.m1v') a = BitStream(filename=filename) self.assertTrue(a.any(True, (31, 12))) a = BitStream(filename=filename) self.assertTrue(a.any(False, (0, 1, 2, 3, 4))) b = ConstBitStream(filename=filename, offset=16) self.assertTrue(b.startswith('0x01')) self.assertFalse(b.any(True, range(0, 7))) self.assertTrue(b.any(True, range(0, 8))) self.assertTrue(b.any(True)) def testAny(self): a = BitStream('0b10011011') self.assertTrue(a.any(True, (1, 2, 3, 5))) self.assertFalse(a.any(True, (1, 2, 5))) self.assertTrue(a.any(True, (-1,))) self.assertFalse(a.any(True, (1,))) def testAllFalse(self): a = BitStream('0b0010011101') self.assertTrue(a.all(False, (0, 1, 3, 4))) self.assertFalse(a.all(False, (0, 1, 2, 3, 4))) def testAnyFalse(self): a = BitStream('0b01001110110111111111111111111') self.assertTrue(a.any(False, (4, 5, 6, 2))) self.assertFalse(a.any(False, (1, 15, 20))) def testAnyEmptyBitstring(self): a = ConstBitStream() self.assertFalse(a.any(True)) self.assertFalse(a.any(False)) def testAllEmptyBitStream(self): a = ConstBitStream() self.assertTrue(a.all(True)) self.assertTrue(a.all(False)) def testAnyWholeBitstring(self): a = ConstBitStream('0xfff') self.assertTrue(a.any(True)) self.assertFalse(a.any(False)) def testAllWholeBitstring(self): a = ConstBitStream('0xfff') self.assertTrue(a.all(True)) self.assertFalse(a.all(False)) def testErrors(self): a = BitStream('0xf') with self.assertRaises(IndexError): a.all(True, [5]) with self.assertRaises(IndexError): a.all(True, [-5]) with self.assertRaises(IndexError): a.any(True, [5]) with self.assertRaises(IndexError): a.any(True, [-5]) ################### def testFloatInitialisation(self): for f in (0.000001, -1.0, 1.0, 0.2, -3.14159265): a = BitStream(float=f, length=64) a.pos = 6 self.assertEqual(a.float, f) a = BitStream('float:64=%s' % str(f)) a.pos = 6 self.assertEqual(a.float, f) a = BitStream('floatbe:64=%s' % str(f)) a.pos = 6 self.assertEqual(a.floatbe, f) a = BitStream('floatle:64=%s' % str(f)) a.pos = 6 self.assertEqual(a.floatle, f) a = BitStream('floatne:64=%s' % str(f)) a.pos = 6 self.assertEqual(a.floatne, f) b = BitStream(float=f, length=32) b.pos = 6 self.assertAlmostEqual(b.float / f, 1.0) b = BitStream('float:32=%s' % str(f)) b.pos = 6 self.assertAlmostEqual(b.float / f, 1.0) b = BitStream('floatbe:32=%s' % str(f)) b.pos = 6 self.assertAlmostEqual(b.floatbe / f, 1.0) b = BitStream('floatle:32=%s' % str(f)) b.pos = 6 self.assertAlmostEqual(b.floatle / f, 1.0) b = BitStream('floatne:32=%s' % str(f)) b.pos = 6 self.assertAlmostEqual(b.floatne / f, 1.0) a = BitStream(float=f, length=16) a.pos = 6 self.assertAlmostEqual(a.float, f, places=2) a = BitStream('float:16=%s' % str(f)) a.pos = 6 self.assertAlmostEqual(a.float, f, places=2) a = BitStream('floatbe:16=%s' % str(f)) a.pos = 6 self.assertAlmostEqual(a.floatbe, f, places=2) a = BitStream('floatle:16=%s' % str(f)) a.pos = 6 self.assertAlmostEqual(a.floatle, f, places=2) a = BitStream('floatne:16=%s' % str(f)) a.pos = 6 self.assertAlmostEqual(a.floatne, f, places=2) a = BitStream('0x12345678') a.pos = 6 a.f = 23 self.assertEqual(a.f, 23.0) def testFloatInitStrings(self): for s in ('5', '+0.0001', '-1e101', '4.', '.2', '-.65', '43.21E+32'): a = BitStream('float:64=%s' % s) self.assertEqual(a.float, float(s)) for s in ('5', '+0.5', '-1e2', '4.', '.25', '-.75'): a = BitStream('float:16=%s' % s) self.assertEqual(a.f, float(s)) def testFloatPacking(self): a = pack('>d', 0.01) self.assertEqual(a.float, 0.01) self.assertEqual(a.floatbe, 0.01) a.byteswap() self.assertEqual(a.floatle, 0.01) b = pack('>f', 1e10) self.assertAlmostEqual(b.float / 1e10, 1.0) c = pack('5d', 10.0, 5.0, 2.5, 1.25, 0.1) self.assertEqual(d.unpack('>5d'), [10.0, 5.0, 2.5, 1.25, 0.1]) e = pack('>3e', -100, 100, 0.25) self.assertEqual(e.unpack('>3e'), [-100.0, 100.0, 0.25]) def testFloatReading(self): a = BitStream('floatle:64=12, floatbe:64=-0.01, floatne:64=3e33') x, y, z = a.readlist('floatle:64, floatbe:64, floatne:64') self.assertEqual(x, 12.0) self.assertEqual(y, -0.01) self.assertEqual(z, 3e33) a = BitStream('floatle:16=12, floatbe:32=-0.01, floatne:32=3e33') x, y, z = a.readlist('floatle:16, floatbe:32, floatne:32') self.assertAlmostEqual(x / 12.0, 1.0) self.assertAlmostEqual(y / -0.01, 1.0) self.assertAlmostEqual(z / 3e33, 1.0) a = BitStream('0b11, floatle:64=12, 0xfffff') a.pos = 2 self.assertEqual(a.read('floatle:64'), 12.0) b = BitStream(floatle=20, length=32) b.floatle = 10.0 b = [0] + b self.assertEqual(b[1:].floatle, 10.0) def testNonAlignedFloatReading(self): s = BitStream('0b1, float:32 = 10.0') x, y = s.readlist('1, float:32') self.assertEqual(y, 10.0) s[1:] = 'floatle:32=20.0' x, y = s.unpack('1, floatle:32') self.assertEqual(y, 20.0) def testFloatErrors(self): a = BitStream('0x3') with self.assertRaises(bitstring.InterpretError): _ = a.float with self.assertRaises(bitstring.CreationError): a.float = -0.2 for le in (8, 10, 12, 18, 30, 128, 200): with self.assertRaises(ValueError): _ = BitStream(float=1.0, length=le) with self.assertRaises(bitstring.CreationError): _ = BitStream(floatle=0.3, length=0) with self.assertRaises(bitstring.CreationError): _ = BitStream(floatle=0.3, length=1) with self.assertRaises(bitstring.CreationError): _ = BitStream(float=2) with self.assertRaises(bitstring.InterpretError): _ = a.read('floatle:2') def testReadErrorChangesPos(self): a = BitStream('0x123123') with self.assertRaises(ValueError): a.read('10, 5') def testRor(self): a = BitStream('0b11001') a.ror(0) self.assertEqual(a, '0b11001') a.ror(1) self.assertEqual(a, '0b11100') a.ror(5) self.assertEqual(a, '0b11100') a.ror(101) self.assertEqual(a, '0b01110') a = BitStream('0b1') a.ror(1000000) self.assertEqual(a, '0b1') def testRorErrors(self): a = BitStream() with self.assertRaises(bitstring.Error): a.ror(0) a += '0b001' with self.assertRaises(ValueError): a.ror(-1) def testRol(self): a = BitStream('0b11001') a.rol(0) self.assertEqual(a, '0b11001') a.rol(1) self.assertEqual(a, '0b10011') a.rol(5) self.assertEqual(a, '0b10011') a.rol(101) self.assertEqual(a, '0b00111') a = BitStream('0b1') a.rol(1000000) self.assertEqual(a, '0b1') def testRolFromFile(self): a = BitStream(filename=os.path.join(THIS_DIR, 'test.m1v')) m = a.len a.rol(1) self.assertTrue(a.startswith('0x000003')) self.assertEqual(a.len, m) self.assertTrue(a.endswith('0x0036e')) def testRorFromFile(self): a = BitStream(filename=os.path.join(THIS_DIR, 'test.m1v')) m = a.len a.ror(1) self.assertTrue(a.startswith('0x800000')) self.assertEqual(a.len, m) self.assertTrue(a.endswith('0x000db')) def testRolErrors(self): a = BitStream() with self.assertRaises(bitstring.Error): a.rol(0) a += '0b001' with self.assertRaises(ValueError): a.rol(-1) def testBytesToken(self): a = BitStream('0x010203') b = a.read('bytes:1') self.assertTrue(isinstance(b, bytes)) self.assertEqual(b, b'\x01') x, y, z = a.unpack('uint:4, bytes:2, uint') self.assertEqual(x, 0) self.assertEqual(y, b'\x10\x20') self.assertEqual(z, 3) s = pack('bytes:4', b'abcd') self.assertEqual(s.bytes, b'abcd') def testBytesTokenMoreThoroughly(self): a = BitStream('0x0123456789abcdef') a.pos += 16 self.assertEqual(a.read('bytes:1'), b'\x45') self.assertEqual(a.read('bytes:3'), b'\x67\x89\xab') x, y, z = a.unpack('bits:28, bytes, bits:12') self.assertEqual(y, b'\x78\x9a\xbc') def testDedicatedReadFunctions(self): a = BitStream('0b11, uint:43=98798798172, 0b11111') x = a._readuint(2, 43) self.assertEqual(x, 98798798172) self.assertEqual(a.pos, 0) x = a._readint(2, 43) self.assertEqual(x, 98798798172) self.assertEqual(a.pos, 0) a = BitStream('0b11, uintbe:48=98798798172, 0b11111') x = a._readuintbe(2, 48) self.assertEqual(x, 98798798172) self.assertEqual(a.pos, 0) x = a._readintbe(2, 48) self.assertEqual(x, 98798798172) self.assertEqual(a.pos, 0) a = BitStream('0b111, uintle:40=123516, 0b111') self.assertEqual(a._readuintle(3, 40), 123516) b = BitStream('0xff, uintle:800=999, 0xffff') self.assertEqual(b._readuintle(8, 800), 999) a = BitStream('0b111, intle:48=999999999, 0b111111111111') self.assertEqual(a._readintle(3, 48), 999999999) b = BitStream('0xff, intle:200=918019283740918263512351235, 0xfffffff') self.assertEqual(b._readintle(8, 200), 918019283740918263512351235) a = BitStream('0b111, bfloat:16=-5.25, 0xffffffff') self.assertEqual(a._readbfloatbe(3, 16), -5.25) a = BitStream('0b111, floatle:64=9.9998, 0b111') self.assertEqual(a._readfloatle(3, 64), 9.9998) def testAutoInitWithInt(self): a = BitStream(0) self.assertFalse(a) a = BitStream(1) self.assertEqual(a, '0b0') a = BitStream(1007) self.assertEqual(a, BitStream(length=1007)) with self.assertRaises(bitstring.CreationError): _ = BitStream(-1) self.assertEqual(ConstBitStream(13), Bits(13)) with self.assertRaises(TypeError): a += 10 def testReadingProblems(self): a = BitStream('0x000001') b = a.read('uint:24') self.assertEqual(b, 1) a.pos = 0 with self.assertRaises(bitstring.ReadError): _ = a.read('bytes:4') @unittest.skip("Bug #266") def testPosResetBug(self): a = BitStream('0x0120310230123', pos=23) self.assertEqual(a.pos, 23) a.u8 = 14 self.assertEqual(a.pos, 0) a.pos = 5 a.u8 = 9 self.assertEqual(a.pos, 0) def testCreationExceptionBug(self): with self.assertRaises(ValueError): _ = BitStream(bin=1) def testAddVersesInPlaceAdd(self): a1 = ConstBitStream('0xabc') b1 = a1 a1 += '0xdef' self.assertEqual(a1, '0xabcdef') self.assertEqual(b1, '0xabc') a2 = BitStream('0xabc') b2 = a2 c2 = a2 + '0x0' a2 += '0xdef' self.assertEqual(a2, '0xabcdef') self.assertEqual(b2, '0xabcdef') self.assertEqual(c2, '0xabc0') def testAndVersesInPlaceAnd(self): a1 = ConstBitStream('0xabc') b1 = a1 a1 &= '0xf0f' self.assertEqual(a1, '0xa0c') self.assertEqual(b1, '0xabc') a2 = BitStream('0xabc') b2 = a2 c2 = a2 & '0x00f' a2 &= '0xf0f' self.assertEqual(a2, '0xa0c') self.assertEqual(b2, '0xa0c') self.assertEqual(c2, '0x00c') def testOrVersesInPlaceOr(self): a1 = ConstBitStream('0xabc') b1 = a1 a1 |= '0xf0f' self.assertEqual(a1, '0xfbf') self.assertEqual(b1, '0xabc') a2 = BitStream('0xabc') b2 = a2 c2 = a2 | '0x00f' a2 |= '0xf0f' self.assertEqual(a2, '0xfbf') self.assertEqual(b2, '0xfbf') self.assertEqual(c2, '0xabf') def testXorVersesInPlaceXor(self): a1 = ConstBitStream('0xabc') b1 = a1 a1 ^= '0xf0f' self.assertEqual(a1, '0x5b3') self.assertEqual(b1, '0xabc') a2 = BitStream('0xabc') b2 = a2 c2 = a2 ^ '0x00f' a2 ^= '0xf0f' self.assertEqual(a2, '0x5b3') self.assertEqual(b2, '0x5b3') self.assertEqual(c2, '0xab3') def testMulVersesInPlaceMul(self): a1 = ConstBitStream('0xabc') b1 = a1 a1 *= 3 self.assertEqual(a1, '0xabcabcabc') self.assertEqual(b1, '0xabc') a2 = BitStream('0xabc') b2 = a2 c2 = a2 * 2 a2 *= 3 self.assertEqual(a2, '0xabcabcabc') self.assertEqual(b2, '0xabcabcabc') self.assertEqual(c2, '0xabcabc') def testLshiftVersesInPlaceLshift(self): a1 = ConstBitStream('0xabc') b1 = a1 a1 <<= 4 self.assertEqual(a1, '0xbc0') self.assertEqual(b1, '0xabc') a2 = BitStream('0xabc') b2 = a2 c2 = a2 << 8 a2 <<= 4 self.assertEqual(a2, '0xbc0') self.assertEqual(b2, '0xbc0') self.assertEqual(c2, '0xc00') def testRshiftVersesInPlaceRshift(self): a1 = ConstBitStream('0xabc') b1 = a1 a1 >>= 4 self.assertEqual(a1, '0x0ab') self.assertEqual(b1, '0xabc') a2 = BitStream('0xabc') b2 = a2 c2 = a2 >> 8 a2 >>= 4 self.assertEqual(a2, '0x0ab') self.assertEqual(b2, '0x0ab') self.assertEqual(c2, '0x00a') def testAutoFromBool(self): with self.assertRaises(TypeError): a = ConstBitStream() + True + False + True class Bugs(unittest.TestCase): def testBugInReplace(self): s = BitStream('0x00112233') li = list(s.split('0x22', start=8, bytealigned=True)) self.assertEqual(li, ['0x11', '0x2233']) s = BitStream('0x00112233') s.replace('0x22', '0xffff', start=8, bytealigned=True) self.assertEqual(s, '0x0011ffff33') s = BitStream('0x0123412341234') s.replace('0x23', '0xf', start=9, bytealigned=True) self.assertEqual(s, '0x012341f41f4') def testTruncateleftBug(self): a = BitStream('0b000000111')[2:] a._truncateleft(6) self.assertEqual(a, '0b1') def testNullBits(self): s = ConstBitStream(bin='') t = ConstBitStream(oct='') u = ConstBitStream(hex='') v = ConstBitStream(bytes=b'') self.assertFalse(s) self.assertFalse(t) self.assertFalse(u) self.assertFalse(v) def testMultiplicativeFactorsCreation(self): s = BitStream('1*0b1') self.assertEqual(s, '0b1') s = BitStream('4*0xc') self.assertEqual(s, '0xcccc') s = BitStream('0b1, 0*0b0') self.assertEqual(s, '0b1') s = BitStream('0b1, 3*uint:8=34, 2*0o755') self.assertEqual(s, '0b1, uint:8=34, uint:8=34, uint:8=34, 0o755755') s = BitStream('0*0b1001010') self.assertFalse(s) def testMultiplicativeFactorsReading(self): s = BitStream('0xc') * 5 a, b, c, d, e = s.readlist('5*uint:4') self.assertTrue(a == b == c == d == e == 12) s = ConstBitStream('2*0b101, 4*uint:7=3') a, b, c, d, e = s.readlist('2*bin:3, 3*uint:7') self.assertTrue(a == b == '101') self.assertTrue(c == d == e == 3) def testMultiplicativeFactorsPacking(self): s = pack('3*bin', '1', '001', '101') self.assertEqual(s, '0b1001101') s = pack('hex, 2*se=-56, 3*uint:37', '34', 1, 2, 3) a, b, c, d, e, f = s.unpack('hex:8, 2*se, 3*uint:37') self.assertEqual(a, '34') self.assertEqual(b, -56) self.assertEqual(c, -56) self.assertEqual((d, e, f), (1, 2, 3)) def testMultiplicativeFactorsUnpacking(self): s = ConstBitStream('0b10111') a, b, c, d = s.unpack('3*bool, bin') self.assertEqual((a, b, c), (True, False, True)) self.assertEqual(d, '11') def testPackingDefaultIntWithKeyword(self): s = pack('uint:12', 100) self.assertEqual(s.unpack('12')[0].uint, 100) s = pack('int:oh_no_not_the_eyes=33', oh_no_not_the_eyes=17) self.assertEqual(s.int, 33) self.assertEqual(s.len, 17) def testInitFromIterable(self): self.assertTrue(isinstance(range(10), collections.abc.Iterable)) s = ConstBitStream(range(12)) self.assertEqual(s, '0x7ff') def testFunctionNegativeIndices(self): # insert s = BitStream('0b0111') s.insert('0b0', -1) self.assertEqual(s, '0b01101') with self.assertRaises(ValueError): s.insert('0b0', -1000) # reverse s.reverse(-2) self.assertEqual(s, '0b01110') t = BitStream('0x778899abcdef') t.reverse(-12, -4) self.assertEqual(t, '0x778899abc7bf') # reversebytes t.byteswap(0, -40, -16) self.assertEqual(t, '0x77ab9988c7bf') # overwrite t.overwrite('0x666', -20) self.assertEqual(t, '0x77ab998666bf') # find found = t.find('0x998', bytealigned=True, start=-31) self.assertFalse(found) found = t.find('0x998', bytealigned=True, start=-32) self.assertTrue(found) self.assertEqual(t.pos, 16) t.pos = 0 found = t.find('0x988', bytealigned=True, end=-21) self.assertFalse(found) found = t.find('0x998', bytealigned=True, end=-20) self.assertTrue(found) self.assertEqual(t.pos, 16) # findall s = BitStream('0x1234151f') li = list(s.findall('0x1', bytealigned=True, start=-15)) self.assertEqual(li, [24]) li = list(s.findall('0x1', bytealigned=True, start=-16)) self.assertEqual(li, [16, 24]) li = list(s.findall('0x1', bytealigned=True, end=-5)) self.assertEqual(li, [0, 16]) li = list(s.findall('0x1', bytealigned=True, end=-4)) self.assertEqual(li, [0, 16, 24]) # rfind found = s.rfind('0x1f', end=-1) self.assertFalse(found) found = s.rfind('0x12', start=-31) self.assertFalse(found) # cut s = BitStream('0x12345') li = list(s.cut(4, start=-12, end=-4)) self.assertEqual(li, ['0x3', '0x4']) # split s = BitStream('0xfe0012fe1200fe') li = list(s.split('0xfe', bytealigned=True, end=-1)) self.assertEqual(li, ['', '0xfe0012', '0xfe1200f, 0b111']) li = list(s.split('0xfe', bytealigned=True, start=-8)) self.assertEqual(li, ['', '0xfe']) # startswith self.assertTrue(s.startswith('0x00f', start=-16)) self.assertTrue(s.startswith('0xfe00', end=-40)) self.assertFalse(s.startswith('0xfe00', end=-41)) # endswith self.assertTrue(s.endswith('0x00fe', start=-16)) self.assertFalse(s.endswith('0x00fe', start=-15)) self.assertFalse(s.endswith('0x00fe', end=-1)) self.assertTrue(s.endswith('0x00f', end=-4)) # replace s.replace('0xfe', '', end=-1) self.assertEqual(s, '0x00121200fe') s.replace('0x00', '', start=-24) self.assertEqual(s, '0x001212fe') def testRotateStartAndEnd(self): a = BitStream('0b110100001') a.rol(1, 3, 6) self.assertEqual(a, '0b110001001') a.ror(1, start=-4) self.assertEqual(a, '0b110001100') a.rol(202, end=-5) self.assertEqual(a, '0b001101100') a.ror(3, end=4) self.assertEqual(a, '0b011001100') with self.assertRaises(ValueError): a.rol(5, start=-4, end=-6) def testByteSwapInt(self): s = pack('5*uintle:16', *range(10, 15)) self.assertEqual(list(range(10, 15)), s.unpack('5*uintle:16')) swaps = s.byteswap(2) self.assertEqual(list(range(10, 15)), s.unpack('5*uintbe:16')) self.assertEqual(swaps, 5) s = BitStream('0xf234567f') swaps = s.byteswap(1, start=4) self.assertEqual(swaps, 3) self.assertEqual(s, '0xf234567f') s.byteswap(2, start=4) self.assertEqual(s, '0xf452367f') s.byteswap(2, start=4, end=-4) self.assertEqual(s, '0xf234567f') s.byteswap(3) self.assertEqual(s, '0x5634f27f') s.byteswap(2, repeat=False) self.assertEqual(s, '0x3456f27f') swaps = s.byteswap(5) self.assertEqual(swaps, 0) swaps = s.byteswap(4, repeat=False) self.assertEqual(swaps, 1) self.assertEqual(s, '0x7ff25634') def testByteSwapPackCode(self): s = BitStream('0x0011223344556677') swaps = s.byteswap('b') self.assertEqual(s, '0x0011223344556677') self.assertEqual(swaps, 8) swaps = s.byteswap('>3h', repeat=False) self.assertEqual(s, '0x1100332255446677') self.assertEqual(swaps, 1) def testByteSwapIterable(self): s = BitStream('0x0011223344556677') swaps = s.byteswap(range(1, 4), repeat=False) self.assertEqual(swaps, 1) self.assertEqual(s, '0x0022115544336677') swaps = s.byteswap([2], start=8) self.assertEqual(s, '0x0011224455663377') self.assertEqual(3, swaps) swaps = s.byteswap([2, 3], start=4) self.assertEqual(swaps, 1) self.assertEqual(s, '0x0120156452463377') def testByteSwapErrors(self): s = BitStream('0x0011223344556677') with self.assertRaises(ValueError): s.byteswap('z') with self.assertRaises(ValueError): s.byteswap(-1) with self.assertRaises(ValueError): s.byteswap([-1]) with self.assertRaises(ValueError): s.byteswap([1, 'e']) with self.assertRaises(ValueError): s.byteswap('!h') with self.assertRaises(ValueError): s.byteswap(2, start=-1000) with self.assertRaises(TypeError): s.byteswap(5.4) def testByteSwapFromFile(self): s = BitStream(filename=os.path.join(THIS_DIR, 'smalltestfile')) swaps = s.byteswap('2bh') self.assertEqual(s, '0x0123674589abefcd') self.assertEqual(swaps, 2) def testBracketExpander(self): be = bitstring.utils.expand_brackets self.assertEqual(be('hello'), 'hello') self.assertEqual(be('(hello)'), 'hello') self.assertEqual(be('1*(hello)'), 'hello') self.assertEqual(be('2*(hello)'), 'hello,hello') self.assertEqual(be('1*(a,b)'), 'a,b') self.assertEqual(be('2*(a,b)'), 'a,b,a,b') self.assertEqual(be('2*(a),3*(b)'), 'a,a,b,b,b') self.assertEqual(be('2*(a,b,3*(c,d),e)'), 'a,b,c,d,c,d,c,d,e,a,b,c,d,c,d,c,d,e') with self.assertRaises(ValueError): _ = be('2*(x,y()') def testBracketTokens(self): s = BitStream('3*(0x0, 0b1)') self.assertEqual(s, '0x0, 0b1, 0x0, 0b1, 0x0, 0b1') s = pack('2*(uint:12, 3*(uint:7, uint:6))', *range(3, 17)) a = s.unpack('12, 7, 6, 7, 6, 7, 6, 12, 7, 6, 7, 6, 7, 6') self.assertEqual([x.uint for x in a], list(range(3, 17))) b = s.unpack('2*(12,3*(7,6))') self.assertEqual(a, b) def testPackCodeDicts(self): self.assertEqual(sorted(bitstring.utils.REPLACEMENTS_BE.keys()), sorted(bitstring.utils.REPLACEMENTS_LE.keys())) self.assertEqual(sorted(bitstring.utils.REPLACEMENTS_BE.keys()), sorted(bitstring.utils.PACK_CODE_SIZE.keys())) for key in bitstring.utils.PACK_CODE_SIZE: be = pack(bitstring.utils.REPLACEMENTS_BE[key], 0) le = pack(bitstring.utils.REPLACEMENTS_LE[key], 0) self.assertEqual(be.len, bitstring.utils.PACK_CODE_SIZE[key] * 8) self.assertEqual(le.len, be.len) def testUnicode(self): a = ConstBitStream(u'uint:12=34') self.assertEqual(a.uint, 34) a += u'0xfe' self.assertEqual(a[12:], '0xfe') a = BitStream('0x1122') c = a.byteswap(u'h') self.assertEqual(c, 1) self.assertEqual(a, u'0x2211') class UnpackWithDict(unittest.TestCase): def testLengthKeywords(self): a = ConstBitStream('2*int:13=100, 0b111') x, y, z = a.unpack('n, ' 'int:m, bin:q', n=13, m=13, q=3) self.assertEqual(x, 'uint:13=100') self.assertEqual(y, 100) self.assertEqual(z, '111') def testLengthKeywordsWithStretch(self): a = ConstBitStream('0xff, 0b000, 0xf') x, y, z = a.unpack('hex:a, bin, hex:b', a=8, b=4) self.assertEqual(y, '000') def testUnusedKeyword(self): a = ConstBitStream('0b110') x, = a.unpack('bin:3', notused=33) self.assertEqual(x, '110') def testLengthKeywordErrors(self): a = pack('uint:p=33', p=12) with self.assertRaises(ValueError): a.unpack('uint:p') with self.assertRaises(TypeError): a.unpack('uint:p', p='a_string') class ReadWithDict(unittest.TestCase): def testLengthKeywords(self): s = BitStream('0x0102') x, y = s.readlist('a, hex:b', a=8, b=4) self.assertEqual((x, y), ('0x01', '0')) self.assertEqual(s.pos, 12) def testBytesKeywordProblem(self): s = BitStream('0x01') x, = s.unpack('bytes:a', a=1) self.assertEqual(x, b'\x01') s = BitStream('0x000ff00a') x, y, z = s.unpack('12, bytes:x, bits', x=2) self.assertEqual((x.int, y, z), (0, b'\xff\x00', '0xa')) class PeekWithDict(unittest.TestCase): def testLengthKeywords(self): s = BitStream('0x0102') x, y = s.peeklist('a, hex:b', a=8, b=4) self.assertEqual((x, y), ('0x01', '0')) self.assertEqual(s.pos, 0) class BoolToken(unittest.TestCase): def testInterpretation(self): a = ConstBitStream('0b1') self.assertEqual(a.bool, True) self.assertEqual(a.read('bool'), True) self.assertEqual(a.unpack('bool')[0], True) b = ConstBitStream('0b0') self.assertEqual(b.bool, False) self.assertEqual(b.peek('bool'), False) self.assertEqual(b.unpack('bool')[0], False) def testPack(self): a = pack('bool=True') b = pack('bool=False') self.assertEqual(a.bool, True) self.assertEqual(b.bool, False) c = pack('4*bool', False, True, 'False', 'True') self.assertEqual(c, '0b0101') def testAssignment(self): a = BitStream() a.bool = True self.assertEqual(a.bool, True) a.hex = 'ee' a.bool = False self.assertEqual(a.bool, False) a.bool = 'False' self.assertEqual(a.bool, False) a.bool = 'True' self.assertEqual(a.bool, True) a.bool = 0 self.assertEqual(a.bool, False) a.bool = 1 self.assertEqual(a.bool, True) def testErrors(self): with self.assertRaises(bitstring.CreationError): pack('bool', 'hello') with self.assertRaises(bitstring.CreationError): pack('bool=true') with self.assertRaises(bitstring.CreationError): pack('True') with self.assertRaises(bitstring.CreationError): pack('bool', 2) with self.assertRaises(bitstring.CreationError): _ = pack('bool', 'hello') with self.assertRaises(bitstring.CreationError): _ = pack('bool=true') with self.assertRaises(bitstring.CreationError): _ = pack('True') with self.assertRaises(bitstring.CreationError): _ = pack('bool', 2) a = BitStream('0b11') with self.assertRaises(bitstring.InterpretError): _ = a.bool b = BitStream() with self.assertRaises(bitstring.InterpretError): _ = b.bool with self.assertRaises(bitstring.CreationError): b.bool = 'false' def testLengthWithBoolRead(self): a = ConstBitStream('0xf') with self.assertRaises(ValueError): _ = a.read('bool:0') with self.assertRaises(ValueError): _ = a.read('bool:2') class ReadWithIntegers(unittest.TestCase): def testReadInt(self): a = ConstBitStream('0xffeedd') b = a.read(8) self.assertEqual(b.hex, 'ff') self.assertEqual(a.pos, 8) b = a.peek(8) self.assertEqual(b.hex, 'ee') self.assertEqual(a.pos, 8) b = a.peek(1) self.assertEqual(b, '0b1') b = a.read(1) self.assertEqual(b, '0b1') def testReadIntList(self): a = ConstBitStream('0xab, 0b110') b, c = a.readlist([8, 3]) self.assertEqual(b.hex, 'ab') self.assertEqual(c.bin, '110') # class FileReadingStrategy(unittest.TestCase): # # # def testBitStreamIsAlwaysRead(self): # filename = os.path.join(THIS_DIR, 'smalltestfile') # a = BitStream(filename=filename) # self.assertTrue(isinstance(a._datastore, bitstring.ByteStore)) # with open(filename, 'rb') as f: # b = BitStream(f) # self.assertTrue(isinstance(b._datastore, bitstring.ByteStore)) # # # def testBitsIsNeverRead(self): # filename = os.path.join(THIS_DIR, 'smalltestfile') # a = ConstBitStream(filename=filename) # self.assertTrue(isinstance(a._datastore.rawarray, bitstring.MmapByteArray)) # with open(filename, 'rb') as f: # b = ConstBitStream(f) # self.assertTrue(isinstance(b._datastore.rawarray, bitstring.MmapByteArray)) class Count(unittest.TestCase): def testCount(self): a = ConstBitStream('0xf0f') self.assertEqual(a.count(True), 8) self.assertEqual(a.count(False), 4) b = BitStream() self.assertEqual(b.count(True), 0) self.assertEqual(b.count(False), 0) def testCountWithOffsetData(self): a = ConstBitStream('0xff0120ff') b = a[1:-1] self.assertEqual(b.count(1), 16) self.assertEqual(b.count(0), 14) class ZeroBitReads(unittest.TestCase): def testInteger(self): a = ConstBitStream('0x123456') with self.assertRaises(bitstring.InterpretError): _ = a.read('uint:0') with self.assertRaises(bitstring.InterpretError): _ = a.read('float:0') class InitialiseFromBytes(unittest.TestCase): def testBytesBehaviour(self): a = ConstBitStream(b'uint:5=2') b = ConstBitStream(b'') c = ConstBitStream(bytes=b'uint:5=2') self.assertEqual(a.bytes, b'uint:5=2') self.assertFalse(b) self.assertEqual(c, b'uint:5=2') def testBytearrayBehaviour(self): a = ConstBitStream(bytearray(b'uint:5=2')) b = ConstBitStream(bytearray(4)) c = ConstBitStream(bytes=bytearray(b'uint:5=2')) self.assertEqual(a.bytes, b'uint:5=2') self.assertEqual(b, '0x00000000') self.assertEqual(c.bytes, b'uint:5=2') class CoverageCompletionTests(unittest.TestCase): def testUeReadError(self): s = ConstBitStream('0b000000001') with self.assertRaises(bitstring.ReadError): _ = s.read('ue') def testOverwriteWithSelf(self): s = BitStream('0b1101') s.overwrite(s) self.assertEqual(s, '0b1101') class Subclassing(unittest.TestCase): def testIsInstance(self): b = BitStream() self.assertTrue(isinstance(b, BitStream)) class SubBits(BitStream): pass a = SubBits() self.assertTrue(isinstance(a, SubBits)) def testClassType(self): class SubBits(BitStream): pass self.assertEqual(SubBits().__class__, SubBits) class BytesProblems(unittest.TestCase): def testOffsetButNoLength(self): b = BitStream(bytes=b'\x00\xaa', offset=8) self.assertEqual(b.hex, 'aa') b = BitStream(bytes=b'\x00\xaa', offset=4) self.assertEqual(b.hex, '0aa') def testInvert(self): b = BitStream(bytes=b'\x00\xaa', offset=8, length=8) self.assertEqual(b.hex, 'aa') b.invert() self.assertEqual(b.hex, '55') def testPrepend(self): b = BitStream(bytes=b'\xaa\xbb', offset=8, length=4) self.assertEqual(b.hex, 'b') b.prepend('0xe') self.assertEqual(b.hex, 'eb') b = BitStream(bytes=b'\x00\xaa', offset=8, length=8) b.prepend('0xee') self.assertEqual(b.hex, 'eeaa') def testByteSwap(self): b = BitStream(bytes=b'\x01\x02\x03\x04', offset=8) b.byteswap() self.assertEqual(b, '0x040302') def testBinProperty(self): b = BitStream(bytes=b'\x00\xaa', offset=8, length=4) self.assertEqual(b.bin, '1010') class Lsb0Streaming(unittest.TestCase): @classmethod def setUpClass(cls): bitstring.lsb0 = True @classmethod def tearDownClass(cls): bitstring.lsb0 = False def testSimpleBitPositions(self): s = BitStream('0x00000f') self.assertEqual(s.pos, 0) v = s.read('uint:8') self.assertEqual(v, 15) self.assertEqual(s.pos, 8) v = s.read(10) self.assertEqual(v, Bits(10)) self.assertEqual(s.pos, 18) def testBitPosAfterFind(self): s = BitStream('0b01100001000011 0000') s.find('0b11', start=1) self.assertEqual(s.pos, 4) def testIter(self): s = BitStream('0b11000') self.assertEqual(list(s), [False, False, False, True, True]) def testBitPosAfterRfind(self): s = BitStream('0b011 000010000110000') s.rfind('0b11') self.assertEqual(s.pos, 15) def testBitPosAfterFindall(self): pass def testBitPosAfterInsert(self): pass def testBitPosAfterOverwrite(self): pass def testBitPosAfterReplace(self): pass def testReadList(self): a = BitStream('0x0123456789abcdef') vals = a.readlist('uint:4, uint:4, uint:24, uint:12, uint:12, uint:8') self.assertEqual(vals, [15, 14, 0x89abcd, 0x567, 0x234, 1]) class TestLsb0PackingUnpacking(unittest.TestCase): @classmethod def setUpClass(cls): bitstring.lsb0 = True @classmethod def tearDownClass(cls): bitstring.lsb0 = False def testBin(self): lsb0 = bitstring.pack('2*b4', '0b0000', '1111') self.assertEqual(lsb0, '0b11110000') a, b = lsb0.unpack('2*h4') self.assertEqual([a, b], ['0', 'f']) a, b = lsb0.unpack('2*bits4') self.assertEqual([a, b], ['0x0', '0xf']) a, b = lsb0.unpack('2*bin4') self.assertEqual([a, b], ['0000', '1111']) def testFloat(self): lsb0 = bitstring.pack('2*bfloat', 0.5, 15) self.assertEqual(lsb0, '0x4170 3f00') a, b = lsb0.unpack('2*bfloat') self.assertEqual([a, b], [0.5, 15]) def testSimplest(self): lsb0 = bitstring.pack('uint:2', 1) self.assertEqual(lsb0.unpack('uint:2'), [1]) lsb0 = bitstring.pack('0xab, 0xc') self.assertEqual(lsb0.unpack('hex8, hex4'), ['ab', 'c']) def testSlightlyHarder(self): lsb0 = bitstring.pack('float:32, hex', 0.25, 'ac') x = lsb0.unpack('float:32, hex') self.assertEqual(x, [0.25, 'ac']) def testMoreComplex(self): lsb0 = bitstring.pack('uint:10, hex, int:13, 0b11', 130, '3d', -23) x = lsb0.unpack('uint:10, hex, int:13, bin:2') self.assertEqual(x, [130, '3d', -23, '11']) def testGolombCodes(self): v = [10, 8, 6, 4, 100, -9] # Exp-Golomb codes can only be read in msb0 mode. So also doesn't # make sense for creation with pack with self.assertRaises(bitstring.CreationError): _ = bitstring.pack('5*ue, sie', *v) # with self.assertRaises(bitstring.CreationError): # _ = BitStream('ue=34') lsb0 = BitStream('0b0010010') with self.assertRaises(bitstring.ReadError): _ = lsb0.unpack('5*ue, sie') with self.assertRaises(bitstring.ReadError): _ = lsb0.read('ue') with self.assertRaises(bitstring.ReadError): _ = lsb0.read('uie') with self.assertRaises(bitstring.ReadError): _ = lsb0.read('se') with self.assertRaises(bitstring.ReadError): _ = lsb0.read('sie') class TestRepr(unittest.TestCase): def testWithoutPos(self): a = BitStream('0x12345', pos=0) self.assertEqual(repr(a), "BitStream('0x12345')") def testWithPos(self): a = BitStream('0b00111', pos=-1) self.assertEqual(a.pos, 4) self.assertEqual(repr(a), "BitStream('0b00111', pos=4)") class TestFormat(unittest.TestCase): def testSimpleFormatStrings(self): a = Bits('0xabc') s = f'{a}' self.assertEqual(s, '0xabc') a += '0b0' self.assertEqual(f'{a}', '0b1010101111000') b = BitStream(10, pos=4) self.assertEqual(f'{b}', '0b0000000000') c = BitStream(filename=os.path.join(THIS_DIR, 'test.m1v')) self.assertEqual(f'{c}'[0:10], '0x000001b3') def testFormatStringsWithInterpretation(self): a = Bits('0xf') self.assertEqual(f'{a.bin}', '1111') class CacheingIssues(unittest.TestCase): def testCacheWithOffset(self): y = BitStream('0xdeadbeef1000') with self.assertRaises(bitstring.CreationError): x = BitStream('0xdeadbeef1000', offset=8) def testCacheWithPos(self): y = BitStream('0xdeadbeef1001', pos=3) self.assertEqual(y.pos, 3) x = BitStream('0xdeadbeef1001', pos=5) self.assertEqual(x.pos, 5) def testCacheWithLength(self): y = BitStream('0xdeadbeef002') with self.assertRaises(bitstring.CreationError): x = BitStream('0xdeadbeef002', length=16) bitstring-bitstring-4.1.4/tests/test_bitstring.py000066400000000000000000000165741453167633600223430ustar00rootroot00000000000000#!/usr/bin/env python """ Module-level unit tests. """ import io import unittest from unittest import mock from contextlib import redirect_stdout import bitstring import copy from collections import abc import sys import os from bitstring import __main__ sys.path.insert(0, '..') THIS_DIR = os.path.dirname(os.path.abspath(__file__)) class ModuleData(unittest.TestCase): def testAll(self): exported = ['ConstBitStream', 'BitStream', 'BitArray', 'Bits', 'pack', 'Error', 'ReadError', 'Array', 'InterpretError', 'ByteAlignError', 'CreationError', 'bytealigned', 'lsb0'] self.assertEqual(set(bitstring.__all__), set(exported)) def testReverseDict(self): d = bitstring.Bits._byteReversalDict for i in range(256): a = bitstring.Bits(uint=i, length=8) b = d[i] self.assertEqual(a.bin[::-1], bitstring.Bits(bytes=b).bin) def testPyprojectVersion(self): filename = os.path.join(THIS_DIR, '../pyproject.toml') try: with open(filename, 'r') as pyprojectfile: found = False for line in pyprojectfile.readlines(): if line.startswith("version"): self.assertFalse(found) self.assertTrue(bitstring.__version__ in line) found = True self.assertTrue(found) except FileNotFoundError: pass # Doesn't run on CI. class Copy(unittest.TestCase): def testConstBitArrayCopy(self): cba = bitstring.Bits(100) cba_copy = copy.copy(cba) self.assertTrue(cba is cba_copy) def testBitArrayCopy(self): ba = bitstring.BitArray(100) ba_copy = copy.copy(ba) self.assertFalse(ba is ba_copy) self.assertFalse(ba._bitstore is ba_copy._bitstore) self.assertTrue(ba == ba_copy) def testConstBitStreamCopy(self): cbs = bitstring.ConstBitStream(100) cbs.pos = 50 cbs_copy = copy.copy(cbs) self.assertEqual(cbs_copy.pos, 0) self.assertTrue(cbs._bitstore is cbs_copy._bitstore) self.assertTrue(cbs == cbs_copy) def testBitStreamCopy(self): bs = bitstring.BitStream(100) bs.pos = 50 bs_copy = copy.copy(bs) self.assertEqual(bs_copy.pos, 0) self.assertFalse(bs._bitstore is bs_copy._bitstore) self.assertTrue(bs == bs_copy) class Interning(unittest.TestCase): def testBits(self): a = bitstring.Bits('0xf') b = bitstring.Bits('0xf') self.assertTrue(a._bitstore is b._bitstore) c = bitstring.Bits('0b1111') self.assertFalse(a is c) def testCBS(self): a = bitstring.ConstBitStream('0b11000') b = bitstring.ConstBitStream('0b11000') self.assertTrue(a._bitstore is b._bitstore) self.assertFalse(a is b) class LSB0(unittest.TestCase): def testGettingAndSetting(self): self.assertEqual(bitstring.lsb0, False) bitstring.lsb0 = True self.assertEqual(bitstring.lsb0, True) bitstring.lsb0 = False self.assertEqual(bitstring.lsb0, False) class Main(unittest.TestCase): def testRunningModuleDirectlyHelp(self): with redirect_stdout(io.StringIO()) as f: with mock.patch('sys.argv', ['bitstring.py', '-h']): bitstring.__main__.main() s = f.getvalue() self.assertTrue(s.find("command-line parameters") >= 0) with redirect_stdout(io.StringIO()) as f: with mock.patch('sys.argv', ['renamed.py']): bitstring.__main__.main() s = f.getvalue() self.assertTrue(s.find("command-line parameters") >= 0) def testRunningModuleWithSingleParameter(self): with redirect_stdout(io.StringIO()) as f: with mock.patch('sys.argv', ['', 'uint:12=352']): bitstring.__main__.main() s = f.getvalue() self.assertEqual(s, '0x160\n') def testRunningModuleWithSingleParameterAndInterpretation(self): with redirect_stdout(io.StringIO()) as f: with mock.patch('sys.argv', ['ignored', 'u12=352', 'i']): bitstring.__main__.main() s = f.getvalue() self.assertEqual(s, '352\n') def testRunningModuleWithMultipleParameters(self): with redirect_stdout(io.StringIO()) as f: with mock.patch('sys.argv', ['b.py', 'uint12=352', '0b101', '0o321', 'f32=51', 'bool=1']): bitstring.__main__.main() s = f.getvalue() self.assertEqual(s, '0x160ad1424c0000, 0b1\n') def testRunningModuleWithMultipleParametersAndInterpretation(self): with redirect_stdout(io.StringIO()) as f: with mock.patch('sys.argv', ['b.py', 'ue=1000', '0xff.bin']): bitstring.__main__.main() s = f.getvalue() self.assertEqual(s, '000000000111110100111111111\n') def testShortInterpretations(self): with redirect_stdout(io.StringIO()) as f: with mock.patch('sys.argv', ['b.py', 'bin=001.b']): bitstring.__main__.main() s = f.getvalue() self.assertEqual(s, '001\n') @unittest.skip('Bug #261') class ABCs(unittest.TestCase): def testBaseClasses(self): # https://github.com/scott-griffiths/bitstring/issues/261 bits = bitstring.Bits() self.assertTrue(isinstance(bits, abc.Sequence)) self.assertFalse(isinstance(bits, abc.MutableSequence)) bitarray = bitstring.BitArray() self.assertTrue(isinstance(bitarray, abc.MutableSequence)) self.assertTrue(isinstance(bitarray, abc.Sequence)) constbitstream = bitstring.ConstBitStream() self.assertTrue(isinstance(constbitstream, abc.Sequence)) self.assertFalse(isinstance(constbitstream, abc.MutableSequence)) bitstream = bitstring.BitArray() self.assertTrue(isinstance(bitstream, abc.MutableSequence)) self.assertTrue(isinstance(bitstream, abc.Sequence)) class DtypeRegister(unittest.TestCase): pass class NoFixedLengthPackingBug(unittest.TestCase): def testPackingBytesWithNoLength(self): a = bitstring.pack('bytes', b'abcd') self.assertEqual(a.bytes, b'abcd') b = bitstring.pack('u12, bytes, bool', 0, b'deadbeef', True) self.assertEqual(b.unpack('u12, bytes, bool'), [0, b'deadbeef', True]) def testPackingBinWithNoLength(self): a = bitstring.pack('bin', '0001') self.assertEqual(a.bin, '0001') def testPackingHexWithNoLength(self): a = bitstring.pack('hex', 'abcd') self.assertEqual(a.hex, 'abcd') def testReadingBytesWithNoLength(self): a = bitstring.BitStream(b'hello') b = a.read('bytes') self.assertEqual(b, b'hello') c = bitstring.BitStream('0xabc, u13=99') c += b'123abc' c += bitstring.Bits('bfloat=4') c.pos = 0 self.assertEqual(c.readlist('h12, u13, bytes, bfloat'), ['abc', 99, b'123abc', 4.0]) def testReadingBinWithNoLength(self): a = bitstring.BitStream('0b1101') b = a.read('bin') self.assertEqual(b, '1101') def testReadingUintWithNoLength(self): a = bitstring.BitStream('0b1101') b = a.read('uint') self.assertEqual(b, 13) def testReadingFloatWithNoLength(self): a = bitstring.BitStream(float=14, length=16) b = a.read('float') self.assertEqual(b, 14.0)bitstring-bitstring-4.1.4/tests/test_constbitstream.py000066400000000000000000000166011453167633600233660ustar00rootroot00000000000000#!/usr/bin/env python import unittest import sys import bitstring import io import os from bitstring import ConstBitStream as CBS sys.path.insert(0, '..') THIS_DIR = os.path.dirname(os.path.abspath(__file__)) class All(unittest.TestCase): def testFromFile(self): s = CBS(filename=os.path.join(THIS_DIR, 'test.m1v')) self.assertEqual(s[0:32].hex, '000001b3') self.assertEqual(s.read(8 * 4).hex, '000001b3') width = s.read(12).uint height = s.read(12).uint self.assertEqual((width, height), (352, 288)) def testFromFileWithOffsetAndLength(self): s = CBS(filename=os.path.join(THIS_DIR, 'test.m1v'), offset=24, length=8) self.assertEqual(s.h, 'b3') reconstructed = '' for bit in s: reconstructed += '1' if bit is True else '0' self.assertEqual(reconstructed, s.bin) class InterleavedExpGolomb(unittest.TestCase): def testReading(self): s = CBS(uie=333) a = s.read('uie') self.assertEqual(a, 333) s = CBS('uie=12, sie=-9, sie=9, uie=1000000') u = s.unpack('uie, 2*sie, uie') self.assertEqual(u, [12, -9, 9, 1000000]) def testReadingErrors(self): s = CBS(10) with self.assertRaises(bitstring.ReadError): s.read('uie') self.assertEqual(s.pos, 0) with self.assertRaises(bitstring.ReadError): s.read('sie') self.assertEqual(s.pos, 0) class ReadTo(unittest.TestCase): def testByteAligned(self): a = CBS('0xaabb00aa00bb') b = a.readto('0x00', bytealigned=True) self.assertEqual(b, '0xaabb00') self.assertEqual(a.bytepos, 3) b = a.readto('0xaa', bytealigned=True) self.assertEqual(b, '0xaa') with self.assertRaises(bitstring.ReadError): b.readto('0xcc', bytealigned=True) def testNotAligned(self): a = CBS('0b00111001001010011011') a.pos = 1 self.assertEqual(a.readto('0b00'), '0b011100') self.assertEqual(a.readto('0b110'), '0b10010100110') with self.assertRaises(ValueError): a.readto('') def testDisallowIntegers(self): a = CBS('0x0f') with self.assertRaises(ValueError): a.readto(4) def testReadingLines(self): s = b"This is a test\nof reading lines\nof text\n" b = CBS(bytes=s) n = bitstring.Bits(bytes=b'\n') self.assertEqual(b.readto(n).bytes, b'This is a test\n') self.assertEqual(b.readto(n).bytes, b'of reading lines\n') self.assertEqual(b.readto(n).bytes, b'of text\n') class Subclassing(unittest.TestCase): def testIsInstance(self): class SubBits(CBS): pass a = SubBits() self.assertTrue(isinstance(a, SubBits)) def testClassType(self): class SubBits(CBS): pass self.assertEqual(SubBits().__class__, SubBits) class PadToken(unittest.TestCase): def testRead(self): s = CBS('0b100011110001') a = s.read('pad:1') self.assertEqual(a, None) self.assertEqual(s.pos, 1) a = s.read(3) self.assertEqual(a, CBS('0b000')) a = s.read('pad:1') self.assertEqual(a, None) self.assertEqual(s.pos, 5) def testReadList(self): s = CBS('0b10001111001') t = s.readlist('pad:1, uint:3, pad:4, uint:3') self.assertEqual(t, [0, 1]) s.pos = 0 t = s.readlist('pad:1, pad:5') self.assertEqual(t, []) self.assertEqual(s.pos, 6) s.pos = 0 t = s.readlist('pad:1, bin, pad:4, uint:3') self.assertEqual(t, ['000', 1]) s.pos = 0 t = s.readlist('pad, bin:3, pad:4, uint:3') self.assertEqual(t, ['000', 1]) class ReadingBytes(unittest.TestCase): def testUnpackingBytes(self): s = CBS(80) t = s.unpack('bytes:1') self.assertEqual(t[0], b'\x00') a, b, c = s.unpack('bytes:1, bytes, bytes2') self.assertEqual(a, b'\x00') self.assertEqual(b, b'\x00'*7) self.assertEqual(c, b'\x00'*2) def testUnpackingBytesWithKeywords(self): s = CBS('0x55'*10) t = s.unpack('pad:a, bytesb, bytes, pad:a', a=4, b=6) self.assertEqual(t, [b'\x55'*6, b'\x55'*3]) class ReadingBitsAsDefault(unittest.TestCase): def testReadBits(self): s = CBS('uint:31=14') v = s.read(31) self.assertEqual(v.uint, 14) s.pos = 0 v = s.read('31') self.assertEqual(v.uint, 14) def testReadListBits(self): s = CBS('uint:5=3, uint:3=0, uint:11=999') v = s.readlist([5, 3, 11]) self.assertEqual([x.uint for x in v], [3, 0, 999]) s.pos = 0 v = s.readlist(['5', '3', 11]) self.assertEqual([x.uint for x in v], [3, 0, 999]) class Lsb0Reading(unittest.TestCase): @classmethod def setUpClass(cls): bitstring.lsb0 = True @classmethod def tearDownClass(cls): bitstring.lsb0 = False def testReadingHex(self): s = CBS('0xabcdef') self.assertEqual(s.read('hex:4'), 'f') self.assertEqual(s.read(4), '0xe') self.assertEqual(s.pos, 8) def testReadingOct(self): s = CBS('0o123456') self.assertEqual(s.read('o6'), '56') self.assertEqual(s.pos, 6) def testReadingBin(self): s = CBS('0b00011') self.assertEqual(s.read('bin:3'), '011') self.assertEqual(s.pos, 3) def testReadingBytes(self): s = CBS(bytes=b'54321') self.assertEqual(s.pos, 0) s.pos = 8 self.assertEqual(s.read('bytes:2'), b'32') class BytesIOCreation(unittest.TestCase): def testSimpleCreation(self): f = io.BytesIO(b"\x12\xff\x77helloworld") s = CBS(f) self.assertEqual(s[0:8], '0x12') self.assertEqual(len(s), 13 * 8) s = CBS(f, offset=8, length=12) self.assertEqual(s, '0xff7') def testExceptions(self): f = io.BytesIO(b"123456789") _ = CBS(f, length=9*8) with self.assertRaises(bitstring.CreationError): _ = CBS(f, length=9*8 + 1) with self.assertRaises(bitstring.CreationError): _ = CBS(f, length=9*8, offset=1) class CreationWithPos(unittest.TestCase): def testDefaultCreation(self): s = CBS('0xabc') self.assertEqual(s.pos, 0) def testPositivePos(self): s = CBS('0xabc', pos=0) self.assertEqual(s.pos, 0) s = CBS('0xabc', pos=1) self.assertEqual(s.pos, 1) s = CBS('0xabc', pos=12) self.assertEqual(s.pos, 12) with self.assertRaises(bitstring.CreationError): _ = CBS('0xabc', pos=13) def testNegativePos(self): s = CBS('0xabc', pos=-1) self.assertEqual(s.pos, 11) s = CBS('0xabc', pos=-12) self.assertEqual(s.pos, 0) with self.assertRaises(bitstring.CreationError): _ = CBS('0xabc', pos=-13) def testStringRepresentation(self): s = CBS('0b110', pos=2) self.assertEqual(s.__repr__(), "ConstBitStream('0b110', pos=2)") def testStringRepresentationFromFile(self): filename = os.path.join(THIS_DIR, 'test.m1v') s = CBS(filename=filename, pos=2001) self.assertEqual(s.__repr__(), f"ConstBitStream(filename={repr(str(filename))}, length=1002400, pos=2001)") s.pos = 0 self.assertEqual(s.__repr__(), f"ConstBitStream(filename={repr(str(filename))}, length=1002400)") bitstring-bitstring-4.1.4/tests/test_fp8.py000066400000000000000000000215671453167633600210310ustar00rootroot00000000000000from __future__ import annotations import sys import unittest import array import struct import math import bitstring from bitstring import Bits, BitArray, BitStream from bitstring.fp8 import e4m3float_fmt, e5m2float_fmt sys.path.insert(0, '..') class Fp8(unittest.TestCase): def testCreation(self): a = Bits(e4m3float=-14.0) self.assertEqual(a.e4m3float, -14.0) b = Bits('e5m2float=3.0') self.assertEqual(b.e5m2float, 3.0) self.assertEqual(len(b), 8) c = Bits('e4m3float=1000000000') self.assertEqual(c.hex, '7f') d = Bits('e5m2float=-1e15774') self.assertEqual(d.hex, 'ff') e = Bits(e5m2float=float('nan')) self.assertEqual(e.hex, '80') def testReassignment(self): a = BitArray() a.e4m3float = -0.25 self.assertEqual(a.e4m3float, -0.25) a.e5m2float = float('inf') self.assertEqual(a.hex, '7f') a.e4m3float = -9000.0 self.assertEqual(a.hex, 'ff') a.e5m2float = -0.00000000001 self.assertEqual(a.e5m2float, 0.0) def testReading(self): a = BitStream('0x00fff') x = a.read('e5m2float') self.assertEqual(x, 0.0) self.assertEqual(a.pos, 8) x = a.read('e4m3float') self.assertEqual(x, -240.0) self.assertEqual(a.pos, 16) def testReadList(self): v = [-6, -2, 0.125, 7, 10] a = bitstring.pack('5*e4m3float', *v) vp = a.readlist('5*e4m3float') self.assertEqual(v, vp) def testInterpretations(self): a = BitArray('0x00') self.assertEqual(a.e4m3float, 0.0) self.assertEqual(a.e5m2float, 0.0) a += '0b1' with self.assertRaises(bitstring.InterpretError): _ = a.e4m3float with self.assertRaises(bitstring.InterpretError): _ = a.e5m2float def createLUT_for_int8_to_float(exp_bits, bias) -> array.array[float]: """Create a LUT to convert an int in range 0-255 representing a float8 into a Python float""" i2f = [] for i in range(256): b = BitArray(uint=i, length=8) sign = b[0] exponent = b[1:1 + exp_bits].u significand = b[1 + exp_bits:] if exponent == 0: significand.prepend([0]) exponent = -bias + 1 else: significand.prepend([1]) exponent -= bias f = float(significand.u) / (2.0 ** (7 - exp_bits)) f *= 2 ** exponent i2f.append(f if not sign else -f) # One special case for minus zero i2f[0b10000000] = float('nan') return array.array('f', i2f) # Create a bytearray where the nth element is the 8 bit float corresponding to the fp16 value interpreted as n. def createLUT_for_float16_to_float8(lut_int8_to_float) -> bytes: # Used to create the LUT that was compressed and stored for the fp8 code fp16_to_fp8 = bytearray(1 << 16) for i in range(1 << 16): b = struct.pack('>H', i) f, = struct.unpack('>e', b) fp8_i = slow_float_to_int8(lut_int8_to_float, f) fp16_to_fp8[i] = fp8_i return bytes(fp16_to_fp8) def slow_float_to_int8(lut_int8_to_float, f: float) -> int: # Slow, but easier to follow than the faster version. Used only for validation. if f >= 0: for i in range(128): if f < lut_int8_to_float[i]: return i - 1 # Clip to positive max return 0b01111111 if f < 0: if f > lut_int8_to_float[129]: # Rounding upwards to zero return 0b00000000 # There's no negative zero so this is a special case for i in range(130, 256): if f > lut_int8_to_float[i]: return i - 1 # Clip to negative max return 0b11111111 # We only have one nan value return 0b10000000 class CheckLUTs(unittest.TestCase): def testLUT_int8_to_e4m3float(self): lut_stored = e4m3float_fmt.lut_int8_to_float self.assertEqual(len(lut_stored), 256) lut_calculated = createLUT_for_int8_to_float(4, 8) for i in range(len(lut_stored)): if lut_stored[i] != lut_calculated[i]: # Either they're equal or they're both nan (which doesn't compare as equal). self.assertTrue(math.isnan(lut_stored[i])) self.assertTrue(math.isnan(lut_calculated[i])) def testLUT_int8_to_e5m2float(self): lut_stored = e5m2float_fmt.lut_int8_to_float self.assertEqual(len(lut_stored), 256) lut_calculated = createLUT_for_int8_to_float(5, 16) for i in range(len(lut_stored)): if lut_stored[i] != lut_calculated[i]: # Either they're equal or they're both nan (which doesn't compare as equal). self.assertTrue(math.isnan(lut_stored[i])) self.assertTrue(math.isnan(lut_calculated[i])) def testLUT_float16_to_e4m3float(self): lut_float16_to_e4m3float = createLUT_for_float16_to_float8(e4m3float_fmt.lut_int8_to_float) self.assertEqual(len(lut_float16_to_e4m3float), 65536) self.assertEqual(lut_float16_to_e4m3float, e4m3float_fmt.lut_float16_to_float8) def testLUT_float16_to_e5m2float(self): lut_float16_to_e5m2float = createLUT_for_float16_to_float8(e5m2float_fmt.lut_int8_to_float) self.assertEqual(len(lut_float16_to_e5m2float), 65536) self.assertEqual(lut_float16_to_e5m2float, e5m2float_fmt.lut_float16_to_float8) class ConversionToFP8(unittest.TestCase): def testSome143Values(self): zero = bitstring.Bits('0b0000 0000') self.assertEqual(e4m3float_fmt.lut_int8_to_float[zero.uint], 0.0) max_normal = bitstring.Bits('0b0111 1111') self.assertEqual(e4m3float_fmt.lut_int8_to_float[max_normal.uint], 240.0) max_normal_neg = bitstring.Bits('0b1111 1111') self.assertEqual(e4m3float_fmt.lut_int8_to_float[max_normal_neg.uint], -240.0) min_normal = bitstring.Bits('0b0000 1000') self.assertEqual(e4m3float_fmt.lut_int8_to_float[min_normal.uint], 2**-7) min_subnormal = bitstring.Bits('0b0000 0001') self.assertEqual(e4m3float_fmt.lut_int8_to_float[min_subnormal.uint], 2**-10) max_subnormal = bitstring.Bits('0b0000 0111') self.assertEqual(e4m3float_fmt.lut_int8_to_float[max_subnormal.uint], 0.875 * 2**-7) nan = bitstring.Bits('0b1000 0000') self.assertTrue(math.isnan(e4m3float_fmt.lut_int8_to_float[nan.uint])) def testSome152Values(self): zero = bitstring.Bits('0b0000 0000') self.assertEqual(e5m2float_fmt.lut_int8_to_float[zero.uint], 0.0) max_normal = bitstring.Bits('0b0111 1111') self.assertEqual(e5m2float_fmt.lut_int8_to_float[max_normal.uint], 57344.0) max_normal_neg = bitstring.Bits('0b1111 1111') self.assertEqual(e5m2float_fmt.lut_int8_to_float[max_normal_neg.uint], -57344.0) min_normal = bitstring.Bits('0b0000 0100') self.assertEqual(e5m2float_fmt.lut_int8_to_float[min_normal.uint], 2**-15) min_subnormal = bitstring.Bits('0b0000 0001') self.assertEqual(e5m2float_fmt.lut_int8_to_float[min_subnormal.uint], 0.25 * 2**-15) max_subnormal = bitstring.Bits('0b0000 0011') self.assertEqual(e5m2float_fmt.lut_int8_to_float[max_subnormal.uint], 0.75 * 2**-15) nan = bitstring.Bits('0b1000 0000') self.assertTrue(math.isnan(e5m2float_fmt.lut_int8_to_float[nan.uint])) def testRoundTrip(self): # For each possible 8bit int, convert to float, then convert that float back to an int for fmt in [e4m3float_fmt, e5m2float_fmt]: for i in range(256): f = fmt.lut_int8_to_float[i] ip = fmt.float_to_int8(f) self.assertEqual(ip, i) def testFloat16Conversion(self): # Convert a float16 to a float8, then convert that to a Python float. Then convert back to a float16. # This value should have been rounded towards zero. Convert back to a float8 again - should be the # same value as before or the adjacent smaller value for fmt in [e4m3float_fmt, e5m2float_fmt]: # Keeping sign bit == 0 so only positive numbers previous_value = 0.0 for i in range(1 << 15): # Check that the f16 is a standard number b = struct.pack('>H', i) f16, = struct.unpack('>e', b) if math.isnan(f16): continue # OK, it's an ordinary number - convert to a float8 f8 = fmt.lut_float16_to_float8[i] # And convert back to a float f = fmt.lut_int8_to_float[f8] # This should have been rounded towards zero compared to the original self.assertTrue(f <= f16) # But not rounded more than to the previous valid value self.assertTrue(f >= previous_value) if f > previous_value: previous_value = f