1#![forbid(unsafe_code)]
8#![warn(missing_docs)]
9#![cfg_attr(
10 not(test),
11 deny(
12 clippy::unwrap_used,
13 clippy::expect_used,
14 clippy::todo,
15 clippy::unimplemented,
16 clippy::panic
17 )
18)]
19
20use rand::{Rng, SeedableRng};
21
22pub use rand::rngs::StdRng;
23
24pub type Seed = [u8; 32];
31
32#[must_use]
37pub fn seed_from_u64(seed: u64) -> Seed {
38 let mut out = [0u8; 32];
39 let mut x = seed.wrapping_add(0x9e3779b97f4a7c15);
40 for chunk in out.chunks_mut(8) {
41 x = splitmix64(x);
42 chunk.copy_from_slice(&x.to_le_bytes());
43 }
44 out
45}
46
47#[must_use]
49pub fn seeded_rng(seed: &Seed) -> StdRng {
50 StdRng::from_seed(*seed)
51}
52
53#[must_use]
55pub fn seeded_rng_from_u64(seed: u64) -> StdRng {
56 seeded_rng(&seed_from_u64(seed))
57}
58
59fn splitmix64(mut x: u64) -> u64 {
60 x = x.wrapping_add(0x9e3779b97f4a7c15);
61 let mut z = x;
62 z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
63 z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
64 z ^ (z >> 31)
65}
66
67pub const LOWER_ALPHANUMERIC: &[u8; 36] = b"abcdefghijklmnopqrstuvwxyz0123456789";
72
73#[must_use]
77pub fn random_index(len: usize) -> Option<usize> {
78 let mut rng = rand::thread_rng();
79 random_index_with_rng(len, &mut rng)
80}
81
82#[must_use]
86pub fn random_index_with_rng<R: Rng + ?Sized>(len: usize, rng: &mut R) -> Option<usize> {
87 if len == 0 {
88 return None;
89 }
90 Some(rng.gen_range(0..len))
91}
92
93#[must_use]
97pub fn random_item<T>(items: &[T]) -> Option<&T> {
98 let mut rng = rand::thread_rng();
99 random_item_with_rng(items, &mut rng)
100}
101
102#[must_use]
106pub fn random_item_with_rng<'a, T, R: Rng + ?Sized>(items: &'a [T], rng: &mut R) -> Option<&'a T> {
107 random_index_with_rng(items.len(), rng).map(|index| &items[index])
108}
109
110#[must_use]
115pub fn chance(probability: f64) -> bool {
116 let mut rng = rand::thread_rng();
117 chance_with_rng(probability, &mut rng)
118}
119
120#[must_use]
125pub fn chance_with_rng<R: Rng + ?Sized>(probability: f64, rng: &mut R) -> bool {
126 if probability.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {
127 return false;
128 }
129 if probability >= 1.0 {
130 return true;
131 }
132 rng.gen::<f64>() < probability
133}
134
135#[must_use]
140pub fn weighted_index(weights: &[f64]) -> Option<usize> {
141 let mut rng = rand::thread_rng();
142 weighted_index_with_rng(weights, &mut rng)
143}
144
145#[must_use]
150pub fn weighted_index_with_rng<R: Rng + ?Sized>(weights: &[f64], rng: &mut R) -> Option<usize> {
151 weighted_index_by_with_rng(weights, |weight| *weight, rng)
152}
153
154#[must_use]
161pub fn weighted_index_by_with_rng<T, R, F>(items: &[T], weight: F, rng: &mut R) -> Option<usize>
162where
163 R: Rng + ?Sized,
164 F: Fn(&T) -> f64,
165{
166 let total = total_usable_weight(items.iter().map(&weight))?;
167 let mut ticket = rng.gen_range(0.0..total);
168 let mut fallback = None;
169
170 for (index, item) in items.iter().enumerate() {
171 let item_weight = weight(item);
172 if !is_usable_weight(item_weight) {
173 continue;
174 }
175 fallback = Some(index);
176 if ticket < item_weight {
177 return Some(index);
178 }
179 ticket -= item_weight;
180 }
181
182 fallback
183}
184
185#[must_use]
187pub fn random_lower_alphanumeric(len: usize) -> String {
188 let mut rng = rand::thread_rng();
189 random_lower_alphanumeric_with_rng(len, &mut rng)
190}
191
192#[must_use]
194pub fn random_lower_alphanumeric_with_rng<R: Rng + ?Sized>(len: usize, rng: &mut R) -> String {
195 sample_ascii_string(len, LOWER_ALPHANUMERIC, rng)
196}
197
198#[must_use]
202pub fn random_ascii_string(len: usize, alphabet: &[u8]) -> Option<String> {
203 let mut rng = rand::thread_rng();
204 random_ascii_string_with_rng(len, alphabet, &mut rng)
205}
206
207#[must_use]
211pub fn random_ascii_string_with_rng<R: Rng + ?Sized>(
212 len: usize,
213 alphabet: &[u8],
214 rng: &mut R,
215) -> Option<String> {
216 if alphabet.is_empty() || alphabet.iter().any(|byte| !byte.is_ascii()) {
217 return None;
218 }
219 Some(sample_ascii_string(len, alphabet, rng))
220}
221
222fn sample_ascii_string<R: Rng + ?Sized>(len: usize, alphabet: &[u8], rng: &mut R) -> String {
223 let mut out = String::with_capacity(len);
224 for _ in 0..len {
225 let Some(index) = random_index_with_rng(alphabet.len(), rng) else {
226 return out;
227 };
228 out.push(char::from(alphabet[index]));
229 }
230 out
231}
232
233fn total_usable_weight<I>(weights: I) -> Option<f64>
234where
235 I: IntoIterator<Item = f64>,
236{
237 let mut total = 0.0;
238 for weight in weights {
239 if is_usable_weight(weight) {
240 total += weight;
241 if !total.is_finite() {
242 return None;
243 }
244 }
245 }
246 (total > 0.0).then_some(total)
247}
248
249fn is_usable_weight(weight: f64) -> bool {
250 weight.is_finite() && weight > 0.0
251}
252
253#[cfg(test)]
254mod tests {
255 use super::{
256 chance, chance_with_rng, random_ascii_string_with_rng, random_index, random_index_with_rng,
257 random_item, random_item_with_rng, random_lower_alphanumeric,
258 random_lower_alphanumeric_with_rng, seed_from_u64, seeded_rng_from_u64, weighted_index,
259 weighted_index_by_with_rng, weighted_index_with_rng, LOWER_ALPHANUMERIC,
260 };
261 use rand::{Rng, SeedableRng};
262
263 #[test]
264 fn random_index_rejects_empty_domain() {
265 assert_eq!(random_index(0), None);
266 }
267
268 #[test]
269 fn random_index_stays_bounded() {
270 for len in 1..16 {
271 for _ in 0..128 {
272 let index = random_index(len).expect("non-empty domain should produce an index");
273 assert!(index < len);
274 }
275 }
276 }
277
278 #[test]
279 fn random_index_with_rng_rejects_empty_domain() {
280 let mut rng = rand::rngs::StdRng::seed_from_u64(7);
281 assert_eq!(random_index_with_rng(0, &mut rng), None);
282 }
283
284 #[test]
285 fn random_index_with_rng_stays_bounded() {
286 let mut rng = rand::rngs::StdRng::seed_from_u64(9);
287 for len in 1..16 {
288 for _ in 0..128 {
289 let index = random_index_with_rng(len, &mut rng)
290 .expect("non-empty domain should produce an index");
291 assert!(index < len);
292 }
293 }
294 }
295
296 #[test]
297 fn random_item_rejects_empty_slice() {
298 assert_eq!(random_item::<u8>(&[]), None);
299 }
300
301 #[test]
302 fn random_item_with_rng_returns_slice_member() {
303 let mut rng = rand::rngs::StdRng::seed_from_u64(19);
304 let items = ["alpha", "bravo", "charlie"];
305 for _ in 0..128 {
306 let item = random_item_with_rng(&items, &mut rng)
307 .expect("non-empty slice should produce an item");
308 assert!(items.contains(item));
309 }
310 }
311
312 #[test]
313 fn chance_rejects_non_positive_and_nan_probabilities() {
314 let mut rng = rand::rngs::StdRng::seed_from_u64(29);
315 assert!(!chance(-1.0));
316 assert!(!chance_with_rng(0.0, &mut rng));
317 assert!(!chance_with_rng(f64::NAN, &mut rng));
318 assert!(!chance_with_rng(f64::NEG_INFINITY, &mut rng));
319 }
320
321 #[test]
322 fn chance_accepts_certain_and_overfull_probabilities() {
323 let mut rng = rand::rngs::StdRng::seed_from_u64(31);
324 assert!(chance_with_rng(1.0, &mut rng));
325 assert!(chance_with_rng(7.0, &mut rng));
326 assert!(chance_with_rng(f64::INFINITY, &mut rng));
327 }
328
329 #[test]
330 fn chance_tracks_probability() {
331 let mut rng = rand::rngs::StdRng::seed_from_u64(33);
332 let mut hits = 0usize;
333 for _ in 0..10_000 {
334 if chance_with_rng(0.25, &mut rng) {
335 hits += 1;
336 }
337 }
338 assert!(
339 (2_350..=2_650).contains(&hits),
340 "0.25 probability should produce about 2500 hits, got {hits}"
341 );
342 }
343
344 #[test]
345 fn weighted_index_rejects_empty_or_unusable_domains() {
346 let mut rng = rand::rngs::StdRng::seed_from_u64(21);
347 assert_eq!(weighted_index(&[]), None);
348 assert_eq!(
349 weighted_index_with_rng(&[0.0, -1.0, f64::NAN, f64::INFINITY], &mut rng),
350 None
351 );
352 }
353
354 #[test]
355 fn weighted_index_ignores_unusable_weights() {
356 let mut rng = rand::rngs::StdRng::seed_from_u64(23);
357 for _ in 0..256 {
358 assert_eq!(
359 weighted_index_with_rng(&[0.0, f64::NAN, 7.0, -2.0], &mut rng),
360 Some(2)
361 );
362 }
363 }
364
365 #[test]
366 fn weighted_index_by_projects_item_weights() {
367 let mut rng = rand::rngs::StdRng::seed_from_u64(25);
368 let items = [
369 ("ignored", 0.0),
370 ("chosen", 4.0),
371 ("also_ignored", f64::NAN),
372 ];
373 assert_eq!(
374 weighted_index_by_with_rng(&items, |(_, weight)| *weight, &mut rng),
375 Some(1)
376 );
377 }
378
379 #[test]
380 fn weighted_index_tracks_weight_ratio() {
381 let mut rng = rand::rngs::StdRng::seed_from_u64(27);
382 let mut second = 0usize;
383 for _ in 0..10_000 {
384 if weighted_index_with_rng(&[1.0, 3.0], &mut rng) == Some(1) {
385 second += 1;
386 }
387 }
388 assert!(
389 (7_200..=7_800).contains(&second),
390 "3:1 weighted sampling should choose index 1 about 75% of the time, got {second}"
391 );
392 }
393
394 #[test]
395 fn lower_alphanumeric_allows_empty_output() {
396 assert_eq!(random_lower_alphanumeric(0), "");
397 }
398
399 #[test]
400 fn lower_alphanumeric_uses_dns_safe_alphabet() {
401 let mut rng = rand::rngs::StdRng::seed_from_u64(11);
402 let value = random_lower_alphanumeric_with_rng(256, &mut rng);
403 assert_eq!(value.len(), 256);
404 assert!(value.bytes().all(|byte| LOWER_ALPHANUMERIC.contains(&byte)));
405 }
406
407 #[test]
408 fn ascii_string_rejects_empty_alphabet() {
409 let mut rng = rand::rngs::StdRng::seed_from_u64(13);
410 assert_eq!(random_ascii_string_with_rng(8, b"", &mut rng), None);
411 }
412
413 #[test]
414 fn ascii_string_rejects_non_ascii_alphabet() {
415 let mut rng = rand::rngs::StdRng::seed_from_u64(15);
416 assert_eq!(random_ascii_string_with_rng(8, &[0xff], &mut rng), None);
417 }
418
419 #[test]
420 fn ascii_string_uses_caller_alphabet() {
421 let mut rng = rand::rngs::StdRng::seed_from_u64(17);
422 let value = random_ascii_string_with_rng(128, b"ab7", &mut rng)
423 .expect("valid alphabet should generate a string");
424 assert_eq!(value.len(), 128);
425 assert!(value.bytes().all(|byte| matches!(byte, b'a' | b'b' | b'7')));
426 }
427
428 #[test]
429 fn seed_from_u64_is_deterministic() {
430 let a = seed_from_u64(42);
431 let b = seed_from_u64(42);
432 assert_eq!(a, b);
433 assert_ne!(a, seed_from_u64(43));
434 }
435
436 #[test]
437 fn seeded_rng_from_u64_reproduces_samples() {
438 let seed = 7;
439 let mut rng_a = seeded_rng_from_u64(seed);
440 let mut rng_b = seeded_rng_from_u64(seed);
441 assert_eq!(rng_a.gen::<u64>(), rng_b.gen::<u64>());
442 assert_eq!(
443 random_index_with_rng(100, &mut rng_a),
444 random_index_with_rng(100, &mut rng_b)
445 );
446 }
447
448 #[test]
449 fn seed_from_u64_expands_to_full_32_bytes() {
450 let seed = seed_from_u64(12345);
451 assert!(
452 seed.iter().any(|b| *b != 0),
453 "seed should expand beyond zeros"
454 );
455 }
456 #[test]
457 fn ascii_string_rejects_invalid_alphabets_even_on_zero_len() {
458 let mut rng = rand::rngs::StdRng::seed_from_u64(19);
459 assert_eq!(random_ascii_string_with_rng(0, b"", &mut rng), None);
460 assert_eq!(random_ascii_string_with_rng(0, &[0x80], &mut rng), None);
461 assert_eq!(
462 random_ascii_string_with_rng(0, b"abc", &mut rng),
463 Some(String::new())
464 );
465 }
466
467 #[test]
468 fn weighted_index_accepts_single_maximal_finite_weight() {
469 let mut rng = rand::rngs::StdRng::seed_from_u64(21);
470 assert_eq!(weighted_index_with_rng(&[f64::MAX], &mut rng), Some(0));
471 }
472
473 #[test]
474 fn weighted_index_ignores_infinite_weights() {
475 let mut rng = rand::rngs::StdRng::seed_from_u64(23);
476 assert_eq!(
477 weighted_index_with_rng(&[f64::INFINITY, f64::NEG_INFINITY], &mut rng),
478 None
479 );
480 assert_eq!(
481 weighted_index_with_rng(&[f64::INFINITY, 5.0, f64::NEG_INFINITY], &mut rng),
482 Some(1)
483 );
484 }
485
486 #[test]
487 fn chance_handles_subnormal_positive_probability() {
488 let mut rng = rand::rngs::StdRng::seed_from_u64(25);
489 let _res = chance_with_rng(f64::MIN_POSITIVE, &mut rng);
490 }
491}