coqui_peer/random.rs
1use alloc::sync::Arc;
2use core::fmt;
3
4use crate::error::Error;
5
6/// What fills a buffer with random bytes.
7type Fill = dyn Fn(&mut [u8]) -> Result<(), Error> + Send + Sync;
8
9/// A source of cryptographically secure random bytes: invitation secrets, user codes and pairing
10/// slots are drawn from it.
11///
12/// This crate keeps no random number generator of its own in a default build, so the caller
13/// passes one: `coqui-peer-tls` gives the one of its TLS provider, and with the `pin` feature
14/// `Random::os` reads the operating system's. A test may pass a deterministic one.
15#[derive(Clone)]
16pub struct Random(Arc<Fill>);
17
18impl Random {
19 /// A source that fills a buffer with `fill`, which must be cryptographically secure.
20 pub fn from_fn(fill: impl Fn(&mut [u8]) -> Result<(), Error> + Send + Sync + 'static) -> Self {
21 Self(Arc::new(fill))
22 }
23
24 /// The operating system's generator.
25 #[cfg(feature = "pin")]
26 pub fn os() -> Self {
27 Self::from_fn(|out| {
28 use rand_core::RngCore;
29 rand_core::OsRng
30 .try_fill_bytes(out)
31 .map_err(|_| Error::Random)
32 })
33 }
34
35 /// Fills `out` with random bytes.
36 ///
37 /// # Errors
38 ///
39 /// [`Error::Random`], or what the source returns, when it cannot.
40 pub fn fill(&self, out: &mut [u8]) -> Result<(), Error> {
41 (self.0)(out)
42 }
43}
44
45impl fmt::Debug for Random {
46 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47 formatter.write_str("Random")
48 }
49}