From d782da8324c5805720cfdb6ab63f9e31f6b01b68 Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Sat, 27 Dec 2025 20:01:34 +0000 Subject: [PATCH 1/7] Add Cargo.lock automation (copied from getrandom) --- .github/dependabot.yml | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 22b1e8da2f5..b42e381cf7f 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,11 +1,17 @@ version: 2 updates: - - package-ecosystem: "cargo" - directory: "/" - schedule: - interval: "monthly" - open-pull-requests-limit: 10 - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "monthly" +- package-ecosystem: cargo + directory: "/" + versioning-strategy: lockfile-only + allow: + - dependency-type: "all" + schedule: + interval: weekly + groups: + all-deps: + patterns: + - "*" +- package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: weekly From 654817076ab276fbc255d384a40169086b241288 Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Tue, 23 Dec 2025 10:27:29 +0000 Subject: [PATCH 2/7] Update rand_core, getrandom and chacha20 --- Cargo.lock | 15 ++++++++------- Cargo.toml | 6 +++--- benches/Cargo.lock | 13 +++++++------ rand_chacha/Cargo.toml | 2 +- rand_pcg/Cargo.toml | 2 +- 5 files changed, 20 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 81ad8fdc0ea..8e39e372f07 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,9 +10,9 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "chacha20" -version = "0.10.0-rc.5" +version = "0.10.0-rc.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99cbf41c6ec3c4b9eaf7f8f5c11a72cd7d3aa0428125c20d5ef4d09907a0f019" +checksum = "f895fb33c1ad22da4bc79d37c0bddff8aee2ba4575705345eb73b8ffbc386074" dependencies = [ "cfg-if", "cpufeatures", @@ -82,13 +82,14 @@ checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" [[package]] name = "getrandom" -version = "0.3.4" +version = "0.4.0-rc.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +checksum = "3b99f0d993a2b9b97b9a201193aa8ad21305cde06a3be9a7e1f8f4201e5cc27e" dependencies = [ "cfg-if", "libc", "r-efi", + "rand_core", "wasip2", ] @@ -180,8 +181,8 @@ dependencies = [ name = "rand_chacha" version = "0.10.0-rc.1" dependencies = [ + "getrandom", "ppv-lite86", - "rand", "rand_core", "serde", "serde_json", @@ -189,9 +190,9 @@ dependencies = [ [[package]] name = "rand_core" -version = "0.10.0-rc-2" +version = "0.10.0-rc-3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "104a23e4e8b77312a823b6b5613edbac78397e2f34320bc7ac4277013ec4478e" +checksum = "f66ee92bc15280519ef199a274fe0cafff4245d31bc39aaa31c011ad56cb1f05" [[package]] name = "rand_pcg" diff --git a/Cargo.toml b/Cargo.toml index 545e0d83d6d..dd1b9cc2e8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,11 +73,11 @@ members = [ exclude = ["benches", "distr_test"] [dependencies] -rand_core = { version = "0.10.0-rc-2", default-features = false } +rand_core = { version = "0.10.0-rc-3", default-features = false } log = { version = "0.4.4", optional = true } serde = { version = "1.0.103", features = ["derive"], optional = true } -chacha20 = { version = "0.10.0-rc.5", default-features = false, features = ["rng"], optional = true } -getrandom = { version = "0.3.0", optional = true } +chacha20 = { version = "0.10.0-rc.6", default-features = false, features = ["rng"], optional = true } +getrandom = { version = "0.4.0-rc.0", optional = true } [dev-dependencies] rand_pcg = { path = "rand_pcg", version = "0.10.0-rc.1" } diff --git a/benches/Cargo.lock b/benches/Cargo.lock index d4caacb331d..808227eac8c 100644 --- a/benches/Cargo.lock +++ b/benches/Cargo.lock @@ -60,9 +60,9 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "chacha20" -version = "0.10.0-rc.5" +version = "0.10.0-rc.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99cbf41c6ec3c4b9eaf7f8f5c11a72cd7d3aa0428125c20d5ef4d09907a0f019" +checksum = "f895fb33c1ad22da4bc79d37c0bddff8aee2ba4575705345eb73b8ffbc386074" dependencies = [ "cfg-if", "cpufeatures", @@ -215,13 +215,14 @@ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "getrandom" -version = "0.3.4" +version = "0.4.0-rc.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +checksum = "3b99f0d993a2b9b97b9a201193aa8ad21305cde06a3be9a7e1f8f4201e5cc27e" dependencies = [ "cfg-if", "libc", "r-efi", + "rand_core", "wasip2", ] @@ -391,9 +392,9 @@ dependencies = [ [[package]] name = "rand_core" -version = "0.10.0-rc-2" +version = "0.10.0-rc-3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "104a23e4e8b77312a823b6b5613edbac78397e2f34320bc7ac4277013ec4478e" +checksum = "f66ee92bc15280519ef199a274fe0cafff4245d31bc39aaa31c011ad56cb1f05" [[package]] name = "rand_pcg" diff --git a/rand_chacha/Cargo.toml b/rand_chacha/Cargo.toml index f8f321e229e..c09cf8a2d15 100644 --- a/rand_chacha/Cargo.toml +++ b/rand_chacha/Cargo.toml @@ -20,7 +20,7 @@ all-features = true rustdoc-args = ["--generate-link-to-definition"] [dependencies] -rand_core = { version = "0.10.0-rc-2" } +rand_core = { version = "0.10.0-rc-3" } ppv-lite86 = { version = "0.2.14", default-features = false, features = ["simd"] } serde = { version = "1.0", features = ["derive"], optional = true } diff --git a/rand_pcg/Cargo.toml b/rand_pcg/Cargo.toml index deec7cb8d3b..b4c13c0c5f5 100644 --- a/rand_pcg/Cargo.toml +++ b/rand_pcg/Cargo.toml @@ -23,7 +23,7 @@ rustdoc-args = ["--generate-link-to-definition"] serde = ["dep:serde"] [dependencies] -rand_core = { version = "0.10.0-rc-2" } +rand_core = { version = "0.10.0-rc-3" } serde = { version = "1", features = ["derive"], optional = true } [dev-dependencies] From 9b18dda4311e0dfae25165bae342bc2eabacb16e Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Tue, 23 Dec 2025 10:31:34 +0000 Subject: [PATCH 3/7] Use getrandom::SysRng --- Cargo.toml | 2 +- rand_chacha/Cargo.toml | 2 +- rand_chacha/src/lib.rs | 8 +-- src/rngs/mod.rs | 5 +- src/rngs/os.rs | 123 ----------------------------------------- 5 files changed, 7 insertions(+), 133 deletions(-) delete mode 100644 src/rngs/os.rs diff --git a/Cargo.toml b/Cargo.toml index dd1b9cc2e8d..58d1f9b4687 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,7 +40,7 @@ std = ["alloc", "getrandom?/std"] alloc = [] # Option: enable OsRng -os_rng = ["dep:getrandom"] +os_rng = ["dep:getrandom", "getrandom/sys_rng"] # Option (requires nightly Rust): experimental SIMD support simd_support = [] diff --git a/rand_chacha/Cargo.toml b/rand_chacha/Cargo.toml index c09cf8a2d15..aa19d735ead 100644 --- a/rand_chacha/Cargo.toml +++ b/rand_chacha/Cargo.toml @@ -27,7 +27,7 @@ serde = { version = "1.0", features = ["derive"], optional = true } [dev-dependencies] # Only to test serde serde_json = "1.0.120" -rand = { path = "..", version = "0.10.0-rc.0" } +getrandom = { version = "0.4.0-rc.0", features = ["sys_rng"] } [features] default = ["std"] diff --git a/rand_chacha/src/lib.rs b/rand_chacha/src/lib.rs index a06976e09fe..1f12d217878 100644 --- a/rand_chacha/src/lib.rs +++ b/rand_chacha/src/lib.rs @@ -24,7 +24,7 @@ //! //! Where secure unpredictable generators are required, it is suggested to use //! [`ChaCha12Rng`] or [`ChaCha20Rng`] and to seed via -//! [`OsRng`]. +//! [`SysRng`]. //! //! See also the [Security] chapter in the rand book. The crate is provided //! "as is", without any form of guarantee, and without a security audit. @@ -37,8 +37,8 @@ //! //! 1. With a fresh seed, **direct from the OS** (implies a syscall): //! ``` -//! # use {rand_core::SeedableRng, rand_chacha::ChaCha12Rng, rand::rngs::OsRng}; -//! let rng = ChaCha12Rng::try_from_rng(&mut OsRng).unwrap(); +//! # use {rand_core::SeedableRng, rand_chacha::ChaCha12Rng, getrandom::SysRng}; +//! let rng = ChaCha12Rng::try_from_rng(&mut SysRng).unwrap(); //! # let _: ChaCha12Rng = rng; //! ``` //! 2. **From a master generator.** This could be [`rand::rng`] @@ -76,7 +76,7 @@ //! [`BlockRngCore`]: rand_core::block::BlockRngCore //! [`RngCore`]: rand_core::RngCore //! [`SeedableRng`]: rand_core::SeedableRng -//! [`OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html +//! [`SysRng`]: https://docs.rs/rand/latest/rand/rngs/struct.SysRng.html //! [`rand::rng`]: https://docs.rs/rand/latest/rand/fn.rng.html //! [`rand::Rng`]: https://docs.rs/rand/latest/rand/trait.Rng.html diff --git a/src/rngs/mod.rs b/src/rngs/mod.rs index 34f8aa781c1..21dc9b85b64 100644 --- a/src/rngs/mod.rs +++ b/src/rngs/mod.rs @@ -110,9 +110,6 @@ mod std; #[cfg(feature = "thread_rng")] pub(crate) mod thread; -#[cfg(feature = "os_rng")] -mod os; - #[cfg(feature = "small_rng")] pub use self::small::SmallRng; #[cfg(feature = "small_rng")] @@ -129,4 +126,4 @@ pub use self::thread::ThreadRng; pub use chacha20::{ChaCha8Rng, ChaCha12Rng, ChaCha20Rng}; #[cfg(feature = "os_rng")] -pub use os::{OsError, OsRng}; +pub use getrandom::{Error as OsError, SysRng as OsRng}; diff --git a/src/rngs/os.rs b/src/rngs/os.rs deleted file mode 100644 index c06ef7a0775..00000000000 --- a/src/rngs/os.rs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2019 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Interface to the random number generator of the operating system. - -use crate::{TryCryptoRng, TryRngCore}; - -/// An interface over the operating-system's random data source -/// -/// This is a zero-sized struct. It can be freely constructed with just `OsRng`. -/// -/// The implementation is provided by the [getrandom] crate. Refer to -/// [getrandom] documentation for details. -/// -/// This struct is available as `rand_core::OsRng` and as `rand::rngs::OsRng`. -/// In both cases, this requires the crate feature `os_rng` or `std` -/// (enabled by default in `rand` but not in `rand_core`). -/// -/// # Blocking and error handling -/// -/// It is possible that when used during early boot the first call to `OsRng` -/// will block until the system's RNG is initialised. It is also possible -/// (though highly unlikely) for `OsRng` to fail on some platforms, most -/// likely due to system mis-configuration. -/// -/// After the first successful call, it is highly unlikely that failures or -/// significant delays will occur (although performance should be expected to -/// be much slower than a user-space -/// [PRNG](https://rust-random.github.io/book/guide-gen.html#pseudo-random-number-generators)). -/// -/// # Usage example -/// ``` -/// use rand::{TryRngCore, rngs::OsRng}; -/// -/// let mut key = [0u8; 16]; -/// OsRng.try_fill_bytes(&mut key).unwrap(); -/// let random_u64 = OsRng.try_next_u64().unwrap(); -/// ``` -/// -/// [getrandom]: https://crates.io/crates/getrandom -#[derive(Clone, Copy, Debug, Default)] -pub struct OsRng; - -/// Error type of [`OsRng`] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct OsError(getrandom::Error); - -impl core::fmt::Display for OsError { - #[inline] - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - self.0.fmt(f) - } -} - -// NOTE: this can use core::error::Error from rustc 1.81.0 -#[cfg(feature = "std")] -impl std::error::Error for OsError { - #[inline] - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - std::error::Error::source(&self.0) - } -} - -// If [`RawOsError`](https://doc.rust-lang.org/std/io/type.RawOsError.html) is stablized, we can use it. - -#[cfg(not(target_os = "uefi"))] -type RawOsError = i32; - -#[cfg(target_os = "uefi")] -type RawOsError = usize; - -impl OsError { - /// Extract the raw OS error code (if this error came from the OS) - /// - /// This method is identical to [`std::io::Error::raw_os_error()`][1], except - /// that it works in `no_std` contexts. If this method returns `None`, the - /// error value can still be formatted via the `Display` implementation. - /// - /// [1]: https://doc.rust-lang.org/std/io/struct.Error.html#method.raw_os_error - #[inline] - pub fn raw_os_error(self) -> Option { - self.0.raw_os_error() - } -} - -impl TryRngCore for OsRng { - type Error = OsError; - - #[inline] - fn try_next_u32(&mut self) -> Result { - getrandom::u32().map_err(OsError) - } - - #[inline] - fn try_next_u64(&mut self) -> Result { - getrandom::u64().map_err(OsError) - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> { - getrandom::fill(dest).map_err(OsError) - } -} - -impl TryCryptoRng for OsRng {} - -#[test] -fn test_os_rng() { - let x = OsRng.try_next_u64().unwrap(); - let y = OsRng.try_next_u64().unwrap(); - assert!(x != 0); - assert!(x != y); -} - -#[test] -fn test_construction() { - assert!(OsRng.try_next_u64().unwrap() != 0); -} From bf57bbc439278bf504fbc1c6e7ba66b2aac4378d Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Tue, 23 Dec 2025 10:34:28 +0000 Subject: [PATCH 4/7] Rename OsRng -> SysRng --- .github/workflows/test.yml | 4 ++-- CHANGELOG.md | 3 +++ Cargo.toml | 8 ++++---- README.md | 8 ++++---- SECURITY.md | 10 +++++----- benches/benches/generators.rs | 10 +++++----- src/lib.rs | 4 ++-- src/rngs/mod.rs | 10 +++++----- src/rngs/reseeding.rs | 4 ++-- src/rngs/std.rs | 6 +++--- src/rngs/thread.rs | 14 +++++++------- 11 files changed, 42 insertions(+), 39 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1882859d1b1..c45ab75a769 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -104,8 +104,8 @@ jobs: - name: Test rand run: | cargo test --target ${{ matrix.target }} --lib --tests --no-default-features - cargo build --target ${{ matrix.target }} --no-default-features --features alloc,os_rng,small_rng,unbiased - cargo test --target ${{ matrix.target }} --lib --tests --no-default-features --features=alloc,os_rng,small_rng + cargo build --target ${{ matrix.target }} --no-default-features --features alloc,sys_rng,small_rng,unbiased + cargo test --target ${{ matrix.target }} --lib --tests --no-default-features --features=alloc,sys_rng,small_rng cargo test --target ${{ matrix.target }} --examples - name: Test rand (all stable features) run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 66a4e280f5e..11b680958b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,12 +19,15 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update. - Remove fns `SeedableRng::from_os_rng`, `try_from_os_rng` (#1674) - Remove `Clone` support for `StdRng`, `ReseedingRng` (#1677) - Use `postcard` instead of `bincode` to test the serde feature (#1693) +- Rename `os_rng` -> `sys_rng`, `OsRng` -> `SysRng`, `OsError` -> `SysError` ([#1697]) ### Additions - Add fns `IndexedRandom::choose_iter`, `choose_weighted_iter` (#1632) - Pub export `Xoshiro128PlusPlus`, `Xoshiro256PlusPlus` prngs (#1649) - Pub export `ChaCha8Rng`, `ChaCha12Rng`, `ChaCha20Rng` behind `chacha` feature (#1659) +[#1697]: https://github.com/rust-random/rand/pull/1697 + ## [0.9.2] - 2025-07-20 ### Deprecated - Deprecate `rand::rngs::mock` module and `StepRng` generator (#1634) diff --git a/Cargo.toml b/Cargo.toml index 58d1f9b4687..622f73ff57b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ features = ["small_rng", "serde"] [features] # Meta-features: -default = ["std", "std_rng", "os_rng", "small_rng", "thread_rng"] +default = ["std", "std_rng", "sys_rng", "small_rng", "thread_rng"] nightly = [] # some additions requiring nightly Rust serde = ["dep:serde"] @@ -39,8 +39,8 @@ std = ["alloc", "getrandom?/std"] # Option: "alloc" enables support for Vec and Box when not using "std" alloc = [] -# Option: enable OsRng -os_rng = ["dep:getrandom", "getrandom/sys_rng"] +# Option: enable SysRng +sys_rng = ["dep:getrandom", "getrandom/sys_rng"] # Option (requires nightly Rust): experimental SIMD support simd_support = [] @@ -52,7 +52,7 @@ std_rng = ["dep:chacha20"] small_rng = [] # Option: enable ThreadRng and rng() -thread_rng = ["std", "std_rng", "os_rng"] +thread_rng = ["std", "std_rng", "sys_rng"] # Option: enable rand::rngs::ChaCha*Rng chacha = ["dep:chacha20"] diff --git a/README.md b/README.md index 433736a6ded..662f3678adb 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ Rand is built with these features enabled by default: - `std` enables functionality dependent on the `std` lib - `alloc` (implied by `std`) enables functionality requiring an allocator -- `os_rng` (implied by `std`) enables `rngs::OsRng`, using the [getrandom] crate +- `sys_rng` (implied by `std`) enables `rngs::SysRng`, using the [getrandom] crate - `std_rng` enables inclusion of `StdRng`, `ThreadRng` - `small_rng` enables inclusion of the `SmallRng` PRNG @@ -89,8 +89,8 @@ compiler versions will be compatible. This is especially true of Rand's experimental `simd_support` feature. Rand supports limited functionality in `no_std` mode (enabled via -`default-features = false`). In this case, `OsRng` is -unavailable (unless `os_rng` is enabled), large parts of `seq` are +`default-features = false`). In this case, `SysRng` is +unavailable (unless `sys_rng` is enabled), large parts of `seq` are unavailable (unless `alloc` is enabled), and `ThreadRng` is unavailable. ## Portability and platform support @@ -105,7 +105,7 @@ The [WASI](https://github.com/WebAssembly/WASI/tree/main) and Emscripten targets are directly supported. The `wasm32-unknown-unknown` target is not *automatically* supported. To enable support for this target, refer to the [`getrandom` documentation for WebAssembly](https://docs.rs/getrandom/latest/getrandom/#webassembly-support). -Alternatively, the `os_rng` feature may be disabled. +Alternatively, the `sys_rng` feature may be disabled. # License diff --git a/SECURITY.md b/SECURITY.md index c848573448b..2058d72e63a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -16,15 +16,15 @@ used according to these additional constraints: - The generator may be constructed using `std::default::Default` where the generator supports this trait. Note that generators should *only* support `Default` where the `default()` instance is appropriately seeded: for - example `OsRng` has no state and thus has a trivial `default()` instance + example `SysRng` has no state and thus has a trivial `default()` instance while `ThreadRng::default()` returns a handle to a thread-local instance - seeded using `OsRng`. + seeded using `SysRng`. - The generator may be constructed using `rand_core::SeedableRng` in any of the following ways where the generator supports this trait: - Via `SeedableRng::from_seed` using a cryptographically secure seed value - Via `SeedableRng::from_rng` or `try_from_rng` using a cryptographically - secure source `rng` such as `OsRng` or `ThreadRng`. + secure source `rng` such as `SysRng` or `ThreadRng`. - The state (memory) of the generator and its seed value (or source `rng`) are not exposed @@ -42,7 +42,7 @@ are expected to provide the following: ### Specific generators -`OsRng` is a stateless "generator" implemented via [getrandom]. As such, it has +`SysRng` is a stateless "generator" implemented via [getrandom]. As such, it has no possible state to leak and cannot be improperly seeded. `StdRng` is a `CryptoRng` and `SeedableRng` using a pseudo-random algorithm @@ -55,7 +55,7 @@ trait and implement `SeedableRng` with a commitment to reproducibility of results. `ThreadRng` is a conveniently-packaged generator over `StdRng` offering -automatic seeding from `OsRng`, periodic reseeding and thread locality. +automatic seeding from `SysRng`, periodic reseeding and thread locality. This random source is intended to offer a good compromise between cryptographic security, fast generation with reasonably low memory and initialization cost overheads, and robustness against misuse. diff --git a/benches/benches/generators.rs b/benches/benches/generators.rs index 1d22b1aa6c7..77f87d918b5 100644 --- a/benches/benches/generators.rs +++ b/benches/benches/generators.rs @@ -10,8 +10,8 @@ use core::time::Duration; use criterion::measurement::WallTime; use criterion::{BenchmarkGroup, Criterion, black_box, criterion_group, criterion_main}; use rand::prelude::*; -use rand::rngs::OsRng; use rand::rngs::ReseedingRng; +use rand::rngs::SysRng; use rand_chacha::rand_core::UnwrapErr; use rand_chacha::{ChaCha8Rng, ChaCha12Rng, ChaCha20Core, ChaCha20Rng}; use rand_pcg::{Pcg32, Pcg64, Pcg64Dxsm, Pcg64Mcg}; @@ -48,7 +48,7 @@ pub fn random_bytes(c: &mut Criterion) { bench(&mut g, "chacha20", ChaCha20Rng::from_rng(&mut rand::rng())); bench(&mut g, "std", StdRng::from_rng(&mut rand::rng())); bench(&mut g, "small", SmallRng::from_rng(&mut rand::rng())); - bench(&mut g, "os", UnwrapErr(OsRng)); + bench(&mut g, "os", UnwrapErr(SysRng)); bench(&mut g, "thread", rand::rng()); g.finish() @@ -76,7 +76,7 @@ pub fn random_u32(c: &mut Criterion) { bench(&mut g, "chacha20", ChaCha20Rng::from_rng(&mut rand::rng())); bench(&mut g, "std", StdRng::from_rng(&mut rand::rng())); bench(&mut g, "small", SmallRng::from_rng(&mut rand::rng())); - bench(&mut g, "os", UnwrapErr(OsRng)); + bench(&mut g, "os", UnwrapErr(SysRng)); bench(&mut g, "thread", rand::rng()); g.finish() @@ -104,7 +104,7 @@ pub fn random_u64(c: &mut Criterion) { bench(&mut g, "chacha20", ChaCha20Rng::from_rng(&mut rand::rng())); bench(&mut g, "std", StdRng::from_rng(&mut rand::rng())); bench(&mut g, "small", SmallRng::from_rng(&mut rand::rng())); - bench(&mut g, "os", UnwrapErr(OsRng)); + bench(&mut g, "os", UnwrapErr(SysRng)); bench(&mut g, "thread", rand::rng()); g.finish() @@ -198,7 +198,7 @@ pub fn reseeding_bytes(c: &mut Criterion) { fn bench(g: &mut BenchmarkGroup, thresh: u64) { let name = format!("chacha20_{thresh}k"); g.bench_function(name.as_str(), |b| { - let mut rng = ReseedingRng::::new(thresh * 1024, OsRng).unwrap(); + let mut rng = ReseedingRng::::new(thresh * 1024, SysRng).unwrap(); let mut buf = [0u8; 1024 * 1024]; b.iter(|| { rng.fill_bytes(&mut buf); diff --git a/src/lib.rs b/src/lib.rs index a42838d52d3..b3530f6b276 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -135,10 +135,10 @@ use crate::distr::{Distribution, StandardUniform}; /// ```no_run /// use std::{io, io::Read}; /// use std::fs::File; -/// use rand::{rngs::OsRng, RngReader}; +/// use rand::{rngs::SysRng, RngReader}; /// /// io::copy( -/// &mut RngReader(OsRng).take(100), +/// &mut RngReader(SysRng).take(100), /// &mut File::create("/tmp/random.bytes").unwrap() /// ).unwrap(); /// ``` diff --git a/src/rngs/mod.rs b/src/rngs/mod.rs index 21dc9b85b64..c99dc3d2ffe 100644 --- a/src/rngs/mod.rs +++ b/src/rngs/mod.rs @@ -15,11 +15,11 @@ //! //! ##### Non-deterministic generators //! -//! - [`OsRng`] is a stateless interface over the operating system's random number +//! - [`SysRng`] is a stateless interface over the operating system's random number //! source. This is typically secure with some form of periodic re-seeding. //! - [`ThreadRng`], provided by [`crate::rng()`], is a handle to a -//! thread-local generator with periodic seeding from [`OsRng`]. Because this -//! is local, it is typically much faster than [`OsRng`]. It should be +//! thread-local generator with periodic seeding from [`SysRng`]. Because this +//! is local, it is typically much faster than [`SysRng`]. It should be //! secure, but see documentation on [`ThreadRng`]. //! //! ##### Standard generators @@ -125,5 +125,5 @@ pub use self::thread::ThreadRng; #[cfg(feature = "chacha")] pub use chacha20::{ChaCha8Rng, ChaCha12Rng, ChaCha20Rng}; -#[cfg(feature = "os_rng")] -pub use getrandom::{Error as OsError, SysRng as OsRng}; +#[cfg(feature = "sys_rng")] +pub use getrandom::{Error as SysError, SysRng}; diff --git a/src/rngs/reseeding.rs b/src/rngs/reseeding.rs index 4a9f107edb0..4eccc799148 100644 --- a/src/rngs/reseeding.rs +++ b/src/rngs/reseeding.rs @@ -55,10 +55,10 @@ use rand_core::{CryptoRng, RngCore, SeedableRng, TryCryptoRng, TryRngCore}; /// use chacha20::ChaCha20Core; // Internal part of ChaChaRng that /// // implements BlockRngCore /// use rand::prelude::*; -/// use rand::rngs::OsRng; +/// use rand::rngs::SysRng; /// use rand::rngs::ReseedingRng; /// -/// let mut reseeding_rng = ReseedingRng::::new(0, OsRng).unwrap(); +/// let mut reseeding_rng = ReseedingRng::::new(0, SysRng).unwrap(); /// /// println!("{}", reseeding_rng.random::()); /// ``` diff --git a/src/rngs/std.rs b/src/rngs/std.rs index 3fc3e491e1d..82142d8d5f2 100644 --- a/src/rngs/std.rs +++ b/src/rngs/std.rs @@ -10,7 +10,7 @@ use rand_core::{CryptoRng, RngCore, SeedableRng}; -#[cfg(any(test, feature = "os_rng"))] +#[cfg(any(test, feature = "sys_rng"))] pub(crate) use chacha20::ChaCha12Core as Core; use chacha20::ChaCha12Rng as Rng; @@ -39,8 +39,8 @@ use chacha20::ChaCha12Rng as Rng; /// /// Using a fresh seed **direct from the OS** is the most secure option: /// ``` -/// # use rand::{SeedableRng, rngs::{StdRng, OsRng}}; -/// let rng = StdRng::try_from_rng(&mut OsRng).unwrap(); +/// # use rand::{SeedableRng, rngs::{StdRng, SysRng}}; +/// let rng = StdRng::try_from_rng(&mut SysRng).unwrap(); /// # let _: StdRng = rng; /// ``` /// diff --git a/src/rngs/thread.rs b/src/rngs/thread.rs index 5acb90df0df..cccb4ad927b 100644 --- a/src/rngs/thread.rs +++ b/src/rngs/thread.rs @@ -13,7 +13,7 @@ use std::fmt; use std::rc::Rc; use std::thread_local; -use super::{OsError, OsRng, ReseedingRng, std::Core}; +use super::{SysError, SysRng, ReseedingRng, std::Core}; use rand_core::{CryptoRng, RngCore}; // Rationale for using `UnsafeCell` in `ThreadRng`: @@ -48,7 +48,7 @@ const THREAD_RNG_RESEED_THRESHOLD: u64 = 1024 * 64; /// requirements. The Rand project can provide no guarantee of fitness for /// purpose. The design criteria for `ThreadRng` are as follows: /// -/// - Automatic seeding via [`OsRng`] and periodically thereafter (see +/// - Automatic seeding via [`SysRng`] and periodically thereafter (see /// ([`ReseedingRng`] documentation). Limitation: there is no automatic /// reseeding on process fork (see [below](#fork)). /// - A rigorusly analyzed, unpredictable (cryptographic) pseudo-random generator @@ -65,7 +65,7 @@ const THREAD_RNG_RESEED_THRESHOLD: u64 = 1024 * 64; /// (where "reasonably secure" implies the above criteria). /// /// We leave it to the user to determine whether this generator meets their -/// security requirements. For an alternative, see [`OsRng`]. +/// security requirements. For an alternative, see [`SysRng`]. /// /// # Fork /// @@ -90,14 +90,14 @@ const THREAD_RNG_RESEED_THRESHOLD: u64 = 1024 * 64; #[derive(Clone)] pub struct ThreadRng { // Rc is explicitly !Send and !Sync - rng: Rc>>, + rng: Rc>>, } impl ThreadRng { /// Immediately reseed the generator /// /// This discards any remaining random data in the cache. - pub fn reseed(&mut self) -> Result<(), OsError> { + pub fn reseed(&mut self) -> Result<(), SysError> { // SAFETY: We must make sure to stop using `rng` before anyone else // creates another mutable reference let rng = unsafe { &mut *self.rng.get() }; @@ -115,9 +115,9 @@ impl fmt::Debug for ThreadRng { thread_local!( // We require Rc<..> to avoid premature freeing when ThreadRng is used // within thread-local destructors. See #968. - static THREAD_RNG_KEY: Rc>> = { + static THREAD_RNG_KEY: Rc>> = { let rng = ReseedingRng::new(THREAD_RNG_RESEED_THRESHOLD, - OsRng).unwrap_or_else(|err| + SysRng).unwrap_or_else(|err| panic!("could not initialize ThreadRng: {}", err)); Rc::new(UnsafeCell::new(rng)) } From 25402ef21d9d5c36e5c543bfb50eb2a80b9a2a7a Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Sun, 30 Nov 2025 11:10:16 +0000 Subject: [PATCH 5/7] Update rand_pcg --- rand_pcg/src/pcg128.rs | 12 +++++------- rand_pcg/src/pcg128cm.rs | 7 +++---- rand_pcg/src/pcg64.rs | 9 ++++----- 3 files changed, 12 insertions(+), 16 deletions(-) diff --git a/rand_pcg/src/pcg128.rs b/rand_pcg/src/pcg128.rs index f7dbada8cb8..e6c4e02bf6d 100644 --- a/rand_pcg/src/pcg128.rs +++ b/rand_pcg/src/pcg128.rs @@ -14,7 +14,7 @@ const MULTIPLIER: u128 = 0x2360_ED05_1FC6_5DA4_4385_DF64_9FCC_F645; use core::fmt; -use rand_core::{RngCore, SeedableRng, le}; +use rand_core::{RngCore, SeedableRng, utils}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; @@ -126,8 +126,7 @@ impl SeedableRng for Lcg128Xsl64 { /// We use a single 255-bit seed to initialise the state and select a stream. /// One `seed` bit (lowest bit of `seed[8]`) is ignored. fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u64 = [0u64; 4]; - le::read_u64_into(&seed, &mut seed_u64); + let seed_u64: [u64; 4] = utils::read_words(&seed); let state = u128::from(seed_u64[0]) | (u128::from(seed_u64[1]) << 64); let incr = u128::from(seed_u64[2]) | (u128::from(seed_u64[3]) << 64); @@ -150,7 +149,7 @@ impl RngCore for Lcg128Xsl64 { #[inline] fn fill_bytes(&mut self, dest: &mut [u8]) { - le::fill_bytes_via_next(self, dest) + utils::fill_bytes_via_next_word(dest, || self.next_u64()); } } @@ -232,8 +231,7 @@ impl SeedableRng for Mcg128Xsl64 { fn from_seed(seed: Self::Seed) -> Self { // Read as if a little-endian u128 value: - let mut seed_u64 = [0u64; 2]; - le::read_u64_into(&seed, &mut seed_u64); + let seed_u64: [u64; 2] = utils::read_words(&seed); let state = u128::from(seed_u64[0]) | (u128::from(seed_u64[1]) << 64); Mcg128Xsl64::new(state) } @@ -253,7 +251,7 @@ impl RngCore for Mcg128Xsl64 { #[inline] fn fill_bytes(&mut self, dest: &mut [u8]) { - le::fill_bytes_via_next(self, dest) + utils::fill_bytes_via_next_word(dest, || self.next_u64()); } } diff --git a/rand_pcg/src/pcg128cm.rs b/rand_pcg/src/pcg128cm.rs index 681ca639b4e..e9ce218f362 100644 --- a/rand_pcg/src/pcg128cm.rs +++ b/rand_pcg/src/pcg128cm.rs @@ -14,7 +14,7 @@ const MULTIPLIER: u64 = 15750249268501108917; use core::fmt; -use rand_core::{RngCore, SeedableRng, le}; +use rand_core::{RngCore, SeedableRng, utils}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; @@ -131,8 +131,7 @@ impl SeedableRng for Lcg128CmDxsm64 { /// We use a single 255-bit seed to initialise the state and select a stream. /// One `seed` bit (lowest bit of `seed[8]`) is ignored. fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u64 = [0u64; 4]; - le::read_u64_into(&seed, &mut seed_u64); + let seed_u64: [u64; 4] = utils::read_words(&seed); let state = u128::from(seed_u64[0]) | (u128::from(seed_u64[1]) << 64); let incr = u128::from(seed_u64[2]) | (u128::from(seed_u64[3]) << 64); @@ -156,7 +155,7 @@ impl RngCore for Lcg128CmDxsm64 { #[inline] fn fill_bytes(&mut self, dest: &mut [u8]) { - le::fill_bytes_via_next(self, dest) + utils::fill_bytes_via_next_word(dest, || self.next_u64()); } } diff --git a/rand_pcg/src/pcg64.rs b/rand_pcg/src/pcg64.rs index 967299fdcb6..4eeabfd0be2 100644 --- a/rand_pcg/src/pcg64.rs +++ b/rand_pcg/src/pcg64.rs @@ -11,7 +11,7 @@ //! PCG random number generators use core::fmt; -use rand_core::{RngCore, SeedableRng, le}; +use rand_core::{RngCore, SeedableRng, utils}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; @@ -127,8 +127,7 @@ impl SeedableRng for Lcg64Xsh32 { /// We use a single 127-bit seed to initialise the state and select a stream. /// One `seed` bit (lowest bit of `seed[8]`) is ignored. fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u64 = [0u64; 2]; - le::read_u64_into(&seed, &mut seed_u64); + let seed_u64: [u64; 2] = utils::read_words(&seed); // The increment must be odd, hence we discard one bit: Lcg64Xsh32::from_state_incr(seed_u64[0], seed_u64[1] | 1) @@ -154,11 +153,11 @@ impl RngCore for Lcg64Xsh32 { #[inline] fn next_u64(&mut self) -> u64 { - le::next_u64_via_u32(self) + utils::next_u64_via_u32(self) } #[inline] fn fill_bytes(&mut self, dest: &mut [u8]) { - le::fill_bytes_via_next(self, dest) + utils::fill_bytes_via_next_word(dest, || self.next_u32()); } } From 66137b15c92f2f5e5d6e61c87455d6e08a6ad25b Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Tue, 23 Dec 2025 10:08:08 +0000 Subject: [PATCH 6/7] Update rand_chacha --- rand_chacha/src/chacha.rs | 63 +++++---------------------------------- rand_chacha/src/lib.rs | 4 +-- 2 files changed, 10 insertions(+), 57 deletions(-) diff --git a/rand_chacha/src/chacha.rs b/rand_chacha/src/chacha.rs index f42232f757c..a455f0123c0 100644 --- a/rand_chacha/src/chacha.rs +++ b/rand_chacha/src/chacha.rs @@ -10,7 +10,7 @@ use crate::guts::ChaCha; use core::fmt; -use rand_core::block::{BlockRng, BlockRngCore, CryptoBlockRng}; +use rand_core::block::{BlockRng, CryptoGenerator, Generator}; use rand_core::{CryptoRng, RngCore, SeedableRng}; #[cfg(feature = "serde")] @@ -21,52 +21,6 @@ const BUF_BLOCKS: u8 = 4; // number of 32-bit words per ChaCha block (fixed by algorithm definition) const BLOCK_WORDS: u8 = 16; -#[repr(transparent)] -pub struct Array64([T; 64]); -impl Default for Array64 -where - T: Default, -{ - #[rustfmt::skip] - fn default() -> Self { - Self([ - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - ]) - } -} -impl AsRef<[T]> for Array64 { - fn as_ref(&self) -> &[T] { - &self.0 - } -} -impl AsMut<[T]> for Array64 { - fn as_mut(&mut self) -> &mut [T] { - &mut self.0 - } -} -impl Clone for Array64 -where - T: Copy + Default, -{ - fn clone(&self) -> Self { - let mut new = Self::default(); - new.0.copy_from_slice(&self.0); - new - } -} -impl fmt::Debug for Array64 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Array64 {{}}") - } -} - macro_rules! chacha_impl { ($ChaChaXCore:ident, $ChaChaXRng:ident, $rounds:expr, $doc:expr, $abst:ident,) => { #[doc=$doc] @@ -82,13 +36,12 @@ macro_rules! chacha_impl { } } - impl BlockRngCore for $ChaChaXCore { - type Item = u32; - type Results = Array64; + impl Generator for $ChaChaXCore { + type Output = [u32; 64]; #[inline] - fn generate(&mut self, r: &mut Self::Results) { - self.state.refill4($rounds, &mut r.0); + fn generate(&mut self, output: &mut Self::Output) { + self.state.refill4($rounds, output); } } @@ -103,7 +56,7 @@ macro_rules! chacha_impl { } } - impl CryptoBlockRng for $ChaChaXCore {} + impl CryptoGenerator for $ChaChaXCore {} /// A cryptographically secure random number generator that uses the ChaCha algorithm. /// @@ -163,12 +116,12 @@ macro_rules! chacha_impl { impl RngCore for $ChaChaXRng { #[inline] fn next_u32(&mut self) -> u32 { - self.rng.next_u32() + self.rng.next_word() } #[inline] fn next_u64(&mut self) -> u64 { - self.rng.next_u64() + self.rng.next_u64_from_u32() } #[inline] diff --git a/rand_chacha/src/lib.rs b/rand_chacha/src/lib.rs index 1f12d217878..b12f24620f4 100644 --- a/rand_chacha/src/lib.rs +++ b/rand_chacha/src/lib.rs @@ -14,7 +14,7 @@ //! ## Generators //! //! This crate provides 8-, 12- and 20-round variants of generators via a "core" -//! implementation (of [`BlockRngCore`]), each with an associated "RNG" type +//! implementation (of [`block::Generator`]), each with an associated "RNG" type //! (implementing [`RngCore`]). //! //! These generators are all deterministic and portable (see [Reproducibility] @@ -73,7 +73,7 @@ //! [Seeding RNGs]: https://rust-random.github.io/book/guide-seeding.html //! [Security]: https://rust-random.github.io/book/guide-rngs.html#security //! [Random Values]: https://rust-random.github.io/book/guide-values.html -//! [`BlockRngCore`]: rand_core::block::BlockRngCore +//! [`block::Generator`]: rand_core::block::Generator //! [`RngCore`]: rand_core::RngCore //! [`SeedableRng`]: rand_core::SeedableRng //! [`SysRng`]: https://docs.rs/rand/latest/rand/rngs/struct.SysRng.html From d78703ef777fca0cbe84a0af7b9a94d5c3d63e81 Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Tue, 23 Dec 2025 10:38:32 +0000 Subject: [PATCH 7/7] Update rand --- src/distr/integer.rs | 3 +- src/lib.rs | 2 +- src/rngs/reseeding.rs | 61 +++++++++++++++++----------------- src/rngs/thread.rs | 2 +- src/rngs/xoshiro128plusplus.rs | 9 +++-- src/rngs/xoshiro256plusplus.rs | 7 ++-- 6 files changed, 40 insertions(+), 44 deletions(-) diff --git a/src/distr/integer.rs b/src/distr/integer.rs index b715d443def..f2bfdc56028 100644 --- a/src/distr/integer.rs +++ b/src/distr/integer.rs @@ -112,8 +112,7 @@ impl Distribution<__m128i> for StandardUniform { fn sample(&self, rng: &mut R) -> __m128i { // NOTE: It's tempting to use the u128 impl here, but confusingly this // results in different code (return via rdx, r10 instead of rax, rdx - // with u128 impl) and is much slower (+130 time). This version calls - // le::fill_bytes_via_next but performs well. + // with u128 impl) and is much slower (+130 time). let mut buf = [0_u8; core::mem::size_of::<__m128i>()]; rng.fill_bytes(&mut buf); diff --git a/src/lib.rs b/src/lib.rs index b3530f6b276..e831cf2e812 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -367,7 +367,7 @@ mod test { } fn fill_bytes(&mut self, dst: &mut [u8]) { - rand_core::le::fill_bytes_via_next(self, dst) + rand_core::utils::fill_bytes_via_next_word(dst, || self.next_u64()); } } diff --git a/src/rngs/reseeding.rs b/src/rngs/reseeding.rs index 4eccc799148..67bfe7f1141 100644 --- a/src/rngs/reseeding.rs +++ b/src/rngs/reseeding.rs @@ -12,10 +12,10 @@ use core::mem::size_of_val; -use rand_core::block::{BlockRng, BlockRngCore, CryptoBlockRng}; +use rand_core::block::{BlockRng, CryptoGenerator, Generator}; use rand_core::{CryptoRng, RngCore, SeedableRng, TryCryptoRng, TryRngCore}; -/// A wrapper around any PRNG that implements [`BlockRngCore`], that adds the +/// A wrapper around any PRNG that implements [`Generator`], that adds the /// ability to reseed it. /// /// `ReseedingRng` reseeds the underlying PRNG in the following cases: @@ -53,7 +53,7 @@ use rand_core::{CryptoRng, RngCore, SeedableRng, TryCryptoRng, TryRngCore}; /// /// ``` /// use chacha20::ChaCha20Core; // Internal part of ChaChaRng that -/// // implements BlockRngCore +/// // implements Generator /// use rand::prelude::*; /// use rand::rngs::SysRng; /// use rand::rngs::ReseedingRng; @@ -63,18 +63,18 @@ use rand_core::{CryptoRng, RngCore, SeedableRng, TryCryptoRng, TryRngCore}; /// println!("{}", reseeding_rng.random::()); /// ``` /// -/// [`BlockRngCore`]: rand_core::block::BlockRngCore +/// [`Generator`]: rand_core::block::Generator /// [`ReseedingRng::new`]: ReseedingRng::new /// [`reseed()`]: ReseedingRng::reseed #[derive(Debug)] -pub struct ReseedingRng(BlockRng>) +pub struct ReseedingRng(BlockRng>) where - R: BlockRngCore + SeedableRng, + G: Generator + SeedableRng, Rsdr: TryRngCore; -impl ReseedingRng +impl ReseedingRng where - R: BlockRngCore + SeedableRng, + G: Generator + SeedableRng, Rsdr: TryRngCore, { /// Create a new `ReseedingRng` from an existing PRNG, combined with a RNG @@ -100,19 +100,19 @@ where // TODO: this should be implemented for any type where the inner type // implements RngCore, but we can't specify that because ReseedingCore is private -impl RngCore for ReseedingRng +impl RngCore for ReseedingRng where - R: BlockRngCore + SeedableRng, + G: Generator + SeedableRng, Rsdr: TryRngCore, { #[inline(always)] fn next_u32(&mut self) -> u32 { - self.0.next_u32() + self.0.next_word() } #[inline(always)] fn next_u64(&mut self) -> u64 { - self.0.next_u64() + self.0.next_u64_from_u32() } fn fill_bytes(&mut self, dest: &mut [u8]) { @@ -120,51 +120,50 @@ where } } -impl CryptoRng for ReseedingRng +impl CryptoRng for ReseedingRng where - R: BlockRngCore + SeedableRng + CryptoBlockRng, + G: Generator + SeedableRng + CryptoGenerator, Rsdr: TryCryptoRng, { } #[derive(Debug)] -struct ReseedingCore { - inner: R, +struct ReseedingCore { + inner: G, reseeder: Rsdr, threshold: i64, bytes_until_reseed: i64, } -impl BlockRngCore for ReseedingCore +impl Generator for ReseedingCore where - R: BlockRngCore + SeedableRng, + G: Generator + SeedableRng, Rsdr: TryRngCore, { - type Item = ::Item; - type Results = ::Results; + type Output = ::Output; - fn generate(&mut self, results: &mut Self::Results) { + fn generate(&mut self, results: &mut Self::Output) { if self.bytes_until_reseed <= 0 { // We get better performance by not calling only `reseed` here // and continuing with the rest of the function, but by directly // returning from a non-inlined function. return self.reseed_and_generate(results); } - let num_bytes = size_of_val(results.as_ref()); + let num_bytes = size_of_val(results); self.bytes_until_reseed -= num_bytes as i64; self.inner.generate(results); } } -impl ReseedingCore +impl ReseedingCore where - R: BlockRngCore + SeedableRng, + G: Generator + SeedableRng, Rsdr: TryRngCore, { /// Create a new `ReseedingCore`. /// /// `threshold` is the maximum number of bytes produced by - /// [`BlockRngCore::generate`] before attempting reseeding. + /// [`Generator::generate`] before attempting reseeding. fn new(threshold: u64, mut reseeder: Rsdr) -> Result { // Because generating more values than `i64::MAX` takes centuries on // current hardware, we just clamp to that value. @@ -178,7 +177,7 @@ where i64::MAX }; - let inner = R::try_from_rng(&mut reseeder)?; + let inner = G::try_from_rng(&mut reseeder)?; Ok(ReseedingCore { inner, @@ -190,17 +189,17 @@ where /// Reseed the internal PRNG. fn reseed(&mut self) -> Result<(), Rsdr::Error> { - R::try_from_rng(&mut self.reseeder).map(|result| { + G::try_from_rng(&mut self.reseeder).map(|result| { self.bytes_until_reseed = self.threshold; self.inner = result }) } #[inline(never)] - fn reseed_and_generate(&mut self, results: &mut ::Results) { + fn reseed_and_generate(&mut self, results: &mut G::Output) { trace!("Reseeding RNG (periodic reseed)"); - let num_bytes = size_of_val(results.as_ref()); + let num_bytes = size_of_val(results); if let Err(e) = self.reseed() { warn!("Reseeding RNG failed: {}", e); @@ -212,9 +211,9 @@ where } } -impl CryptoBlockRng for ReseedingCore +impl CryptoGenerator for ReseedingCore where - R: BlockRngCore + SeedableRng + CryptoBlockRng, + G: Generator + SeedableRng + CryptoGenerator, Rsdr: TryCryptoRng, { } diff --git a/src/rngs/thread.rs b/src/rngs/thread.rs index cccb4ad927b..ef6db822446 100644 --- a/src/rngs/thread.rs +++ b/src/rngs/thread.rs @@ -13,7 +13,7 @@ use std::fmt; use std::rc::Rc; use std::thread_local; -use super::{SysError, SysRng, ReseedingRng, std::Core}; +use super::{ReseedingRng, SysError, SysRng, std::Core}; use rand_core::{CryptoRng, RngCore}; // Rationale for using `UnsafeCell` in `ThreadRng`: diff --git a/src/rngs/xoshiro128plusplus.rs b/src/rngs/xoshiro128plusplus.rs index 5d6b9318c5e..1e8713db2e9 100644 --- a/src/rngs/xoshiro128plusplus.rs +++ b/src/rngs/xoshiro128plusplus.rs @@ -6,7 +6,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use rand_core::{RngCore, SeedableRng, le}; +use rand_core::{RngCore, SeedableRng, utils}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; @@ -31,8 +31,7 @@ impl SeedableRng for Xoshiro128PlusPlus { /// mapped to a different seed. #[inline] fn from_seed(seed: [u8; 16]) -> Xoshiro128PlusPlus { - let mut state = [0; 4]; - le::read_u32_into(&seed, &mut state); + let state = utils::read_words(&seed); // Check for zero on aligned integers for better code generation. // Furtermore, seed_from_u64(0) will expand to a constant when optimized. if state.iter().all(|&x| x == 0) { @@ -88,12 +87,12 @@ impl RngCore for Xoshiro128PlusPlus { #[inline] fn next_u64(&mut self) -> u64 { - le::next_u64_via_u32(self) + utils::next_u64_via_u32(self) } #[inline] fn fill_bytes(&mut self, dst: &mut [u8]) { - le::fill_bytes_via_next(self, dst) + utils::fill_bytes_via_next_word(dst, || self.next_u32()); } } diff --git a/src/rngs/xoshiro256plusplus.rs b/src/rngs/xoshiro256plusplus.rs index 4ef433abe12..b9615741501 100644 --- a/src/rngs/xoshiro256plusplus.rs +++ b/src/rngs/xoshiro256plusplus.rs @@ -6,7 +6,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use rand_core::{RngCore, SeedableRng, le}; +use rand_core::{RngCore, SeedableRng, utils}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; @@ -31,8 +31,7 @@ impl SeedableRng for Xoshiro256PlusPlus { /// mapped to a different seed. #[inline] fn from_seed(seed: [u8; 32]) -> Xoshiro256PlusPlus { - let mut state = [0; 4]; - le::read_u64_into(&seed, &mut state); + let state = utils::read_words(&seed); // Check for zero on aligned integers for better code generation. // Furtermore, seed_from_u64(0) will expand to a constant when optimized. if state.iter().all(|&x| x == 0) { @@ -95,7 +94,7 @@ impl RngCore for Xoshiro256PlusPlus { #[inline] fn fill_bytes(&mut self, dst: &mut [u8]) { - le::fill_bytes_via_next(self, dst) + utils::fill_bytes_via_next_word(dst, || self.next_u64()); } }