Skip to content

Commit e52789a

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 e52789a

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.
2323
- Add fns `IndexedRandom::choose_iter`, `choose_weighted_iter` (#1632)
2424
- Pub export `Xoshiro128PlusPlus`, `Xoshiro256PlusPlus` prngs (#1649)
2525
- Pub export `ChaCha8Rng`, `ChaCha12Rng`, `ChaCha20Rng` behind `chacha` feature (#1659)
26+
- `OsRng::seed` and `try_seed` as replacements for `SeedableRng::from_os_rng`, `try_from_os_rng`
2627

2728
## [0.9.2 — 2025-07-20]
2829
### Deprecated

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)