aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEelco Dolstra <edolstra@gmail.com>2021-08-06 17:41:11 +0200
committerGitHub <noreply@github.com>2021-08-06 17:41:11 +0200
commite277c0c479d58bcd0f55e71ec9ebe43a6161a1d4 (patch)
treedcb00c552206f6914c0368a1194446025db25cc1
parentd64f9671fcce47e792974b372dc72de8c49994b7 (diff)
parentb9c9c2576658706939d20b1861309fefa7f20889 (diff)
Merge pull request #5075 from andir/libutil-base64-init
libutil: initialize the base64 decode array only once
-rw-r--r--src/libutil/util.cc22
1 files changed, 10 insertions, 12 deletions
diff --git a/src/libutil/util.cc b/src/libutil/util.cc
index d876315c8..d1270cd31 100644
--- a/src/libutil/util.cc
+++ b/src/libutil/util.cc
@@ -6,14 +6,15 @@
#include <cctype>
#include <cerrno>
+#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
-#include <climits>
+#include <future>
#include <iostream>
+#include <mutex>
#include <sstream>
#include <thread>
-#include <future>
#include <fcntl.h>
#include <grp.h>
@@ -1447,7 +1448,7 @@ std::string filterANSIEscapes(const std::string & s, bool filterAll, unsigned in
static char base64Chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
+static std::array<char, 256> base64DecodeChars;
string base64Encode(std::string_view s)
{
@@ -1472,15 +1473,12 @@ string base64Encode(std::string_view s)
string base64Decode(std::string_view s)
{
- bool init = false;
- char decode[256];
- if (!init) {
- // FIXME: not thread-safe.
- memset(decode, -1, sizeof(decode));
+ static std::once_flag flag;
+ std::call_once(flag, [](){
+ base64DecodeChars = { (char)-1 };
for (int i = 0; i < 64; i++)
- decode[(int) base64Chars[i]] = i;
- init = true;
- }
+ base64DecodeChars[(int) base64Chars[i]] = i;
+ });
string res;
unsigned int d = 0, bits = 0;
@@ -1489,7 +1487,7 @@ string base64Decode(std::string_view s)
if (c == '=') break;
if (c == '\n') continue;
- char digit = decode[(unsigned char) c];
+ char digit = base64DecodeChars[(unsigned char) c];
if (digit == -1)
throw Error("invalid character in Base64 string: '%c'", c);