getrandom_or_panic/
lib.rs

1//! Returns `OsRng` with `getrandom`, or a `CryptoRng` which panics without `getrandom`.
2
3#![no_std]
4
5/// Re-export rand_core types to simplify dependences
6pub use rand_core::{self,RngCore,CryptoRng,CryptoRngCore,SeedableRng};
7
8
9#[cfg(all( feature = "getrandom", not(feature = "std") ))]
10pub fn getrandom_or_panic() -> impl RngCore+CryptoRng {
11    rand_core::OsRng
12}
13
14#[cfg(all( feature = "getrandom", feature = "std" ))]
15pub fn getrandom_or_panic() -> impl RngCore+CryptoRng {
16    rand::thread_rng()
17}
18
19#[cfg(not(feature = "getrandom"))]
20pub fn getrandom_or_panic() -> impl RngCore+CryptoRng {
21    const PRM: &'static str = "Attempted to use functionality that requires system randomness!!";
22
23    // Should we panic when invoked or when used?
24
25    struct PanicRng;
26    impl rand_core::RngCore for PanicRng {
27        fn next_u32(&mut self) -> u32 {  panic!("{}", PRM)  }
28        fn next_u64(&mut self) -> u64 {  panic!("{}", PRM)  }
29        fn fill_bytes(&mut self, _dest: &mut [u8]) {  panic!("{}", PRM)  }
30        fn try_fill_bytes(&mut self, _dest: &mut [u8]) -> Result<(), rand_core::Error> {  panic!("{}", PRM)  }
31    }
32    impl rand_core::CryptoRng for PanicRng {}
33
34    PanicRng
35}
36