bitstring 4.2.2__tar.gz → 4.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {bitstring-4.2.2 → bitstring-4.2.3}/MANIFEST.in +1 -1
  2. {bitstring-4.2.2/bitstring.egg-info → bitstring-4.2.3}/PKG-INFO +54 -68
  3. {bitstring-4.2.2 → bitstring-4.2.3}/README.md +53 -67
  4. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/__init__.py +33 -14
  5. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/__main__.py +1 -1
  6. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/array_.py +12 -6
  7. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/bitarray_.py +3 -4
  8. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/bits.py +20 -17
  9. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/bitstore.py +3 -3
  10. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/bitstore_helpers.py +11 -1
  11. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/bitstream.py +1 -1
  12. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/bitstring_options.py +2 -1
  13. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/dtypes.py +3 -4
  14. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/exceptions.py +0 -1
  15. bitstring-4.2.3/bitstring/luts.py +245 -0
  16. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/mxfp.py +19 -13
  17. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/utils.py +8 -3
  18. {bitstring-4.2.2 → bitstring-4.2.3/bitstring.egg-info}/PKG-INFO +54 -68
  19. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring.egg-info/SOURCES.txt +2 -1
  20. {bitstring-4.2.2 → bitstring-4.2.3}/pyproject.toml +1 -1
  21. bitstring-4.2.2/release_notes.txt → bitstring-4.2.3/release_notes.md +751 -689
  22. {bitstring-4.2.2 → bitstring-4.2.3}/tests/test_array.py +1 -1
  23. bitstring-4.2.3/tests/test_benchmarks.py +72 -0
  24. {bitstring-4.2.2 → bitstring-4.2.3}/tests/test_bitarray.py +3 -3
  25. {bitstring-4.2.2 → bitstring-4.2.3}/tests/test_bits.py +16 -27
  26. {bitstring-4.2.2 → bitstring-4.2.3}/tests/test_mxfp.py +26 -0
  27. bitstring-4.2.2/bitstring/luts.py +0 -248
  28. {bitstring-4.2.2 → bitstring-4.2.3}/LICENSE +0 -0
  29. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/fp8.py +0 -0
  30. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/methods.py +0 -0
  31. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring/py.typed +0 -0
  32. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring.egg-info/dependency_links.txt +0 -0
  33. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring.egg-info/requires.txt +0 -0
  34. {bitstring-4.2.2 → bitstring-4.2.3}/bitstring.egg-info/top_level.txt +0 -0
  35. {bitstring-4.2.2 → bitstring-4.2.3}/setup.cfg +0 -0
  36. {bitstring-4.2.2 → bitstring-4.2.3}/tests/__init__.py +0 -0
  37. {bitstring-4.2.2 → bitstring-4.2.3}/tests/smalltestfile +0 -0
  38. {bitstring-4.2.2 → bitstring-4.2.3}/tests/test.m1v +0 -0
  39. {bitstring-4.2.2 → bitstring-4.2.3}/tests/test_bitstore.py +0 -0
  40. {bitstring-4.2.2 → bitstring-4.2.3}/tests/test_bitstream.py +0 -0
  41. {bitstring-4.2.2 → bitstring-4.2.3}/tests/test_bitstring.py +0 -0
  42. {bitstring-4.2.2 → bitstring-4.2.3}/tests/test_constbitstream.py +0 -0
  43. {bitstring-4.2.2 → bitstring-4.2.3}/tests/test_dtypes.py +0 -0
  44. {bitstring-4.2.2 → bitstring-4.2.3}/tests/test_fp8.py +0 -0
  45. {bitstring-4.2.2 → bitstring-4.2.3}/tests/test_scaled_dtypes.py +0 -0
@@ -1,7 +1,7 @@
1
1
  include tests/test.m1v
2
2
  include tests/smalltestfile
3
3
  include tests/__init__.py
4
- include release_notes.txt
4
+ include release_notes.md
5
5
  include README.md
6
6
  include bitstring/py.typed
