-
Notifications
You must be signed in to change notification settings - Fork 14
Add rand, srand, and rand_r implementations #31
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
a1f810e
Implement rand_r
Sympatron bd5c82f
Implement rand and srand
Sympatron 329b743
Use rand_r algorithm for rand
Sympatron f109f21
Export RAND_MAX symbol
Sympatron 9ff85c7
Require CAS for rand
Sympatron bc612e3
Small optimizations to rand
Sympatron File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
//! Rust implementation of C library functions `rand` and `srand` | ||
//! | ||
//! Licensed under the Blue Oak Model Licence 1.0.0 | ||
use core::{ | ||
ffi::{c_int, c_uint}, | ||
sync::atomic::Ordering, | ||
}; | ||
|
||
use portable_atomic::AtomicU32; | ||
|
||
static RAND_STATE: AtomicU32 = AtomicU32::new(0x0); | ||
|
||
/// Rust implementation of C library function `srand` | ||
#[cfg_attr(feature = "rand", no_mangle)] | ||
pub extern "C" fn srand(seed: c_uint) { | ||
RAND_STATE.store(seed, Ordering::Relaxed); | ||
} | ||
|
||
/// Rust implementation of C library function `rand`. | ||
/// | ||
/// Returns a pseudo-random integer in the range 0 to [`RAND_MAX`](crate::RAND_MAX) (inclusive). | ||
/// This requires CAS operations. If your platform does not support them natively, | ||
/// you either have to enable the `rand-cs` feature of `tinyrlibc`, | ||
/// or the [`critical-section`](https://docs.rs/portable-atomic/1.9.0/portable_atomic/#optional-features-critical-section) feature, | ||
/// or the [`unsafe-assume-single-core`](https://docs.rs/portable-atomic/1.9.0/portable_atomic/#optional-features-unsafe-assume-single-core) feature | ||
/// in [`portable-atomic`](https://crates.io/crates/portable-atomic). | ||
#[cfg_attr(feature = "rand", no_mangle)] | ||
pub extern "C" fn rand() -> c_int { | ||
let mut current_state = RAND_STATE.load(Ordering::Relaxed); | ||
|
||
loop { | ||
let mut new_state = current_state; | ||
let result = unsafe { crate::rand_r(&mut new_state as *mut _) }; | ||
match RAND_STATE.compare_exchange_weak( | ||
current_state, | ||
new_state, | ||
Ordering::Relaxed, | ||
Ordering::Relaxed, | ||
) { | ||
Ok(_) => return result as _, | ||
Err(c) => current_state = c, | ||
} | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod test { | ||
use super::*; | ||
#[test] | ||
fn test_rand() { | ||
assert_eq!(rand(), 1012483); | ||
assert_eq!(rand(), 1716955678); | ||
assert_eq!(rand(), 1792309081); | ||
srand(5); | ||
assert_eq!(rand(), 234104183); | ||
assert_eq!(rand(), 1214203243); | ||
assert_eq!(rand(), 1803669307); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
//! Rust implementation of C library function `rand_r` | ||
//! | ||
//! Licensed under the Blue Oak Model Licence 1.0.0 | ||
use core::ffi::{c_int, c_uint}; | ||
|
||
#[cfg_attr(not(feature = "rand_r"), export_name = "tinyrlibc_RAND_MAX")] | ||
#[cfg_attr(feature = "rand_r", no_mangle)] | ||
pub static RAND_MAX: c_int = 0x7FFF_FFFC as _; | ||
|
||
/// Rust implementation of C library function `rand_r` | ||
/// | ||
/// Passing NULL (core::ptr::null()) gives undefined behaviour. | ||
#[cfg_attr(not(feature = "rand_r"), export_name = "tinyrlibc_rand_r")] | ||
#[cfg_attr(feature = "rand_r", no_mangle)] | ||
pub unsafe extern "C" fn rand_r(seedp: *mut c_uint) -> c_int { | ||
// This algorithm is mentioned in the ISO C standard, here extended for 32 bits. | ||
let mut next = *seedp; | ||
let mut result: c_int; | ||
|
||
next = next.wrapping_mul(1103515245); | ||
next = next.wrapping_add(12345); | ||
result = ((next / 65536) % 2048) as c_int; | ||
|
||
next = next.wrapping_mul(1103515245); | ||
next = next.wrapping_add(12345); | ||
result <<= 10; | ||
result ^= ((next / 65536) % 1024) as c_int; | ||
|
||
next = next.wrapping_mul(1103515245); | ||
next = next.wrapping_add(12345); | ||
result <<= 10; | ||
result ^= ((next / 65536) % 1024) as c_int; | ||
|
||
*seedp = next; | ||
|
||
result - 1 | ||
} | ||
|
||
#[cfg(test)] | ||
mod test { | ||
use super::*; | ||
#[test] | ||
fn test_rand_r() { | ||
unsafe { | ||
let mut seed = 5; | ||
// Values taken from glibc implementation | ||
assert_eq!(rand_r(&mut seed), 234104183); | ||
assert_eq!(rand_r(&mut seed), 1214203243); | ||
assert_eq!(rand_r(&mut seed), 1803669307); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should be odd.
As you're pulling 31 random bits, I'm pretty sure this should be 0x7fff_ffff.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I tested all
2^32
possible seeds and the value never went over0x7FFF_FFFC
. This seemed strange to me and I didn't really know what to do withRAND_MAX
in that case. The original algorithm goes to up0x7FFF_FFFD
, but does not include0
. That is why I subtracted1
, because I thought it would be way more unexpected to never get0
then to never get0x7FFF_FFFD
.Since it may be odd to have
RAND_MAX
not be2^n - 1
, we could either reduce it to 30 bits at0x3FFF_FFFF
or "lie" and set it to0x7FFF_FFFF
which could be bad, because knowingRAND_MAX
is necessary if you want to userand
to get a non-biased distribution.Since
tinyrlibc
is mainly used by C code,RAND_MAX
will probably never be used directly, because in CRAND_MAX
is a ´#defineanyway, so this value will not be seen by the code using
rand`.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How many times did you call rand()? The 10 or 11 bits that get pulled should be relatively uniform. It might be worth logging them individually. Then if they are uniform, you should get values from 0 to 2^31 - 1 by combining 31 random bits together.