Skip to main content

byteflow/
entropy.rs

1//! OS CSPRNG bytes for [`crate::CapId`].
2//!
3//! [`getrandom::getrandom`] reads the platform generator (`ProcessPrng` on
4//! Windows, `getrandom` / `/dev/urandom` on Linux). A failed read is
5//! [`EntropyError`] and keeps the OS error. This module does not substitute
6//! a hash.
7
8use core::fmt;
9
10/// The operating system refused or failed the entropy read.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct EntropyError {
13    inner: getrandom::Error,
14}
15
16impl From<getrandom::Error> for EntropyError {
17    fn from(inner: getrandom::Error) -> Self {
18        Self { inner }
19    }
20}
21
22impl fmt::Display for EntropyError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        self.inner.fmt(f)
25    }
26}
27
28impl std::error::Error for EntropyError {
29    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
30        Some(&self.inner)
31    }
32}
33
34/// Fill `buf` with OS CSPRNG bytes. An empty buffer succeeds. Never panics.
35#[inline]
36pub fn fill_bytes(buf: &mut [u8]) -> Result<(), EntropyError> {
37    getrandom::getrandom(buf).map_err(EntropyError::from)
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    #[test]
45    fn empty_fill_succeeds() -> Result<(), EntropyError> {
46        let mut buf = [];
47        fill_bytes(&mut buf)
48    }
49
50    #[test]
51    fn fill_bytes_varies() -> Result<(), EntropyError> {
52        let mut a = [0u8; 16];
53        let mut b = [0u8; 16];
54        fill_bytes(&mut a)?;
55        fill_bytes(&mut b)?;
56        assert_ne!(a, b);
57        Ok(())
58    }
59}