Skip to main content

hotl_platform/entropy/
unix.rs

1//! `getrandom`, which is `getrandom(2)` where the kernel has it and `/dev/urandom` otherwise.
2
3use super::Entropy;
4use std::io;
5
6#[derive(Debug, Clone, Copy, Default)]
7pub struct UnixEntropy;
8
9impl UnixEntropy {
10    pub const fn new() -> Self {
11        Self
12    }
13}
14
15impl crate::sealed::Sealed for UnixEntropy {}
16
17impl Entropy for UnixEntropy {
18    fn fill(&self, buf: &mut [u8]) -> io::Result<()> {
19        // The error is propagated rather than absorbed: the contract forbids a
20        // fallback, and a caller that cannot get entropy must fail loudly.
21        getrandom::fill(buf).map_err(|e| match e.raw_os_error() {
22            Some(code) => io::Error::from_raw_os_error(code),
23            None => io::Error::other(format!("the OS CSPRNG refused: {e}")),
24        })
25    }
26}