33 lines
865 B
Rust
33 lines
865 B
Rust
use core::cell::Cell;
|
|
|
|
/// A simple implementation of the XorShift64* pseudorandom number generator (PRNG).
|
|
/// Based on the algorithm described by George Marsaglia.
|
|
pub struct XorShift64Star {
|
|
state: Cell<u64>,
|
|
}
|
|
|
|
impl XorShift64Star {
|
|
/// Initializes the prng with a seed. Provided seed must be nonzero.
|
|
pub fn new(seed: u64) -> Self {
|
|
XorShift64Star {
|
|
state: Cell::new(seed),
|
|
}
|
|
}
|
|
|
|
/// Returns a pseudorandom number.
|
|
pub fn next(&self) -> u64 {
|
|
let mut x = self.state.get();
|
|
debug_assert_ne!(x, 0);
|
|
x ^= x >> 12;
|
|
x ^= x << 25;
|
|
x ^= x >> 27;
|
|
self.state.set(x);
|
|
x.wrapping_mul(0x2545_f491_4f6c_dd1d)
|
|
}
|
|
|
|
/// Return a pseudorandom number from `0..n`.
|
|
pub fn next_usize(&self, n: usize) -> usize {
|
|
(self.next() % n as u64) as usize
|
|
}
|
|
}
|