Rollup merge of #150781 - pr/cleanup-rand-usages, r=Mark-Simulacrum

Use `rand` crate more idiomatically

Small cleanup, found while working on something else.
We were using `rand` un-idiomatically in a couple of places, and it was bugging me...
This commit is contained in:
Matthias Krüger 2026-01-11 09:56:40 +01:00 committed by GitHub
commit 57da460fc7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 25 additions and 18 deletions

View file

@ -2,6 +2,7 @@ use std::collections::BTreeMap;
use std::ops::RangeBounds;
use rand::Rng;
use rand::distr::{Distribution, Uniform};
use rand::seq::SliceRandom;
use test::{Bencher, black_box};
@ -106,7 +107,8 @@ macro_rules! map_find_rand_bench {
// setup
let mut rng = crate::bench_rng();
let mut keys: Vec<_> = (0..n).map(|_| rng.random::<u32>() % n).collect();
let mut keys: Vec<_> =
Uniform::new(0, n).unwrap().sample_iter(&mut rng).take(n as usize).collect();
for &k in &keys {
map.insert(k, k);

View file

@ -27,21 +27,20 @@ where
{
// :.:.:.::
let mut rng: XorShiftRng = rand::SeedableRng::seed_from_u64(get_or_init_rand_seed());
let rng: XorShiftRng = rand::SeedableRng::seed_from_u64(get_or_init_rand_seed());
// Abstracting over ranges in Rust :(
let dist = Uniform::try_from(range).unwrap();
(0..len).map(|_| dist.sample(&mut rng)).collect()
rng.sample_iter(dist).take(len).collect()
}
pub fn random_zipf(len: usize, exponent: f64) -> Vec<i32> {
// https://en.wikipedia.org/wiki/Zipf's_law
let mut rng: XorShiftRng = rand::SeedableRng::seed_from_u64(get_or_init_rand_seed());
let rng: XorShiftRng = rand::SeedableRng::seed_from_u64(get_or_init_rand_seed());
// Abstracting over ranges in Rust :(
let dist = ZipfDistribution::new(len, exponent).unwrap();
(0..len).map(|_| dist.sample(&mut rng) as i32).collect()
rng.sample_iter(dist).map(|val| val as i32).take(len).collect()
}
pub fn random_sorted(len: usize, sorted_percent: f64) -> Vec<i32> {
@ -68,7 +67,7 @@ pub fn all_equal(len: usize) -> Vec<i32> {
// ......
// ::::::
(0..len).map(|_| 66).collect::<Vec<_>>()
vec![66; len]
}
pub fn ascending(len: usize) -> Vec<i32> {
@ -206,6 +205,6 @@ fn rand_root_seed() -> u64 {
}
fn random_vec(len: usize) -> Vec<i32> {
let mut rng: XorShiftRng = rand::SeedableRng::seed_from_u64(get_or_init_rand_seed());
(0..len).map(|_| rng.random::<i32>()).collect()
let rng: XorShiftRng = rand::SeedableRng::seed_from_u64(get_or_init_rand_seed());
rng.random_iter().take(len).collect()
}