Skip to content

Commit eeba8fd

Browse files
committed
Small optimizations to rand
1 parent 9ff85c7 commit eeba8fd

File tree

1 file changed

+4
-9
lines changed

1 file changed

+4
-9
lines changed

src/rand.rs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,12 @@ use core::{
88

99
use portable_atomic::AtomicU32;
1010

11-
// static mut RAND: Option<GnuRand> = None;
1211
static RAND_STATE: AtomicU32 = AtomicU32::new(0x0);
1312

1413
/// Rust implementation of C library function `srand`
1514
#[cfg_attr(feature = "rand", no_mangle)]
1615
pub extern "C" fn srand(seed: c_uint) {
17-
RAND_STATE.store(seed, Ordering::Release);
16+
RAND_STATE.store(seed, Ordering::Relaxed);
1817
}
1918

2019
/// Rust implementation of C library function `rand`.
@@ -28,24 +27,20 @@ pub extern "C" fn srand(seed: c_uint) {
2827
#[cfg_attr(feature = "rand", no_mangle)]
2928
pub extern "C" fn rand() -> c_int {
3029
let mut current_state = RAND_STATE.load(Ordering::Relaxed);
31-
let mut new_state = current_state;
32-
let mut result = unsafe { crate::rand_r(&mut new_state as *mut _) };
3330

3431
loop {
32+
let mut new_state = current_state;
33+
let result = unsafe { crate::rand_r(&mut new_state as *mut _) };
3534
match RAND_STATE.compare_exchange_weak(
3635
current_state,
3736
new_state,
3837
Ordering::SeqCst,
3938
Ordering::Relaxed,
4039
) {
41-
Ok(_) => break,
40+
Ok(_) => return result as _,
4241
Err(c) => current_state = c,
4342
}
44-
new_state = current_state;
45-
result = unsafe { crate::rand_r(&mut new_state as *mut _) };
4643
}
47-
48-
result as _
4944
}
5045

5146
#[cfg(test)]

0 commit comments

Comments
 (0)