Skip to content

Commit a4e2299

Browse files
committed
Add OsRng::{seed, try_seed}
Adds methods for seeding `SeedableRng`s as replacements for the trait methods `SeedableRng::{from_os_rng, try_from_os_rng}` which were removed in #1674.
1 parent 737be86 commit a4e2299

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

src/rngs/os.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
//! Interface to the random number generator of the operating system.
1010
11-
use crate::{TryCryptoRng, TryRngCore};
11+
use crate::{SeedableRng, TryCryptoRng, TryRngCore};
1212

1313
/// An interface over the operating-system's random data source
1414
///
@@ -109,6 +109,34 @@ impl TryRngCore for OsRng {
109109

110110
impl TryCryptoRng for OsRng {}
111111

112+
impl OsRng {
113+
/// Creates a new instance of the RNG `R` seeded via [`OsRng`].
114+
///
115+
/// This method is the recommended way to construct non-deterministic PRNGs
116+
/// since it is convenient and secure.
117+
///
118+
/// Note that this method may panic on (extremely unlikely) [`OsRng`] errors.
119+
/// If it's not desirable, use the [`OsRng::try_seed`] method instead.
120+
///
121+
/// # Panics
122+
///
123+
/// If [`OsRng`] is unable to provide secure entropy this method will panic.
124+
pub fn seed<R: SeedableRng>(&mut self) -> R {
125+
match self.try_seed::<R>() {
126+
Ok(res) => res,
127+
Err(err) => panic!("OsRng::try_seed failed: {}", err),
128+
}
129+
}
130+
131+
/// Creates a new instance of the RNG `R` seeded via [`OsRng`], propagating any errors that may
132+
/// occur.
133+
pub fn try_seed<R: SeedableRng>(&mut self) -> Result<R, OsError> {
134+
let mut seed = R::Seed::default();
135+
self.try_fill_bytes(seed.as_mut())?;
136+
Ok(R::from_seed(seed))
137+
}
138+
}
139+
112140
#[test]
113141
fn test_os_rng() {
114142
let x = OsRng.try_next_u64().unwrap();

0 commit comments

Comments
 (0)