grain_id/rand.rs
1use super::*;
2use ::rand::{
3 Rng, RngExt as _,
4 distr::{Distribution, StandardUniform},
5};
6
7impl Distribution<GrainId> for StandardUniform {
8 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> GrainId {
9 <GrainId>::from_u64_lossy(rng.random())
10 }
11}
12impl GrainId {
13 /// Generate a new random [`GrainId`].
14 ///
15 /// Every value, including [`NIL`](Self::NIL) and [`MAX`](Self::MAX), is equally likely.
16 /// Uses [`rand::rng()`](::rand::rng); to use another generator, sample
17 /// [`StandardUniform`] with it instead (e.g. `rng.random::<GrainId>()`).
18 ///
19 /// # Examples
20 ///
21 /// ```
22 /// # use grain_id::*;
23 /// let id = GrainId::random();
24 /// assert!(id <= GrainId::MAX);
25 /// ```
26 #[cfg(feature = "std")]
27 pub fn random() -> Self {
28 <GrainId>::from_u64_lossy(::rand::random())
29 }
30}