summaryrefslogtreecommitdiffstats
path: root/src/rand.rs
blob: 03f6350b40bd74936c9bb3d5e1b43e15322664b4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
use std::sync::Mutex;
use std::time::SystemTime;

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

pub fn seed() {
    let n = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap();
    *STATE.lock().unwrap() = n.as_nanos() as u64;
}

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);
    (*s >> 32) as f64 / 4294967296.
}