1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//! Tiny wrapper to make [ring::rand::SystemRandom] slightly more ergonomic to
//! use.

use once_cell::sync::Lazy;
use ring::rand::{self, SecureRandom};

/// The lazily initialized [SecureRandom] object. Only lazy in name: the
/// initialization is forced right near the start of this program's `main`,
/// before any other calls to this module.
static RAND: Lazy<rand::SystemRandom> = Lazy::new(rand::SystemRandom::new);

/// See [SecureRandom::fill].
pub fn gen_bytes(bytes: &mut [u8]) {
    RAND.fill(bytes).unwrap();
}

/// Uses [SecureRandom::fill] to generate eight [u8]s, and then the [u64] from
/// those.
pub fn gen_u64() -> u64 {
    let mut bytes = [0u8; 8];
    RAND.fill(&mut bytes).unwrap();
    u64::from_be_bytes(bytes)
}