Rename Rng::gen to Rng::random (#1438)

This commit is contained in:
Vinzent Steinberg 2024-04-29 20:41:10 +02:00 committed by GitHub
parent 089d99368d
commit 4f8257a986
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 76 additions and 67 deletions

View File

@ -11,6 +11,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.
## [Unreleased]
- Add `rand::distributions::WeightedIndex::{weight, weights, total_weight}` (#1420)
- Bump the MSRV to 1.61.0
- Rename `Rng::gen` to `Rng::random` to avoid conflict with the new `gen` keyword in Rust 2024 (#1435)
- Move all benchmarks to new `benches` crate (#1439)
## [0.9.0-alpha.1] - 2024-03-18

View File

@ -101,7 +101,7 @@ fn gen_1kb_u16_iter_repeat(b: &mut Bencher) {
use core::iter;
let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();
b.iter(|| {
let v: Vec<u16> = iter::repeat(()).map(|()| rng.gen()).take(512).collect();
let v: Vec<u16> = iter::repeat(()).map(|()| rng.random()).take(512).collect();
v
});
b.bytes = 1024;
@ -122,7 +122,7 @@ fn gen_1kb_u16_gen_array(b: &mut Bencher) {
let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();
b.iter(|| {
// max supported array length is 32!
let v: [[u16; 32]; 16] = rng.gen();
let v: [[u16; 32]; 16] = rng.random();
v
});
b.bytes = 1024;
@ -144,7 +144,7 @@ fn gen_1kb_u64_iter_repeat(b: &mut Bencher) {
use core::iter;
let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();
b.iter(|| {
let v: Vec<u64> = iter::repeat(()).map(|()| rng.gen()).take(128).collect();
let v: Vec<u64> = iter::repeat(()).map(|()| rng.random()).take(128).collect();
v
});
b.bytes = 1024;
@ -165,7 +165,7 @@ fn gen_1kb_u64_gen_array(b: &mut Bencher) {
let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();
b.iter(|| {
// max supported array length is 32!
let v: [[u64; 32]; 4] = rng.gen();
let v: [[u64; 32]; 4] = rng.random();
v
});
b.bytes = 1024;

View File

@ -45,7 +45,7 @@ fn simulate<R: Rng>(random_door: &Uniform<u32>, rng: &mut R) -> SimulationResult
let open = game_host_open(car, choice, rng);
// Shall we switch?
let switch = rng.gen();
let switch = rng.random();
if switch {
choice = switch_door(choice, open);
}

View File

@ -136,7 +136,7 @@ impl Distribution<bool> for Bernoulli {
if self.p_int == ALWAYS_TRUE {
return true;
}
let v: u64 = rng.gen();
let v: u64 = rng.random();
v < self.p_int
}
}

View File

@ -115,7 +115,7 @@ macro_rules! float_impls {
let precision = $fraction_bits + 1;
let scale = 1.0 / ((1 as $u_scalar << precision) as $f_scalar);
let value: $uty = rng.gen();
let value: $uty = rng.random();
let value = value >> $uty::splat(float_size - precision);
$ty::splat(scale) * $ty::cast_from_int(value)
}
@ -132,7 +132,7 @@ macro_rules! float_impls {
let precision = $fraction_bits + 1;
let scale = 1.0 / ((1 as $u_scalar << precision) as $f_scalar);
let value: $uty = rng.gen();
let value: $uty = rng.random();
let value = value >> $uty::splat(float_size - precision);
// Add 1 to shift up; will not overflow because of right-shift:
$ty::splat(scale) * $ty::cast_from_int(value + $uty::splat(1))
@ -149,7 +149,7 @@ macro_rules! float_impls {
use core::$f_scalar::EPSILON;
let float_size = mem::size_of::<$f_scalar>() as $u_scalar * 8;
let value: $uty = rng.gen();
let value: $uty = rng.random();
let fraction = value >> $uty::splat(float_size - $fraction_bits);
fraction.into_float_with_exponent(0) - $ty::splat(1.0 - EPSILON / 2.0)
}
@ -192,11 +192,11 @@ mod tests {
// Standard
let mut zeros = StepRng::new(0, 0);
assert_eq!(zeros.gen::<$ty>(), $ZERO);
assert_eq!(zeros.random::<$ty>(), $ZERO);
let mut one = StepRng::new(1 << 8 | 1 << (8 + 32), 0);
assert_eq!(one.gen::<$ty>(), $EPSILON / two);
assert_eq!(one.random::<$ty>(), $EPSILON / two);
let mut max = StepRng::new(!0, 0);
assert_eq!(max.gen::<$ty>(), $ty::splat(1.0) - $EPSILON / two);
assert_eq!(max.random::<$ty>(), $ty::splat(1.0) - $EPSILON / two);
// OpenClosed01
let mut zeros = StepRng::new(0, 0);
@ -234,11 +234,11 @@ mod tests {
// Standard
let mut zeros = StepRng::new(0, 0);
assert_eq!(zeros.gen::<$ty>(), $ZERO);
assert_eq!(zeros.random::<$ty>(), $ZERO);
let mut one = StepRng::new(1 << 11, 0);
assert_eq!(one.gen::<$ty>(), $EPSILON / two);
assert_eq!(one.random::<$ty>(), $EPSILON / two);
let mut max = StepRng::new(!0, 0);
assert_eq!(max.gen::<$ty>(), $ty::splat(1.0) - $EPSILON / two);
assert_eq!(max.random::<$ty>(), $ty::splat(1.0) - $EPSILON / two);
// OpenClosed01
let mut zeros = StepRng::new(0, 0);

View File

@ -81,7 +81,7 @@ macro_rules! impl_int_from_uint {
impl Distribution<$ty> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $ty {
rng.gen::<$uty>() as $ty
rng.random::<$uty>() as $ty
}
}
};
@ -99,7 +99,7 @@ macro_rules! impl_nzint {
impl Distribution<$ty> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $ty {
loop {
if let Some(nz) = $new(rng.gen()) {
if let Some(nz) = $new(rng.random()) {
break nz;
}
}

View File

@ -11,7 +11,7 @@
//!
//! This module is the home of the [`Distribution`] trait and several of its
//! implementations. It is the workhorse behind some of the convenient
//! functionality of the [`Rng`] trait, e.g. [`Rng::gen`] and of course
//! functionality of the [`Rng`] trait, e.g. [`Rng::random`] and of course
//! [`Rng::sample`].
//!
//! Abstractly, a [probability distribution] describes the probability of
@ -31,13 +31,13 @@
//! # The `Standard` distribution
//!
//! The [`Standard`] distribution is important to mention. This is the
//! distribution used by [`Rng::gen`] and represents the "default" way to
//! distribution used by [`Rng::random`] and represents the "default" way to
//! produce a random value for many different types, including most primitive
//! types, tuples, arrays, and a few derived types. See the documentation of
//! [`Standard`] for more details.
//!
//! Implementing `Distribution<T>` for [`Standard`] for user types `T` makes it
//! possible to generate type `T` with [`Rng::gen`], and by extension also
//! possible to generate type `T` with [`Rng::random`], and by extension also
//! with the [`random`] function.
//!
//! ## Random characters
@ -181,7 +181,7 @@ use crate::Rng;
///
/// impl Distribution<MyF32> for Standard {
/// fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> MyF32 {
/// MyF32 { x: rng.gen() }
/// MyF32 { x: rng.random() }
/// }
/// }
/// ```

View File

@ -156,10 +156,10 @@ impl Distribution<bool> for Standard {
///
/// ```ignore
/// // this may be faster...
/// let x = unsafe { _mm_blendv_epi8(a.into(), b.into(), rng.gen::<__m128i>()) };
/// let x = unsafe { _mm_blendv_epi8(a.into(), b.into(), rng.random::<__m128i>()) };
///
/// // ...than this
/// let x = rng.gen::<mask8x16>().select(b, a);
/// let x = rng.random::<mask8x16>().select(b, a);
/// ```
///
/// Since most bits are unused you could also generate only as many bits as you need, i.e.:
@ -169,7 +169,7 @@ impl Distribution<bool> for Standard {
/// use rand::prelude::*;
/// let mut rng = thread_rng();
///
/// let x = u16x8::splat(rng.gen::<u8>() as u16);
/// let x = u16x8::splat(rng.random::<u8>() as u16);
/// let mask = u16x8::splat(1) << u16x8::from([0, 1, 2, 3, 4, 5, 6, 7]);
/// let rand_mask = (x & mask).simd_eq(mask);
/// ```
@ -189,7 +189,7 @@ where
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Mask<T, LANES> {
// `MaskElement` must be a signed integer, so this is equivalent
// to the scalar `i32 < 0` method
let var = rng.gen::<Simd<T, LANES>>();
let var = rng.random::<Simd<T, LANES>>();
var.simd_lt(Simd::default())
}
}
@ -208,7 +208,7 @@ macro_rules! tuple_impl {
let out = ($(
// use the $tyvar's to get the appropriate number of
// repeats (they're not actually needed)
rng.gen::<$tyvar>()
rng.random::<$tyvar>()
,)*);
// Suppress the unused variable warning for empty tuple
@ -247,7 +247,7 @@ where Standard: Distribution<T>
let mut buff: [MaybeUninit<T>; N] = unsafe { MaybeUninit::uninit().assume_init() };
for elem in &mut buff {
*elem = MaybeUninit::new(_rng.gen());
*elem = MaybeUninit::new(_rng.random());
}
unsafe { mem::transmute_copy::<_, _>(&buff) }
@ -260,8 +260,8 @@ where Standard: Distribution<T>
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Option<T> {
// UFCS is needed here: https://github.com/rust-lang/rust/issues/24066
if rng.gen::<bool>() {
Some(rng.gen())
if rng.random::<bool>() {
Some(rng.random())
} else {
None
}
@ -273,7 +273,7 @@ where Standard: Distribution<T>
{
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Wrapping<T> {
Wrapping(rng.gen())
Wrapping(rng.random())
}
}
@ -300,7 +300,7 @@ mod tests {
// Test by generating a relatively large number of chars, so we also
// take the rejection sampling path.
let word: String = iter::repeat(())
.map(|()| rng.gen::<char>())
.map(|()| rng.random::<char>())
.take(1000)
.collect();
assert!(!word.is_empty());

View File

@ -515,12 +515,12 @@ macro_rules! uniform_int_impl {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
let range = self.range as $uty as $sample_ty;
if range == 0 {
return rng.gen();
return rng.random();
}
let thresh = self.thresh as $uty as $sample_ty;
let hi = loop {
let (hi, lo) = rng.gen::<$sample_ty>().wmul(range);
let (hi, lo) = rng.random::<$sample_ty>().wmul(range);
if lo >= thresh {
break hi;
}
@ -563,16 +563,16 @@ macro_rules! uniform_int_impl {
let range = high.wrapping_sub(low).wrapping_add(1) as $uty as $sample_ty;
if range == 0 {
// Range is MAX+1 (unrepresentable), so we need a special case
return Ok(rng.gen());
return Ok(rng.random());
}
// generate a sample using a sensible integer type
let (mut result, lo_order) = rng.gen::<$sample_ty>().wmul(range);
let (mut result, lo_order) = rng.random::<$sample_ty>().wmul(range);
// if the sample is biased...
if lo_order > range.wrapping_neg() {
// ...generate a new sample to reduce bias...
let (new_hi_order, _) = (rng.gen::<$sample_ty>()).wmul(range as $sample_ty);
let (new_hi_order, _) = (rng.random::<$sample_ty>()).wmul(range as $sample_ty);
// ... incrementing result on overflow
let is_overflow = lo_order.checked_add(new_hi_order as $sample_ty).is_none();
result += is_overflow as $sample_ty;
@ -602,11 +602,11 @@ macro_rules! uniform_int_impl {
return Ok(rng.gen());
}
let (mut result, mut lo) = rng.gen::<$sample_ty>().wmul(range);
let (mut result, mut lo) = rng.random::<$sample_ty>().wmul(range);
// In contrast to the biased sampler, we use a loop:
while lo > range.wrapping_neg() {
let (new_hi, new_lo) = (rng.gen::<$sample_ty>()).wmul(range);
let (new_hi, new_lo) = (rng.random::<$sample_ty>()).wmul(range);
match lo.checked_add(new_hi) {
Some(x) if x < $sample_ty::MAX => {
// Anything less than MAX: last term is 0
@ -732,7 +732,7 @@ macro_rules! uniform_simd_int_impl {
// rejection. The replacement method does however add a little
// overhead. Benchmarking or calculating probabilities might
// reveal contexts where this replacement method is slower.
let mut v: Simd<$unsigned, LANES> = rng.gen();
let mut v: Simd<$unsigned, LANES> = rng.random();
loop {
let (hi, lo) = v.wmul(range);
let mask = lo.simd_ge(thresh);
@ -747,7 +747,7 @@ macro_rules! uniform_simd_int_impl {
return range.simd_gt(Simd::splat(0)).select(result, v);
}
// Replace only the failing lanes
v = mask.select(v, rng.gen());
v = mask.select(v, rng.random());
}
}
}
@ -970,7 +970,7 @@ macro_rules! uniform_float_impl {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
// Generate a value in the range [1, 2)
let value1_2 = (rng.gen::<$uty>() >> $uty::splat($bits_to_discard)).into_float_with_exponent(0);
let value1_2 = (rng.random::<$uty>() >> $uty::splat($bits_to_discard)).into_float_with_exponent(0);
// Get a value in the range [0, 1) to avoid overflow when multiplying by scale
let value0_1 = value1_2 - <$ty>::splat(1.0);
@ -1006,7 +1006,7 @@ macro_rules! uniform_float_impl {
loop {
// Generate a value in the range [1, 2)
let value1_2 =
(rng.gen::<$uty>() >> $uty::splat($bits_to_discard)).into_float_with_exponent(0);
(rng.random::<$uty>() >> $uty::splat($bits_to_discard)).into_float_with_exponent(0);
// Get a value in the range [0, 1) to avoid overflow when multiplying by scale
let value0_1 = value1_2 - <$ty>::splat(1.0);
@ -1079,7 +1079,7 @@ macro_rules! uniform_float_impl {
// Generate a value in the range [1, 2)
let value1_2 =
(rng.gen::<$uty>() >> $uty::splat($bits_to_discard)).into_float_with_exponent(0);
(rng.random::<$uty>() >> $uty::splat($bits_to_discard)).into_float_with_exponent(0);
// Get a value in the range [0, 1) to avoid overflow when multiplying by scale
let value0_1 = value1_2 - <$ty>::splat(1.0);

View File

@ -29,7 +29,7 @@
//! }
//!
//! let mut rng = rand::thread_rng();
//! let y: f64 = rng.gen(); // generates a float between 0 and 1
//! let y: f64 = rng.random(); // generates a float between 0 and 1
//!
//! let mut nums: Vec<i32> = (1..100).collect();
//! nums.shuffle(&mut rng);
@ -147,7 +147,7 @@ use crate::distributions::{Distribution, Standard};
/// let mut rng = rand::thread_rng();
///
/// for x in v.iter_mut() {
/// *x = rng.gen();
/// *x = rng.random();
/// }
/// ```
///
@ -158,7 +158,7 @@ use crate::distributions::{Distribution, Standard};
#[inline]
pub fn random<T>() -> T
where Standard: Distribution<T> {
thread_rng().gen()
thread_rng().random()
}
#[cfg(test)]

View File

@ -15,7 +15,7 @@
//! ```
//! use rand::prelude::*;
//! # let mut r = StdRng::from_rng(thread_rng()).unwrap();
//! # let _: f32 = r.gen();
//! # let _: f32 = r.random();
//! ```
#[doc(no_inline)] pub use crate::distributions::Distribution;

View File

@ -37,7 +37,7 @@ use core::{mem, slice};
/// on references (including type-erased references). Unfortunately within the
/// function `foo` it is not known whether `rng` is a reference type or not,
/// hence many uses of `rng` require an extra reference, either explicitly
/// (`distr.sample(&mut rng)`) or implicitly (`rng.gen()`); one may hope the
/// (`distr.sample(&mut rng)`) or implicitly (`rng.random()`); one may hope the
/// optimiser can remove redundant references later.
///
/// Example:
@ -47,7 +47,7 @@ use core::{mem, slice};
/// use rand::Rng;
///
/// fn foo<R: Rng + ?Sized>(rng: &mut R) -> f32 {
/// rng.gen()
/// rng.random()
/// }
///
/// # let v = foo(&mut thread_rng());
@ -61,14 +61,14 @@ pub trait Rng: RngCore {
/// use rand::{thread_rng, Rng};
///
/// let mut rng = thread_rng();
/// let x: u32 = rng.gen();
/// let x: u32 = rng.random();
/// println!("{}", x);
/// println!("{:?}", rng.gen::<(f64, bool)>());
/// println!("{:?}", rng.random::<(f64, bool)>());
/// ```
///
/// # Arrays and tuples
///
/// The `rng.gen()` method is able to generate arrays
/// The `rng.random()` method is able to generate arrays
/// and tuples (up to 12 elements), so long as all element types can be
/// generated.
///
@ -79,16 +79,16 @@ pub trait Rng: RngCore {
/// use rand::{thread_rng, Rng};
///
/// let mut rng = thread_rng();
/// let tuple: (u8, i32, char) = rng.gen(); // arbitrary tuple support
/// let tuple: (u8, i32, char) = rng.random(); // arbitrary tuple support
///
/// let arr1: [f32; 32] = rng.gen(); // array construction
/// let arr1: [f32; 32] = rng.random(); // array construction
/// let mut arr2 = [0u8; 128];
/// rng.fill(&mut arr2); // array fill
/// ```
///
/// [`Standard`]: distributions::Standard
#[inline]
fn gen<T>(&mut self) -> T
fn random<T>(&mut self) -> T
where Standard: Distribution<T> {
Standard.sample(self)
}
@ -321,6 +321,14 @@ pub trait Rng: RngCore {
let d = distributions::Bernoulli::from_ratio(numerator, denominator).unwrap();
self.sample(d)
}
/// Alias for [`Rng::random`].
#[inline]
#[deprecated(since="0.9.0", note="Renamed to `random` to avoid conflict with the new `gen` keyword in Rust 2024.")]
fn gen<T>(&mut self) -> T
where Standard: Distribution<T> {
self.random()
}
}
impl<R: RngCore + ?Sized> Rng for R {}
@ -343,7 +351,7 @@ macro_rules! impl_fill_each {
impl Fill for [$t] {
fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error> {
for elt in self.iter_mut() {
*elt = rng.gen();
*elt = rng.random();
}
Ok(())
}
@ -474,7 +482,7 @@ mod test {
// Check equivalence for generated floats
let mut array = [0f32; 2];
rng.fill(&mut array);
let gen: [f32; 2] = rng.gen();
let gen: [f32; 2] = rng.random();
assert_eq!(array, gen);
}
@ -555,7 +563,7 @@ mod test {
let mut rng = rng(109);
let mut r = &mut rng as &mut dyn RngCore;
r.next_u32();
r.gen::<i32>();
r.random::<i32>();
assert_eq!(r.gen_range(0..1), 0);
let _c: u8 = Standard.sample(&mut r);
}
@ -567,7 +575,7 @@ mod test {
let rng = rng(110);
let mut r = Box::new(rng) as Box<dyn RngCore>;
r.next_u32();
r.gen::<i32>();
r.random::<i32>();
assert_eq!(r.gen_range(0..1), 0);
let _c: u8 = Standard.sample(&mut r);
}

View File

@ -35,7 +35,7 @@ use serde::{Serialize, Deserialize};
/// use rand::rngs::mock::StepRng;
///
/// let mut my_rng = StepRng::new(2, 1);
/// let sample: [u64; 3] = my_rng.gen();
/// let sample: [u64; 3] = my_rng.random();
/// assert_eq!(sample, [2, 3, 4]);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]

View File

@ -62,10 +62,10 @@ use rand_core::block::{BlockRng, BlockRngCore, CryptoBlockRng};
/// let prng = ChaCha20Core::from_entropy();
/// let mut reseeding_rng = ReseedingRng::new(prng, 0, OsRng);
///
/// println!("{}", reseeding_rng.gen::<u64>());
/// println!("{}", reseeding_rng.random::<u64>());
///
/// let mut cloned_rng = reseeding_rng.clone();
/// assert!(reseeding_rng.gen::<u64>() != cloned_rng.gen::<u64>());
/// assert!(reseeding_rng.random::<u64>() != cloned_rng.random::<u64>());
/// ```
///
/// [`BlockRngCore`]: rand_core::block::BlockRngCore
@ -283,12 +283,12 @@ mod test {
let rng = Core::from_rng(&mut zero).unwrap();
let mut rng1 = ReseedingRng::new(rng, 32 * 4, zero);
let first: u32 = rng1.gen();
let first: u32 = rng1.random();
for _ in 0..10 {
let _ = rng1.gen::<u32>();
let _ = rng1.random::<u32>();
}
let mut rng2 = rng1.clone();
assert_eq!(first, rng2.gen::<u32>());
assert_eq!(first, rng2.random::<u32>());
}
}

View File

@ -185,7 +185,7 @@ mod test {
fn test_thread_rng() {
use crate::Rng;
let mut r = crate::thread_rng();
r.gen::<i32>();
r.random::<i32>();
assert_eq!(r.gen_range(0..1), 0);
}

View File

@ -348,7 +348,7 @@ where
while index < length {
let weight = weight(index.as_usize()).into();
if weight > 0.0 {
let key = rng.gen::<f64>().powf(1.0 / weight);
let key = rng.random::<f64>().powf(1.0 / weight);
candidates.push(Element { index, key });
} else if !(weight >= 0.0) {
return Err(WeightError::InvalidWeight);