From e0f63c2bf43dcf5f8681ec5458839439291f26a2 Mon Sep 17 00:00:00 2001 From: Vinzent Steinberg Date: Fri, 26 Apr 2024 15:02:29 +0200 Subject: [PATCH] Rename `Rng::gen` to `Rng::random` This anticipates `gen` being a keyword in Rust 2024. A deprecated alias for `Rng::gen` stays in place to make the transition easier. Fixes #1435. --- benches/benches/misc.rs | 8 ++++---- examples/monty-hall.rs | 2 +- src/distributions/bernoulli.rs | 2 +- src/distributions/float.rs | 18 +++++++++--------- src/distributions/integer.rs | 4 ++-- src/distributions/mod.rs | 8 ++++---- src/distributions/other.rs | 14 +++++++------- src/distributions/uniform.rs | 24 ++++++++++++------------ src/lib.rs | 6 +++--- src/prelude.rs | 2 +- src/rng.rs | 32 ++++++++++++++++++++------------ src/rngs/mock.rs | 2 +- src/rngs/reseeding.rs | 10 +++++----- src/rngs/thread.rs | 2 +- src/seq/index.rs | 2 +- 15 files changed, 72 insertions(+), 64 deletions(-) diff --git a/benches/benches/misc.rs b/benches/benches/misc.rs index a3aef17c57..a3c353bbdd 100644 --- a/benches/benches/misc.rs +++ b/benches/benches/misc.rs @@ -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 = iter::repeat(()).map(|()| rng.gen()).take(512).collect(); + let v: Vec = 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 = iter::repeat(()).map(|()| rng.gen()).take(128).collect(); + let v: Vec = 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; diff --git a/examples/monty-hall.rs b/examples/monty-hall.rs index bb4bd87000..aaff41cad3 100644 --- a/examples/monty-hall.rs +++ b/examples/monty-hall.rs @@ -45,7 +45,7 @@ fn simulate(random_door: &Uniform, 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); } diff --git a/src/distributions/bernoulli.rs b/src/distributions/bernoulli.rs index d72620ea7c..a68a82965c 100644 --- a/src/distributions/bernoulli.rs +++ b/src/distributions/bernoulli.rs @@ -136,7 +136,7 @@ impl Distribution for Bernoulli { if self.p_int == ALWAYS_TRUE { return true; } - let v: u64 = rng.gen(); + let v: u64 = rng.random(); v < self.p_int } } diff --git a/src/distributions/float.rs b/src/distributions/float.rs index 1eaad89d44..ace6fe6611 100644 --- a/src/distributions/float.rs +++ b/src/distributions/float.rs @@ -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); diff --git a/src/distributions/integer.rs b/src/distributions/integer.rs index d7bb988d1b..ca27c6331d 100644 --- a/src/distributions/integer.rs +++ b/src/distributions/integer.rs @@ -81,7 +81,7 @@ macro_rules! impl_int_from_uint { impl Distribution<$ty> for Standard { #[inline] fn sample(&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(&self, rng: &mut R) -> $ty { loop { - if let Some(nz) = $new(rng.gen()) { + if let Some(nz) = $new(rng.random()) { break nz; } } diff --git a/src/distributions/mod.rs b/src/distributions/mod.rs index ee3615cf92..050e75d98e 100644 --- a/src/distributions/mod.rs +++ b/src/distributions/mod.rs @@ -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` 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 for Standard { /// fn sample(&self, rng: &mut R) -> MyF32 { -/// MyF32 { x: rng.gen() } +/// MyF32 { x: rng.random() } /// } /// } /// ``` diff --git a/src/distributions/other.rs b/src/distributions/other.rs index 5b922bd37e..bdf1e8c2db 100644 --- a/src/distributions/other.rs +++ b/src/distributions/other.rs @@ -189,7 +189,7 @@ where fn sample(&self, rng: &mut R) -> Mask { // `MaskElement` must be a signed integer, so this is equivalent // to the scalar `i32 < 0` method - let var = rng.gen::>(); + let var = rng.random::>(); 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 let mut buff: [MaybeUninit; 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 #[inline] fn sample(&self, rng: &mut R) -> Option { // UFCS is needed here: https://github.com/rust-lang/rust/issues/24066 - if rng.gen::() { - Some(rng.gen()) + if rng.random::() { + Some(rng.random()) } else { None } @@ -273,7 +273,7 @@ where Standard: Distribution { #[inline] fn sample(&self, rng: &mut R) -> Wrapping { - 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::()) + .map(|()| rng.random::()) .take(1000) .collect(); assert!(!word.is_empty()); diff --git a/src/distributions/uniform.rs b/src/distributions/uniform.rs index 26e1cb5dec..7fbf0fced2 100644 --- a/src/distributions/uniform.rs +++ b/src/distributions/uniform.rs @@ -515,12 +515,12 @@ macro_rules! uniform_int_impl { fn sample(&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(&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); diff --git a/src/lib.rs b/src/lib.rs index dc9e29d627..5410b16f33 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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 = (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 where Standard: Distribution { - thread_rng().gen() + thread_rng().random() } #[cfg(test)] diff --git a/src/prelude.rs b/src/prelude.rs index 35fee3d73f..2f9fa4c8ff 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -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; diff --git a/src/rng.rs b/src/rng.rs index 206275f8d7..7a8485e27b 100644 --- a/src/rng.rs +++ b/src/rng.rs @@ -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,12 +47,20 @@ use core::{mem, slice}; /// use rand::Rng; /// /// fn foo(rng: &mut R) -> f32 { -/// rng.gen() +/// rng.random() /// } /// /// # let v = foo(&mut thread_rng()); /// ``` pub trait Rng: RngCore { + /// Alias for [`Rng::random`]. + #[inline] + #[deprecated(since="0.9.0", note="This method conflicts with a keyword in Rust 2024. Use `Rng::random` instead.")] + fn gen(&mut self) -> T + where Standard: Distribution { + self.random() + } + /// Return a random value via the [`Standard`] distribution. /// /// # Example @@ -61,14 +69,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 +87,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(&mut self) -> T + fn random(&mut self) -> T where Standard: Distribution { Standard.sample(self) } @@ -343,7 +351,7 @@ macro_rules! impl_fill_each { impl Fill for [$t] { fn try_fill(&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::(); + r.random::(); 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; r.next_u32(); - r.gen::(); + r.random::(); assert_eq!(r.gen_range(0..1), 0); let _c: u8 = Standard.sample(&mut r); } diff --git a/src/rngs/mock.rs b/src/rngs/mock.rs index 0d9e0f905c..66705a008c 100644 --- a/src/rngs/mock.rs +++ b/src/rngs/mock.rs @@ -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)] diff --git a/src/rngs/reseeding.rs b/src/rngs/reseeding.rs index 88878cedb7..752952e67e 100644 --- a/src/rngs/reseeding.rs +++ b/src/rngs/reseeding.rs @@ -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::()); +/// println!("{}", reseeding_rng.random::()); /// /// let mut cloned_rng = reseeding_rng.clone(); -/// assert!(reseeding_rng.gen::() != cloned_rng.gen::()); +/// assert!(reseeding_rng.random::() != cloned_rng.random::()); /// ``` /// /// [`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::(); + let _ = rng1.random::(); } let mut rng2 = rng1.clone(); - assert_eq!(first, rng2.gen::()); + assert_eq!(first, rng2.random::()); } } diff --git a/src/rngs/thread.rs b/src/rngs/thread.rs index 449d6d6cf4..f79ded83e3 100644 --- a/src/rngs/thread.rs +++ b/src/rngs/thread.rs @@ -185,7 +185,7 @@ mod test { fn test_thread_rng() { use crate::Rng; let mut r = crate::thread_rng(); - r.gen::(); + r.random::(); assert_eq!(r.gen_range(0..1), 0); } diff --git a/src/seq/index.rs b/src/seq/index.rs index c1f889d4f1..e7b1e2b22f 100644 --- a/src/seq/index.rs +++ b/src/seq/index.rs @@ -348,7 +348,7 @@ where while index < length { let weight = weight(index.as_usize()).into(); if weight > 0.0 { - let key = rng.gen::().powf(1.0 / weight); + let key = rng.random::().powf(1.0 / weight); candidates.push(Element { index, key }); } else if !(weight >= 0.0) { return Err(WeightError::InvalidWeight);