Skip to content

Commit

Permalink
Add better random number functions.
Browse files Browse the repository at this point in the history
Useful if you want to draw random lines.
  • Loading branch information
thejpster committed Dec 30, 2024
1 parent dc84465 commit 6458662
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ static ARG_COUNT: AtomicUsize = AtomicUsize::new(0);
static ARG_PTR: AtomicPtr<FfiString> = AtomicPtr::new(core::ptr::null_mut());

/// Random number generator state
static RAND_STATE: core::sync::atomic::AtomicU16 = core::sync::atomic::AtomicU16::new(0);
static RAND_STATE: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);

// ============================================================================
// Types
Expand Down Expand Up @@ -459,17 +459,34 @@ pub fn wait_for_key() -> WaitForKey {
}

/// Seed the 16-bit psuedorandom number generator
pub fn srand(seed: u16) {
pub fn srand(seed: u32) {
RAND_STATE.store(seed, core::sync::atomic::Ordering::Relaxed);
}

/// Get a 16-bit psuedorandom number
pub fn rand() -> u16 {
/// Get a 32-bit psuedorandom number
pub fn rand() -> u32 {
let mut state = RAND_STATE.load(core::sync::atomic::Ordering::Relaxed);
let bit = (state ^ (state >> 2) ^ (state >> 3) ^ (state >> 5)) & 0x01;
state = (state >> 1) | (bit << 15);
state = state.wrapping_mul(1103515245).wrapping_add(12345);
let bits1 = state >> 16;
state = state.wrapping_mul(1103515245).wrapping_add(12345);
let bits2 = state >> 16;
RAND_STATE.store(state, core::sync::atomic::Ordering::Relaxed);
state
(bits1 << 16) | bits2
}

/// Get a random number from a range
pub fn random_in(range: core::ops::Range<u32>) -> u32 {
let count = range.end - range.start;
let bucket_size = u32::MAX / count;
let limit = bucket_size * count;
let rand_value = loop {
let temp = rand() as u32;

Check warning on line 483 in src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

casting to the same type is unnecessary (`u32` -> `u32`)

warning: casting to the same type is unnecessary (`u32` -> `u32`) --> src/lib.rs:483:20 | 483 | let temp = rand() as u32; | ^^^^^^^^^^^^^ help: try: `rand()` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast = note: `#[warn(clippy::unnecessary_cast)]` on by default
if temp <= limit {
break temp;
}
};
let result = rand_value / bucket_size;
result + range.start
}

/// Get the API structure so we can call APIs manually.
Expand Down

0 comments on commit 6458662

Please sign in to comment.