Skip to main content

tor_llcrypto/util/
rng.rs

1//! Prng utilities.
2
3use std::convert::Infallible;
4
5/// Helper to implement rand_core_06 for an Rng providing RngCore from rand_core 0.9.
6///
7/// We need this (for now) for compatibility with *-dalek and
8/// some other crypto libraries.
9///
10/// (Please avoid propagating this type outside of the tor-llcrypto crate.
11/// If you need it for a legacy crypto tool, it is usually better to wrap
12/// that tool with an API that uses RngCompat.)
13#[cfg_attr(feature = "rng-compat", visibility::make(pub))]
14pub struct RngCompat<R>(R);
15
16impl<R> RngCompat<R> {
17    /// Create a ne RngCompat to wrap `rng`
18    #[cfg_attr(feature = "rng-compat", visibility::make(pub))]
19    pub(crate) fn new(rng: R) -> Self {
20        Self(rng)
21    }
22}
23
24impl<R: rand_core::Rng> rand_core_06::RngCore for RngCompat<R> {
25    fn next_u32(&mut self) -> u32 {
26        self.0.next_u32()
27    }
28
29    fn next_u64(&mut self) -> u64 {
30        self.0.next_u64()
31    }
32
33    fn fill_bytes(&mut self, dest: &mut [u8]) {
34        self.0.fill_bytes(dest);
35    }
36
37    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core_06::Error> {
38        self.0.fill_bytes(dest);
39        Ok(())
40    }
41}
42impl<R: rand_core::CryptoRng> rand_core_06::CryptoRng for RngCompat<R> {}
43
44impl<R: rand_core_06::RngCore> rand_core::TryRng for RngCompat<R> {
45    type Error = Infallible;
46
47    fn try_next_u32(&mut self) -> Result<u32, Infallible> {
48        Ok(self.0.next_u32())
49    }
50
51    fn try_next_u64(&mut self) -> Result<u64, Infallible> {
52        Ok(self.0.next_u64())
53    }
54
55    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Infallible> {
56        self.0.fill_bytes(dest);
57        Ok(())
58    }
59}
60
61impl<R: rand_core_06::CryptoRng + rand_core_06::RngCore> rand_core::TryCryptoRng for RngCompat<R> {}