Skip to content

Commit f2dce5f

Browse files
committed
Add OsRng
1 parent 6fbf58b commit f2dce5f

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

src/lib.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,13 @@ mod util;
3939
#[cfg(feature = "std")]
4040
mod error_std_impls;
4141

42+
#[cfg(feature = "rng")]
43+
mod rng;
44+
#[cfg(feature = "rng")]
45+
pub extern crate rand_core;
46+
#[cfg(feature = "rng")]
47+
pub use rng::OsRng;
48+
4249
pub use crate::error::{Error, RawOsError};
4350

4451
/// Fill `dest` with random bytes from the system's preferred random number source.

src/rng.rs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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

Comments
 (0)