Replace rejection sampling and remove use of rand() (#2180)

This commit is contained in:
Martin Chang 2024-10-10 13:45:46 +08:00 committed by GitHub
parent bf1fc03bff
commit 3fce70b535
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 6 additions and 17 deletions

View File

@ -33,6 +33,7 @@
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <mutex> #include <mutex>
#include <random>
#include <algorithm> #include <algorithm>
#include <array> #include <array>
#include <locale> #include <locale>
@ -162,28 +163,16 @@ bool isBase64(std::string_view str)
std::string genRandomString(int length) std::string genRandomString(int length)
{ {
static const char char_space[] = static const std::string_view char_space =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static std::once_flag once; std::uniform_int_distribution<size_t> dist(0, char_space.size() - 1);
static const size_t len = strlen(char_space); thread_local std::mt19937 rng(std::random_device{}());
static const int randMax = RAND_MAX - (RAND_MAX % len);
std::call_once(once, []() {
std::srand(static_cast<unsigned int>(time(nullptr)));
});
int i;
std::string str; std::string str;
str.resize(length); str.resize(length);
for (char &ch : str)
for (i = 0; i < length; ++i)
{ {
int x = std::rand(); ch = char_space[dist(rng)];
while (x >= randMax)
{
x = std::rand();
}
x = (x % len);
str[i] = char_space[x];
} }
return str; return str;