rng-pack 0.2.5

Random number generator variety pack
Documentation
use crate::rng32::Rng32;
use std::slice::from_raw_parts_mut;

/// A 32-bit Xorshift random number generator.
///
/// This generator uses a shift-register based algorithm.
///
/// # Examples
///
/// ```
/// use rng_pack::xorshift32::Xorshift32;
///
/// let mut rng = Xorshift32::new(12345);
/// let val = rng.nextu();
/// ```
#[repr(C)]
pub struct Xorshift32 {
    a: u32,
}

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

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

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

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

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

    /// Returns a random element from a slice.
    ///
    /// # Arguments
    ///
    /// * `choices` - The slice to choose from.
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift32::Xorshift32;
    ///
    /// let mut rng = Xorshift32::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 i32 - 1);
        &choices[index as usize]
    }
}

impl Rng32 for Xorshift32 {
    #[inline]
    fn randi(&mut self, min: i32, max: i32) -> i32 {
        self.randi(min, max)
    }

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

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

#[unsafe(no_mangle)]
pub extern "C" fn xorshift32_new(seed: u32) -> *mut Xorshift32 {
    Box::into_raw(Box::new(Xorshift32::new(seed)))
}

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

#[unsafe(no_mangle)]
pub extern "C" fn xorshift32_next_u32s(ptr: *mut Xorshift32, out: *mut u32, 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 xorshift32_next_f32s(ptr: *mut Xorshift32, out: *mut f32, 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 xorshift32_rand_i32s(
    ptr: *mut Xorshift32,
    out: *mut i32,
    count: usize,
    min: i32,
    max: i32,
) {
    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 xorshift32_rand_f32s(
    ptr: *mut Xorshift32,
    out: *mut f32,
    count: usize,
    min: f32,
    max: f32,
) {
    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::xorshift32::Xorshift32;

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

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