use std::cell::RefCell;
use crate::wyrand::WyRand;
thread_local! {
static THREAD_RNG: RefCell<Option<WyRand>> = RefCell::new(None);
}
pub fn from_local() -> u64 {
THREAD_RNG.with_borrow_mut(|state| {
state.get_or_insert_with(|| WyRand::with_seed(from_system())).next()
})
}
#[cfg(not(target_arch = "wasm32"))]
pub fn from_system() -> u64 {
match getrandom::u64() {
Ok(v) => v,
Err(e) => {
eprintln!("(just-rng) getrandom entropy failed with err: '{e:?}'. Falling back to SystemTime");
use std::time::{SystemTime, UNIX_EPOCH};
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
((nanos >> 64) ^ nanos) as u64
}
}
}
#[cfg(target_arch = "wasm32")]
pub fn from_system() -> u64 {
use web_time::{SystemTime, UNIX_EPOCH};
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
((nanos >> 64) ^ nanos) as u64
}