Skip to main content

security/
random_bytes.rs

1use crate::bridge;
2use crate::error::Result;
3
4/// Wraps `SecRandomCopyBytes`.
5pub struct SecureRandom;
6
7impl SecureRandom {
8    /// Wraps the corresponding `SecRandomCopyBytes` operation.
9    pub fn fill(buffer: &mut [u8]) -> Result<()> {
10        if buffer.is_empty() {
11            return Ok(());
12        }
13        let mut error = std::ptr::null_mut();
14        let status = unsafe {
15            bridge::security_random_fill(
16                buffer.as_mut_ptr().cast(),
17                bridge::len_to_isize(buffer.len())?,
18                &mut error,
19            )
20        };
21        bridge::status_result("security_random_fill", status, error)
22    }
23
24    /// Wraps the corresponding `SecRandomCopyBytes` operation.
25    pub fn bytes(length: usize) -> Result<Vec<u8>> {
26        let mut bytes = vec![0_u8; length];
27        Self::fill(&mut bytes)?;
28        Ok(bytes)
29    }
30}