use std::cell::Cell;
cfg_rt! {
use std::sync::Mutex;
#[derive(Debug)]
pub(crate) struct RngSeedGenerator {
state: Mutex<FastRand>,
}
impl RngSeedGenerator {
pub(crate) fn new(seed: RngSeed) -> Self {
Self {
state: Mutex::new(FastRand::new(seed)),
}
}
pub(crate) fn next_seed(&self) -> RngSeed {
let rng = self
.state
.lock()
.expect("RNG seed generator is internally corrupt");
let s = rng.fastrand();
let r = rng.fastrand();
RngSeed::from_pair(s, r)
}
pub(crate) fn next_generator(&self) -> Self {
RngSeedGenerator::new(self.next_seed())
}
}
}
#[allow(unreachable_pub)]
#[derive(Clone, Debug)]
pub struct RngSeed {
s: u32,
r: u32,
}
impl RngSeed {
pub(crate) fn new() -> Self {
Self::from_u64(crate::loom::rand::seed())
}
cfg_unstable! {
#[cfg(feature = "rt")]
pub fn from_bytes(bytes: &[u8]) -> Self {
use std::{collections::hash_map::DefaultHasher, hash::Hasher};
let mut hasher = DefaultHasher::default();
hasher.write(bytes);
Self::from_u64(hasher.finish())
}
}
fn from_u64(seed: u64) -> Self {
let one = (seed >> 32) as u32;
let mut two = seed as u32;
if two == 0 {
two = 1;
}
Self::from_pair(one, two)
}
fn from_pair(s: u32, r: u32) -> Self {
Self { s, r }
}
}
#[derive(Debug)]
pub(crate) struct FastRand {
one: Cell<u32>,
two: Cell<u32>,
}
impl FastRand {
pub(crate) fn new(seed: RngSeed) -> FastRand {
FastRand {
one: Cell::new(seed.s),
two: Cell::new(seed.r),
}
}
#[cfg(feature = "rt")]
pub(crate) fn replace_seed(&self, seed: RngSeed) -> RngSeed {
let old_seed = RngSeed::from_pair(self.one.get(), self.two.get());
self.one.replace(seed.s);
self.two.replace(seed.r);
old_seed
}
#[cfg(any(feature = "macros", feature = "rt-multi-thread"))]
pub(crate) fn fastrand_n(&self, n: u32) -> u32 {
let mul = (self.fastrand() as u64).wrapping_mul(n as u64);
(mul >> 32) as u32
}
fn fastrand(&self) -> u32 {
let mut s1 = self.one.get();
let s0 = self.two.get();
s1 ^= s1 << 17;
s1 = s1 ^ s0 ^ s1 >> 7 ^ s0 >> 16;
self.one.set(s0);
self.two.set(s1);
s0.wrapping_add(s1)
}
}