Skip to main content

logicaffeine_system/
random.rs

1//! Random Number Generation
2//!
3//! Provides random number generation using thread-local RNG with
4//! cryptographically secure seeding from system entropy.
5//!
6//! # Thread Safety
7//!
8//! Uses thread-local RNG via `rand::thread_rng()`. Each thread gets its
9//! own independent RNG instance, so this is safe to call from any thread
10//! without synchronization.
11//!
12//! # Platform Support
13//!
14//! - **Native**: Uses system entropy for seeding (getrandom)
15//! - **WASM**: Not available (module not compiled for wasm32)
16//!
17//! # Example
18//!
19//! ```
20//! use logicaffeine_system::random;
21//!
22//! let dice_roll = random::randomInt(1, 6);
23//! assert!((1..=6).contains(&dice_roll));
24//!
25//! let probability = random::randomFloat();
26//! assert!((0.0..1.0).contains(&probability));
27//! ```
28
29use rand::Rng;
30
31/// Generates a random integer in an inclusive range.
32///
33/// # Arguments
34///
35/// * `min` - Minimum value (inclusive)
36/// * `max` - Maximum value (inclusive)
37///
38/// # Returns
39///
40/// A random integer in the range `[min, max]`.
41///
42/// # Panics
43///
44/// Panics if `min > max`.
45///
46/// # Example
47///
48/// ```
49/// use logicaffeine_system::random;
50///
51/// let dice = random::randomInt(1, 6); // 1, 2, 3, 4, 5, or 6
52/// assert!((1..=6).contains(&dice));
53/// ```
54#[allow(non_snake_case)]
55pub fn randomInt(min: i64, max: i64) -> i64 {
56    if let Some(sealed) = crate::testworld::intercept_random_int(min, max) {
57        return sealed;
58    }
59    let mut rng = rand::thread_rng();
60    rng.gen_range(min..=max)
61}
62
63/// Generates a random floating-point number.
64///
65/// # Returns
66///
67/// A random float in the range `[0.0, 1.0)` (includes 0.0, excludes 1.0).
68///
69/// # Example
70///
71/// ```
72/// use logicaffeine_system::random;
73///
74/// let chance = random::randomFloat();
75/// assert!((0.0..1.0).contains(&chance));
76/// ```
77#[allow(non_snake_case)]
78pub fn randomFloat() -> f64 {
79    if let Some(sealed) = crate::testworld::intercept_random_float() {
80        return sealed;
81    }
82    let mut rng = rand::thread_rng();
83    rng.gen()
84}
85
86/// Fill `buf` from the operating system's entropy: what a nonce or a key is drawn from. A sealed test
87/// world never decides it, since a nonce a test world fixed would repeat across seals.
88pub fn fill_from_entropy(buf: &mut [u8]) -> Result<(), String> {
89    getrandom::getrandom(buf).map_err(|e| format!("the system gave no entropy: {e}"))
90}