Skip to main content

x86_64/instructions/
random.rs

1//! Support for build-in RNGs
2
3#[derive(Copy, Clone, Debug)]
4/// Used to obtain random numbers using x86_64's RDRAND opcode
5pub struct RdRand(());
6
7impl RdRand {
8    /// Creates Some(RdRand) if RDRAND is supported, None otherwise
9    #[inline]
10    pub fn new() -> Option<Self> {
11        // RDRAND support indicated by CPUID page 01h, ecx bit 30
12        // https://en.wikipedia.org/wiki/RdRand#Overview
13        #[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    /// Uniformly sampled u64.
23    /// May fail in rare circumstances or heavy load.
24    #[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    /// Uniformly sampled u32.
38    /// May fail in rare circumstances or heavy load.
39    #[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    /// Uniformly sampled u16.
53    /// May fail in rare circumstances or heavy load.
54    #[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}