Skip to main content

byteflow/
entropy.rs

1//! OS CSPRNG bytes for [`crate::CapId`].
2//!
3//! [`getrandom::fill`] 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 EntropyError {
17    fn new(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.
35pub fn fill_bytes(buf: &mut [u8]) -> Result<(), EntropyError> {
36    match getrandom::fill(buf) {
37        Ok(()) => Ok(()),
38        Err(inner) => Err(EntropyError::new(inner)),
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45
46    #[test]
47    fn empty_fill_succeeds() -> Result<(), EntropyError> {
48        let mut buf = [];
49        fill_bytes(&mut buf)
50    }
51
52    #[test]
53    fn fill_bytes_varies() -> Result<(), EntropyError> {
54        let mut a = [0u8; 16];
55        let mut b = [0u8; 16];
56        fill_bytes(&mut a)?;
57        fill_bytes(&mut b)?;
58        assert_ne!(a, b);
59        Ok(())
60    }
61}