rustls/
rand.rs

1//! The single place where we generate random material for our own use.
2
3use crate::crypto::SecureRandom;
4
5/// Make an array of size `N` containing random material.
6pub(crate) fn random_array<const N: usize>(
7    secure_random: &dyn SecureRandom,
8) -> Result<[u8; N], GetRandomFailed> {
9    let mut v = [0; N];
10    secure_random.fill(&mut v)?;
11    Ok(v)
12}
13
14/// Return a uniformly random [`u32`].
15pub(crate) fn random_u32(secure_random: &dyn SecureRandom) -> Result<u32, GetRandomFailed> {
16    Ok(u32::from_be_bytes(random_array(secure_random)?))
17}
18
19/// Return a uniformly random [`u16`].
20pub(crate) fn random_u16(secure_random: &dyn SecureRandom) -> Result<u16, GetRandomFailed> {
21    Ok(u16::from_be_bytes(random_array(secure_random)?))
22}
23
24/// Random material generation failed.
25#[allow(clippy::exhaustive_structs)]
26#[derive(Debug)]
27pub struct GetRandomFailed;