rng-pack 0.2.5

Random number generator variety pack
Documentation
use crate::rng64::Rng64;
use std::slice::from_raw_parts_mut;

/// A 64-bit Xorshift random number generator.
///
/// # Examples
///
/// ```
/// use rng_pack::xorshift64::Xorshift64;
///
/// let mut rng = Xorshift64::new(12345);
/// let val = rng.nextu();
/// ```
#[repr(C)]
pub struct Xorshift64 {
    a: u64,
}

impl Xorshift64 {
    /// Creates a new `Xorshift64` instance.
    ///
    /// # Arguments
    ///
    /// * `seed` - The initial seed value.
    pub fn new(seed: u64) -> Self {
        Self { a: seed }
    }

    /// Generates the next random `u64` value.
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift64::Xorshift64;
    ///
    /// let mut rng = Xorshift64::new(12345);
    /// let val = rng.nextu();
    /// ```
    #[inline]
    pub fn nextu(&mut self) -> u64 {
        let mut x = self.a;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.a = x;
        x
    }

    /// Generates the next random `f64` value in the range [0, 1).
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift64::Xorshift64;
    ///
    /// let mut rng = Xorshift64::new(12345);
    /// let val = rng.nextf();
    /// assert!(val >= 0.0 && val < 1.0);
    /// ```
    #[inline]
    pub fn nextf(&mut self) -> f64 {
        self.nextu() as f64 * (1.0 / (u64::MAX as f64 + 1.0))
    }

    /// Generates a random `i64` value in the range [min, max].
    ///
    /// # Arguments
    ///
    /// * `min` - The lower bound (inclusive).
    /// * `max` - The upper bound (inclusive).
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift64::Xorshift64;
    ///
    /// let mut rng = Xorshift64::new(12345);
    /// let val = rng.randi(1, 10);
    /// assert!(val >= 1 && val <= 10);
    /// ```
    #[inline]
    pub fn randi(&mut self, min: i64, max: i64) -> i64 {
        let range = (max as i128 - min as i128 + 1) as u128;
        let x = self.nextu();
        ((x as u128 * range) >> 64) as i64 + min
    }

    /// Generates a random `f64` value in the range [min, max).
    ///
    /// # Arguments
    ///
    /// * `min` - The lower bound (inclusive).
    /// * `max` - The upper bound (exclusive).
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift64::Xorshift64;
    ///
    /// let mut rng = Xorshift64::new(12345);
    /// let val = rng.randf(1.0, 10.0);
    /// assert!(val >= 1.0 && val < 10.0);
    /// ```
    #[inline]
    pub fn randf(&mut self, min: f64, max: f64) -> f64 {
        let range = max - min;
        let scale = range * (1.0 / (u64::MAX as f64 + 1.0));
        (self.nextu() as f64 * scale) + min
    }

    /// Returns a random element from a slice.
    ///
    /// # Arguments
    ///
    /// * `choices` - The slice to choose from.
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift64::Xorshift64;
    ///
    /// let mut rng = Xorshift64::new(12345);
    /// let choices = [1, 2, 3, 4, 5];
    /// let val = rng.choice(&choices);
    /// assert!(choices.contains(val));
    /// ```
    #[inline]
    pub fn choice<'a, T>(&mut self, choices: &'a [T]) -> &'a T {
        let index = self.randi(0, choices.len() as i64 - 1);
        &choices[index as usize]
    }
}

impl Rng64 for Xorshift64 {
    #[inline]
    fn randi(&mut self, min: i64, max: i64) -> i64 {
        self.randi(min, max)
    }

    #[inline]
    fn randf(&mut self, min: f64, max: f64) -> f64 {
        self.randf(min, max)
    }

    #[inline]
    fn choice<'a, T>(&mut self, choices: &'a [T]) -> &'a T {
        self.choice(choices)
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn xorshift64_new(seed: u64) -> *mut Xorshift64 {
    Box::into_raw(Box::new(Xorshift64::new(seed)))
}

#[unsafe(no_mangle)]
pub extern "C" fn xorshift64_free(ptr: *mut Xorshift64) {
    if !ptr.is_null() {
        unsafe { drop(Box::from_raw(ptr)) };
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn xorshift64_next_u64s(ptr: *mut Xorshift64, out: *mut u64, count: usize) {
    unsafe {
        let rng = &mut *ptr;
        let buffer = from_raw_parts_mut(out, count);
        for v in buffer {
            *v = rng.nextu();
        }
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn xorshift64_next_f64s(ptr: *mut Xorshift64, out: *mut f64, count: usize) {
    unsafe {
        let rng = &mut *ptr;
        let buffer = from_raw_parts_mut(out, count);
        for v in buffer {
            *v = rng.nextf();
        }
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn xorshift64_rand_i64s(
    ptr: *mut Xorshift64,
    out: *mut i64,
    count: usize,
    min: i64,
    max: i64,
) {
    unsafe {
        let rng = &mut *ptr;
        let buffer = from_raw_parts_mut(out, count);
        for v in buffer {
            *v = rng.randi(min, max);
        }
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn xorshift64_rand_f64s(
    ptr: *mut Xorshift64,
    out: *mut f64,
    count: usize,
    min: f64,
    max: f64,
) {
    unsafe {
        let rng = &mut *ptr;
        let buffer = from_raw_parts_mut(out, count);
        for v in buffer {
            *v = rng.randf(min, max);
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::xorshift64::Xorshift64;

    #[test]
    fn it_works() {
        let mut rng = Xorshift64::new(1);

        assert_eq!(rng.nextu(), 1082269761);
        assert_eq!(rng.nextf(), 0.06250387570981203);
        assert_eq!(rng.randi(10, 20), 16);
        assert_eq!(rng.randf(10.0, 20.0), 19.58327592195351);
        assert_eq!(*rng.choice(&[0, 1, 2, 3, 4]), 2);
        assert_eq!(*rng.choice(&[1, 2, 3, 4, 5]), 5);
        assert_eq!(*rng.choice(&[2, 3, 4, 5, 6]), 5);
        assert_eq!(*rng.choice(&[3, 4, 5, 6, 7]), 6);
    }
}