xorshift64star

This commit is contained in:
Janis 2025-07-02 18:46:02 +02:00
parent 119b49e20d
commit 56faa52d0d
2 changed files with 33 additions and 0 deletions

View file

@ -9,6 +9,7 @@ extern crate std;
pub mod cachepadded;
pub mod drop_guard;
pub mod ptr;
pub mod rand;
#[cfg(feature = "alloc")]
pub mod smallbox;
pub mod util;

32
src/rand.rs Normal file
View file

@ -0,0 +1,32 @@
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
}
}