Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/bitstring/__init__.py: 72%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1#!/usr/bin/env python
2r"""
3This package defines classes that simplify bit-wise creation, manipulation and
4interpretation of data.
6Classes:
8Bits -- An immutable container for binary data.
9BitArray -- A mutable container for binary data.
10ConstBitStream -- An immutable container with streaming methods.
11BitStream -- A mutable container with streaming methods.
12Array -- An efficient list-like container where each item has a fixed-length binary format.
13Dtype -- Encapsulate the data types used in the other classes.
15Functions:
17pack -- Create a BitStream from a format string.
19Data:
21options -- Module-wide options.
23Exceptions:
25Error -- Module exception base class.
26CreationError -- Error during creation.
27InterpretError -- Inappropriate interpretation of binary data.
28ByteAlignError -- Whole byte position or length needed.
29ReadError -- Reading or peeking past the end of a bitstring.
31https://github.com/scott-griffiths/bitstring
32"""
34__licence__ = """
35The MIT License
37Copyright (c) 2006 Scott Griffiths (dr.scottgriffiths@gmail.com)
39Permission is hereby granted, free of charge, to any person obtaining a copy
40of this software and associated documentation files (the "Software"), to deal
41in the Software without restriction, including without limitation the rights
42to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
43copies of the Software, and to permit persons to whom the Software is
44furnished to do so, subject to the following conditions:
46The above copyright notice and this permission notice shall be included in
47all copies or substantial portions of the Software.
49THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
50IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
51FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
52AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
53LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
54OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
55THE SOFTWARE.
56"""
58__version__ = "4.4.0"
60__author__ = "Scott Griffiths"
62import sys
63import os
64import importlib
66# New ability to use tibs for core operations instead of bitarray.
67# Tibs is written in Rust and is still in beta. Use the environment variable
68# BITSTRING_USE_RUST_CORE=1 before importing the module to turn it on.
69_env_core = os.getenv('BITSTRING_USE_RUST_CORE', '').strip().lower()
70_USE_RUST_CORE = _env_core in ('1', 'true', 'yes', 'on')
71if _USE_RUST_CORE:
72 bitstore = importlib.import_module('bitstring.bitstore_tibs')
73 bitstore_helpers = importlib.import_module('bitstring.bitstore_tibs_helpers')
74else:
75 bitstore = importlib.import_module('bitstring.bitstore_bitarray')
76 bitstore_helpers = importlib.import_module('bitstring.bitstore_bitarray_helpers')
77bitstore_common_helpers = importlib.import_module('bitstring.bitstore_common_helpers')
79from .bits import Bits
80from .bitstring_options import Options
81from .bitarray_ import BitArray
82from .bitstream import ConstBitStream, BitStream
83from .methods import pack
84from .array_ import Array
85from .exceptions import Error, ReadError, InterpretError, ByteAlignError, CreationError
86from .dtypes import DtypeDefinition, dtype_register, Dtype
87import types
88from typing import List, Tuple, Literal
89from .mxfp import decompress_luts as mxfp_decompress_luts
90from .fp8 import decompress_luts as binary8_decompress_luts
92# Decompress the LUTs for the exotic floating point formats
93mxfp_decompress_luts()
94binary8_decompress_luts()
96# The Options class returns a singleton.
97options = Options()
99# These get defined properly by the module magic below. This just stops mypy complaining about them.
100bytealigned = lsb0 = None
103# An opaque way of adding module level properties. Taken from https://peps.python.org/pep-0549/
104# This is now deprecated. Use the options object directly instead.
105class _MyModuleType(types.ModuleType):
106 @property
107 def bytealigned(self) -> bool:
108 """Determines whether a number of methods default to working only on byte boundaries."""
109 return options.bytealigned
111 @bytealigned.setter
112 def bytealigned(self, value: bool) -> None:
113 """Determines whether a number of methods default to working only on byte boundaries."""
114 options.bytealigned = value
116 @property
117 def lsb0(self) -> bool:
118 """If True, the least significant bit (the final bit) is indexed as bit zero."""
119 return options.lsb0
121 @lsb0.setter
122 def lsb0(self, value: bool) -> None:
123 """If True, the least significant bit (the final bit) is indexed as bit zero."""
124 options.lsb0 = value
127sys.modules[__name__].__class__ = _MyModuleType
130# These methods convert a bit length to the number of characters needed to print it for different interpretations.
131def hex_bits2chars(bitlength: int):
132 # One character for every 4 bits
133 return bitlength // 4
136def oct_bits2chars(bitlength: int):
137 # One character for every 3 bits
138 return bitlength // 3
141def bin_bits2chars(bitlength: int):
142 # One character for each bit
143 return bitlength
146def bytes_bits2chars(bitlength: int):
147 # One character for every 8 bits
148 return bitlength // 8
151def uint_bits2chars(bitlength: int):
152 # How many characters is largest possible int of this length?
153 return len(str((1 << bitlength) - 1))
156def int_bits2chars(bitlength: int):
157 # How many characters is largest negative int of this length? (To include minus sign).
158 return len(str((-1 << (bitlength - 1))))
161def float_bits2chars(bitlength: Literal[16, 32, 64]):
162 # These bit lengths were found by looking at lots of possible values
163 if bitlength in [16, 32]:
164 return 23 # Empirical value
165 else:
166 return 24 # Empirical value
169def p3binary_bits2chars(_: Literal[8]):
170 return 19 # Empirical value
173def p4binary_bits2chars(_: Literal[8]):
174 # Found by looking at all the possible values
175 return 13 # Empirical value
178def e4m3mxfp_bits2chars(_: Literal[8]):
179 return 13
182def e5m2mxfp_bits2chars(_: Literal[8]):
183 return 19
186def e3m2mxfp_bits2chars(_: Literal[6]):
187 # Not sure what the best value is here. It's 7 without considering the scale that could be applied.
188 return 7
191def e2m3mxfp_bits2chars(_: Literal[6]):
192 # Not sure what the best value is here.
193 return 7
196def e2m1mxfp_bits2chars(_: Literal[4]):
197 # Not sure what the best value is here.
198 return 7
201def e8m0mxfp_bits2chars(_: Literal[8]):
202 # Has same range as float32
203 return 23
206def mxint_bits2chars(_: Literal[8]):
207 # Not sure what the best value is here.
208 return 10
211def bfloat_bits2chars(_: Literal[16]):
212 # Found by looking at all the possible values
213 return 23 # Empirical value
216def bits_bits2chars(bitlength: int):
217 # For bits type we can see how long it needs to be printed by trying any value
218 temp = Bits(bitlength)
219 return len(str(temp))
222def bool_bits2chars(_: Literal[1]):
223 # Bools are printed as 1 or 0, not True or False, so are one character each
224 return 1
227dtype_definitions = [
228 # Integer types
229 DtypeDefinition('uint', Bits._setuint, Bits._getuint, int, False, uint_bits2chars,
230 description="a two's complement unsigned int"),
231 DtypeDefinition('uintle', Bits._setuintle, Bits._getuintle, int, False, uint_bits2chars,
232 allowed_lengths=(8, 16, 24, ...), description="a two's complement little-endian unsigned int"),
233 DtypeDefinition('uintbe', Bits._setuintbe, Bits._getuintbe, int, False, uint_bits2chars,
234 allowed_lengths=(8, 16, 24, ...), description="a two's complement big-endian unsigned int"),
235 DtypeDefinition('int', Bits._setint, Bits._getint, int, True, int_bits2chars,
236 description="a two's complement signed int"),
237 DtypeDefinition('intle', Bits._setintle, Bits._getintle, int, True, int_bits2chars,
238 allowed_lengths=(8, 16, 24, ...), description="a two's complement little-endian signed int"),
239 DtypeDefinition('intbe', Bits._setintbe, Bits._getintbe, int, True, int_bits2chars,
240 allowed_lengths=(8, 16, 24, ...), description="a two's complement big-endian signed int"),
241 # String types
242 DtypeDefinition('hex', Bits._sethex, Bits._gethex, str, False, hex_bits2chars,
243 allowed_lengths=(0, 4, 8, ...), description="a hexadecimal string"),
244 DtypeDefinition('bin', Bits._setbin, Bits._getbin, str, False, bin_bits2chars,
245 description="a binary string"),
246 DtypeDefinition('oct', Bits._setoct, Bits._getoct, str, False, oct_bits2chars,
247 allowed_lengths=(0, 3, 6, ...), description="an octal string"),
248 # Float types
249 DtypeDefinition('float', Bits._setfloatbe, Bits._getfloatbe, float, True, float_bits2chars,
250 allowed_lengths=(16, 32, 64), description="a big-endian floating point number"),
251 DtypeDefinition('floatle', Bits._setfloatle, Bits._getfloatle, float, True, float_bits2chars,
252 allowed_lengths=(16, 32, 64), description="a little-endian floating point number"),
253 DtypeDefinition('bfloat', Bits._setbfloatbe, Bits._getbfloatbe, float, True, bfloat_bits2chars,
254 allowed_lengths=(16,), description="a 16 bit big-endian bfloat floating point number"),
255 DtypeDefinition('bfloatle', Bits._setbfloatle, Bits._getbfloatle, float, True, bfloat_bits2chars,
256 allowed_lengths=(16,), description="a 16 bit little-endian bfloat floating point number"),
257 # Other known length types
258 DtypeDefinition('bits', Bits._setbits, Bits._getbits, Bits, False, bits_bits2chars,
259 description="a bitstring object"),
260 DtypeDefinition('bool', Bits._setbool, Bits._getbool, bool, False, bool_bits2chars,
261 allowed_lengths=(1,), description="a bool (True or False)"),
262 DtypeDefinition('bytes', Bits._setbytes, Bits._getbytes, bytes, False, bytes_bits2chars,
263 multiplier=8, description="a bytes object"),
264 # Unknown length types
265 DtypeDefinition('se', Bits._setse, Bits._getse, int, True, None,
266 variable_length=True, description="a signed exponential-Golomb code"),
267 DtypeDefinition('ue', Bits._setue, Bits._getue, int, False, None,
268 variable_length=True, description="an unsigned exponential-Golomb code"),
269 DtypeDefinition('sie', Bits._setsie, Bits._getsie, int, True, None,
270 variable_length=True, description="a signed interleaved exponential-Golomb code"),
271 DtypeDefinition('uie', Bits._setuie, Bits._getuie, int, False, None,
272 variable_length=True, description="an unsigned interleaved exponential-Golomb code"),
273 # Special case pad type
274 DtypeDefinition('pad', Bits._setpad, Bits._getpad, None, False, None,
275 description="a skipped section of padding"),
277 # MXFP and IEEE 8-bit float types
278 DtypeDefinition('p3binary', Bits._setp3binary, Bits._getp3binary, float, True, p3binary_bits2chars,
279 allowed_lengths=(8,), description="an 8 bit float with binary8p3 format"),
280 DtypeDefinition('p4binary', Bits._setp4binary, Bits._getp4binary, float, True, p4binary_bits2chars,
281 allowed_lengths=(8,), description="an 8 bit float with binary8p4 format"),
282 DtypeDefinition('e4m3mxfp', Bits._sete4m3mxfp, Bits._gete4m3mxfp, float, True, e4m3mxfp_bits2chars,
283 allowed_lengths=(8,), description="an 8 bit float with MXFP E4M3 format"),
284 DtypeDefinition('e5m2mxfp', Bits._sete5m2mxfp, Bits._gete5m2mxfp, float, True, e5m2mxfp_bits2chars,
285 allowed_lengths=(8,), description="an 8 bit float with MXFP E5M2 format"),
286 DtypeDefinition('e3m2mxfp', Bits._sete3m2mxfp, Bits._gete3m2mxfp, float, True, e3m2mxfp_bits2chars,
287 allowed_lengths=(6,), description="a 6 bit float with MXFP E3M2 format"),
288 DtypeDefinition('e2m3mxfp', Bits._sete2m3mxfp, Bits._gete2m3mxfp, float, True, e2m3mxfp_bits2chars,
289 allowed_lengths=(6,), description="a 6 bit float with MXFP E2M3 format"),
290 DtypeDefinition('e2m1mxfp', Bits._sete2m1mxfp, Bits._gete2m1mxfp, float, True, e2m1mxfp_bits2chars,
291 allowed_lengths=(4,), description="a 4 bit float with MXFP E2M1 format"),
292 DtypeDefinition('e8m0mxfp', Bits._sete8m0mxfp, Bits._gete8m0mxfp, float, False, e8m0mxfp_bits2chars,
293 allowed_lengths=(8,), description="an 8 bit float with MXFP E8M0 format"),
294 DtypeDefinition('mxint', Bits._setmxint, Bits._getmxint, float, True, mxint_bits2chars,
295 allowed_lengths=(8,), description="an 8 bit float with MXFP INT8 format"),
296]
299aliases: List[Tuple[str, str]] = [
300 # Floats default to big endian
301 ('float', 'floatbe'),
302 ('bfloat', 'bfloatbe'),
304 # Some single letter aliases for popular types
305 ('int', 'i'),
306 ('uint', 'u'),
307 ('hex', 'h'),
308 ('oct', 'o'),
309 ('bin', 'b'),
310 ('float', 'f'),
311]
313# Create native-endian aliases depending on the byteorder of the system
314byteorder: str = sys.byteorder
315if byteorder == 'little':
316 aliases.extend([
317 ('uintle', 'uintne'),
318 ('intle', 'intne'),
319 ('floatle', 'floatne'),
320 ('bfloatle', 'bfloatne'),
321 ])
322else:
323 aliases.extend([
324 ('uintbe', 'uintne'),
325 ('intbe', 'intne'),
326 ('floatbe', 'floatne'),
327 ('bfloatbe', 'bfloatne'),
328 ])
331for dt in dtype_definitions:
332 dtype_register.add_dtype(dt)
333for alias in aliases:
334 dtype_register.add_dtype_alias(alias[0], alias[1])
336property_docstrings = [f'{name} -- Interpret as {dtype_register[name].description}.' for name in dtype_register.names]
337property_docstring = '\n '.join(property_docstrings)
339# We can't be sure the docstrings are present, as it might be compiled without docstrings.
340if Bits.__doc__ is not None:
341 Bits.__doc__ = Bits.__doc__.replace('[GENERATED_PROPERTY_DESCRIPTIONS]', property_docstring)
342if BitArray.__doc__ is not None:
343 BitArray.__doc__ = BitArray.__doc__.replace('[GENERATED_PROPERTY_DESCRIPTIONS]', property_docstring)
344if ConstBitStream.__doc__ is not None:
345 ConstBitStream.__doc__ = ConstBitStream.__doc__.replace('[GENERATED_PROPERTY_DESCRIPTIONS]', property_docstring)
346if BitStream.__doc__ is not None:
347 BitStream.__doc__ = BitStream.__doc__.replace('[GENERATED_PROPERTY_DESCRIPTIONS]', property_docstring)
350__all__ = ['ConstBitStream', 'BitStream', 'BitArray', 'Array',
351 'Bits', 'pack', 'Error', 'ReadError', 'InterpretError',
352 'ByteAlignError', 'CreationError', 'bytealigned', 'lsb0', 'Dtype', 'options']