Skip to content

Commit 8a31dbb

Browse files
committed
process rotate: precomputed translations, comprehension instead of a loop
1 parent a2f0c5a commit 8a31dbb

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

kaitaistruct.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -356,18 +356,22 @@ def process_xor_many(data, key):
356356
else:
357357
return bytes(a ^ b for a, b in zip(data, itertools.cycle(key)))
358358

359+
# formula taken from: http://stackoverflow.com/a/812039
360+
precomputed_rotations = {amount:[(i << amount) & 0xff | (i >> (-amount & 7)) for i in range(256)] for amount in range(8)}
361+
359362
@staticmethod
360363
def process_rotate_left(data, amount, group_size):
361364
if group_size != 1:
362365
raise Exception(
363366
"unable to rotate group of %d bytes yet" %
364367
(group_size,)
365368
)
369+
amount = amount % 8
370+
if amount == 0:
371+
return data
366372

367-
mask = group_size * 8 - 1
368-
anti_amount = -amount & mask
369-
370-
r = bytearray(data)
371-
for i in range(len(r)):
372-
r[i] = (r[i] << amount) & 0xff | (r[i] >> anti_amount)
373-
return bytes(r)
373+
translate = KaitaiStream.precomputed_rotations[amount]
374+
if PY2:
375+
return bytes(bytearray(translate[a] for a in bytearray(data)))
376+
else:
377+
return bytes(translate[a] for a in data)

0 commit comments

Comments
 (0)