Skip to content

Commit 3fce70b

Browse files
authored
Replace rejection sampling and remove use of rand() (#2180)
1 parent bf1fc03 commit 3fce70b

File tree

1 file changed

+7
-18
lines changed

1 file changed

+7
-18
lines changed

lib/src/Utilities.cc

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
#include <sstream>
3434
#include <string>
3535
#include <mutex>
36+
#include <random>
3637
#include <algorithm>
3738
#include <array>
3839
#include <locale>
@@ -162,28 +163,16 @@ bool isBase64(std::string_view str)
162163

163164
std::string genRandomString(int length)
164165
{
165-
static const char char_space[] =
166+
static const std::string_view char_space =
166167
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
167-
static std::once_flag once;
168-
static const size_t len = strlen(char_space);
169-
static const int randMax = RAND_MAX - (RAND_MAX % len);
170-
std::call_once(once, []() {
171-
std::srand(static_cast<unsigned int>(time(nullptr)));
172-
});
173-
174-
int i;
168+
std::uniform_int_distribution<size_t> dist(0, char_space.size() - 1);
169+
thread_local std::mt19937 rng(std::random_device{}());
170+
175171
std::string str;
176172
str.resize(length);
177-
178-
for (i = 0; i < length; ++i)
173+
for (char &ch : str)
179174
{
180-
int x = std::rand();
181-
while (x >= randMax)
182-
{
183-
x = std::rand();
184-
}
185-
x = (x % len);
186-
str[i] = char_space[x];
175+
ch = char_space[dist(rng)];
187176
}
188177

189178
return str;

0 commit comments

Comments
 (0)