/rust/registry/src/index.crates.io-1949cf8c6b5b557f/rustls-0.23.35/src/rand.rs
Line | Count | Source |
1 | | //! The single place where we generate random material for our own use. |
2 | | |
3 | | use alloc::vec; |
4 | | use alloc::vec::Vec; |
5 | | |
6 | | use crate::crypto::SecureRandom; |
7 | | |
8 | | /// Make a [`Vec<u8>`] of the given size containing random material. |
9 | 0 | pub(crate) fn random_vec( |
10 | 0 | secure_random: &dyn SecureRandom, |
11 | 0 | len: usize, |
12 | 0 | ) -> Result<Vec<u8>, GetRandomFailed> { |
13 | 0 | let mut v = vec![0; len]; |
14 | 0 | secure_random.fill(&mut v)?; |
15 | 0 | Ok(v) |
16 | 0 | } |
17 | | |
18 | | /// Return a uniformly random [`u32`]. |
19 | 0 | pub(crate) fn random_u32(secure_random: &dyn SecureRandom) -> Result<u32, GetRandomFailed> { |
20 | 0 | let mut buf = [0u8; 4]; |
21 | 0 | secure_random.fill(&mut buf)?; |
22 | 0 | Ok(u32::from_be_bytes(buf)) |
23 | 0 | } |
24 | | |
25 | | /// Return a uniformly random [`u16`]. |
26 | 0 | pub(crate) fn random_u16(secure_random: &dyn SecureRandom) -> Result<u16, GetRandomFailed> { |
27 | 0 | let mut buf = [0u8; 2]; |
28 | 0 | secure_random.fill(&mut buf)?; |
29 | 0 | Ok(u16::from_be_bytes(buf)) |
30 | 0 | } |
31 | | |
32 | | /// Random material generation failed. |
33 | | #[derive(Debug)] |
34 | | pub struct GetRandomFailed; |