fstd/
rand.rs

1//! Utilities for random number generation.
2//!
3//! The implementation uses [`wyrand`] for now. It's **NOT** cryptographically secure.
4//!
5//! # Examples
6//!
7//! The public functions in [`rand`] is **NOT** reproducible due to possible replacement in future library versions.
8//!
9//! For a reproducible generator, use a named PRNG struct, e.g. [`WyRng`].
10//!
11//!
12//! Generate a random `u64`:
13//!
14//! ```
15//! let r = fstd::rand::u64(..);
16//! ```
17//! Generate a random `u64` in the `[0,100)`:
18//!
19//! ```
20//! let r = fstd::rand::u64(0..100);
21//! ```
22//!
23//! Create a local PRNG with a random seed and generate a random `u64`:
24//!
25//! ```
26//! use fstd::rand::WyRng;
27//! let rng = WyRng::new();
28//! let r = rng.u64(..);
29//! ```
30//!
31//! Create a local PRNG with specific seed and generate a random `u64`,
32//! it is a reproducible generator.
33//!
34//! ```
35//! use fstd::rand::WyRng;
36//! let rng = WyRng::from_seed_u64(123);
37//! let r = rng.u64(..);
38//! ```
39
40//! [`rand`]: crate::rand
41//! [`wyrand`]: https://github.com/wangyi-fudan/wyhash
42
43pub(crate) mod wyrand;
44
45use self::wyrand::THREAD_WYRAND as THREAD_RNG;
46use std::ops::RangeBounds;
47use std::stringify;
48pub use wyrand::WyRng;
49
50macro_rules! api_impl {
51    // Raw API.
52    ($t:tt,$doc:tt) => {
53        #[doc = $doc]
54        #[inline(always)]
55        pub fn $t() -> $t {
56            THREAD_RNG.try_with(|rng| rng.$t()).unwrap()
57        }
58    };
59    // API with specific range.
60    ($t:tt) => {
61        #[doc = "Returns a random `"]
62        #[doc = stringify!($t)]
63        #[doc = "` in the given range(thread-safe, but not cryptographically secure)."]
64        #[doc = "Panics if the range is invalid."]
65        #[inline(always)]
66        pub fn $t(range: impl RangeBounds<$t>) -> $t {
67            THREAD_RNG.try_with(|rng| rng.$t(range)).unwrap()
68        }
69    };
70}
71
72api_impl!(
73    f64,
74    "Returns a random `f64` in the `[0.0,1.0)`. (thread-safe, but not cryptographically secure)"
75);
76api_impl!(
77    f32,
78    "Returns a random `f32` in the `[0.0,1.0)`. (thread-safe, but not cryptographically secure)"
79);
80
81api_impl!(u32);
82api_impl!(i32);
83api_impl!(u64);
84api_impl!(i64);
85api_impl!(usize);
86api_impl!(isize);