Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rename Rng -> RngExt, RngCore -> Rng #1288

Closed
wants to merge 1 commit into from
Closed
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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

A Rust library for random number generation, featuring:

- Easy random value generation and usage via the [`Rng`](https://docs.rs/rand/*/rand/trait.Rng.html),
- Easy random value generation and usage via the [`RngExt`](https://docs.rs/rand/*/rand/trait.RngExt.html),
[`SliceRandom`](https://docs.rs/rand/*/rand/seq/trait.SliceRandom.html) and
[`IteratorRandom`](https://docs.rs/rand/*/rand/seq/trait.IteratorRandom.html) traits
- Secure seeding via the [`getrandom` crate](https://crates.io/crates/getrandom)
Expand Down Expand Up @@ -82,7 +82,7 @@ and breaking releases are infrequent.

Rand libs have inter-dependencies and make use of the
[semver trick](https://github.com/dtolnay/semver-trick/) in order to make traits
compatible across crate versions. (This is especially important for `RngCore`
compatible across crate versions. (This is especially important for `Rng`
and `SeedableRng`.) A few crate releases are thus compatibility shims,
depending on the *next* lib version (e.g. `rand_core` versions `0.2.2` and
`0.3.1`). This means, for example, that `rand_core_0_4_0::SeedableRng` and
Expand Down
10 changes: 5 additions & 5 deletions benches/seq_choose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,36 +22,36 @@ pub fn bench(c: &mut Criterion) {
bench_rng::<rand_pcg::Pcg64>(c, "Pcg64");
}

fn bench_rng<Rng: RngCore + SeedableRng>(c: &mut Criterion, rng_name: &'static str) {
fn bench_rng<R: Rng + SeedableRng>(c: &mut Criterion, rng_name: &'static str) {
for length in [1, 2, 3, 10, 100, 1000].map(|x| black_box(x)) {
c.bench_function(
format!("choose_size-hinted_from_{length}_{rng_name}").as_str(),
|b| {
let mut rng = Rng::seed_from_u64(123);
let mut rng = R::seed_from_u64(123);
b.iter(|| choose_size_hinted(length, &mut rng))
},
);

c.bench_function(
format!("choose_stable_from_{length}_{rng_name}").as_str(),
|b| {
let mut rng = Rng::seed_from_u64(123);
let mut rng = R::seed_from_u64(123);
b.iter(|| choose_stable(length, &mut rng))
},
);

c.bench_function(
format!("choose_unhinted_from_{length}_{rng_name}").as_str(),
|b| {
let mut rng = Rng::seed_from_u64(123);
let mut rng = R::seed_from_u64(123);
b.iter(|| choose_unhinted(length, &mut rng))
},
);

c.bench_function(
format!("choose_windowed_from_{length}_{rng_name}").as_str(),
|b| {
let mut rng = Rng::seed_from_u64(123);
let mut rng = R::seed_from_u64(123);
b.iter(|| choose_windowed(length, 7, &mut rng))
},
);
Expand Down
6 changes: 3 additions & 3 deletions benches/shuffle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ pub fn bench(c: &mut Criterion) {
bench_rng::<rand_pcg::Pcg64>(c, "Pcg64");
}

fn bench_rng<Rng: RngCore + SeedableRng>(c: &mut Criterion, rng_name: &'static str) {
fn bench_rng<R: Rng + SeedableRng>(c: &mut Criterion, rng_name: &'static str) {
for length in [1, 2, 3, 10, 100, 1000, 10000].map(|x| black_box(x)) {
c.bench_function(format!("shuffle_{length}_{rng_name}").as_str(), |b| {
let mut rng = Rng::seed_from_u64(123);
let mut rng = R::seed_from_u64(123);
let mut vec: Vec<usize> = (0..length).collect();
b.iter(|| {
vec.shuffle(&mut rng);
Expand All @@ -37,7 +37,7 @@ fn bench_rng<Rng: RngCore + SeedableRng>(c: &mut Criterion, rng_name: &'static s
c.bench_function(
format!("partial_shuffle_{length}_{rng_name}").as_str(),
|b| {
let mut rng = Rng::seed_from_u64(123);
let mut rng = R::seed_from_u64(123);
let mut vec: Vec<usize> = (0..length).collect();
b.iter(|| {
vec.partial_shuffle(&mut rng, length / 2);
Expand Down
2 changes: 1 addition & 1 deletion benches/weighted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
extern crate test;

use rand::distributions::WeightedIndex;
use rand::Rng;
use rand::RngExt;
use test::Bencher;

#[bench]
Expand Down
2 changes: 1 addition & 1 deletion examples/monty-hall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
#![cfg(all(feature = "std", feature = "std_rng"))]

use rand::distributions::{Distribution, Uniform};
use rand::Rng;
use rand::{Rng, RngExt};

struct SimulationResult {
win: bool,
Expand Down
2 changes: 1 addition & 1 deletion examples/rayon-monte-carlo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
//!
//! Instead, we do our own batching, so that a Rayon work item becomes a
//! batch. Then we can fix our rng stream to the batched work item.
//! Batching amortizes the cost of constructing the Rng from a fixed seed
//! Batching amortizes the cost of constructing the RNG from a fixed seed
//! over BATCH_SIZE trials. Manually batching also turns out to be faster
//! for the nondeterministic version of this program as well.

Expand Down
8 changes: 4 additions & 4 deletions rand_chacha/src/chacha.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use self::core::fmt;
use crate::guts::ChaCha;
use rand_core::block::{BlockRng, BlockRngCore, CryptoBlockRng};
use rand_core::{CryptoRng, Error, RngCore, SeedableRng};
use rand_core::{CryptoRng, Error, Rng, SeedableRng};

#[cfg(feature = "serde1")] use serde::{Serialize, Deserialize, Serializer, Deserializer};

Expand Down Expand Up @@ -132,7 +132,7 @@ macro_rules! chacha_impl {
/// ```
///
/// This implementation uses an output buffer of sixteen `u32` words, and uses
/// [`BlockRng`] to implement the [`RngCore`] methods.
/// [`BlockRng`] to implement the [`Rng`] methods.
///
/// [^1]: D. J. Bernstein, [*ChaCha, a variant of Salsa20*](
/// https://cr.yp.to/chacha.html)
Expand All @@ -155,7 +155,7 @@ macro_rules! chacha_impl {
}
}

impl RngCore for $ChaChaXRng {
impl Rng for $ChaChaXRng {
#[inline]
fn next_u32(&mut self) -> u32 {
self.rng.next_u32()
Expand Down Expand Up @@ -340,7 +340,7 @@ chacha_impl!(ChaCha8Core, ChaCha8Rng, 4, "ChaCha with 8 rounds", abstract8);

#[cfg(test)]
mod test {
use rand_core::{RngCore, SeedableRng};
use rand_core::{Rng, SeedableRng};

#[cfg(feature = "serde1")] use super::{ChaCha20Rng, ChaCha12Rng, ChaCha8Rng};

Expand Down
10 changes: 5 additions & 5 deletions rand_core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
Core traits and error types of the [rand] library, plus tools for implementing
RNGs.

This crate is intended for use when implementing the core trait, `RngCore`; it
This crate is intended for use when implementing the core trait, `Rng`; it
defines the core traits to be implemented as well as several small functions to
aid in their implementation and types required for error handling.

The main [rand] crate re-exports most items defined in this crate, along with
tools to convert the integer samples generated by `RngCore` to many different
tools to convert the integer samples generated by `Rng` to many different
applications (including sampling from restricted ranges, conversion to floating
point, list permutations and secure initialisation of RNGs). Most users should
prefer to use the main [rand] crate.
Expand Down Expand Up @@ -48,7 +48,7 @@ rand_core = "0.6.4"

Rand libs have inter-dependencies and make use of the
[semver trick](https://github.com/dtolnay/semver-trick/) in order to make traits
compatible across crate versions. (This is especially important for `RngCore`
compatible across crate versions. (This is especially important for `Rng`
and `SeedableRng`.) A few crate releases are thus compatibility shims,
depending on the *next* lib version (e.g. `rand_core` versions `0.2.2` and
`0.3.1`). This means, for example, that `rand_core_0_4_0::SeedableRng` and
Expand All @@ -59,8 +59,8 @@ cause build errors. Usually, running `cargo update` is enough to fix any issues.

`rand_core` supports `no_std` and `alloc`-only configurations, as well as full
`std` functionality. The differences between `no_std` and full `std` are small,
comprising `RngCore` support for `Box<R>` types where `R: RngCore`,
`std::io::Read` support for types supporting `RngCore`, and
comprising `Rng` support for `Box<R>` types where `R: Rng`,
`std::io::Read` support for types supporting `Rng`, and
extensions to the `Error` type's functionality.

The `std` feature is *not enabled by default*. This is primarily to avoid build
Expand Down
44 changes: 22 additions & 22 deletions rand_core/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@
//!
//! Usage of this trait is optional, but provides two advantages:
//! implementations only need to concern themselves with generation of the
//! block, not the various [`RngCore`] methods (especially [`fill_bytes`], where
//! block, not the various [`Rng`] methods (especially [`fill_bytes`], where
//! the optimal implementations are not trivial), and this allows
//! `ReseedingRng` (see [`rand`](https://docs.rs/rand) crate) perform periodic
//! reseeding with very low overhead.
//!
//! # Example
//!
//! ```no_run
//! use rand_core::{RngCore, SeedableRng};
//! use rand_core::{Rng, SeedableRng};
//! use rand_core::block::{BlockRngCore, BlockRng};
//!
//! struct MyRngCore;
Expand Down Expand Up @@ -51,10 +51,10 @@
//! ```
//!
//! [`BlockRngCore`]: crate::block::BlockRngCore
//! [`fill_bytes`]: RngCore::fill_bytes
//! [`fill_bytes`]: Rng::fill_bytes

use crate::impls::{fill_via_u32_chunks, fill_via_u64_chunks};
use crate::{Error, CryptoRng, RngCore, SeedableRng};
use crate::{Error, CryptoRng, Rng, SeedableRng};
use core::convert::AsRef;
use core::fmt;
#[cfg(feature = "serde1")]
Expand All @@ -77,25 +77,25 @@ pub trait BlockRngCore {
fn generate(&mut self, results: &mut Self::Results);
}

/// A marker trait used to indicate that an [`RngCore`] implementation is
/// A marker trait used to indicate that an [`Rng`] implementation is
/// supposed to be cryptographically secure.
///
/// See [`CryptoRng`][crate::CryptoRng] docs for more information.
pub trait CryptoBlockRng: BlockRngCore { }

/// A wrapper type implementing [`RngCore`] for some type implementing
/// A wrapper type implementing [`Rng`] for some type implementing
/// [`BlockRngCore`] with `u32` array buffer; i.e. this can be used to implement
/// a full RNG from just a `generate` function.
///
/// The `core` field may be accessed directly but the results buffer may not.
/// PRNG implementations can simply use a type alias
/// (`pub type MyRng = BlockRng<MyRngCore>;`) but might prefer to use a
/// wrapper type (`pub struct MyRng(BlockRng<MyRngCore>);`); the latter must
/// re-implement `RngCore` but hides the implementation details and allows
/// re-implement `Rng` but hides the implementation details and allows
/// extra functionality to be defined on the RNG
/// (e.g. `impl MyRng { fn set_stream(...){...} }`).
///
/// `BlockRng` has heavily optimized implementations of the [`RngCore`] methods
/// `BlockRng` has heavily optimized implementations of the [`Rng`] methods
/// reading values from the results buffer, as well as
/// calling [`BlockRngCore::generate`] directly on the output array when
/// [`fill_bytes`] / [`try_fill_bytes`] is called on a large array. These methods
Expand All @@ -114,10 +114,10 @@ pub trait CryptoBlockRng: BlockRngCore { }
///
/// For easy initialization `BlockRng` also implements [`SeedableRng`].
///
/// [`next_u32`]: RngCore::next_u32
/// [`next_u64`]: RngCore::next_u64
/// [`fill_bytes`]: RngCore::fill_bytes
/// [`try_fill_bytes`]: RngCore::try_fill_bytes
/// [`next_u32`]: Rng::next_u32
/// [`next_u64`]: Rng::next_u64
/// [`fill_bytes`]: Rng::fill_bytes
/// [`try_fill_bytes`]: Rng::try_fill_bytes
#[derive(Clone)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
#[cfg_attr(
Expand Down Expand Up @@ -184,7 +184,7 @@ impl<R: BlockRngCore> BlockRng<R> {
}
}

impl<R: BlockRngCore<Item = u32>> RngCore for BlockRng<R> {
impl<R: BlockRngCore<Item = u32>> Rng for BlockRng<R> {
#[inline]
fn next_u32(&mut self) -> u32 {
if self.index >= self.results.as_ref().len() {
Expand Down Expand Up @@ -257,14 +257,14 @@ impl<R: BlockRngCore + SeedableRng> SeedableRng for BlockRng<R> {
}

#[inline(always)]
fn from_rng<S: RngCore>(rng: S) -> Result<Self, Error> {
fn from_rng<S: Rng>(rng: S) -> Result<Self, Error> {
Ok(Self::new(R::from_rng(rng)?))
}
}

impl<R: CryptoBlockRng + BlockRngCore<Item = u32>> CryptoRng for BlockRng<R> {}

/// A wrapper type implementing [`RngCore`] for some type implementing
/// A wrapper type implementing [`Rng`] for some type implementing
/// [`BlockRngCore`] with `u64` array buffer; i.e. this can be used to implement
/// a full RNG from just a `generate` function.
///
Expand All @@ -282,10 +282,10 @@ impl<R: CryptoBlockRng + BlockRngCore<Item = u32>> CryptoRng for BlockRng<R> {}
/// values. If the requested length is not a multiple of 8, some bytes will be
/// discarded.
///
/// [`next_u32`]: RngCore::next_u32
/// [`next_u64`]: RngCore::next_u64
/// [`fill_bytes`]: RngCore::fill_bytes
/// [`try_fill_bytes`]: RngCore::try_fill_bytes
/// [`next_u32`]: Rng::next_u32
/// [`next_u64`]: Rng::next_u64
/// [`fill_bytes`]: Rng::fill_bytes
/// [`try_fill_bytes`]: Rng::try_fill_bytes
#[derive(Clone)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct BlockRng64<R: BlockRngCore + ?Sized> {
Expand Down Expand Up @@ -351,7 +351,7 @@ impl<R: BlockRngCore> BlockRng64<R> {
}
}

impl<R: BlockRngCore<Item = u64>> RngCore for BlockRng64<R> {
impl<R: BlockRngCore<Item = u64>> Rng for BlockRng64<R> {
#[inline]
fn next_u32(&mut self) -> u32 {
let mut index = self.index - self.half_used as usize;
Expand Down Expand Up @@ -425,7 +425,7 @@ impl<R: BlockRngCore + SeedableRng> SeedableRng for BlockRng64<R> {
}

#[inline(always)]
fn from_rng<S: RngCore>(rng: S) -> Result<Self, Error> {
fn from_rng<S: Rng>(rng: S) -> Result<Self, Error> {
Ok(Self::new(R::from_rng(rng)?))
}
}
Expand All @@ -434,7 +434,7 @@ impl<R: CryptoBlockRng + BlockRngCore<Item = u64>> CryptoRng for BlockRng64<R> {

#[cfg(test)]
mod test {
use crate::{SeedableRng, RngCore};
use crate::{SeedableRng, Rng};
use crate::block::{BlockRng, BlockRng64, BlockRngCore};

#[derive(Debug, Clone)]
Expand Down
12 changes: 6 additions & 6 deletions rand_core/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Helper functions for implementing `RngCore` functions.
//! Helper functions for implementing `Rng` functions.
//!
//! For cross-platform reproducibility, these functions all use Little Endian:
//! least-significant part first. For example, `next_u64_via_u32` takes `u32`
Expand All @@ -17,11 +17,11 @@
//! to/from byte sequences, and since its purpose is reproducibility,
//! non-reproducible sources (e.g. `OsRng`) need not bother with it.

use crate::RngCore;
use crate::Rng;
use core::cmp::min;

/// Implement `next_u64` via `next_u32`, little-endian order.
pub fn next_u64_via_u32<R: RngCore + ?Sized>(rng: &mut R) -> u64 {
pub fn next_u64_via_u32<R: Rng + ?Sized>(rng: &mut R) -> u64 {
// Use LE; we explicitly generate one value before the next.
let x = u64::from(rng.next_u32());
let y = u64::from(rng.next_u32());
Expand All @@ -34,7 +34,7 @@ pub fn next_u64_via_u32<R: RngCore + ?Sized>(rng: &mut R) -> u64 {
/// integers. That is why this method mostly uses `next_u64`, and only when
/// there are 4 or less bytes remaining at the end of the slice it uses
/// `next_u32` once.
pub fn fill_bytes_via_next<R: RngCore + ?Sized>(rng: &mut R, dest: &mut [u8]) {
pub fn fill_bytes_via_next<R: Rng + ?Sized>(rng: &mut R, dest: &mut [u8]) {
let mut left = dest;
while left.len() >= 8 {
let (l, r) = { left }.split_at_mut(8);
Expand Down Expand Up @@ -159,14 +159,14 @@ pub fn fill_via_u64_chunks(src: &mut [u64], dest: &mut [u8]) -> (usize, usize) {
}

/// Implement `next_u32` via `fill_bytes`, little-endian order.
pub fn next_u32_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u32 {
pub fn next_u32_via_fill<R: Rng + ?Sized>(rng: &mut R) -> u32 {
let mut buf = [0; 4];
rng.fill_bytes(&mut buf);
u32::from_le_bytes(buf)
}

/// Implement `next_u64` via `fill_bytes`, little-endian order.
pub fn next_u64_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u64 {
pub fn next_u64_via_fill<R: Rng + ?Sized>(rng: &mut R) -> u64 {
let mut buf = [0; 8];
rng.fill_bytes(&mut buf);
u64::from_le_bytes(buf)
Expand Down
Loading