oscall 0.0.2

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! The system random number generator.

use std::mem::MaybeUninit;

use oscall::rand;

/// The lengths around the limits of the systems' calls: `getentropy` and an
/// uninterruptible `getrandom` stop at 256 bytes.
const LENGTHS: [usize; 8] = [0, 1, 2, 255, 256, 257, 4097, 65536];

/// Whether `bytes` could plausibly be random: for 32 bytes and more, all
/// zeros, or any single repeated value, has a probability below 2^-248.
fn looks_random(bytes: &[u8]) -> bool {
    bytes.len() < 32 || bytes.iter().any(|&b| b != bytes[0])
}

#[test]
fn fill() {
    for len in LENGTHS {
        // A canary after the buffer: exactly `len` bytes are written.
        let mut buf = vec![0u8; len + 8];
        rand::fill(&mut buf[..len]).unwrap();
        assert!(looks_random(&buf[..len]), "length {len}");
        assert_eq!(buf[len..], [0; 8], "length {len}");

        // The end of the buffer is filled too, not only its first chunk:
        // 16 zero bytes there have a probability of 2^-128.
        if len >= 32 {
            assert!(buf[len - 16..len].iter().any(|&b| b != 0), "length {len}");
        }

        let mut other = vec![0u8; len];
        rand::fill(&mut other).unwrap();
        if len >= 32 {
            assert_ne!(buf[..len], other[..], "length {len}");
        }
    }
}

#[test]
fn fill_uninit() {
    for len in LENGTHS {
        let mut buf = vec![MaybeUninit::<u8>::uninit(); len];
        let ptr = buf.as_ptr().cast::<u8>();
        let bytes = rand::fill_uninit(&mut buf).unwrap();
        // The same memory, whole.
        assert_eq!(bytes.as_ptr(), ptr);
        assert_eq!(bytes.len(), len);
        assert!(looks_random(bytes), "length {len}");
        if len >= 32 {
            assert!(bytes[len - 16..].iter().any(|&b| b != 0), "length {len}");
        }
    }
}

#[test]
fn bytes_are_uniform() {
    // Every byte value turns up in 64 KiB: a value is absent with
    // probability 256 * (255/256)^65536, about 10^-109. And every position
    // of the chunks gets set bits and clear bits.
    let mut buf = vec![0u8; 65536];
    rand::fill(&mut buf).unwrap();
    let mut seen = [false; 256];
    for &b in &buf {
        seen[b as usize] = true;
    }
    assert!(seen.iter().all(|&s| s));

    let ones: u64 = buf.iter().map(|b| u64::from(b.count_ones())).sum();
    // 524288 bits, each set with probability 1/2: within 1% of half is
    // more than seven standard deviations (362 bits each).
    let half = 65536 * 4;
    assert!(ones.abs_diff(half) < half / 100, "{ones} bits set");
}

#[test]
fn concurrent() {
    if cfg!(target_os = "wasi") {
        return; // no threads
    }
    let threads: Vec<_> = (0..4)
        .map(|_| {
            std::thread::spawn(|| {
                let mut buf = [0u8; 64];
                rand::fill(&mut buf).unwrap();
                buf
            })
        })
        .collect();
    let mut outputs: Vec<_> = threads.into_iter().map(|t| t.join().unwrap()).collect();
    outputs.sort();
    outputs.dedup();
    assert_eq!(outputs.len(), 4);
}