Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,8 @@ jobs:
cargo test --target ${{ matrix.target }} --features=serde,log,small_rng
- name: Test rand_core
run: |
cargo test --target ${{ matrix.target }} --manifest-path rand_core/Cargo.toml
cargo test --target ${{ matrix.target }} --manifest-path rand_core/Cargo.toml --no-default-features
cargo test --target ${{ matrix.target }} --manifest-path rand_core/Cargo.toml --no-default-features --features=os_rng
cargo test --target ${{ matrix.target }} --manifest-path rand_core/Cargo.toml --features serde
- name: Test rand_pcg
run: cargo test --target ${{ matrix.target }} --manifest-path rand_pcg/Cargo.toml --features=serde
- name: Test rand_chacha
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.
- Rename fns `IndexedRandom::choose_multiple` -> `sample`, `choose_multiple_array` -> `sample_array`, `choose_multiple_weighted` -> `sample_weighted`, struct `SliceChooseIter` -> `IndexedSamples` and fns `IteratorRandom::choose_multiple` -> `sample`, `choose_multiple_fill` -> `sample_fill` (#1632)
- Use Edition 2024 and MSRV 1.85 (#1653)
- Let `Fill` be implemented for element types, not sliceable types (#1652)
- Fix `OsError::raw_os_error` on UEFI targets by returning `Option<usize>` (#1665)
- Replace fn `TryRngCore::read_adapter(..) -> RngReadAdapter` with simpler struct `RngReader` (#1669)
- Remove fns `SeedableRng::from_os_rng`, `try_from_os_rng` (#1674)

### Additions
- Add fns `IndexedRandom::choose_iter`, `choose_weighted_iter` (#1632)
Expand Down
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ serde = ["dep:serde", "rand_core/serde"]

# Option (enabled by default): without "std" rand uses libcore; this option
# enables functionality expected to be available on a standard platform.
std = ["rand_core/std", "alloc"]
std = ["alloc", "getrandom?/std"]

# Option: "alloc" enables support for Vec and Box when not using "std"
alloc = []

# Option: enable OsRng
os_rng = ["rand_core/os_rng"]
os_rng = ["dep:getrandom"]

# Option (requires nightly Rust): experimental SIMD support
simd_support = []
Expand Down Expand Up @@ -83,6 +83,7 @@ rand_core = { path = "rand_core", version = "0.9.0", 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.2", default-features = false, features = ["rng"], optional = true }
getrandom = { version = "0.3.0", optional = true }

[dev-dependencies]
rand_pcg = { path = "rand_pcg", version = "0.9.0" }
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ 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` and `from_os_rng` are
`default-features = false`). In this case, `OsRng` is
unavailable (unless `os_rng` is enabled), large parts of `seq` are
unavailable (unless `alloc` is enabled), and `ThreadRng` is unavailable.

Expand Down
3 changes: 1 addition & 2 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ used according to these additional constraints:

- Via `SeedableRng::from_seed` using a cryptographically secure seed value
- Via `SeedableRng::from_rng` or `try_from_rng` using a cryptographically
secure source `rng`
- Via `SeedableRng::from_os_rng` or `try_from_os_rng`
secure source `rng` such as `OsRng` or `ThreadRng`.
- The state (memory) of the generator and its seed value (or source `rng`) are
not exposed

Expand Down
1 change: 1 addition & 0 deletions rand_chacha/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [0.10.0] - UNRELEASED
### Changed
- Bump MSRV to 1.85 and edition to 2024 (#1671)
- Remove feature `os_rng` (#1674)

## [0.9.0] - 2025-01-27
### Dependencies and features
Expand Down
6 changes: 3 additions & 3 deletions rand_chacha/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ serde = { version = "1.0", features = ["derive"], optional = true }
[dev-dependencies]
# Only to test serde
serde_json = "1.0.120"
rand_core = { path = "../rand_core", version = "0.9.0", features = ["os_rng"] }
rand_core = { path = "../rand_core", version = "0.9.0" }
rand = { path = "..", version = "0.10.0-rc.0" }

[features]
default = ["std"]
os_rng = ["rand_core/os_rng"]
std = ["ppv-lite86/std", "rand_core/std"]
std = ["ppv-lite86/std"]
serde = ["dep:serde"]
3 changes: 1 addition & 2 deletions rand_chacha/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ Links:

`rand_chacha` is `no_std` compatible when disabling default features; the `std`
feature can be explicitly required to re-enable `std` support. Using `std`
allows detection of CPU features and thus better optimisation. Using `std`
also enables `os_rng` functionality, such as `ChaCha20Rng::from_os_rng()`.
allows detection of CPU features and thus better optimisation.


# License
Expand Down
8 changes: 4 additions & 4 deletions rand_chacha/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
//!
//! Where secure unpredictable generators are required, it is suggested to use
//! [`ChaCha12Rng`] or [`ChaCha20Rng`] and to seed via
//! [`SeedableRng::from_os_rng`].
//! [`OsRng`].
//!
//! 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.
Expand All @@ -37,8 +37,8 @@
//!
//! 1. With a fresh seed, **direct from the OS** (implies a syscall):
//! ```
//! # use {rand_core::SeedableRng, rand_chacha::ChaCha12Rng};
//! let rng = ChaCha12Rng::from_os_rng();
//! # use {rand_core::SeedableRng, rand_chacha::ChaCha12Rng, rand::rngs::OsRng};
//! let rng = ChaCha12Rng::try_from_rng(&mut OsRng).unwrap();
//! # let _: ChaCha12Rng = rng;
//! ```
//! 2. **From a master generator.** This could be [`rand::rng`]
Expand Down Expand Up @@ -76,7 +76,7 @@
//! [`BlockRngCore`]: rand_core::block::BlockRngCore
//! [`RngCore`]: rand_core::RngCore
//! [`SeedableRng`]: rand_core::SeedableRng
//! [`SeedableRng::from_os_rng`]: rand_core::SeedableRng::from_os_rng
//! [`OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html
//! [`rand::rng`]: https://docs.rs/rand/latest/rand/fn.rng.html
//! [`rand::Rng`]: https://docs.rs/rand/latest/rand/trait.Rng.html

Expand Down
4 changes: 3 additions & 1 deletion rand_core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## Unreleased
### API changes
- Relax `Sized` bound on impls of `SeedableRng` (#1641)
- Fix `OsError::raw_os_error` on UEFI targets by returning `Option<usize>` (#1665)
- Move `rand_core::impls::*` to `rand_core::le` module (#1667)
- Use Edition 2024 and MSRV 1.85 (#1668)
- Remove fn `TryRngCore::read_adapter(..) -> RngReadAdapter` (replaced with `rand::RngReader`) (#1669)
- 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)

## [0.9.3] — 2025-02-29
### Other
Expand Down
3 changes: 0 additions & 3 deletions rand_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@ rustdoc-args = ["--generate-link-to-definition"]
all-features = true

[features]
std = ["getrandom?/std"]
os_rng = ["dep:getrandom"]
serde = ["dep:serde"] # enables serde for BlockRng wrapper

[dependencies]
serde = { version = "1", features = ["derive"], optional = true }
getrandom = { version = "0.3.0", optional = true }
56 changes: 6 additions & 50 deletions rand_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,10 @@
#![cfg_attr(docsrs, feature(doc_cfg))]
#![no_std]

#[cfg(feature = "std")]
extern crate std;

use core::{fmt, ops::DerefMut};

pub mod block;
pub mod le;
#[cfg(feature = "os_rng")]
mod os;

#[cfg(feature = "os_rng")]
pub use os::{OsError, OsRng};

/// Implementation-level interface for RNGs
///
Expand Down Expand Up @@ -168,6 +160,8 @@ where
/// An optional property of CSPRNGs is backtracking resistance: if the CSPRNG's
/// state is revealed, it will not be computationally-feasible to reconstruct
/// prior output values. This property is not required by `CryptoRng`.
///
/// [`OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html
pub trait CryptoRng: RngCore {}

impl<T: DerefMut> CryptoRng for T where T::Target: CryptoRng {}
Expand All @@ -184,6 +178,8 @@ impl<T: DerefMut> CryptoRng for T where T::Target: CryptoRng {}
/// An implementation of this trait may be made compatible with code requiring
/// an [`RngCore`] through [`TryRngCore::unwrap_err`]. The resulting RNG will
/// panic in case the underlying fallible RNG yields an error.
///
/// [`OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html
pub trait TryRngCore {
/// The type returned in the event of a RNG error.
type Error: fmt::Debug + fmt::Display;
Expand Down Expand Up @@ -246,6 +242,8 @@ impl<R: RngCore + ?Sized> TryRngCore for R {
/// `default()` instances are themselves secure generators: for example if the
/// implementing type is a stateless interface over a secure external generator
/// (like [`OsRng`]) or if the `default()` instance uses a strong, fresh seed.
///
/// [`OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html
pub trait TryCryptoRng: TryRngCore {}

impl<R: CryptoRng + ?Sized> TryCryptoRng for R {}
Expand Down Expand Up @@ -490,48 +488,6 @@ pub trait SeedableRng: Sized {
rng.try_fill_bytes(seed.as_mut())?;
Ok(Self::from_seed(seed))
}

/// Creates a new instance of the RNG seeded via [`getrandom`].
///
/// This method is the recommended way to construct non-deterministic PRNGs
/// since it is convenient and secure.
///
/// Note that this method may panic on (extremely unlikely) [`getrandom`] errors.
/// If it's not desirable, use the [`try_from_os_rng`] method instead.
///
/// In case the overhead of using [`getrandom`] to seed *many* PRNGs is an
/// issue, one may prefer to seed from a local PRNG, e.g.
/// `from_rng(rand::rng()).unwrap()`.
///
/// # Panics
///
/// If [`getrandom`] is unable to provide secure entropy this method will panic.
///
/// [`getrandom`]: https://docs.rs/getrandom
/// [`try_from_os_rng`]: SeedableRng::try_from_os_rng
#[cfg(feature = "os_rng")]
fn from_os_rng() -> Self {
match Self::try_from_os_rng() {
Ok(res) => res,
Err(err) => panic!("from_os_rng failed: {}", err),
}
}

/// Creates a new instance of the RNG seeded via [`getrandom`] without unwrapping
/// potential [`getrandom`] errors.
///
/// In case the overhead of using [`getrandom`] to seed *many* PRNGs is an
/// issue, one may prefer to seed from a local PRNG, e.g.
/// `from_rng(&mut rand::rng()).unwrap()`.
///
/// [`getrandom`]: https://docs.rs/getrandom
#[cfg(feature = "os_rng")]
fn try_from_os_rng() -> Result<Self, getrandom::Error> {
let mut seed = Self::Seed::default();
getrandom::fill(seed.as_mut())?;
let res = Self::from_seed(seed);
Ok(res)
}
}

#[cfg(test)]
Expand Down
1 change: 1 addition & 0 deletions rand_pcg/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [0.10.0 — Unreleased]
### Changes
- Use Edition 2024 and MSRV 1.85 (#1653)
- Remove feature `os_rng` (#1674)

## [0.9.0] - 2025-01-27
### Dependencies and features
Expand Down
3 changes: 1 addition & 2 deletions rand_pcg/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ rustdoc-args = ["--generate-link-to-definition"]

[features]
serde = ["dep:serde"]
os_rng = ["rand_core/os_rng"]

[dependencies]
rand_core = { path = "../rand_core", version = "0.9.0" }
Expand All @@ -32,4 +31,4 @@ serde = { version = "1", features = ["derive"], optional = true }
# deps yet, see: https://github.com/rust-lang/cargo/issues/1596
# Versions prior to 1.1.4 had incorrect minimal dependencies.
bincode = { version = "1.1.4" }
rand_core = { path = "../rand_core", version = "0.9.0", features = ["os_rng"] }
rand_core = { path = "../rand_core", version = "0.9.0" }
5 changes: 4 additions & 1 deletion src/rngs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ 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")]
Expand All @@ -126,4 +129,4 @@ pub use self::thread::ThreadRng;
pub use chacha20::{ChaCha8Rng, ChaCha12Rng, ChaCha20Rng};

#[cfg(feature = "os_rng")]
pub use rand_core::OsRng;
pub use os::{OsError, OsRng};
2 changes: 1 addition & 1 deletion rand_core/src/os.rs → src/rngs/os.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use crate::{TryCryptoRng, TryRngCore};
///
/// # Usage example
/// ```
/// use rand_core::{TryRngCore, OsRng};
/// use rand::{TryRngCore, rngs::OsRng};
///
/// let mut key = [0u8; 16];
/// OsRng.try_fill_bytes(&mut key).unwrap();
Expand Down
7 changes: 0 additions & 7 deletions src/rngs/small.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,6 @@ type Rng = super::xoshiro256plusplus::Xoshiro256PlusPlus;
/// let rng = SmallRng::from_rng(&mut rand::rng());
/// # let _: SmallRng = rng;
/// ```
/// or [`SeedableRng::from_os_rng`]:
/// ```
/// # use rand::SeedableRng;
/// # use rand::rngs::SmallRng;
/// let rng = SmallRng::from_os_rng();
/// # let _: SmallRng = rng;
/// ```
/// 2. To use a deterministic integral seed, use `seed_from_u64`. This uses a
/// hash function internally to yield a (typically) good seed from any
/// input.
Expand Down
4 changes: 2 additions & 2 deletions src/rngs/std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
/// let rng = StdRng::from_os_rng();
/// # use rand::{SeedableRng, rngs::{StdRng, OsRng}};
/// let rng = StdRng::try_from_rng(&mut OsRng).unwrap();
/// # let _: StdRng = rng;
Comment on lines 40 to 44
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is certainly less ergonomic than before, but affected us very little.

Unknown: how much this impacts other users.

/// ```
///
Expand Down
7 changes: 2 additions & 5 deletions src/rngs/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,9 @@ use std::fmt;
use std::rc::Rc;
use std::thread_local;

use super::{OsError, OsRng, ReseedingRng, std::Core};
use rand_core::{CryptoRng, RngCore};

use super::std::Core;
use crate::rngs::OsRng;
use crate::rngs::ReseedingRng;

// Rationale for using `UnsafeCell` in `ThreadRng`:
//
// Previously we used a `RefCell`, with an overhead of ~15%. There will only
Expand Down Expand Up @@ -100,7 +97,7 @@ impl ThreadRng {
/// Immediately reseed the generator
///
/// This discards any remaining random data in the cache.
pub fn reseed(&mut self) -> Result<(), rand_core::OsError> {
pub fn reseed(&mut self) -> Result<(), OsError> {
// SAFETY: We must make sure to stop using `rng` before anyone else
// creates another mutable reference
let rng = unsafe { &mut *self.rng.get() };
Expand Down