Files
continuwuity/src/core/utils/rand.rs
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

44 lines
908 B
Rust
Raw Normal View History

2024-07-03 08:44:59 +00:00
use std::{
ops::Range,
time::{Duration, SystemTime},
};
use arrayvec::ArrayString;
2026-02-20 22:57:45 +00:00
use rand::{Rng, RngExt, seq::SliceRandom};
2024-10-14 05:16:18 +00:00
pub fn shuffle<T>(vec: &mut [T]) {
2026-02-20 22:57:45 +00:00
let mut rng = rand::rng();
2024-10-14 05:16:18 +00:00
vec.shuffle(&mut rng);
}
2024-07-03 08:44:59 +00:00
pub fn string(length: usize) -> String {
2026-02-20 22:57:45 +00:00
rand::rng()
.sample_iter(&rand::distr::Alphanumeric)
2024-07-03 08:44:59 +00:00
.take(length)
.map(char::from)
.collect()
}
#[inline]
pub fn string_array<const LENGTH: usize>() -> ArrayString<LENGTH> {
let mut ret = ArrayString::<LENGTH>::new();
2026-02-20 22:57:45 +00:00
rand::rng()
.sample_iter(&rand::distr::Alphanumeric)
.take(LENGTH)
.map(char::from)
.for_each(|c| ret.push(c));
ret
}
2024-07-03 08:44:59 +00:00
#[inline]
#[must_use]
2025-01-22 08:51:15 +00:00
pub fn time_from_now_secs(range: Range<u64>) -> SystemTime {
2024-07-07 04:46:16 +00:00
SystemTime::now()
.checked_add(secs(range))
.expect("range does not overflow SystemTime")
}
2024-07-03 08:44:59 +00:00
#[must_use]
2026-02-20 22:57:45 +00:00
pub fn secs(range: Range<u64>) -> Duration { Duration::from_secs(rand::random_range(range)) }