oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! The operating system's random number generator.
//!
//! [`fill`] and [`fill_uninit`] write bytes from the system's
//! cryptographically secure generator: unpredictable, and suitable for keys.
//!
//! | System | Source |
//! |---|---|
//! | Linux | `getrandom` |
//! | macOS | `getentropy`, 256 bytes at a time |
//! | Windows | `ProcessPrng` (`bcryptprimitives.dll`) |
//! | WASI | `random_get` |
//!
//! Each call reaches the system: nothing is buffered in the process. A
//! program that wants many small random values should seed its own generator
//! from one call.

use core::mem::MaybeUninit;

use crate::Result;
use crate::sys;

/// Fills `buf` with random bytes.
///
/// The whole buffer is filled or an error is returned: where the system
/// hands out bytes in pieces, this function asks again for the rest. This is
/// one of the few places oscall loops, because a partly filled buffer is of
/// no use to anybody.
///
/// On Linux, early in the boot of a system that has not gathered entropy
/// yet, the call blocks until the generator is ready; a signal handler
/// running in the meantime makes it fail with
/// [`Interrupted`](crate::ErrorKind::Interrupted). Once the generator is
/// ready the call neither blocks nor is interrupted. Elsewhere it does not
/// fail.
///
/// Fails with [`Unsupported`](crate::ErrorKind::Unsupported) on WebAssembly
/// without WASI.
pub fn fill(buf: &mut [u8]) -> Result<()> {
    let len = buf.len();
    // SAFETY: initialised bytes are valid `MaybeUninit<u8>`s, and the
    // backends only ever write initialised bytes through the slice.
    let buf = unsafe { core::slice::from_raw_parts_mut(buf.as_mut_ptr().cast(), len) };
    sys::rand::fill(buf)
}

/// Fills `buf` with random bytes, and returns it as initialised.
///
/// This is [`fill`] for a buffer that has not been initialised: it saves
/// zeroing memory that is about to be overwritten.
pub fn fill_uninit(buf: &mut [MaybeUninit<u8>]) -> Result<&mut [u8]> {
    sys::rand::fill(buf)?;
    let len = buf.len();
    // SAFETY: the backend initialised every byte of `buf`.
    Ok(unsafe { core::slice::from_raw_parts_mut(buf.as_mut_ptr().cast(), len) })
}