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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#![feature(target_feature, asm, platform_intrinsics)]
extern crate rand;
use rand::Rng;
use std::result::Result;
mod util;
extern "platform-intrinsic" {
fn x86_rdrand16_step() -> (u16, i32);
fn x86_rdrand32_step() -> (u32, i32);
fn x86_rdrand64_step() -> (u64, i32);
fn x86_rdseed16_step() -> (u16, i32);
fn x86_rdseed32_step() -> (u32, i32);
fn x86_rdseed64_step() -> (u64, i32);
}
macro_rules! loop_rand {
($f:ident) => {
loop {
unsafe {
let (val, succ) = ($f)();
if succ != 0 { return val; }
}
}
}
}
#[derive(Copy, Clone, Debug)]
pub enum Error {
UnsupportedProcessor
}
impl ::std::error::Error for Error {
fn description(&self) -> &str {
match self {
&Error::UnsupportedProcessor => "processor does not support the instruction",
}
}
}
impl ::std::fmt::Display for Error {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match self {
&Error::UnsupportedProcessor => write!(f, "processor does not support the instruction")
}
}
}
impl From<Error> for ::std::io::Error {
fn from(e: Error) -> ::std::io::Error {
::std::io::Error::new(::std::io::ErrorKind::Other, format!("{}", e))
}
}
#[derive(Clone, Copy)]
pub struct RdRand(());
impl RdRand {
pub fn new() -> Result<RdRand, Error> {
if util::has_rdrand() {
return Ok(RdRand(()));
} else {
return Err(Error::UnsupportedProcessor);
}
}
#[target_feature="+rdrnd"]
pub fn next_u16(&self) -> u16 {
loop_rand!(x86_rdrand16_step);
}
}
impl Rng for RdRand {
#[target_feature="+rdrnd"]
fn next_u32(&mut self) -> u32 {
loop_rand!(x86_rdrand32_step);
}
#[target_feature="+rdrnd"]
fn next_u64(&mut self) -> u64 {
loop_rand!(x86_rdrand64_step);
}
}
#[derive(Clone, Copy)]
pub struct RdSeed(());
impl RdSeed {
pub fn new() -> Result<RdSeed, Error> {
if util::has_rdseed() {
return Ok(RdSeed(()));
} else {
return Err(Error::UnsupportedProcessor);
}
}
#[target_feature="+rdseed"]
pub fn next_u16(&self) -> u16 {
loop_rand!(x86_rdseed16_step);
}
}
impl Rng for RdSeed {
#[target_feature="+rdseed"]
fn next_u32(&mut self) -> u32 {
loop_rand!(x86_rdseed32_step);
}
#[target_feature="+rdseed"]
fn next_u64(&mut self) -> u64 {
loop_rand!(x86_rdseed64_step);
}
}
#[test]
fn rdrand_works() {
let _ = RdRand::new().map(|mut r| {
r.next_u32();
r.next_u64();
});
}
#[test]
fn rdseed_works() {
let _ = RdSeed::new().map(|mut r| {
r.next_u32();
r.next_u64();
});
}