#[derive(Debug, Clone)]
pub(super) struct Random {
state: u64,
}
impl Random {
pub(super) fn new(seed: u64) -> Self {
Self { state: seed }
}
pub(super) fn next_u64(&mut self) -> u64 {
self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
pub(super) fn below(&mut self, bound: usize) -> usize {
debug_assert!(bound > 0, "an empty range has no index");
let bound = u64::try_from(bound).expect("usize fits in u64");
let wide = u128::from(self.next_u64()) * u128::from(bound);
usize::try_from(wide >> 64).expect("below the bound")
}
pub(super) fn unit(&mut self) -> f64 {
#[expect(
clippy::cast_precision_loss,
reason = "53 random bits fit an f64 mantissa exactly"
)]
let mantissa = (self.next_u64() >> 11) as f64;
mantissa / 9_007_199_254_740_992.0
}
pub(super) fn weighted(&mut self, weights: &[f64]) -> Option<usize> {
let total: f64 = weights.iter().sum();
if total <= 0.0 {
return None;
}
let mut target = self.unit() * total;
for (index, &weight) in weights.iter().enumerate() {
if target < weight {
return Some(index);
}
target -= weight;
}
weights.iter().rposition(|&weight| weight > 0.0)
}
pub(super) fn shuffle<T>(&mut self, items: &mut [T]) {
for last in (1..items.len()).rev() {
items.swap(last, self.below(last + 1));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_deterministic_and_in_range() {
let (mut a, mut b) = (Random::new(7), Random::new(7));
for bound in 1..100 {
let index = a.below(bound);
assert_eq!(index, b.below(bound));
assert!(index < bound);
}
}
#[test]
fn weighted_skips_zero_weights() {
let mut random = Random::new(1);
for _ in 0..100 {
assert_eq!(random.weighted(&[0.0, 2.0, 0.0]), Some(1));
}
assert_eq!(random.weighted(&[0.0, 0.0]), None);
}
}