nanorand/
tls.rs

1use crate::rand::{wyrand::WyRand, Rng, SeedableRng};
2use std::{cell::RefCell, rc::Rc};
3
4thread_local! {
5	static WYRAND: Rc<RefCell<WyRand>> = Rc::new(RefCell::new(WyRand::new()));
6}
7
8#[derive(Clone)]
9#[doc(hidden)]
10pub struct TlsWyRand(Rc<RefCell<WyRand>>);
11
12impl Rng<8> for TlsWyRand {
13	fn rand(&mut self) -> [u8; 8] {
14		self.0.borrow_mut().rand()
15	}
16}
17
18impl SeedableRng<8, 8> for TlsWyRand {
19	fn reseed(&mut self, seed: [u8; 8]) {
20		self.0.borrow_mut().reseed(seed);
21	}
22}
23
24/// Fetch a thread-local [`WyRand`]
25/// ```rust
26/// use nanorand::Rng;
27///
28/// let mut rng = nanorand::tls_rng();
29/// println!("Random number: {}", rng.generate::<u64>());
30/// ```
31/// This cannot be passed to another thread, as something like this will fail to compile:
32/// ```compile_fail
33/// use nanorand::Rng;
34///
35/// let mut rng = nanorand::tls_rng();
36/// std::thread::spawn(move || {
37///     println!("Random number: {}", rng.generate::<u64>());
38/// });
39/// ```
40pub fn tls_rng() -> TlsWyRand {
41	WYRAND.with(|tls| TlsWyRand(tls.clone()))
42}