pub trait SearchRng {
fn below(&mut self, bound: u32) -> u32;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RngKind {
Legacy,
Xoshiro,
}
impl std::str::FromStr for RngKind {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"legacy" | "randu" => Ok(RngKind::Legacy),
"xoshiro" | "xoshiro256++" | "default" => Ok(RngKind::Xoshiro),
_ => Err(format!(
"unknown random number generator '{s}' (expected 'xoshiro' or 'legacy')"
)),
}
}
}
#[derive(Clone, Debug)]
pub struct Randu {
state: i64,
}
impl Randu {
pub fn new(seed: i64) -> Self {
Randu { state: seed }
}
}
impl SearchRng for Randu {
#[inline]
fn below(&mut self, bound: u32) -> u32 {
self.state = self.state.wrapping_mul(65539) & 0x7fff_ffff;
((self.state / 7) % i64::from(bound)) as u32
}
}
#[derive(Clone, Debug)]
pub struct Xoshiro {
s: [u64; 4],
}
#[inline]
fn splitmix64(state: &mut u64) -> u64 {
*state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = *state;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
impl Xoshiro {
pub fn new(seed: u64) -> Self {
let mut sm = seed;
Xoshiro {
s: [
splitmix64(&mut sm),
splitmix64(&mut sm),
splitmix64(&mut sm),
splitmix64(&mut sm),
],
}
}
pub fn for_stream(seed: u64, stream: u64) -> Self {
let mut sm = stream ^ 0x5851_f42d_4c95_7f2d;
Xoshiro::new(seed ^ splitmix64(&mut sm))
}
#[inline]
pub fn next_u64(&mut self) -> u64 {
let s = &mut self.s;
let result = s[0].wrapping_add(s[3]).rotate_left(23).wrapping_add(s[0]);
let t = s[1] << 17;
s[2] ^= s[0];
s[3] ^= s[1];
s[1] ^= s[2];
s[0] ^= s[3];
s[2] ^= t;
s[3] = s[3].rotate_left(45);
result
}
#[inline]
pub fn next_f64(&mut self) -> f64 {
(self.next_u64() >> 11) as f64 * (1.0 / (1u64 << 53) as f64)
}
}
impl SearchRng for Xoshiro {
#[inline]
fn below(&mut self, bound: u32) -> u32 {
let bound = u64::from(bound);
let mut m = (self.next_u64() >> 32) * bound;
let mut low = m & 0xffff_ffff;
if low < bound {
let threshold = (u32::MAX as u64 + 1 - bound) % bound;
while low < threshold {
m = (self.next_u64() >> 32) * bound;
low = m & 0xffff_ffff;
}
}
(m >> 32) as u32
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn randu_matches_the_c_macro() {
let mut r = Randu::new(1);
let mut state: i64 = 1;
for bound in [10u32, 7, 1000, 3, 65536, 2] {
state = (state * 65539) & 0x7fff_ffff;
assert_eq!(r.below(bound) as i64, (state / 7) % bound as i64);
}
let mut zero = Randu::new(0);
assert!((0..10).all(|_| zero.below(5) == 0));
}
#[test]
fn xoshiro_below_is_in_range_and_roughly_uniform() {
let mut r = Xoshiro::new(42);
let mut counts = [0usize; 6];
for _ in 0..60_000 {
counts[r.below(6) as usize] += 1;
}
assert!(
counts.iter().all(|&c| (9_000..11_000).contains(&c)),
"{counts:?}"
);
assert_ne!(
Xoshiro::for_stream(1, 0).next_u64(),
Xoshiro::for_stream(1, 1).next_u64()
);
}
}