summaryrefslogtreecommitdiffstats
path: root/src/rand.rs
blob: 404e115bac2e1662bbef6bd361401a23b4ca7b1f (plain) (blame)
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
use std::fs::File;
use std::io::Read;
use std::sync::Mutex;
use std::time::SystemTime;

static STATE: Mutex<u64> = Mutex::new(0);

fn seed_urandom() -> Option<()> {
    let mut f = File::open("/dev/urandom").ok()?;
    let mut bytes = [0; 8];
    f.read_exact(&mut bytes).ok()?;

    *STATE.lock().unwrap() = u64::from_ne_bytes(bytes);
    return Some(());
}

fn seed_time() -> Option<()> {
    let n = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .ok()?;

    *STATE.lock().unwrap() = n.as_nanos() as u64;
    return Some(());
}

pub fn seed() -> Option<()> {
    match seed_urandom() {
        Some(()) => return Some(()),
        None => (),
    }
    match seed_time() {
        Some(()) => return Some(()),
        None => (),
    }
    return None;
}

fn mix(s: &mut u64) {
    // https://en.wikipedia.org/wiki/Linear_congruential_generator
    *s = s.wrapping_mul(6364136223846793005).wrapping_add(1);
}

pub fn random() -> f64 {
    let mut s = STATE.lock().unwrap();
    mix(&mut s);
    return (*s >> 32) as f64 / 4294967296.;
}