use crate::Error;
use core::{ffi::c_void, num::NonZeroU32, ptr};
const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 0x00000002;
extern "system" {
fn BCryptGenRandom(
hAlgorithm: *mut c_void,
pBuffer: *mut u8,
cbBuffer: u32,
dwFlags: u32,
) -> u32;
}
pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
for chunk in dest.chunks_mut(u32::max_value() as usize) {
let ret = unsafe {
BCryptGenRandom(
ptr::null_mut(),
chunk.as_mut_ptr(),
chunk.len() as u32,
BCRYPT_USE_SYSTEM_PREFERRED_RNG,
)
};
match ret >> 30 {
0b01 => {
info!("BCryptGenRandom: information code 0x{:08X}", ret);
}
0b10 => {
warn!("BCryptGenRandom: warning code 0x{:08X}", ret);
}
0b11 => {
error!("BCryptGenRandom: failed with 0x{:08X}", ret);
let code = ret ^ (1 << 31);
let code = unsafe { NonZeroU32::new_unchecked(code) };
return Err(Error::from(code));
}
_ => (),
}
}
Ok(())
}