Skip to content

Commit 836d7a3

Browse files
committed
process rotate: precomputed translations, comprehension instead of a loop
1 parent 88e41ac commit 836d7a3

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

kaitaistruct.py

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

358+
# formula taken from: http://stackoverflow.com/a/812039
359+
precomputed_rotations = {amount:[(i << amount) & 0xff | (i >> (-amount & 7)) for i in range(256)] for amount in range(8)}
360+
358361
@staticmethod
359362
def process_rotate_left(data, amount, group_size):
360363
if group_size != 1:
361-
raise Exception(
362-
"unable to rotate group of %d bytes yet" %
363-
(group_size,)
364-
)
365-
366-
mask = group_size * 8 - 1
367-
anti_amount = -amount & mask
364+
raise Exception("unable to rotate groups other than 1 byte")
365+
amount = amount % 8
366+
if amount == 0:
367+
return data
368368

369-
r = bytearray(data)
370-
for i in range(len(r)):
371-
r[i] = (r[i] << amount) & 0xff | (r[i] >> anti_amount)
372-
return bytes(r)
369+
translate = KaitaiStream.precomputed_rotations[amount]
370+
if PY2:
371+
return bytes(bytearray(translate[a] for a in bytearray(data)))
372+
else:
373+
return bytes(translate[a] for a in data)

0 commit comments

Comments
 (0)