1
//! Prng utilities.
2

            
3
use 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))]
14
pub struct RngCompat<R>(R);
15

            
16
impl<R> RngCompat<R> {
17
    /// Create a ne RngCompat to wrap `rng`
18
9291
    #[cfg_attr(feature = "rng-compat", visibility::make(pub))]
19
9291
    pub(crate) fn new(rng: R) -> Self {
20
9291
        Self(rng)
21
9291
    }
22
}
23

            
24
impl<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
77302
    fn fill_bytes(&mut self, dest: &mut [u8]) {
34
77302
        self.0.fill_bytes(dest);
35
77302
    }
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
}
42
impl<R: rand_core::CryptoRng> rand_core_06::CryptoRng for RngCompat<R> {}
43

            
44
impl<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

            
61
impl<R: rand_core_06::CryptoRng + rand_core_06::RngCore> rand_core::TryCryptoRng for RngCompat<R> {}