Skip to main content

byteflow/
entropy.rs

1//! OS entropy without external crates.
2//!
3//! Uses [`std::collections::hash_map::RandomState`], whose keys are drawn
4//! from the platform CSPRNG inside `std`. Adequate for [`crate::CapId`]
5//! uniqueness (collision retries remain in the caller).
6
7use core::fmt;
8use std::collections::hash_map::RandomState;
9use std::hash::{BuildHasher, Hasher};
10
11/// Entropy fill failed (should be unreachable with `std` RandomState).
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct EntropyError;
14
15impl fmt::Display for EntropyError {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        f.write_str("entropy fill failed")
18    }
19}
20
21impl std::error::Error for EntropyError {}
22
23/// Fill `buf` with entropy-derived bytes. Never panics.
24pub fn fill_bytes(buf: &mut [u8]) -> Result<(), EntropyError> {
25    let mut filled = 0;
26    while filled < buf.len() {
27        let mut hasher = RandomState::new().build_hasher();
28        hasher.write_usize(filled);
29        let word = hasher.finish().to_ne_bytes();
30        let take = (buf.len() - filled).min(word.len());
31        buf[filled..filled + take].copy_from_slice(&word[..take]);
32        filled += take;
33    }
34    Ok(())
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn fill_bytes_varies() {
43        let mut a = [0u8; 16];
44        let mut b = [0u8; 16];
45        let _ = fill_bytes(&mut a);
46        let _ = fill_bytes(&mut b);
47        // Astronomically unlikely to collide for two fresh RandomState draws.
48        assert_ne!(a, b);
49    }
50}