From 2cd89152bc26a62857e6e3b28893eadaf10340df Mon Sep 17 00:00:00 2001 From: Arthur Gautier Date: Wed, 5 Nov 2025 12:33:41 -0800 Subject: [PATCH] add `SeedableRng::fork` methods This provide a fork method to "clone" an Rng. This is handy to initialize an Rng that needs to be given to another thread for example. --- CHANGELOG.md | 2 ++ src/lib.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 52194b60..35ea45a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Remove feature `os_rng`, structs `OsRng` and `OsError` and fns `from_os_rng`, `try_from_os_rng` ([#1674]) - Remove feature `std` ([#1674]) - Removed dependency `getrandom` ([#1674]) +- Add `SeedableRng::fork` methods ([#17]) ### Other - Changed repository from [rust-random/rand] to [rust-random/core]. @@ -23,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [#1668]: https://github.com/rust-random/rand/pull/1668 [#1669]: https://github.com/rust-random/rand/pull/1669 [#1674]: https://github.com/rust-random/rand/pull/1674 +[#17]: https://github.com/rust-random/rand-core/pull/17 [rust-random/rand]: https://github.com/rust-random/rand [rust-random/core]: https://github.com/rust-random/core diff --git a/src/lib.rs b/src/lib.rs index dc8e3f01..13d53628 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -488,6 +488,34 @@ pub trait SeedableRng: Sized { rng.try_fill_bytes(seed.as_mut())?; Ok(Self::from_seed(seed)) } + + /// Fork this PRNG + /// + /// This creates a new PRNG from the current one by initializing a new one and + /// seeding it from the current one. + /// + /// This is useful when initializing a PRNG for a thread + fn fork(&mut self) -> Self + where + Self: RngCore, + { + Self::from_rng(self) + } + + /// Fork this PRNG + /// + /// This creates a new PRNG from the current one by initializing a new one and + /// seeding it from the current one. + /// + /// This is useful when initializing a PRNG for a thread. + /// + /// This is the failable equivalent to [`SeedableRng::fork`] + fn try_fork(&mut self) -> Result + where + Self: TryRngCore, + { + Self::try_from_rng(self) + } } #[cfg(test)]