uwuifier/
rng.rs

1// xorshift32
2// literally one of the simplest and fastest RNGs
3// augmented with a simple counter like "xorwow"
4
5pub struct XorShift32 {
6    state: u32,
7    counter: u32
8}
9
10impl XorShift32 {
11    #[inline(always)]
12    pub fn new(seed: &[u8; 4]) -> Self {
13        let mut state = 0u32;
14        state |= (seed[0] as u32) << 0;
15        state |= (seed[1] as u32) << 8;
16        state |= (seed[2] as u32) << 16;
17        state |= (seed[3] as u32) << 24;
18        XorShift32 { state: state | 1, counter: state }
19    }
20
21    #[inline(always)]
22    pub fn gen_u32(&mut self) -> u32 {
23        self.state ^= self.state << 13;
24        self.state ^= self.state >> 17;
25        self.state ^= self.state << 5;
26        self.counter = self.counter.wrapping_add(1234567891u32);
27        self.state.wrapping_add(self.counter)
28    }
29
30    #[inline(always)]
31    pub fn gen_bits(&mut self, bits: u32) -> u32 {
32        self.gen_u32() & ((1 << bits) - 1)
33    }
34
35    #[inline(always)]
36    pub fn gen_bool(&mut self) -> bool {
37        // kinda wasteful but ok
38        self.gen_bits(1) > 0
39    }
40}