Replace rejection sampling and remove use of rand() (#2180)
This commit is contained in:
parent
bf1fc03bff
commit
3fce70b535
|
@ -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;
|
||||||
|
|
Loading…
Reference in New Issue