//! A seeded random — xorshift64*, which is enough for invented data and is //! the same on every machine. Implements the tools crate's `Random` so a //! handler's uuids come off the seed too. use crate::random::Random; use std::sync::Mutex; #[derive(Debug)] pub struct SeededRandom(Mutex); impl SeededRandom { pub fn new(seed: u64) -> SeededRandom { // A zero state never leaves zero; fold the seed with a constant. SeededRandom(Mutex::new(seed ^ 0x9E37_79B9_7F4A_7C15 | 1)) } pub fn next_u64(&self) -> u64 { let mut state = self.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let mut x = *state; x ^= x >> 12; x ^= x << 25; x ^= x >> 27; *state = x; x.wrapping_mul(0x2545_F491_4F6C_DD1D) } /// `0..n`. pub fn below(&self, n: usize) -> usize { if n == 0 { return 0; } (self.next_u64() % n as u64) as usize } /// `lo..=hi`. pub fn between(&self, lo: i64, hi: i64) -> i64 { if hi <= lo { return lo; } lo + (self.next_u64() % (hi - lo + 1) as u64) as i64 } pub fn chance(&self, per_cent: u64) -> bool { self.next_u64() % 100 < per_cent } pub fn pick<'a, T>(&self, items: &'a [T]) -> &'a T { &items[self.below(items.len())] } } impl Random for SeededRandom { fn fill(&self, bytes: &mut [u8]) { for chunk in bytes.chunks_mut(8) { let word = self.next_u64().to_le_bytes(); chunk.copy_from_slice(&word[..chunk.len()]); } } }