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
48
use core::usize;

use rng_trait::Rng;


// https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
#[cfg(target_pointer_width = "32")]
pub const OFFSET: usize = 1013904223;
#[cfg(target_pointer_width = "32")]
pub const MULTIPLIER: usize = 1664525;

#[cfg(target_pointer_width = "64")]
pub const OFFSET: usize = 1442695040888963407;
#[cfg(target_pointer_width = "64")]
pub const MULTIPLIER: usize = 6364136223846793005;

pub const MAX: usize = usize::MAX as usize;


#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Prng {
    seed: usize,
}

impl Prng {
    #[inline(always)]
    pub fn new() -> Self {
        Prng {
            // get a value for initial seed
            seed: &false as *const _ as usize,
        }
    }
    #[inline(always)]
    pub fn seed(&self) -> usize { self.seed }
    #[inline(always)]
    pub fn set_seed(&mut self, seed: usize) {
        self.seed = seed;
    }
}

impl Rng for Prng {
    // http://indiegamr.com/generate-repeatable-random-numbers-in-js/
    #[inline]
    fn next(&mut self) -> usize {
        self.seed = ((MULTIPLIER.wrapping_mul(self.seed)).wrapping_add(OFFSET)) % MAX;
        self.seed
    }
}