Skip to main content

sendmock_core/random_source/
seeded_random_source.rs

1use std::sync::atomic::{AtomicU64, Ordering};
2
3use super::RandomSource;
4
5/// The SplitMix64 increment; any odd constant works, this one spreads bits well.
6const GOLDEN_RATIO_INCREMENT: u64 = 0x9E37_79B9_7F4A_7C15;
7
8/// A repeatable sequence for tests: the same seed always gives the same numbers.
9#[derive(Debug)]
10pub struct SeededRandomSource {
11    state: AtomicU64,
12}
13
14impl SeededRandomSource {
15    pub fn new(seed: u64) -> Self {
16        Self {
17            state: AtomicU64::new(seed),
18        }
19    }
20}
21
22impl RandomSource for SeededRandomSource {
23    fn next_u64(&self) -> u64 {
24        let previous_state = self
25            .state
26            .fetch_add(GOLDEN_RATIO_INCREMENT, Ordering::Relaxed);
27        mix_bits(previous_state.wrapping_add(GOLDEN_RATIO_INCREMENT))
28    }
29}
30
31/// The SplitMix64 finaliser.
32fn mix_bits(state: u64) -> u64 {
33    let mut mixed = state;
34    mixed = (mixed ^ (mixed >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
35    mixed = (mixed ^ (mixed >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
36    mixed ^ (mixed >> 31)
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn the_same_seed_gives_the_same_sequence() {
45        let first_source = SeededRandomSource::new(42);
46        let second_source = SeededRandomSource::new(42);
47
48        let first_sequence: Vec<u64> = (0..4).map(|_| first_source.next_u64()).collect();
49        let second_sequence: Vec<u64> = (0..4).map(|_| second_source.next_u64()).collect();
50
51        assert_eq!(first_sequence, second_sequence);
52    }
53
54    #[test]
55    fn different_seeds_give_different_numbers() {
56        assert_ne!(
57            SeededRandomSource::new(1).next_u64(),
58            SeededRandomSource::new(2).next_u64()
59        );
60    }
61
62    #[test]
63    fn matches_the_published_splitmix64_sequence_for_seed_zero() {
64        let source = SeededRandomSource::new(0);
65
66        assert_eq!(source.next_u64(), 0xE220_A839_7B1D_CDAF);
67    }
68}