|
| 1 | +//! rand_core adapter |
| 2 | +
|
| 3 | +use crate::Error; |
| 4 | +use rand_core::{TryCryptoRng, TryRngCore}; |
| 5 | + |
| 6 | +/// An RNG over the operating-system's random data source |
| 7 | +/// |
| 8 | +/// This is a zero-sized struct. It can be freely constructed with just `OsRng`. |
| 9 | +/// |
| 10 | +/// This struct is also available as [`rand::rngs::OsRng`] when using [rand]. |
| 11 | +/// |
| 12 | +/// # Usage example |
| 13 | +/// ``` |
| 14 | +/// use getrandom::{rand_core::{TryRngCore, RngCore}, OsRng}; |
| 15 | +/// |
| 16 | +/// let mut key = [0u8; 32]; |
| 17 | +/// OsRng.try_fill_bytes(&mut key).unwrap(); |
| 18 | +/// |
| 19 | +/// let mut rng = OsRng.unwrap_err(); |
| 20 | +/// let random_u64 = rng.next_u64(); |
| 21 | +/// ``` |
| 22 | +/// |
| 23 | +/// [rand]: https://crates.io/crates/rand |
| 24 | +/// [`rand::rngs::OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html |
| 25 | +#[derive(Clone, Copy, Debug, Default)] |
| 26 | +pub struct OsRng; |
| 27 | + |
| 28 | +impl TryRngCore for OsRng { |
| 29 | + type Error = Error; |
| 30 | + |
| 31 | + #[inline] |
| 32 | + fn try_next_u32(&mut self) -> Result<u32, Error> { |
| 33 | + crate::u32() |
| 34 | + } |
| 35 | + |
| 36 | + #[inline] |
| 37 | + fn try_next_u64(&mut self) -> Result<u64, Error> { |
| 38 | + crate::u64() |
| 39 | + } |
| 40 | + |
| 41 | + #[inline] |
| 42 | + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { |
| 43 | + crate::fill(dest) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +impl TryCryptoRng for OsRng {} |
| 48 | + |
| 49 | +#[test] |
| 50 | +fn test_os_rng() { |
| 51 | + let x = OsRng.try_next_u64().unwrap(); |
| 52 | + let y = OsRng.try_next_u64().unwrap(); |
| 53 | + assert!(x != 0); |
| 54 | + assert!(x != y); |
| 55 | +} |
| 56 | + |
| 57 | +#[test] |
| 58 | +fn test_construction() { |
| 59 | + assert!(OsRng.try_next_u64().unwrap() != 0); |
| 60 | +} |
0 commit comments