added locking to xorshift64

This commit is contained in:
monica 2023-03-22 14:33:34 -04:00
parent dc64a277c6
commit 3919e368dc
No known key found for this signature in database
GPG key ID: ADCCDBBE0E3D3B3B

View file

@ -1,4 +1,4 @@
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Mutex};
use libc::c_int; use libc::c_int;
@ -119,14 +119,15 @@ unsafe impl Send for SecureRandom {}
/// Get a non-cryptographic random number. /// Get a non-cryptographic random number.
pub fn xorshift64_random() -> u64 { pub fn xorshift64_random() -> u64 {
static mut XORSHIFT64_STATE: AtomicU64 = AtomicU64::new(0); static mut XORSHIFT64_STATE: Mutex<u64> = Mutex::new(0);
let mut x = unsafe { XORSHIFT64_STATE.load(Ordering::Relaxed) }; let mut state = unsafe { XORSHIFT64_STATE.lock().unwrap() };
let mut x = *state;
while x == 0 { while x == 0 {
x = next_u64_secure(); x = next_u64_secure();
} }
x ^= x.wrapping_shl(13); x ^= x.wrapping_shl(13);
x ^= x.wrapping_shr(7); x ^= x.wrapping_shr(7);
x ^= x.wrapping_shl(17); x ^= x.wrapping_shl(17);
unsafe { XORSHIFT64_STATE.store(x, Ordering::Relaxed) }; *state = x;
x x
} }