tlspuffin/tls/rustls/
rand.rs

1use puffin::codec;
2/// The single place where we generate random material
3/// for our own use.  These functions never fail,
4/// they panic on error.
5use ring::rand::{SecureRandom, SystemRandom};
6
7/// Fill the whole slice with random material.
8pub fn fill_random(bytes: &mut [u8]) -> Result<(), GetRandomFailed> {
9    SystemRandom::new().fill(bytes).map_err(|_| GetRandomFailed)
10}
11
12/// Make a `Vec<u8>` of the given size
13/// containing random material.
14pub 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 fn random_u32() -> Result<u32, GetRandomFailed> {
22    let mut buf = [0u8; 4];
23    fill_random(&mut buf)?;
24    codec::decode_u32(&buf).ok_or(GetRandomFailed)
25}
26
27#[derive(Debug)]
28pub struct GetRandomFailed;