From 68cd84c3308c6617f4c43dcb1801689eb087b029 Mon Sep 17 00:00:00 2001 From: James Turner Date: Sat, 5 Oct 2013 23:24:51 +0100 Subject: [PATCH] Make base64 decode significantly faster. Use a reverse lookup table instead of a call to string.find for each input byte, much speedier. --- simgear/misc/strutils.cxx | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/simgear/misc/strutils.cxx b/simgear/misc/strutils.cxx index 47f0b4ef..34d93074 100644 --- a/simgear/misc/strutils.cxx +++ b/simgear/misc/strutils.cxx @@ -344,7 +344,24 @@ static const std::string base64_chars = "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; - +static const unsigned char base64_decode_map[128] = +{ + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 62, 127, 127, 127, 63, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, 127, 127, + 127, 64, 127, 127, 127, 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 127, 127, 127, 127, 127, 127, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 127, 127, 127, 127, 127 +}; + + static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } @@ -375,7 +392,7 @@ std::string decodeBase64(const std::string& encoded_string) char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) - char_array_4[i] = base64_chars.find(char_array_4[i]); + char_array_4[i] = base64_decode_map[char_array_4[i]]; char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); @@ -392,7 +409,7 @@ std::string decodeBase64(const std::string& encoded_string) char_array_4[j] = 0; for (j = 0; j <4; j++) - char_array_4[j] = base64_chars.find(char_array_4[j]); + char_array_4[j] = base64_decode_map[char_array_4[j]]; char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); -- 2.39.5