-
Notifications
You must be signed in to change notification settings - Fork 0
/
RDRAND_seed.hpp
81 lines (66 loc) · 1.43 KB
/
RDRAND_seed.hpp
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
76
77
78
79
80
#include <cstdio>
#include <assert.h>
#include <immintrin.h>
#include <cpuid.h>
class RDRAND_seed
{
using rd64_type = long long unsigned int;
public:
RDRAND_seed()
{
// May not be the nicest way
assert(supports_rdrand());
// Check we don't just get a zero
rd64_type temp;
unsigned int temp32;
assert(_rdrand32_step(&temp32) != 0 and _rdrand64_step(&temp) != 0);
}
template <typename Iter>
void generate(Iter begin, Iter end)
{
for(; begin != end; ++begin)
*begin = get_rand32();
}
template <typename Iter>
void generate64(Iter begin, Iter end)
{
for(; begin != end; ++begin)
*begin = get_rand64();
}
uint32_t get_rand32()
{
return static_cast<uint32_t>(get_rdrand32());
}
uint64_t get_rand64()
{
return static_cast<uint64_t>(get_rdrand64());
}
uint32_t operator()()
{
return get_rand32();
}
private:
unsigned int get_rdrand32()
{
unsigned int rand;
_rdrand32_step(&rand);
return rand;
}
rd64_type get_rdrand64()
{
rd64_type rand;
_rdrand64_step(&rand);
return rand;
}
bool supports_rdrand()
{
// For comparison with bit 30 of the ECX register
const unsigned int flag_RDRAND = (1 << 30);
// Hold information from the registers
unsigned int eax, ebx, ecx, edx;
// Returns cpuid data for cpuid leaf 1
__get_cpuid(1, &eax, &ebx, &ecx, &edx);
// Bitwise AND what we get from the ecx register and the RDRAND flag
return ((ecx & flag_RDRAND) == flag_RDRAND);
}
};