scsys_core/id/impls/
impl_id_rand.rs

1/*
2    appellation: impl_id_rand <module>
3    authors: @FL03
4*/
5use crate::id::Id;
6use rand_distr::uniform::{SampleRange, SampleUniform};
7use rand_distr::{Distribution, StandardNormal, StandardUniform};
8
9impl<T> Id<T> {
10    /// generate a new, random identifier from a value of type `T`
11    pub fn random() -> Self
12    where
13        StandardUniform: Distribution<T>,
14    {
15        use rand::Rng;
16        let mut rng = rand::rng();
17        Self::new(rng.random())
18    }
19
20    pub fn random_between<R>(range: R) -> Self
21    where
22        R: SampleRange<T>,
23        T: SampleUniform,
24    {
25        Self::new(rand::random_range(range))
26    }
27    /// generate a random index from a value of type `T` using the provided [`Rng`](rand::Rng)
28    pub fn random_with<R, Dist>(rng: &mut R, distr: Dist) -> Self
29    where
30        R: ?Sized + rand::RngCore,
31        Dist: Distribution<T>,
32    {
33        use rand::Rng;
34        // generate a random u128 and cast it to usize
35        let rid = rng.sample(distr);
36        // cast the random u128 to usize
37        Self::new(rid)
38    }
39}
40
41impl<T> Distribution<Id<T>> for StandardNormal
42where
43    StandardNormal: Distribution<T>,
44{
45    fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> Id<T> {
46        Id::new(rng.sample(StandardNormal))
47    }
48}
49
50impl<T> Distribution<Id<T>> for StandardUniform
51where
52    StandardUniform: Distribution<T>,
53{
54    fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> Id<T> {
55        Id::new(rng.sample(StandardUniform))
56    }
57}