Skip to content

Commit 4048e69

Browse files
Merge pull request #27 from quentinlampin/buffer_concat_right_left_bugfix
[bugfix] buffer concatenation
2 parents 8fc991f + df666fd commit 4048e69

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

microschc/binary/buffer.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -321,13 +321,14 @@ def __add__(self, other: 'Buffer') -> 'Buffer':
321321
bit_shift: int = abs(right.padding_length - left.padding_length)
322322
if right.padding_length > left.padding_length:
323323
new_content: bytes = b''
324-
# shift right to the left
324+
# shift right to the right
325325
carry: int = 0
326-
for b in right.content[::-1]:
327-
sb:int = (b << bit_shift) & 0xff + carry
328-
new_content = sb.to_bytes(1, 'big') + new_content
329-
carry = b >> (8-bit_shift)
330-
new_content = left.content[0:-1] + (left.content[-1] + new_content[0]).to_bytes(1, 'big') + new_content[1:]
326+
carry_mask: int = (1 << bit_shift) - 1
327+
for b in right.content[::]:
328+
sb:int = (b >> bit_shift) + carry
329+
carry = (b & carry_mask) << (8 - bit_shift)
330+
new_content += sb.to_bytes(1, 'big')
331+
new_content = left.content[0:-1] + (left.content[-1] + new_content[0]).to_bytes(1, 'big') + new_content[1:] + carry.to_bytes(1, 'big')
331332
else:
332333
# shift right to the left, careful with the carry that will spill over right's left boundary
333334
new_content: bytes = b''

tests/binary/test_buffer.py

+8
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,14 @@ def test_add():
299299

300300
expected: Buffer = Buffer(content=b'\x06', length=4, padding=Padding.LEFT)
301301
assert left_right == expected
302+
303+
left:Buffer = Buffer(content=b'\xe0', length=7, padding=Padding.RIGHT)
304+
right: Buffer = Buffer(content=b'\x05', length=4, padding=Padding.LEFT)
305+
left_right: Buffer = left + right
306+
307+
expected: Buffer = Buffer(content=b'\xe0\xa0', length=11, padding=Padding.RIGHT)
308+
assert left_right == expected
309+
302310

303311
def test_or():
304312
# 0x08 0x68

0 commit comments

Comments
 (0)