7
7
"""Bit sequence helpers for JTAG.
8
8
9
9
BitSequence handle bit manipulation for the JTAG tools.
10
+
11
+ To run all tests, use:
12
+ python3 jtagtools/bits/__init__.py [-v]
13
+
14
+ To test a single function, install pytest and use:
15
+ pytest --doctest-modules jtagtools/bits -k <function>
10
16
"""
11
17
12
18
from typing import Any , Iterable , Union
@@ -22,7 +28,7 @@ class BitSequenceError(Exception):
22
28
"""
23
29
24
30
25
- BitSequenceInitializer = Union ['BitSequence' , str , int , memoryview ,
31
+ BitSequenceInitializer = Union ['BitSequence' , str , int , bytes , bytearray ,
26
32
Iterable [int ], Iterable [bool ], None ]
27
33
"""Supported types to initialize a BitSequence."""
28
34
@@ -155,7 +161,7 @@ def from_int(cls, value: int, width: int) -> 'BitSequence':
155
161
return bseq
156
162
157
163
@classmethod
158
- def from_bytes (cls , value : memoryview ) -> 'BitSequence' :
164
+ def from_bytes (cls , value : Union [ bytes , bytearray ] ) -> 'BitSequence' :
159
165
"""Instanciate a BitSequence from a sequence of bytes, one bit for each
160
166
input byte.
161
167
@@ -165,8 +171,8 @@ def from_bytes(cls, value: memoryview) -> 'BitSequence':
165
171
return cls .from_iterable (value )
166
172
167
173
@classmethod
168
- def from_bytestream (cls , value : memoryview , lsbyte : bool = False ) \
169
- -> 'BitSequence' :
174
+ def from_bytestream (cls , value : Union [ bytes , bytearray ],
175
+ lsbyte : bool = False ) -> 'BitSequence' :
170
176
"""Instanciate a BitSequence from a sequence of bytes, 8 bits for each
171
177
input byte.
172
178
@@ -342,12 +348,23 @@ def to_bytestream(self, lsbyte: bool = False, lsbit: bool = False)\
342
348
b'0ba523'
343
349
>>> hexlify(BitSequence(0xC4A5D01234, 40).to_bytestream(False, False))
344
350
b'c4a5d01234'
351
+ >>> hexlify(BitSequence(0x51234, 20).to_bytestream(False, False))
352
+ b'051234'
353
+ >>> hexlify(BitSequence(0x51234, 21).to_bytestream(False, False))
354
+ b'051234'
355
+ >>> hexlify(BitSequence(0x51234, 21).to_bytestream(True, False))
356
+ b'341205'
357
+ >>> hexlify(BitSequence(0x51234, 21).to_bytestream(True, True))
358
+ b'2c48a0'
345
359
"""
346
360
out : list [int ] = []
347
361
bseq = BitSequence (self )
362
+ xbitlen = len (bseq ) & 7
363
+ if xbitlen :
364
+ bseq .push_left ([0 ] * (8 - xbitlen ))
348
365
if lsbit :
349
366
bseq .reverse ()
350
- while bseq ._width :
367
+ while bseq ._width > 0 :
351
368
out .append (bseq ._int & 0xff )
352
369
bseq ._int >>= 8
353
370
bseq ._width -= 8
0 commit comments