use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EntropyError {
inner: getrandom::Error,
}
impl From<getrandom::Error> for EntropyError {
fn from(inner: getrandom::Error) -> Self {
Self { inner }
}
}
impl fmt::Display for EntropyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}
impl std::error::Error for EntropyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.inner)
}
}
#[inline]
pub fn fill_bytes(buf: &mut [u8]) -> Result<(), EntropyError> {
getrandom::getrandom(buf).map_err(EntropyError::from)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_fill_succeeds() -> Result<(), EntropyError> {
let mut buf = [];
fill_bytes(&mut buf)
}
#[test]
fn fill_bytes_varies() -> Result<(), EntropyError> {
let mut a = [0u8; 16];
let mut b = [0u8; 16];
fill_bytes(&mut a)?;
fill_bytes(&mut b)?;
assert_ne!(a, b);
Ok(())
}
}