Skip to content

Commit 7ff59f2

Browse files
committed
[ot] python/qemu: jtagtools.bits: fix to_bytestream implementation
This function was not able to cope with BitSequence whose length was not a multiple of 8 bits Signed-off-by: Emmanuel Blot <[email protected]>
1 parent ca04ede commit 7ff59f2

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

python/qemu/jtagtools/bits/__init__.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@
77
"""Bit sequence helpers for JTAG.
88
99
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>
1016
"""
1117

1218
from typing import Any, Iterable, Union
@@ -22,7 +28,7 @@ class BitSequenceError(Exception):
2228
"""
2329

2430

25-
BitSequenceInitializer = Union['BitSequence', str, int, memoryview,
31+
BitSequenceInitializer = Union['BitSequence', str, int, bytes, bytearray,
2632
Iterable[int], Iterable[bool], None]
2733
"""Supported types to initialize a BitSequence."""
2834

@@ -155,7 +161,7 @@ def from_int(cls, value: int, width: int) -> 'BitSequence':
155161
return bseq
156162

157163
@classmethod
158-
def from_bytes(cls, value: memoryview) -> 'BitSequence':
164+
def from_bytes(cls, value: Union[bytes, bytearray]) -> 'BitSequence':
159165
"""Instanciate a BitSequence from a sequence of bytes, one bit for each
160166
input byte.
161167
@@ -165,8 +171,8 @@ def from_bytes(cls, value: memoryview) -> 'BitSequence':
165171
return cls.from_iterable(value)
166172

167173
@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':
170176
"""Instanciate a BitSequence from a sequence of bytes, 8 bits for each
171177
input byte.
172178
@@ -342,12 +348,23 @@ def to_bytestream(self, lsbyte: bool = False, lsbit: bool = False)\
342348
b'0ba523'
343349
>>> hexlify(BitSequence(0xC4A5D01234, 40).to_bytestream(False, False))
344350
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'
345359
"""
346360
out: list[int] = []
347361
bseq = BitSequence(self)
362+
xbitlen = len(bseq) & 7
363+
if xbitlen:
364+
bseq.push_left([0] * (8 - xbitlen))
348365
if lsbit:
349366
bseq.reverse()
350-
while bseq._width:
367+
while bseq._width > 0:
351368
out.append(bseq._int & 0xff)
352369
bseq._int >>= 8
353370
bseq._width -= 8

0 commit comments

Comments
 (0)