Skip to content

Commit 66b11eb

Browse files
authored
Rename gen_iter → random_iter, misc.. (#1500)
This extracts the non-inherent-methods stuff from #1492.
1 parent e2092e9 commit 66b11eb

File tree

8 files changed

+99
-89
lines changed

8 files changed

+99
-89
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.
2626
- Require `Clone` and `AsRef` bound for `SeedableRng::Seed`. (#1491)
2727
- Implement `Distribution<u64>` for `Poisson<f64>` (#1498)
2828
- Limit the maximal acceptable lambda for `Poisson` to solve (#1312) (#1498)
29+
- Rename `Rng::gen_iter` to `random_iter` (#1500)
2930

3031
## [0.9.0-alpha.1] - 2024-03-18
3132
- Add the `Slice::num_choices` method to the Slice distribution (#1402)

README.md

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,26 +6,31 @@
66
[![API](https://img.shields.io/badge/api-master-yellow.svg)](https://rust-random.github.io/rand/rand)
77
[![API](https://docs.rs/rand/badge.svg)](https://docs.rs/rand)
88

9-
A Rust library for random number generation, featuring:
9+
Rand is a Rust library supporting random generators:
1010

11-
- Easy random value generation and usage via the [`Rng`](https://docs.rs/rand/*/rand/trait.Rng.html),
12-
[`SliceRandom`](https://docs.rs/rand/*/rand/seq/trait.SliceRandom.html) and
13-
[`IteratorRandom`](https://docs.rs/rand/*/rand/seq/trait.IteratorRandom.html) traits
14-
- Secure seeding via the [`getrandom` crate](https://crates.io/crates/getrandom)
15-
and fast, convenient generation via [`thread_rng`](https://docs.rs/rand/*/rand/fn.thread_rng.html)
16-
- A modular design built over [`rand_core`](https://crates.io/crates/rand_core)
17-
([see the book](https://rust-random.github.io/book/crates.html))
11+
- A standard RNG trait: [`rand_core::RngCore`](https://docs.rs/rand_core/latest/rand_core/trait.RngCore.html)
1812
- Fast implementations of the best-in-class [cryptographic](https://rust-random.github.io/book/guide-rngs.html#cryptographically-secure-pseudo-random-number-generators-csprngs) and
19-
[non-cryptographic](https://rust-random.github.io/book/guide-rngs.html#basic-pseudo-random-number-generators-prngs) generators
13+
[non-cryptographic](https://rust-random.github.io/book/guide-rngs.html#basic-pseudo-random-number-generators-prngs) generators: [`rand::rngs`](https://docs.rs/rand/latest/rand/rngs/index.html), and more RNGs: [`rand_chacha`](https://docs.rs/rand_chacha), [`rand_xoshiro`](https://docs.rs/rand_xoshiro/), [`rand_pcg`](https://docs.rs/rand_pcg/), [rngs repo](https://github.com/rust-random/rngs/)
14+
- [`rand::thread_rng`](https://docs.rs/rand/latest/rand/fn.thread_rng.html) is an asymtotically-fast, reasonably secure generator available on all `std` targets
15+
- Secure seeding via the [`getrandom` crate](https://crates.io/crates/getrandom)
16+
17+
Supporting random value generation and random processes:
18+
19+
- [`Standard`](https://docs.rs/rand/latest/rand/distributions/struct.Standard.html) random value generation
20+
- Ranged [`Uniform`](https://docs.rs/rand/latest/rand/distributions/struct.Uniform.html) number generation for many types
2021
- A flexible [`distributions`](https://docs.rs/rand/*/rand/distr/index.html) module
2122
- Samplers for a large number of random number distributions via our own
2223
[`rand_distr`](https://docs.rs/rand_distr) and via
2324
the [`statrs`](https://docs.rs/statrs/0.13.0/statrs/)
25+
- Random processes (mostly choose and shuffle) via [`rand::seq`](https://docs.rs/rand/latest/rand/seq/index.html) traits
26+
27+
All with:
28+
2429
- [Portably reproducible output](https://rust-random.github.io/book/portability.html)
2530
- `#[no_std]` compatibility (partial)
2631
- *Many* performance optimisations
2732

28-
It's also worth pointing out what `rand` *is not*:
33+
It's also worth pointing out what Rand *is not*:
2934

3035
- Small. Most low-level crates are small, but the higher-level `rand` and
3136
`rand_distr` each contain a lot of functionality.
@@ -73,8 +78,7 @@ Rand is built with these features enabled by default:
7378
- `alloc` (implied by `std`) enables functionality requiring an allocator
7479
- `getrandom` (implied by `std`) is an optional dependency providing the code
7580
behind `rngs::OsRng`
76-
- `std_rng` enables inclusion of `StdRng`, `thread_rng` and `random`
77-
(the latter two *also* require that `std` be enabled)
81+
- `std_rng` enables inclusion of `StdRng`, `thread_rng`
7882

7983
Optionally, the following dependencies can be enabled:
8084

@@ -94,8 +98,7 @@ experimental `simd_support` feature.
9498
Rand supports limited functionality in `no_std` mode (enabled via
9599
`default-features = false`). In this case, `OsRng` and `from_os_rng` are
96100
unavailable (unless `getrandom` is enabled), large parts of `seq` are
97-
unavailable (unless `alloc` is enabled), and `thread_rng` and `random` are
98-
unavailable.
101+
unavailable (unless `alloc` is enabled), and `thread_rng` is unavailable.
99102

100103
## Portability and platform support
101104

benches/benches/seq_choose.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ criterion_group!(
1919
criterion_main!(benches);
2020

2121
pub fn bench(c: &mut Criterion) {
22-
c.bench_function("seq_slice_choose_1_of_1000", |b| {
22+
c.bench_function("seq_slice_choose_1_of_100", |b| {
2323
let mut rng = Pcg32::from_rng(thread_rng());
2424
let mut buf = [0i32; 100];
2525
rng.fill(&mut buf);

rand_core/src/lib.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,11 @@ pub use getrandom;
5454
#[cfg(feature = "getrandom")]
5555
pub use os::OsRng;
5656

57-
/// The core of a random number generator.
57+
/// Implementation-level interface for RNGs
5858
///
5959
/// This trait encapsulates the low-level functionality common to all
6060
/// generators, and is the "back end", to be implemented by generators.
61-
/// End users should normally use the `Rng` trait from the [`rand`] crate,
61+
/// End users should normally use the [`rand::Rng`] trait
6262
/// which is automatically implemented for every type implementing `RngCore`.
6363
///
6464
/// Three different methods for generating random data are provided since the
@@ -129,7 +129,7 @@ pub use os::OsRng;
129129
/// rand_core::impl_try_rng_from_rng_core!(CountingRng);
130130
/// ```
131131
///
132-
/// [`rand`]: https://docs.rs/rand
132+
/// [`rand::Rng`]: https://docs.rs/rand/latest/rand/trait.Rng.html
133133
/// [`fill_bytes`]: RngCore::fill_bytes
134134
/// [`next_u32`]: RngCore::next_u32
135135
/// [`next_u64`]: RngCore::next_u64

rand_distr/src/weighted_alias.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -275,9 +275,10 @@ where
275275
}
276276
}
277277

278-
/// Trait that must be implemented for weights, that are used with
279-
/// [`WeightedAliasIndex`]. Currently no guarantees on the correctness of
280-
/// [`WeightedAliasIndex`] are given for custom implementations of this trait.
278+
/// Weight bound for [`WeightedAliasIndex`]
279+
///
280+
/// Currently no guarantees on the correctness of [`WeightedAliasIndex`] are
281+
/// given for custom implementations of this trait.
281282
pub trait AliasableWeight:
282283
Sized
283284
+ Copy

src/lib.rs

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,25 +14,24 @@
1414
//!
1515
//! # Quick Start
1616
//!
17-
//! To get you started quickly, the easiest and highest-level way to get
18-
//! a random value is to use [`random()`]; alternatively you can use
19-
//! [`thread_rng()`]. The [`Rng`] trait provides a useful API on all RNGs, while
20-
//! the [`distr`] and [`seq`] modules provide further
21-
//! functionality on top of RNGs.
22-
//!
2317
//! ```
18+
//! // The prelude import enables methods we use below, specifically
19+
//! // Rng::random, Rng::sample, SliceRandom::shuffle and IndexedRandom::choose.
2420
//! use rand::prelude::*;
2521
//!
26-
//! if rand::random() { // generates a boolean
27-
//! // Try printing a random unicode code point (probably a bad idea)!
28-
//! println!("char: {}", rand::random::<char>());
29-
//! }
30-
//!
22+
//! // Get an RNG:
3123
//! let mut rng = rand::thread_rng();
32-
//! let y: f64 = rng.random(); // generates a float between 0 and 1
3324
//!
25+
//! // Try printing a random unicode code point (probably a bad idea)!
26+
//! println!("char: '{}'", rng.random::<char>());
27+
//! // Try printing a random alphanumeric value instead!
28+
//! println!("alpha: '{}'", rng.sample(rand::distr::Alphanumeric) as char);
29+
//!
30+
//! // Generate and shuffle a sequence:
3431
//! let mut nums: Vec<i32> = (1..100).collect();
3532
//! nums.shuffle(&mut rng);
33+
//! // And take a random pick (yes, we didn't need to shuffle first!):
34+
//! let _ = nums.choose(&mut rng);
3635
//! ```
3736
//!
3837
//! # The Book

src/rng.rs

Lines changed: 56 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,14 @@ use core::num::Wrapping;
1515
use core::{mem, slice};
1616
use rand_core::RngCore;
1717

18-
/// An automatically-implemented extension trait on [`RngCore`] providing high-level
19-
/// generic methods for sampling values and other convenience methods.
18+
/// User-level interface for RNGs
2019
///
21-
/// This is the primary trait to use when generating random values.
20+
/// [`RngCore`] is the `dyn`-safe implementation-level interface for Random
21+
/// (Number) Generators. This trait, `Rng`, provides a user-level interface on
22+
/// RNGs. It is implemented automatically for any `R: RngCore`.
23+
///
24+
/// This trait must usually be brought into scope via `use rand::Rng;` or
25+
/// `use rand::prelude::*;`.
2226
///
2327
/// # Generic usage
2428
///
@@ -96,67 +100,25 @@ pub trait Rng: RngCore {
96100
Standard.sample(self)
97101
}
98102

99-
/// Generate a random value in the given range.
100-
///
101-
/// This function is optimised for the case that only a single sample is
102-
/// made from the given range. See also the [`Uniform`] distribution
103-
/// type which may be faster if sampling from the same range repeatedly.
104-
///
105-
/// All types support `low..high_exclusive` and `low..=high` range syntax.
106-
/// Unsigned integer types also support `..high_exclusive` and `..=high` syntax.
107-
///
108-
/// # Panics
109-
///
110-
/// Panics if the range is empty, or if `high - low` overflows for floats.
111-
///
112-
/// # Example
113-
///
114-
/// ```
115-
/// use rand::{thread_rng, Rng};
116-
///
117-
/// let mut rng = thread_rng();
118-
///
119-
/// // Exclusive range
120-
/// let n: u32 = rng.gen_range(..10);
121-
/// println!("{}", n);
122-
/// let m: f64 = rng.gen_range(-40.0..1.3e5);
123-
/// println!("{}", m);
124-
///
125-
/// // Inclusive range
126-
/// let n: u32 = rng.gen_range(..=10);
127-
/// println!("{}", n);
128-
/// ```
129-
///
130-
/// [`Uniform`]: distr::uniform::Uniform
131-
#[track_caller]
132-
fn gen_range<T, R>(&mut self, range: R) -> T
133-
where
134-
T: SampleUniform,
135-
R: SampleRange<T>,
136-
{
137-
assert!(!range.is_empty(), "cannot sample empty range");
138-
range.sample_single(self).unwrap()
139-
}
140-
141-
/// Generate values via an iterator
103+
/// Return an iterator over [`random`](Self::random) variates
142104
///
143105
/// This is a just a wrapper over [`Rng::sample_iter`] using
144106
/// [`distr::Standard`].
145107
///
146108
/// Note: this method consumes its argument. Use
147-
/// `(&mut rng).gen_iter()` to avoid consuming the RNG.
109+
/// `(&mut rng).random_iter()` to avoid consuming the RNG.
148110
///
149111
/// # Example
150112
///
151113
/// ```
152114
/// use rand::{rngs::mock::StepRng, Rng};
153115
///
154116
/// let rng = StepRng::new(1, 1);
155-
/// let v: Vec<i32> = rng.gen_iter().take(5).collect();
117+
/// let v: Vec<i32> = rng.random_iter().take(5).collect();
156118
/// assert_eq!(&v, &[1, 2, 3, 4, 5]);
157119
/// ```
158120
#[inline]
159-
fn gen_iter<T>(self) -> distr::DistIter<Standard, Self, T>
121+
fn random_iter<T>(self) -> distr::DistIter<Standard, Self, T>
160122
where
161123
Self: Sized,
162124
Standard: Distribution<T>,
@@ -247,6 +209,48 @@ pub trait Rng: RngCore {
247209
dest.fill(self)
248210
}
249211

212+
/// Generate a random value in the given range.
213+
///
214+
/// This function is optimised for the case that only a single sample is
215+
/// made from the given range. See also the [`Uniform`] distribution
216+
/// type which may be faster if sampling from the same range repeatedly.
217+
///
218+
/// All types support `low..high_exclusive` and `low..=high` range syntax.
219+
/// Unsigned integer types also support `..high_exclusive` and `..=high` syntax.
220+
///
221+
/// # Panics
222+
///
223+
/// Panics if the range is empty, or if `high - low` overflows for floats.
224+
///
225+
/// # Example
226+
///
227+
/// ```
228+
/// use rand::{thread_rng, Rng};
229+
///
230+
/// let mut rng = thread_rng();
231+
///
232+
/// // Exclusive range
233+
/// let n: u32 = rng.gen_range(..10);
234+
/// println!("{}", n);
235+
/// let m: f64 = rng.gen_range(-40.0..1.3e5);
236+
/// println!("{}", m);
237+
///
238+
/// // Inclusive range
239+
/// let n: u32 = rng.gen_range(..=10);
240+
/// println!("{}", n);
241+
/// ```
242+
///
243+
/// [`Uniform`]: distr::uniform::Uniform
244+
#[track_caller]
245+
fn gen_range<T, R>(&mut self, range: R) -> T
246+
where
247+
T: SampleUniform,
248+
R: SampleRange<T>,
249+
{
250+
assert!(!range.is_empty(), "cannot sample empty range");
251+
range.sample_single(self).unwrap()
252+
}
253+
250254
/// Return a bool with a probability `p` of being true.
251255
///
252256
/// See also the [`Bernoulli`] distribution, which may be faster if
@@ -316,7 +320,7 @@ pub trait Rng: RngCore {
316320
since = "0.9.0",
317321
note = "Renamed to `random` to avoid conflict with the new `gen` keyword in Rust 2024."
318322
)]
319-
fn gen<T>(&mut self) -> T
323+
fn r#gen<T>(&mut self) -> T
320324
where
321325
Standard: Distribution<T>,
322326
{
@@ -474,8 +478,8 @@ mod test {
474478
// Check equivalence for generated floats
475479
let mut array = [0f32; 2];
476480
rng.fill(&mut array);
477-
let gen: [f32; 2] = rng.random();
478-
assert_eq!(array, gen);
481+
let arr2: [f32; 2] = rng.random();
482+
assert_eq!(array, arr2);
479483
}
480484

481485
#[test]

src/seq/index.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -282,10 +282,12 @@ where
282282
}
283283
}
284284

285-
/// Randomly sample exactly `amount` distinct indices from `0..length`, and
286-
/// return them in an arbitrary order (there is no guarantee of shuffling or
287-
/// ordering). The weights are to be provided by the input function `weights`,
288-
/// which will be called once for each index.
285+
/// Randomly sample exactly `amount` distinct indices from `0..length`
286+
///
287+
/// Results are in arbitrary order (there is no guarantee of shuffling or
288+
/// ordering).
289+
///
290+
/// Function `weight` is called once for each index to provide weights.
289291
///
290292
/// This method is used internally by the slice sampling methods, but it can
291293
/// sometimes be useful to have the indices themselves so this is provided as

0 commit comments

Comments
 (0)