1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
/// A generic Random number generator
///
/// # Example
///
/// ```rust
/// use common_traits::{Rng, RngNext};
///
/// pub struct Xorshift64(u64);
///
/// impl Rng for Xorshift64 {
/// fn new(seed: u64) -> Self {
/// Self(seed.saturating_add(1))
/// }
/// }
///
/// impl RngNext<u64> for Xorshift64 {
/// fn next_inner(&mut self) -> u64 {
/// self.0 ^= self.0 << 13;
/// self.0 ^= self.0 >> 7;
/// self.0 ^= self.0 << 17;
/// self.0
/// }
/// }
///
/// impl RngNext<f64> for Xorshift64 {
/// fn next_inner(&mut self) -> f64 {
/// let v: u64 = (self.next::<u64>() >> 11) | (1023 << 52);
/// let r: f64 = f64::from_le_bytes(v.to_le_bytes());
/// r - 1f64
/// }
/// }
/// ```
pub trait Rng {
/// Instantiate a new Rng making no assumptions on its seed.
fn new(seed: u64) -> Self;
/// automatic dispatching of the implemmentation, no need to re-implement
#[inline(always)]
fn next<T>(&mut self) -> T
where
Self: RngNext<T>,
{
<Self as RngNext<T>>::next_inner(self)
}
}
/// Implementation of a specific type generation for a Rng
///
/// # Example
///
/// ```rust
/// use common_traits::{Rng, RngNext};
///
/// pub struct Xorshift64(u64);
///
/// impl Rng for Xorshift64 {
/// fn new(seed: u64) -> Self {
/// Self(seed.saturating_add(1))
/// }
/// }
///
/// impl RngNext<u64> for Xorshift64 {
/// fn next_inner(&mut self) -> u64 {
/// self.0 ^= self.0 << 13;
/// self.0 ^= self.0 >> 7;
/// self.0 ^= self.0 << 17;
/// self.0
/// }
/// }
///
/// impl RngNext<f64> for Xorshift64 {
/// fn next_inner(&mut self) -> f64 {
/// let v: u64 = (self.next::<u64>() >> 11) | (1023 << 52);
/// let r: f64 = f64::from_le_bytes(v.to_le_bytes());
/// r - 1f64
/// }
/// }
/// ```
pub trait RngNext<T> {
fn next_inner(&mut self) -> T;
}