use alloc::sync::Arc;
use core::fmt;
use crate::error::Error;
type Fill = dyn Fn(&mut [u8]) -> Result<(), Error> + Send + Sync;
#[derive(Clone)]
pub struct Random(Arc<Fill>);
impl Random {
pub fn from_fn(fill: impl Fn(&mut [u8]) -> Result<(), Error> + Send + Sync + 'static) -> Self {
Self(Arc::new(fill))
}
#[cfg(feature = "pin")]
pub fn os() -> Self {
Self::from_fn(|out| {
use rand_core::RngCore;
rand_core::OsRng
.try_fill_bytes(out)
.map_err(|_| Error::Random)
})
}
pub fn fill(&self, out: &mut [u8]) -> Result<(), Error> {
(self.0)(out)
}
}
impl fmt::Debug for Random {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Random")
}
}