Skip to main content

bb_runtime/framework/
rng.rs

1//! `RngU64Source` - pluggable u64 RNG used by the `RngU64`
2//! syscall op. Default impl wraps `getrandom`.
3
4/// Source of `u64` random values. Trait so tests can supply a
5/// deterministic counter via a different impl.
6pub trait RngU64Source: Send + Sync {
7    /// Pull the next `u64`.
8    fn next_u64(&mut self) -> u64;
9}
10
11/// Default `getrandom`-backed RNG.
12#[derive(Default)]
13pub struct GetrandomU64;
14
15impl GetrandomU64 {
16    /// Construct a fresh RNG.
17    pub fn new() -> Self {
18        Self
19    }
20}
21
22impl RngU64Source for GetrandomU64 {
23    fn next_u64(&mut self) -> u64 {
24        let mut buf = [0u8; 8];
25        // Panic on failure - entropy exhaustion is unrecoverable for
26        // the engine.
27        getrandom::getrandom(&mut buf).expect("getrandom");
28        u64::from_le_bytes(buf)
29    }
30}
31
32/// Deterministic counter RNG for tests.
33pub struct CounterRng(pub u64);
34
35impl RngU64Source for CounterRng {
36    fn next_u64(&mut self) -> u64 {
37        let v = self.0;
38        self.0 = self.0.wrapping_add(1);
39        v
40    }
41}
42