bsd4random 0.9.0

4.4BSD random number generator
Documentation
#![forbid(unsafe_code)]
#![allow(non_camel_case_types)]
#![forbid(missing_docs)]

// Copyright (c) Radim Kolar 2024
// SPDX-License-Identifier: BSD-3-Clause

//! BSD random number generator.
//!
//! It is Linear congruential generator with nodulus 2^31,
//! multiplier 1103515245 and increment 12345. Outputs 31
//! bits of randomness with more randomness in higher bits.


/**
Classic 32-bit 4.4BSD rand() number generator.

It got replaced in FreeBSD 5, still included
in NetBSD and OpenBSD.
*/ 
pub struct BSD(u32);

/**
  Maximum random number returned by generator.

  Returned numbers are positive integers in
  [0, RAND_MAX] range inclusive.
*/
const RAND_MAX: i32 = 0x7fffffff;

impl BSD {
   /**
    Constructs new BSD random generator.

    Generator is implicitly initialized
    as if srand(1) had been invoked explicitly.
   */   
   pub fn new() -> Self {
      Self (1)
   }

   /**
    Seeds the algorithm with the seed parameter.

    Repeatable sequence of rand() output may be
    obtained by calling srand() with the same
    seed.
   */
   pub fn srand(seed: u32) -> Self {
      Self (seed)
   }

   /**
     Computes a sequence of pseudo-random integers
     in the range 0 to RAND_MAX, inclusive.
   */
   pub fn rand(&mut self) -> i32 {
        self.0 = self.0.wrapping_mul(1103515245).wrapping_add(12345);
   	( self.0 % (RAND_MAX as u32 + 1) ) as i32
   }

   /** 
     Computes a random number from provided seed.

     Seed is updated and random number is returned.
   */
   pub fn rand_r(seed: &mut u32) -> i32 {
        *seed = seed.wrapping_mul(1103515245).wrapping_add(12345);
   	( *seed % (RAND_MAX as u32 + 1) ) as i32
   }
}


#[cfg(test)]
#[path = "bsd_tests.rs"]
mod tests;