use crate::error::Result;
use crate::fs::File;
use crate::io::Read;
use rusl::error::Errno;
use rusl::string::unix_str::UnixStr;
const DEV_RANDOM: &UnixStr = UnixStr::from_str_checked("/dev/random\0");
pub fn system_random(buf: &mut [u8]) -> Result<()> {
let mut file = File::open(DEV_RANDOM)?;
let mut offset = 0;
while offset < buf.len() {
match file.read(&mut buf[offset..]) {
Ok(read) => {
offset += read;
}
Err(e) => {
if e.matches_errno(Errno::EINTR) {
continue;
}
return Err(e);
}
}
}
Ok(())
}
pub struct Prng {
seed: u64,
}
impl Prng {
const MOD: u128 = 2u128.pow(48);
const A: u128 = 25_214_903_917;
const C: u128 = 11;
#[must_use]
#[expect(clippy::cast_sign_loss)]
pub fn new_time_seeded() -> Self {
let time = crate::time::MonotonicInstant::now();
let time_nanos_in_u64 = (time.0.seconds() as u64)
.overflowing_add(time.0.nanoseconds() as u64)
.0;
Prng {
seed: time_nanos_in_u64,
}
}
#[inline]
#[must_use]
pub fn new(seed: u64) -> Self {
Prng {
seed,
}
}
pub fn next_u64(&mut self) -> u64 {
self.seed = ((Self::A * u128::from(self.seed) + Self::C) % Self::MOD) as u64;
self.seed
}
}
impl Iterator for Prng {
type Item = u64;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
Some(self.next_u64())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gets_random() {
let mut buf = [0u8; 4096];
system_random(&mut buf).unwrap();
let mut count_zero = 0;
for i in buf {
if i == 0 {
count_zero += 1;
}
}
assert!(count_zero < 32, "After filling a buf with random bytes {count_zero} zeroes were found, should be around 16.");
}
#[test]
fn gets_pseudo_random() {
let mut count_zero = 0;
let prng = Prng::new(55);
for val in prng.take(4096) {
if val == 0 {
count_zero += val;
}
}
assert_eq!(0, count_zero);
}
#[test]
fn prng_seeded_not_same() {
let time_seeded1 = Prng::new_time_seeded();
let time_seeded2 = Prng::new_time_seeded();
assert_ne!(time_seeded1.seed, time_seeded2.seed);
}
}