rustls/
rand.rs

1//! The single place where we generate random material for our own use.
2
3use ring::rand::{SecureRandom, SystemRandom};
4
5/// Fill the whole slice with random material.
6pub(crate) fn fill_random(bytes: &mut [u8]) -> Result<(), GetRandomFailed> {
7    SystemRandom::new()
8        .fill(bytes)
9        .map_err(|_| GetRandomFailed)
10}
11
12/// Make a Vec<u8> of the given size
13/// containing random material.
14pub(crate) fn random_vec(len: usize) -> Result<Vec<u8>, GetRandomFailed> {
15    let mut v = vec![0; len];
16    fill_random(&mut v)?;
17    Ok(v)
18}
19
20/// Return a uniformly random u32.
21pub(crate) fn random_u32() -> Result<u32, GetRandomFailed> {
22    let mut buf = [0u8; 4];
23    fill_random(&mut buf)?;
24    Ok(u32::from_be_bytes(buf))
25}
26
27#[derive(Debug)]
28pub struct GetRandomFailed;