1# Copyright (c) 2008 - 2024, Ilan Schnell; All Rights Reserved
2"""
3This package defines an object type which can efficiently represent
4a bitarray. Bitarrays are sequence types and behave very much like lists.
5
6Please find a description of this package at:
7
8 https://github.com/ilanschnell/bitarray
9
10Author: Ilan Schnell
11"""
12from __future__ import absolute_import
13
14from bitarray._bitarray import (bitarray, decodetree, _sysinfo,
15 _bitarray_reconstructor,
16 get_default_endian, _set_default_endian,
17 __version__)
18
19
20__all__ = ['bitarray', 'frozenbitarray', 'decodetree', 'bits2bytes']
21
22
23class frozenbitarray(bitarray):
24 """frozenbitarray(initializer=0, /, endian='big', buffer=None) -> \
25frozenbitarray
26
27Return a `frozenbitarray` object. Initialized the same way a `bitarray`
28object is initialized. A `frozenbitarray` is immutable and hashable,
29and may therefore be used as a dictionary key.
30"""
31 def __init__(self, *args, **kwargs):
32 self._freeze()
33
34 def __repr__(self):
35 return 'frozen' + bitarray.__repr__(self)
36
37 def __hash__(self):
38 "Return hash(self)."
39 # ensure hash is independent of endianness
40 a = bitarray(self, 'big')
41 return hash((len(a), a.tobytes()))
42
43 # Technically the code below is not necessary, as all these methods will
44 # raise a TypeError on read-only memory. However, with a different error
45 # message.
46 def __delitem__(self, *args, **kwargs):
47 "" # no docstring
48 raise TypeError("frozenbitarray is immutable")
49
50 append = bytereverse = clear = extend = encode = fill = __delitem__
51 frombytes = fromfile = insert = invert = pack = pop = __delitem__
52 remove = reverse = setall = sort = __setitem__ = __delitem__
53 __iadd__ = __iand__ = __imul__ = __ior__ = __ixor__ = __delitem__
54 __ilshift__ = __irshift__ = __delitem__
55
56
57def bits2bytes(__n):
58 """bits2bytes(n, /) -> int
59
60Return the number of bytes necessary to store n bits.
61"""
62 import sys
63 if not isinstance(__n, (int, long) if sys.version_info[0] == 2 else int):
64 raise TypeError("integer expected")
65 if __n < 0:
66 raise ValueError("non-negative integer expected")
67 return (__n + 7) // 8
68
69
70def test(verbosity=1):
71 """test(verbosity=1) -> TextTestResult
72
73Run self-test, and return unittest.runner.TextTestResult object.
74"""
75 from bitarray import test_bitarray
76 return test_bitarray.run(verbosity=verbosity)