|
| 1 | +//! Rust implementation of C library function `rand_r` |
| 2 | +//! |
| 3 | +//! Licensed under the Blue Oak Model Licence 1.0.0 |
| 4 | +use core::ffi::{c_int, c_uint}; |
| 5 | + |
| 6 | +#[cfg_attr(not(feature = "rand_r"), export_name = "tinyrlibc_RAND_MAX")] |
| 7 | +#[cfg_attr(feature = "rand_r", no_mangle)] |
| 8 | +pub static RAND_MAX: c_int = c_int::MAX; |
| 9 | + |
| 10 | +/// Rust implementation of C library function `rand_r` |
| 11 | +/// |
| 12 | +/// Passing NULL (core::ptr::null()) gives undefined behaviour. |
| 13 | +#[cfg_attr(not(feature = "rand_r"), export_name = "tinyrlibc_rand_r")] |
| 14 | +#[cfg_attr(feature = "rand_r", no_mangle)] |
| 15 | +pub unsafe extern "C" fn rand_r(seedp: *mut c_uint) -> c_int { |
| 16 | + let mut result: c_int; |
| 17 | + |
| 18 | + fn pump(input: u32) -> u32 { |
| 19 | + // This algorithm is mentioned in the ISO C standard |
| 20 | + input.wrapping_mul(1103515245).wrapping_add(12345) |
| 21 | + } |
| 22 | + |
| 23 | + fn select_top(state: u32, bits: usize) -> c_int { |
| 24 | + // ignore the lower 16 bits, as they are low quality |
| 25 | + ((state >> 16) & ((1 << bits) - 1)) as c_int |
| 26 | + } |
| 27 | + |
| 28 | + let mut next = *seedp as u32; |
| 29 | + if c_int::MAX == 32767 || cfg!(feature = "rand_max_i16") { |
| 30 | + // pull 15 bits in one go |
| 31 | + next = pump(next); |
| 32 | + result = select_top(next, 15); |
| 33 | + } else { |
| 34 | + // pull 31 bits in three goes |
| 35 | + next = pump(next); |
| 36 | + result = select_top(next, 11) << 20; |
| 37 | + next = pump(next); |
| 38 | + result |= select_top(next, 10) << 10; |
| 39 | + next = pump(next); |
| 40 | + result |= select_top(next, 10); |
| 41 | + } |
| 42 | + *seedp = next as c_uint; |
| 43 | + |
| 44 | + result as c_int |
| 45 | +} |
| 46 | + |
| 47 | +#[cfg(test)] |
| 48 | +mod test { |
| 49 | + use super::*; |
| 50 | + #[test] |
| 51 | + fn test_rand_r() { |
| 52 | + if c_int::MAX == 32767 || cfg!(feature = "rand_max_i16") { |
| 53 | + unsafe { |
| 54 | + let mut seed = 5; |
| 55 | + assert_eq!(rand_r(&mut seed), 18655); |
| 56 | + assert_eq!(rand_r(&mut seed), 8457); |
| 57 | + assert_eq!(rand_r(&mut seed), 10616); |
| 58 | + } |
| 59 | + } else { |
| 60 | + unsafe { |
| 61 | + let mut seed = 5; |
| 62 | + assert_eq!(rand_r(&mut seed), 234104184); |
| 63 | + assert_eq!(rand_r(&mut seed), 1214203244); |
| 64 | + assert_eq!(rand_r(&mut seed), 1803669308); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments