Skip to main content

lib_jsl_random/
split_mix_64.rs

1//! SplitMix64, used to seed larger generators.
2//!
3//! See the book entry [Pseudo-random number generators](https://jwkunz.github.io/lib_jsl/book/random/generators.html#seeding-with-splitmix64).
4
5/// SplitMix64 — used only for seeding.
6/// Prevents zero seeds
7pub struct SplitMix64 {
8    state: u64,
9}
10
11impl SplitMix64 {
12    pub fn new(seed: u64) -> Self {
13        Self { state: seed }
14    }
15
16    // ANCHOR: splitmix
17    pub fn next_u64(&mut self) -> u64 {
18        let mut z = {
19            self.state = self.state.wrapping_add(0x9E3779B97F4A7C15);
20            self.state
21        };
22
23        z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
24        z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
25        let result = z ^ (z >> 31);
26        if result == 0{
27            self.next_u64()
28        }else{
29            result
30        }
31    }
32    // ANCHOR_END: splitmix
33}