x86_64/instructions/
random.rs1#[derive(Copy, Clone, Debug)]
4pub struct RdRand(());
6
7impl RdRand {
8 #[inline]
10 pub fn new() -> Option<Self> {
11 #[allow(unused_unsafe)]
14 let cpuid = unsafe { core::arch::x86_64::__cpuid(0x1) };
15 if cpuid.ecx & (1 << 30) != 0 {
16 Some(RdRand(()))
17 } else {
18 None
19 }
20 }
21
22 #[inline]
25 pub fn get_u64(self) -> Option<u64> {
26 let mut res: u64 = 0;
27 unsafe {
28 match core::arch::x86_64::_rdrand64_step(&mut res) {
29 1 => Some(res),
30 x => {
31 debug_assert_eq!(x, 0, "rdrand64 returned non-binary value");
32 None
33 }
34 }
35 }
36 }
37 #[inline]
40 pub fn get_u32(self) -> Option<u32> {
41 let mut res: u32 = 0;
42 unsafe {
43 match core::arch::x86_64::_rdrand32_step(&mut res) {
44 1 => Some(res),
45 x => {
46 debug_assert_eq!(x, 0, "rdrand32 returned non-binary value");
47 None
48 }
49 }
50 }
51 }
52 #[inline]
55 pub fn get_u16(self) -> Option<u16> {
56 let mut res: u16 = 0;
57 unsafe {
58 match core::arch::x86_64::_rdrand16_step(&mut res) {
59 1 => Some(res),
60 x => {
61 debug_assert_eq!(x, 0, "rdrand16 returned non-binary value");
62 None
63 }
64 }
65 }
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 #[test]
74 pub fn test_rdrand() {
75 let rand = RdRand::new();
76 if is_x86_feature_detected!("rdrand") {
77 let rand = rand.unwrap();
78 assert!(rand.get_u16().is_some());
79 assert!(rand.get_u32().is_some());
80 assert!(rand.get_u64().is_some());
81 } else {
82 assert!(rand.is_none());
83 }
84 }
85}