rmls/crypto/provider/rust/
rand.rs

1use rand_core::{RngCore, SeedableRng};
2use std::sync::RwLock;
3
4use crate::utilities::error::*;
5
6#[derive(Debug)]
7pub(super) struct RandChacha {
8    pub(super) rng: RwLock<rand_chacha::ChaCha20Rng>,
9}
10
11impl Default for RandChacha {
12    fn default() -> Self {
13        Self {
14            rng: RwLock::new(rand_chacha::ChaCha20Rng::from_entropy()),
15        }
16    }
17}
18
19impl crate::crypto::provider::Rand for RandChacha {
20    fn fill(&self, buf: &mut [u8]) -> Result<()> {
21        let mut rng = self
22            .rng
23            .write()
24            .map_err(|err| Error::Other(err.to_string()))?;
25        rng.try_fill_bytes(buf)
26            .map_err(|err| Error::Other(err.to_string()))?;
27        Ok(())
28    }
29}