Initialize mt19937 statically in function

This reduces startup time
This commit is contained in:
topjohnwu 2021-11-16 03:20:07 -08:00
parent 4b5651bd6f
commit e1b63d7dec

View File

@ -33,21 +33,17 @@ int fork_no_orphan() {
return 0;
}
constexpr char ALPHANUM[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
static bool seeded = false;
static std::mt19937 gen;
static std::uniform_int_distribution<int> dist(0, sizeof(ALPHANUM) - 2);
int gen_rand_str(char *buf, int len, bool varlen) {
if (!seeded) {
constexpr char ALPHANUM[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
static std::mt19937 gen([]{
if (access("/dev/urandom", F_OK) != 0)
mknod("/dev/urandom", 0600 | S_IFCHR, makedev(1, 9));
int fd = xopen("/dev/urandom", O_RDONLY | O_CLOEXEC);
unsigned seed;
xxread(fd, &seed, sizeof(seed));
gen.seed(seed);
close(fd);
seeded = true;
}
return seed;
}());
std::uniform_int_distribution<int> dist(0, sizeof(ALPHANUM) - 2);
if (varlen) {
std::uniform_int_distribution<int> len_dist(len / 2, len);
len = len_dist(gen);