data_faking/utils/
seeder.rs

1use rand::distributions::uniform::{SampleRange, SampleUniform};
2use rand::distributions::{DistIter, Distribution, Standard};
3use rand::{Rng, SeedableRng};
4use rand_pcg::Pcg64Mcg;
5use std::cell::RefCell;
6use std::sync::RwLock;
7use wasm_bindgen::prelude::*;
8
9thread_local! {
10  static RNG: RefCell<Pcg64Mcg> = RefCell::new(Pcg64Mcg::from_entropy());
11}
12
13lazy_static! {
14	static ref SEED: RwLock<Option<u64>> = RwLock::new(None);
15}
16
17#[wasm_bindgen]
18pub fn set_seed(i: u64) {
19	let mut guard = SEED.write().unwrap();
20	*guard = Some(i);
21	RNG.set(Pcg64Mcg::seed_from_u64(i));
22}
23
24#[wasm_bindgen]
25pub fn get_seed() -> Option<u64> {
26	let guard = SEED.read().unwrap();
27	return *guard;
28}
29
30pub fn gen_range<T, R>(range: R) -> T
31where
32	T: SampleUniform,
33	R: SampleRange<T>,
34{
35	RNG.with(|rng| rng.borrow_mut().gen_range(range))
36}
37
38pub fn gen<T>() -> T
39where
40	Standard: Distribution<T>,
41{
42	RNG.with(|rng| rng.borrow_mut().gen())
43}
44
45pub fn sample_iter<T, D>(distr: D) -> DistIter<D, Pcg64Mcg, T>
46where
47    D: Distribution<T>,
48    Pcg64Mcg: Sized
49{
50  RNG.with(|rng| rng.borrow_mut().clone().sample_iter(distr))
51}