-
Notifications
You must be signed in to change notification settings - Fork 82
/
EasyRandom.cc
75 lines (65 loc) · 1.93 KB
/
EasyRandom.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
copyright 2018 Paul Dreik
Distributed under GPL v 2.0 or later, at your option.
See LICENSE for further details.
*/
#include "config.h"
// std
#include <algorithm>
#include <array>
#include <random>
// project
#include "EasyRandom.hh"
class EasyRandom::GlobalRandom final
{
public:
char randomFileChar() { return getChar(m_dist(m_gen)); }
GlobalRandom()
{
// there are pitfalls of random device - may be nondeterministic. for that,
// one needs platform dependent initialization.
const std::size_t state_size_in_bytes =
std::mt19937::state_size * sizeof(std::mt19937::default_seed);
using array_element = std::random_device::result_type;
std::array<array_element, state_size_in_bytes / sizeof(array_element)> seed;
std::random_device rd;
std::generate_n(seed.data(), seed.size(), [&]() { return rd(); });
std::seed_seq seq(seed.cbegin(), seed.cend());
m_gen.seed(seq);
}
// this is expensive to copy, so disable that.
GlobalRandom(const GlobalRandom&) = delete;
private:
std::mt19937 m_gen{};
static const int nchars = 64;
static char getChar(int i)
{
const char acceptable_filename_chars[] = "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789"
"_-";
static_assert(nchars + 1 == sizeof(acceptable_filename_chars),
"mismatch in size");
return acceptable_filename_chars[i];
}
std::uniform_int_distribution<int> m_dist{ 0, nchars - 1 };
};
EasyRandom::GlobalRandom&
EasyRandom::getGlobalObject()
{
// thread safe (magic static)
static GlobalRandom global{};
return global;
}
EasyRandom::EasyRandom()
: m_rand(getGlobalObject())
{}
std::string
EasyRandom::makeRandomFileString(std::size_t N)
{
std::string ret(N, '\0');
for (auto& c : ret) {
c = m_rand.randomFileChar();
}
return ret;
}