use alloc::string::{String, ToString};
use core::{
fmt,
fmt::{Debug, Display, Formatter},
};
#[derive(Debug)]
pub struct Error {
inner: String,
}
pub trait Entropy {
fn fill_bytes(&mut self, bytes: &mut [u8]) -> Result<(), Error>;
}
impl Error {
pub fn new<E>(error: E) -> Self
where
E: Display + Debug,
{
Self {
inner: error.to_string(),
}
}
}
impl core::error::Error for Error {}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "entropy error: {}", self.inner)
}
}
#[derive(Default)]
pub struct OsEntropy {}
impl OsEntropy {
pub fn new() -> Self {
Self::default()
}
}
impl Entropy for OsEntropy {
fn fill_bytes(&mut self, bytes: &mut [u8]) -> Result<(), Error> {
getrandom::fill(bytes).map_err(Error::new)
}
}