7
7
  prune doc
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: bitstring
3
- Version: 4.2.2
3
+ Version: 4.2.3
4
4
  Summary: Simple construction, analysis and modification of binary data.
5
5
  Author-email: Scott Griffiths <dr.scottgriffiths@gmail.com>
6
6
  Project-URL: homepage, https://github.com/scott-griffiths/bitstring
@@ -40,26 +40,13 @@ It has been actively maintained since 2006.
40
40
  [![Pepy Total Downlods](https://img.shields.io/pepy/dt/bitstring?logo=python&logoColor=white&labelColor=blue&color=blue)](https://www.pepy.tech/projects/bitstring)
41
41
  [![PyPI - Downloads](https://img.shields.io/pypi/dm/bitstring?label=%40&labelColor=blue&color=blue)](https://pypistats.org/packages/bitstring)
42
42
 
43
-
44
- News
45
43
  ----
46
- **May 2024**: bitstring 4.2.2 released.
47
-
48
- New in version 4.2:
49
-
50
- * Dropped support for Python 3.7. Minimum version is now 3.8.
51
- * A new `Dtype` class can be optionally used to specify types.
52
- * The `bitstring.options` object is now the preferred method for changing module options.
53
- * New `fromstring` method as another way to create bitstrings from formatted strings.
54
- * More types can now be pretty printed.
55
- * A range of 8-bit, 6-bit and even 4-bit floating point formats added (beta):
56
- * Performance improvements.
57
44
 
58
- 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.
45
+ > [!NOTE]
46
+ > 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.md).
59
47
 
60
48
 
61
- Overview
62
- --------
49
+ # Overview
63
50
 
64
51
  * Efficiently store and manipulate binary data in idiomatic Python.
65
52
  * Create bitstrings from hex, octal, binary, files, formatted strings, bytes, integers and floats of different endiannesses.
@@ -70,8 +57,8 @@ Overview
70
57
  * Rich API - chances are that whatever you want to do there's a simple and elegant way of doing it.
71
58
  * Open source software, released under the MIT licence.
72
59
 
73
- Documentation
74
- -------------
60
+ # Documentation
61
+
75
62
  Extensive documentation for the bitstring module is available.
76
63
  Some starting points are given below:
77
64
 
@@ -81,67 +68,66 @@ Some starting points are given below:
81
68
 
82
69
  There is also an introductory walkthrough notebook on [binder](https://mybinder.org/v2/gh/scott-griffiths/bitstring/main?labpath=doc%2Fwalkthrough.ipynb).
83
70
 
84
- Release Notes
85
- -------------
86
-
87
- 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).
88
-
89
- Examples
90
- --------
71
+ # Examples
91
72
 
92
73
  ### Installation
93
-
94
- $ pip install bitstring
74
+ ```
75
+ $ pip install bitstring
76
+ ```
95
77
 
96
78
  ### Creation
97
-
98
- >>> from bitstring import Bits, BitArray, BitStream, pack
99
- >>> a = BitArray(bin='00101')
100
- >>> b = Bits(a_file_object)
101
- >>> c = BitArray('0xff, 0b101, 0o65, uint6=22')
102
- >>> d = pack('intle16, hex=a, 0b1', 100, a='0x34f')
103
- >>> e = pack('<16h', *range(16))
79
+ ```pycon
80
+ >>> from bitstring import Bits, BitArray, BitStream, pack
81
+ >>> a = BitArray(bin='00101')
82
+ >>> b = Bits(a_file_object)
83
+ >>> c = BitArray('0xff, 0b101, 0o65, uint6=22')
84
+ >>> d = pack('intle16, hex=a, 0b1', 100, a='0x34f')
85
+ >>> e = pack('<16h', *range(16))
86
+ ```
104
87
 
105
88
  ### Different interpretations, slicing and concatenation
106
-
107
- >>> a = BitArray('0x3348')
108
- >>> a.hex, a.bin, a.uint, a.float, a.bytes
109
- ('3348', '0011001101001000', 13128, 0.2275390625, b'3H')
110
- >>> a[10:3:-1].bin
111
- '0101100'
112
- >>> '0b100' + 3*a
113
- BitArray('0x866906690669, 0b000')
89
+ ```pycon
90
+ >>> a = BitArray('0x3348')
91
+ >>> a.hex, a.bin, a.uint, a.float, a.bytes
92
+ ('3348', '0011001101001000', 13128, 0.2275390625, b'3H')
93
+ >>> a[10:3:-1].bin
94
+ '0101100'
95
+ >>> '0b100' + 3*a
96
+ BitArray('0x866906690669, 0b000')
97
+ ```
114
98
 
115
99
  ### Reading data sequentially
116
-
117
- >>> b = BitStream('0x160120f')
118
- >>> b.read(12).hex
119
- '160'
120
- >>> b.pos = 0
121
- >>> b.read('uint12')
122
- 352
123
- >>> b.readlist('uint12, bin3')
124
- [288, '111']
100
+ ```pycon
101
+ >>> b = BitStream('0x160120f')
102
+ >>> b.read(12).hex
103
+ '160'
104
+ >>> b.pos = 0
105
+ >>> b.read('uint12')
106
+ 352
107
+ >>> b.readlist('uint12, bin3')
108
+ [288, '111']
109
+ ```
125
110
 
126
111
  ### Searching, inserting and deleting
127
-
128
- >>> c = BitArray('0b00010010010010001111') # c.hex == '0x1248f'
129
- >>> c.find('0x48')
130
- (8,)
131
- >>> c.replace('0b001', '0xabc')
132
- >>> c.insert('0b0000', pos=3)
133
- >>> del c[12:16]
112
+ ```pycon
113
+ >>> c = BitArray('0b00010010010010001111') # c.hex == '0x1248f'
114
+ >>> c.find('0x48')
115
+ (8,)
116
+ >>> c.replace('0b001', '0xabc')
117
+ >>> c.insert('0b0000', pos=3)
118
+ >>> del c[12:16]
119
+ ```
134
120
 
135
121
  ### Arrays of fixed-length formats
136
-
137
- >>> from bitstring import Array
138
- >>> a = Array('uint7', [9, 100, 3, 1])
139
- >>> a.data
140
- BitArray('0x1390181')
141
- >>> a[::2] *= 5
142
- >>> a
143
- Array('uint7', [45, 100, 15, 1])
144
-
122
+ ```pycon
123
+ >>> from bitstring import Array
124
+ >>> a = Array('uint7', [9, 100, 3, 1])
125
+ >>> a.data
126
+ BitArray('0x1390181')
127
+ >>> a[::2] *= 5
128
+ >>> a
129
+ Array('uint7', [45, 100, 15, 1])
130
+ ```
145
131
 
146
132
 
147
133
  <sub>Copyright (c) 2006 - 2024 Scott Griffiths</sub>
@@ -16,26 +16,13 @@ It has been actively maintained since 2006.
16
16
  [![Pepy Total Downlods](https://img.shields.io/pepy/dt/bitstring?logo=python&logoColor=white&labelColor=blue&color=blue)](https://www.pepy.tech/projects/bitstring)
17
17
  [![PyPI - Downloads](https://img.shields.io/pypi/dm/bitstring?label=%40&labelColor=blue&color=blue)](https://pypistats.org/packages/bitstring)
18
18
 
19
-
20
- News
21
19
  ----
22
- **May 2024**: bitstring 4.2.2 released.
23
-
24
- New in version 4.2:
25
-
26
- * Dropped support for Python 3.7. Minimum version is now 3.8.
27
- * A new `Dtype` class can be optionally used to specify types.
28
- * The `bitstring.options` object is now the preferred method for changing module options.
29
- * New `fromstring` method as another way to create bitstrings from formatted strings.
30
- * More types can now be pretty printed.
31
- * A range of 8-bit, 6-bit and even 4-bit floating point formats added (beta):
32
- * Performance improvements.
33
20
 
34
- 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.
21
+ > [!NOTE]
22
+ > 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.md).
35
23
 
36
24
 
37
- Overview
38
- --------
25
+ # Overview
39
26
 
40
27
  * Efficiently store and manipulate binary data in idiomatic Python.
41
28
  * Create bitstrings from hex, octal, binary, files, formatted strings, bytes, integers and floats of different endiannesses.
@@ -46,8 +33,8 @@ Overview
46
33
  * Rich API - chances are that whatever you want to do there's a simple and elegant way of doing it.
47
34
  * Open source software, released under the MIT licence.
48
35
 
49
- Documentation
50
- -------------
36
+ # Documentation
37
+
51
38
  Extensive documentation for the bitstring module is available.
52
39
  Some starting points are given below:
53
40
 
@@ -57,67 +44,66 @@ Some starting points are given below:
57
44
 
58
45
  There is also an introductory walkthrough notebook on [binder](https://mybinder.org/v2/gh/scott-griffiths/bitstring/main?labpath=doc%2Fwalkthrough.ipynb).
59
46
 
60
- Release Notes
61
- -------------
62
-
63
- 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).
64
-
65
- Examples
66
- --------
47
+ # Examples
67
48
 
68
49
  ### Installation
69
-
70
- $ pip install bitstring
50
+ ```
51
+ $ pip install bitstring
52
+ ```
71
53
 
72
54
  ### Creation
73
-
74
- >>> from bitstring import Bits, BitArray, BitStream, pack
75
- >>> a = BitArray(bin='00101')
76
- >>> b = Bits(a_file_object)
77
- >>> c = BitArray('0xff, 0b101, 0o65, uint6=22')
78
- >>> d = pack('intle16, hex=a, 0b1', 100, a='0x34f')
79
- >>> e = pack('<16h', *range(16))
55
+ ```pycon
56
+ >>> from bitstring import Bits, BitArray, BitStream, pack
57
+ >>> a = BitArray(bin='00101')
58
+ >>> b = Bits(a_file_object)
59
+ >>> c = BitArray('0xff, 0b101, 0o65, uint6=22')
60
+ >>> d = pack('intle16, hex=a, 0b1', 100, a='0x34f')
61
+ >>> e = pack('<16h', *range(16))
62
+ ```
80
63
 
81
64
  ### Different interpretations, slicing and concatenation
82
-
83
- >>> a = BitArray('0x3348')
84
- >>> a.hex, a.bin, a.uint, a.float, a.bytes
85
- ('3348', '0011001101001000', 13128, 0.2275390625, b'3H')
86
- >>> a[10:3:-1].bin
87
- '0101100'
88
- >>> '0b100' + 3*a
89
- BitArray('0x866906690669, 0b000')
65
+ ```pycon
66
+ >>> a = BitArray('0x3348')
67
+ >>> a.hex, a.bin, a.uint, a.float, a.bytes
68
+ ('3348', '0011001101001000', 13128, 0.2275390625, b'3H')
69
+ >>> a[10:3:-1].bin
70
+ '0101100'
71
+ >>> '0b100' + 3*a
72
+ BitArray('0x866906690669, 0b000')
73
+ ```
90
74
 
91
75
  ### Reading data sequentially
92
-
93
- >>> b = BitStream('0x160120f')
94
- >>> b.read(12).hex
95
- '160'
96
- >>> b.pos = 0
97
- >>> b.read('uint12')
98
- 352
99
- >>> b.readlist('uint12, bin3')
100
- [288, '111']
76
+ ```pycon
77
+ >>> b = BitStream('0x160120f')
78
+ >>> b.read(12).hex
79
+ '160'
80
+ >>> b.pos = 0
81
+ >>> b.read('uint12')
82
+ 352
83
+ >>> b.readlist('uint12, bin3')
84
+ [288, '111']
85
+ ```
101
86
 
102
87
  ### Searching, inserting and deleting
103
-
104
- >>> c = BitArray('0b00010010010010001111') # c.hex == '0x1248f'
105
- >>> c.find('0x48')
106
- (8,)
107
- >>> c.replace('0b001', '0xabc')
108
- >>> c.insert('0b0000', pos=3)
109
- >>> del c[12:16]
88
+ ```pycon
89
+ >>> c = BitArray('0b00010010010010001111') # c.hex == '0x1248f'
90
+ >>> c.find('0x48')
91
+ (8,)
92
+ >>> c.replace('0b001', '0xabc')
93
+ >>> c.insert('0b0000', pos=3)
94
+ >>> del c[12:16]
95
+ ```
110
96
 
111
97
  ### Arrays of fixed-length formats
112
-
113
- >>> from bitstring import Array
114
- >>> a = Array('uint7', [9, 100, 3, 1])
115
- >>> a.data
116
- BitArray('0x1390181')
117
- >>> a[::2] *= 5
118
- >>> a
119
- Array('uint7', [45, 100, 15, 1])
120
-
98
+ ```pycon
99
+ >>> from bitstring import Array
100
+ >>> a = Array('uint7', [9, 100, 3, 1])
101
+ >>> a.data
102
+ BitArray('0x1390181')
103
+ >>> a[::2] *= 5
104
+ >>> a
105
+ Array('uint7', [45, 100, 15, 1])
106
+ ```
121
107
 
122
108
 
123
109
  <sub>Copyright (c) 2006 - 2024 Scott Griffiths</sub>
@@ -55,7 +55,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
55
55
  THE SOFTWARE.
56
56
  """
57
57
 
58
- __version__ = "4.2.2"
58
+ __version__ = "4.2.3"
59
59
 
60
60
  __author__ = "Scott Griffiths"
61
61
 
@@ -111,31 +111,38 @@ class _MyModuleType(types.ModuleType):
111
111
 
112
112
  sys.modules[__name__].__class__ = _MyModuleType
113
113
 
114
- """These methods convert a bit length to the number of characters needed to print it for different interpretations."""
114
+
115
+ # These methods convert a bit length to the number of characters needed to print it for different interpretations.
115
116
  def hex_bits2chars(bitlength: int):
116
117
  # One character for every 4 bits
117
118
  return bitlength // 4
118
119
 
120
+
119
121
  def oct_bits2chars(bitlength: int):
120
122
  # One character for every 3 bits
121
123
  return bitlength // 3
122
124
 
125
+
123
126
  def bin_bits2chars(bitlength: int):
124
127
  # One character for each bit
125
128
  return bitlength
126
129
 
130
+
127
131
  def bytes_bits2chars(bitlength: int):
128
132
  # One character for every 8 bits
129
133
  return bitlength // 8
130
134
 
135
+
131
136
  def uint_bits2chars(bitlength: int):
132
137
  # How many characters is largest possible int of this length?
133
138
  return len(str((1 << bitlength) - 1))
134
139
 
140
+
135
141
  def int_bits2chars(bitlength: int):
136
142
  # How many characters is largest negative int of this length? (To include minus sign).
137
143
  return len(str((-1 << (bitlength - 1))))
138
144
 
145
+
139
146
  def float_bits2chars(bitlength: Literal[16, 32, 64]):
140
147
  # These bit lengths were found by looking at lots of possible values
141
148
  if bitlength in [16, 32]:
@@ -143,53 +150,65 @@ def float_bits2chars(bitlength: Literal[16, 32, 64]):
143
150
  else:
144
151
  return 24 # Empirical value
145
152
 
146
- def p3binary_bits2chars(bitlength: Literal[8]):
153
+
154
+ def p3binary_bits2chars(_: Literal[8]):
147
155
  return 19 # Empirical value
148
156
 
149
- def p4binary_bits2chars(bitlength: Literal[8]):
157
+
158
+ def p4binary_bits2chars(_: Literal[8]):
150
159
  # Found by looking at all the possible values
151
160
  return 13 # Empirical value
152
161
 
153
- def e4m3mxfp_bits2chars(bitlength: Literal[8]):
162
+
163
+ def e4m3mxfp_bits2chars(_: Literal[8]):
154
164
  return 13
155
165
 
156
- def e5m2mxfp_bits2chars(bitlength: Literal[8]):
166
+
167
+ def e5m2mxfp_bits2chars(_: Literal[8]):
157
168
  return 19
158
169
 
159
- def e3m2mxfp_bits2chars(bitlength: Literal[6]):
170
+
171
+ def e3m2mxfp_bits2chars(_: Literal[6]):
160
172
  # Not sure what the best value is here. It's 7 without considering the scale that could be applied.
161
173
  return 7
162
174
 
163
- def e2m3mxfp_bits2chars(bitlength: Literal[6]):
175
+
176
+ def e2m3mxfp_bits2chars(_: Literal[6]):
164
177
  # Not sure what the best value is here.
165
178
  return 7
166
179
 
167
- def e2m1mxfp_bits2chars(bitlength: Literal[4]):
180
+
181
+ def e2m1mxfp_bits2chars(_: Literal[4]):
168
182
  # Not sure what the best value is here.
169
183
  return 7
170
184
 
171
- def e8m0mxfp_bits2chars(bitlength: Literal[8]):
172
- # Can range same as float32
185
+
186
+ def e8m0mxfp_bits2chars(_: Literal[8]):
187
+ # Has same range as float32
173
188
  return 23
174
189
 
175
- def mxint_bits2chars(bitlength: Literal[8]):
190
+
191
+ def mxint_bits2chars(_: Literal[8]):
176
192
  # Not sure what the best value is here.
177
193
  return 10
178
194
 
179
195
 
180
- def bfloat_bits2chars(bitlength: Literal[16]):
196
+ def bfloat_bits2chars(_: Literal[16]):
181
197
  # Found by looking at all the possible values
182
198
  return 23 # Empirical value
183
199
 
200
+
184
201
  def bits_bits2chars(bitlength: int):
185
202
  # For bits type we can see how long it needs to be printed by trying any value
186
203
  temp = Bits(bitlength)
187
204
  return len(str(temp))
188
205
 
189
- def bool_bits2chars(bitlength: Literal[1]):
206
+
207
+ def bool_bits2chars(_: Literal[1]):
190
208
  # Bools are printed as 1 or 0, not True or False, so are one character each
191
209
  return 1
192
210
 
211
+
193
212
  dtype_definitions = [
194
213
  # Integer types
195
214
  DtypeDefinition('uint', Bits._setuint, Bits._getuint, int, False, uint_bits2chars,
@@ -47,4 +47,4 @@ $ python -m bitstring hex=01, uint:12=352.hex
47
47
 
48
48
 
49
49
  if __name__ == '__main__':
50
- main()
50
+ main()
@@ -93,6 +93,7 @@ class Array:
93
93
  self.data += BitArray._create_from_bitstype(trailing_bits)
94
94
 
95
95
  _largest_values = None
96
+
96
97
  @staticmethod
97
98
  def _calculate_auto_scale(initializer, name: str, length: Optional[int]) -> float:
98
99
  # Now need to find the largest power of 2 representable with this format.
@@ -112,12 +113,15 @@ class Array:
112
113
  }
113
114
  if f'{name}{length}' in Array._largest_values.keys():
114
115
  float_values = Array('float64', initializer).tolist()
116
+ if not float_values:
117
+ raise ValueError("Can't calculate an 'auto' scale with an empty Array initializer.")
115
118
  max_float_value = max(abs(x) for x in float_values)
116
119
  if max_float_value == 0:
117
120
  # This special case isn't covered in the standard. I'm choosing to return no scale.
118
121
  return 1.0
119
- log2 = int(math.log2(max_float_value))
120
- lp2 = int(math.log2(Array._largest_values[f'{name}{length}']))
122
+ # We need to find the largest power of 2 that is less than the max value
123
+ log2 = math.floor(math.log2(max_float_value))
124
+ lp2 = math.floor(math.log2(Array._largest_values[f'{name}{length}']))
121
125
  lg_scale = log2 - lp2
122
126
  # Saturate at values representable in E8M0 format.
123
127
  if lg_scale > 127:
@@ -155,7 +159,7 @@ class Array:
155
159
  except ValueError:
156
160
  name_length = utils.parse_single_struct_token(new_dtype)
157
161
  if name_length is not None:
158
- dtype = Dtype(*name_length)
162
+ dtype = Dtype(name_length[0], name_length[1])
159
163
  else:
160
164
  raise ValueError(f"Inappropriate Dtype for Array: '{new_dtype}'.")
161
165
  if dtype.length is None:
@@ -270,7 +274,7 @@ class Array:
270
274
  return new_array
271
275
 
272
276
  def tolist(self) -> List[ElementType]:
273
- return [self._dtype.read_fn(self.data, start=start)
277
+ return [self._dtype.read_fn(self.data, start=start)
274
278
  for start in range(0, len(self.data) - self._dtype.length + 1, self._dtype.length)]
275
279
 
276
280
  def append(self, x: ElementType) -> None:
@@ -408,9 +412,11 @@ class Array:
408
412
  token_list = utils.preprocess_tokens(fmt)
409
413
  if len(token_list) not in [1, 2]:
410
414
  raise ValueError(f"Only one or two tokens can be used in an Array.pp() format - '{fmt}' has {len(token_list)} tokens.")
411
- dtype1 = Dtype(*utils.parse_name_length_token(token_list[0]))
415
+ name1, length1 = utils.parse_name_length_token(token_list[0])
416
+ dtype1 = Dtype(name1, length1)
412
417
  if len(token_list) == 2:
413
- dtype2 = Dtype(*utils.parse_name_length_token(token_list[1]))
418
+ name2, length2 = utils.parse_name_length_token(token_list[1])
419
+ dtype2 = Dtype(name2, length2)
414
420
 
415
421
  token_length = dtype1.bitlength
416
422
  if dtype2 is not None:
@@ -11,6 +11,7 @@ from bitstring.bits import Bits, BitsType, TBits
11
11
 
12
12
  import bitstring.dtypes
13
13
 
14
+
14
15
  class BitArray(Bits):
15
16
  """A container holding a mutable sequence of bits.
16
17
 
@@ -71,7 +72,6 @@ class BitArray(Bits):
71
72
  # As BitArray objects are mutable, we shouldn't allow them to be hashed.
72
73
  __hash__: None = None
73
74
 
74
-
75
75
  def __init__(self, auto: Optional[Union[BitsType, int]] = None, /, length: Optional[int] = None,
76
76
  offset: Optional[int] = None, **kwargs) -> None:
77
77
  """Either specify an 'auto' initialiser:
@@ -172,6 +172,7 @@ class BitArray(Bits):
172
172
 
173
173
  def _setitem_slice(self, key: slice, value: BitsType) -> None:
174
174
  if isinstance(value, numbers.Integral):
175
+ value = int(value)
175
176
  if key.step not in [None, -1, 1]:
176
177
  if value in [0, 1]:
177
178
  self.set(value, range(*key.indices(len(self))))
@@ -195,7 +196,7 @@ class BitArray(Bits):
195
196
 
196
197
  def __setitem__(self, key: Union[slice, int], value: BitsType) -> None:
197
198
  if isinstance(key, numbers.Integral):
198
- self._setitem_int(key, value)
199
+ self._setitem_int(int(key), value)
199
200
  else:
200
201
  self._setitem_slice(key, value)
201
202
 
@@ -573,5 +574,3 @@ class BitArray(Bits):
573
574
  def clear(self) -> None:
574
575
  """Remove all bits, reset to zero length."""
575
576
  self._clear()
576
-
577
-
@@ -1699,34 +1699,37 @@ class Bits:
1699
1699
 
1700
1700
  @staticmethod
1701
1701
  def _process_pp_tokens(token_list, fmt):
1702
+ if len(token_list) not in [1, 2]:
1703
+ raise ValueError(
1704
+ f"Only one or two tokens can be used in an pp() format - '{fmt}' has {len(token_list)} tokens.")
1702
1705
  has_length_in_fmt = True
1703
- if len(token_list) == 1:
1704
- dtype1 = Dtype(*utils.parse_name_length_token(token_list[0]))
1705
- dtype2 = None
1706
- bits_per_group = dtype1.bitlength
1706
+ name1, length1 = utils.parse_name_length_token(token_list[0])
1707
+ dtype1 = Dtype(name1, length1)
1708
+ bits_per_group = dtype1.bitlength
1709
+ dtype2 = None
1710
+
1711
+ if len(token_list) == 2:
1712
+ name2, length2 = utils.parse_name_length_token(token_list[1])
1713
+ dtype2 = Dtype(name2, length2)
1714
+ if None not in {dtype1.bitlength, dtype2.bitlength} and dtype1.bitlength != dtype2.bitlength:
1715
+ raise ValueError(
1716
+ f"Differing bit lengths of {dtype1.bitlength} and {dtype2.bitlength} in format string '{fmt}'.")
1707
1717
  if bits_per_group is None:
1708
- has_length_in_fmt = False
1718
+ bits_per_group = dtype2.bitlength
1719
+
1720
+ if bits_per_group is None:
1721
+ has_length_in_fmt = False
1722
+ if len(token_list) == 1:
1709
1723
  bits_per_group = {'bin': 8, 'hex': 8, 'oct': 12, 'bytes': 32}.get(dtype1.name)
1710
1724
  if bits_per_group is None:
1711
1725
  raise ValueError(f"No length or default length available for pp() format '{fmt}'.")
1712
- elif len(token_list) == 2:
1713
- dtype1 = Dtype(*utils.parse_name_length_token(token_list[0]))
1714
- dtype2 = Dtype(*utils.parse_name_length_token(token_list[1]))
1715
- if dtype1.bitlength is not None and dtype2.bitlength is not None and dtype1.bitlength != dtype2.bitlength:
1716
- raise ValueError(
1717
- f"Differing bit lengths of {dtype1.bitlength} and {dtype2.bitlength} in format string '{fmt}'.")
1718
- bits_per_group = dtype1.bitlength if dtype1.bitlength is not None else dtype2.bitlength
1719
- if bits_per_group is None:
1720
- has_length_in_fmt = False
1726
+ else:
1721
1727
  try:
1722
1728
  bits_per_group = 2 * Bits._bits_per_char(dtype1.name) * Bits._bits_per_char(dtype2.name)
1723
1729
  except ValueError:
1724
1730
  raise ValueError(f"Can't find a default bitlength to use for pp() format '{fmt}'.")
1725
1731
  if bits_per_group >= 24:
1726
1732
  bits_per_group //= 2
1727
- else:
1728
- raise ValueError(
1729
- f"Only one or two tokens can be used in an pp() format - '{fmt}' has {len(token_list)} tokens.")
1730
1733
  return dtype1, dtype2, bits_per_group, has_length_in_fmt
1731
1734
 
1732
1735
  def pp(self, fmt: Optional[str] = None, width: int = 120, sep: str = ' ',
@@ -14,7 +14,8 @@ def offset_slice_indices_lsb0(key: slice, length: int) -> slice:
14
14
  # For negative step we sometimes get a negative stop, which can't be used correctly in a new slice
15
15
  return slice(new_start, None if new_stop < 0 else new_stop, step)
16
16
 
17
- def offset_start_stop_lsb0(start: Optional[int], stop: Optional[int], length: int) -> slice:
17
+
18
+ def offset_start_stop_lsb0(start: Optional[int], stop: Optional[int], length: int) -> tuple[int, int]:
18
19
  # First convert slice to all integers
19
20
  # Length already should take account of the offset
20
21
  start, stop, _ = slice(start, stop, None).indices(length)
@@ -218,7 +219,6 @@ class BitStore:
218
219
  def getindex_lsb0(self, index: int, /) -> bool:
219
220
  return bool(self._bitarray.__getitem__(-index - 1))
220
221
 
221
-
222
222
  @overload
223
223
  def setitem_lsb0(self, key: int, value: int, /) -> None:
224
224
  ...
@@ -269,4 +269,4 @@ class BitStore:
269
269
  self._bitarray.__setitem__(key, value)
270
270
 
271
271
  def delitem_msb0(self, key, /):
272
- self._bitarray.__delitem__(key)
272
+ self._bitarray.__delitem__(key)