From 0fca87513dd738c48c39bbf5bd7f89210f78f003 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bulski Date: Mon, 9 Apr 2018 21:24:12 +0200 Subject: [PATCH] process rol: precomputing single rotations in static code --- kaitai/kaitaistream.cpp | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/kaitai/kaitaistream.cpp b/kaitai/kaitaistream.cpp index 7453d61..6ff5566 100644 --- a/kaitai/kaitaistream.cpp +++ b/kaitai/kaitaistream.cpp @@ -460,6 +460,19 @@ std::string kaitai::kstream::process_xor_many(std::string data, std::string key) return result; } +// NOTE: perhaps it should be heap allocated? +uint8_t precomputedSingleRotations[8][256]; + +// NOTE: code based on StackOverflow answer at https://stackoverflow.com/a/34321324/2375119 +computeSingleRotations { + for (int amount = 1; amount < 8; amount++) { + int anti_amount = 8 - amount; + for (uint8_t i = 0; i < 256; i++) { + precomputedSingleRotations[amount][i] = (uint8_t)((i << amount) | (i >> anti_amount)); + } + } +} + std::string kaitai::kstream::process_rotate_left(std::string data, int amount, int groupSize = 1) { if (groupSize < 1) throw std::runtime_error("process_rotate_left: groupSize must be at least 1"); @@ -473,11 +486,8 @@ std::string kaitai::kstream::process_rotate_left(std::string data, int amount, i std::string result(len, ' '); if (groupSize == 1) { - int anti_amount = 8 - amount; - uint8_t translate[256]; - for (uint8_t i = 0; i < 256; i++) { - translate[i] = (uint8_t)((i << amount) | (i >> anti_amount)); - } + // NOTE: perhaps its `amount * 256` in the index? + uint8_t *translate = &precomputedSingleRotations[amount]; for (size_t i = 0; i < len; i++) { result[i] = translate[data[i]];