-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibmtrandom.cpp
More file actions
65 lines (49 loc) · 1.33 KB
/
libmtrandom.cpp
File metadata and controls
65 lines (49 loc) · 1.33 KB
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
#include <cstring>
#include <fcntl.h>
#include <random>
#include <unistd.h>
#include <cstdio>
#define likely(x) (!__builtin_expect(!(x), 0))
#define unlikely(x) __builtin_expect((x), 0)
#define unused(x) (!(x))
static bool initialized = false;
static std::mt19937 *generator = nullptr;
__attribute__((destructor))
static void destroy_generator() {
if(generator != nullptr) {
free(generator);
generator = nullptr;
}
}
static std::mt19937 &get_generator() {
if(unlikely(generator == nullptr)) {
std::mt19937 proto;
generator = (std::mt19937 *)(malloc(sizeof(std::mt19937)));
memcpy(generator, &proto, sizeof(std::mt19937));
*generator = std::mt19937();
}
return *generator;
}
static void init() {
if(likely(initialized)) {
return;
}
unsigned char *sys_seed = new unsigned char[4096];
char const path[] = "/dev/urandom";
int fd = open(path, O_RDONLY | O_NONBLOCK);
unused(read(fd, sys_seed, 4096));
close(fd);
std::seed_seq seq;
seq.generate(sys_seed, sys_seed + 4096);
get_generator().seed(seq);
delete[] sys_seed;
initialized = true;
}
extern "C" void srand(unsigned int seed) {
get_generator().seed(seed);
initialized = true;
}
extern "C" int rand(void) {
init();
return get_generator()() & 0x7FFFFFFF;
}