| 1 | //! Fast pseudo-random numbers whose sequence differs across concurrently running processes. |
| 2 | //! |
| 3 | //! These numbers are *not* cryptographically secure. Unlike the global generators of the |
| 4 | //! [`fastrand`] crate, whose per-thread seed is derived only from values that can coincide between |
| 5 | //! separate processes (such as small thread IDs), the generator here is seeded from a high-entropy |
| 6 | //! source so that concurrent processes don't easily share a sequence. |
| 7 | //! |
| 8 | //! This matters wherever a collision causes a real problem, such as the jitter used for retry |
| 9 | //! backoff (to avoid a [thundering herd](https://en.wikipedia.org/wiki/Thundering_herd_problem)) or |
| 10 | //! the temporary file names used while probing filesystem capabilities. |
| 11 | |
| 12 | use std::{cell::Cell, ops::RangeBounds}; |
| 13 | |
| 14 | thread_local! { |
| 15 | static RNG: Cell<fastrand::Rng> = Cell::new(new_rng()); |
| 16 | } |
| 17 | |
| 18 | /// Return an unsigned number in the given `range`, drawn from a per-thread generator that is seeded to differ |
| 19 | /// across concurrently running processes. |
| 20 | pub fn usize(range: impl RangeBounds<usize>) -> usize { |
| 21 | RNG.with(|cell| { |
| 22 | let mut rng = cell.replace(fastrand::Rng::with_seed(0)); |
| 23 | let n = rng.usize(range); |
| 24 | cell.set(rng); |
| 25 | n |
| 26 | }) |
| 27 | } |
| 28 | |
| 29 | #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] |
| 30 | fn new_rng() -> fastrand::Rng { |
| 31 | fastrand::Rng::with_seed(seed()) |
| 32 | } |
| 33 | |
| 34 | /// `wasm32-unknown-unknown` has no OS entropy source and traps at runtime on APIs like |
| 35 | /// `std::process::id()` and `Instant::now()`; it also runs a single process, so the cross-process |
| 36 | /// concern doesn't apply. Use a fixed seed there. |
| 37 | #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] |
| 38 | fn new_rng() -> fastrand::Rng { |
| 39 | fastrand::Rng::with_seed(0x9e37_79b9_7f4a_7c15) |
| 40 | } |
| 41 | |
| 42 | /// Seed a generator from a high-entropy OS source, so that generators in separate processes don't |
| 43 | /// share a sequence. |
| 44 | #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] |
| 45 | fn seed() -> u64 { |
| 46 | getrandom::u64().unwrap_or_else(|_| fallback_seed()) |
| 47 | } |
| 48 | |
| 49 | /// A best-effort seed used only when the OS entropy source is unavailable. `std::process::id()` is |
| 50 | /// the reliable differentiator across concurrent processes. |
| 51 | #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] |
| 52 | fn fallback_seed() -> u64 { |
| 53 | use std::hash::{BuildHasher, Hash, Hasher}; |
| 54 | |
| 55 | let mut hasher = std::collections::hash_map::RandomState::new().build_hasher(); |
| 56 | std::process::id().hash(&mut hasher); |
| 57 | std::thread::current().id().hash(&mut hasher); |
| 58 | hasher.finish() |
| 59 | } |
| 60 | |
| 61 | #[cfg(test)] |
| 62 | mod tests { |
| 63 | #[test] |
| 64 | fn values_are_in_range_and_not_constant() { |
| 65 | let mut seen = std::collections::HashSet::new(); |
| 66 | for _ in 0..256 { |
| 67 | let n = super::usize(0..1_000); |
| 68 | assert!(n < 1_000, "value {n} must be within the requested range"); |
| 69 | seen.insert(n); |
| 70 | } |
| 71 | assert!( |
| 72 | seen.len() > 1, |
| 73 | "the generator wasn't made for the Playstation 3 (imprecise, but still funny?)" |
| 74 | ); |
| 75 | } |
| 76 | } |