Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 3.5 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! A small seeded random number generator.
5//!
6//! Written here rather than taken from a crate so that a seed replays the same
7//! run on every platform and with any version of the dependencies.
8
9/// xoshiro256**, with its state expanded from the seed by SplitMix64.
10#[derive(Clone, Debug)]
11pub struct Rng {
12 state: [u64; 4],
13}
14
15impl Rng {
16 /// A generator whose whole output follows from `seed`.
17 pub fn new(seed: u64) -> Self {
18 let mut mix = seed;
19 let mut next = || {
20 mix = mix.wrapping_add(0x9e37_79b9_7f4a_7c15);
21 let mut z = mix;
22 z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
23 z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
24 z ^ (z >> 31)
25 };
26 Rng {
27 state: [next(), next(), next(), next()],
28 }
29 }
30
31 /// The next 64 random bits.
32 pub fn next_u64(&mut self) -> u64 {
33 let [s0, s1, s2, s3] = &mut self.state;
34 let result = s1.wrapping_mul(5).rotate_left(7).wrapping_mul(9);
35 let t = *s1 << 17;
36 *s2 ^= *s0;
37 *s3 ^= *s1;
38 *s1 ^= *s2;
39 *s0 ^= *s3;
40 *s2 ^= t;
41 *s3 = s3.rotate_left(45);
42 result
43 }
44
45 /// A number in `0..n`, without bias. `n` must not be 0.
46 pub fn below(&mut self, n: usize) -> usize {
47 assert!(n > 0, "below(0) has no answer");
48 let n = n as u64;
49 // Lemire's multiply-and-shift, rejecting the few values that would
50 // favour small results.
51 let threshold = n.wrapping_neg() % n;
52 loop {
53 let product = u128::from(self.next_u64()) * u128::from(n);
54 if (product as u64) >= threshold {
55 return (product >> 64) as usize;
56 }
57 }
58 }
59
60 /// A number in `low..high`, which must not be empty.
61 pub fn range(&mut self, low: usize, high: usize) -> usize {
62 low + self.below(high - low)
63 }
64
65 /// True with the given probability.
66 pub fn chance(&mut self, probability: f64) -> bool {
67 const SCALE: f64 = 1.0 / (1u64 << 53) as f64;
68 ((self.next_u64() >> 11) as f64) * SCALE < probability
69 }
70
71 /// One of `items`, which must not be empty.
72 pub fn pick<'a, T>(&mut self, items: &'a [T]) -> &'a T {
73 &items[self.below(items.len())]
74 }
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 #[test]
82 fn the_same_seed_gives_the_same_numbers() {
83 let mut a = Rng::new(7);
84 let mut b = Rng::new(7);
85 let mut c = Rng::new(8);
86 let first: Vec<u64> = (0..16).map(|_| a.next_u64()).collect();
87 let second: Vec<u64> = (0..16).map(|_| b.next_u64()).collect();
88 let other: Vec<u64> = (0..16).map(|_| c.next_u64()).collect();
89 assert_eq!(first, second);
90 assert_ne!(first, other);
91 }
92
93 #[test]
94 fn known_output() {
95 // Pinned so that a change to the generator, which would change every
96 // run, does not go unnoticed.
97 let mut rng = Rng::new(0);
98 assert_eq!(rng.next_u64(), 0x99ec_5f36_cb75_f2b4);
99 }
100
101 #[test]
102 fn ranges_stay_in_bounds_and_cover_them() {
103 let mut rng = Rng::new(1);
104 let mut seen = [0u32; 7];
105 for _ in 0..7000 {
106 seen[rng.below(7)] += 1;
107 let x = rng.range(3, 5);
108 assert!((3..5).contains(&x));
109 }
110 assert!(seen.iter().all(|count| *count > 800), "{seen:?}");
111 assert!(!rng.chance(0.0));
112 assert!(rng.chance(1.0));
113 assert_eq!(*rng.pick(&[42]), 42);
114 }
115}