brutils 0.1.51

Some utilities for Rust
Documentation
//! Random number generation

use std::time::{SystemTime, UNIX_EPOCH};

/// Initializes random number generator
/// 
/// Call once at startup
pub fn random_init() {
    unsafe {
        libc::srand(SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u32);
        libc::rand();
    };
}

/// Returns maximum number that random_int() can return
pub fn random_max_int() -> i32 {
    libc::RAND_MAX
}

/// Generates random int
/// 
/// 0 - random_max_int()
pub fn random_int() -> i32 {
    unsafe { libc::rand() }
}

/// Generates random int between min and max
/// 
/// inclusive - exclusive
pub fn random_int_range(min: i32, max: i32) -> i32 {
    unsafe { min + (libc::rand() % (max - min)) }
}

/// Generates random float between 0 - 1
pub fn random_float() -> f32 {
    unsafe { libc::rand() as f32 / libc::RAND_MAX as f32 }
}

/// Generates random float between min and max
/// 
/// inclusive - exclusive
pub fn random_float_range(min: f32, max: f32) -> f32 {
    unsafe { min + libc::rand() as f32 / libc::RAND_MAX as f32 * (max - min) }
}

/// Generates random double between 0 - 1
pub fn random_double() -> f64 {
    unsafe { libc::rand() as f64 / libc::RAND_MAX as f64 }
}

/// Generates random double between min and max
/// 
/// inclusive - exclusive
pub fn random_double_range(min: f64, max: f64) -> f64 {
    unsafe { min + libc::rand() as f64 / libc::RAND_MAX as f64 * (max - min) }
}