Skip to main content

relibc/header/sys_random/
mod.rs

1//! `sys/random.h` implementation.
2//!
3//! Non-POSIX, see <https://www.man7.org/linux/man-pages/man2/getrandom.2.html>.
4
5use core::slice;
6
7use crate::{
8    error::ResultExt,
9    platform::{
10        Pal, Sys,
11        types::{c_uint, c_void, size_t, ssize_t},
12    },
13};
14
15/// See <https://www.man7.org/linux/man-pages/man2/getrandom.2.html>.
16///
17/// Do not block when requesting random bytes.
18/// Will set `errno` to `EAGAIN` if requested entropy is not available.
19pub const GRND_NONBLOCK: c_uint = 1;
20/// See <https://www.man7.org/linux/man-pages/man2/getrandom.2.html>.
21///
22/// If this bit is set, then random bytes are drawn from the `random` source
23/// instead of the `urandom` source.
24pub const GRND_RANDOM: c_uint = 2;
25
26/// See <https://www.man7.org/linux/man-pages/man2/getrandom.2.html>.
27///
28/// Fills the buffer pointed to by `buf` with up to `buflen` random bytes.
29#[unsafe(no_mangle)]
30pub unsafe extern "C" fn getrandom(buf: *mut c_void, buflen: size_t, flags: c_uint) -> ssize_t {
31    Sys::getrandom(
32        unsafe { slice::from_raw_parts_mut(buf.cast::<u8>(), buflen) },
33        flags,
34    )
35    .map(|read| read as ssize_t)
36    .or_minus_one_errno()
37}