haar_lib/rand/
mod.rs

1//! 乱数
2use std::arch::asm;
3
4/// `u64`型の範囲で乱数を返す。
5#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
6pub fn rand() -> u64 {
7    let b = [0_u8; 8];
8
9    unsafe {
10        asm!(
11            "syscall",
12            in("rax") 0x13e,
13            in("rdi") b.as_ptr(),
14            in("rsi") b.len(),
15            in("rdx") 0,
16            out("rcx") _,
17            out("r11") _,
18            lateout("rax") _,
19            options(nostack),
20        );
21    }
22
23    u64::from_be_bytes(b)
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn test() {
32        let mut s: u64 = 0;
33
34        for _ in 0..1000000 {
35            let a = rand();
36            s = s.wrapping_add(a);
37        }
38
39        dbg!(s);
40    }
41}