diff --git a/src/stdlib/Cargo.toml b/src/stdlib/Cargo.toml index 97f5d44187b6fc477f3bb8ece793d9fd6d56fddd..cc96a5dc070fbb56e8961f4b62c2a339c27a3d88 100644 --- a/src/stdlib/Cargo.toml +++ b/src/stdlib/Cargo.toml @@ -12,3 +12,4 @@ platform = { path = "../platform" } ralloc = { path = "../../ralloc", default-features = false } ctype = { path = "../ctype" } errno = { path = "../errno" } +rand = { git = "https://github.com/rust-lang-nursery/rand/", default-features = false } diff --git a/src/stdlib/src/lib.rs b/src/stdlib/src/lib.rs index 575f759a264f4eb6624c2577be08145114bbac14..9c948d6779a381db7afdb911fa20aad476e1f982 100644 --- a/src/stdlib/src/lib.rs +++ b/src/stdlib/src/lib.rs @@ -8,8 +8,10 @@ extern crate ctype; extern crate errno; extern crate platform; extern crate ralloc; +extern crate rand; use core::{ptr, str}; +use rand::{Rng, SeedableRng, XorShiftRng}; use errno::*; use platform::types::*; @@ -19,8 +21,10 @@ static ALLOCATOR: ralloc::Allocator = ralloc::Allocator; pub const EXIT_FAILURE: c_int = 1; pub const EXIT_SUCCESS: c_int = 0; +pub const RAND_MAX: c_int = 2147483647; static mut ATEXIT_FUNCS: [Option<extern "C" fn()>; 32] = [None; 32]; +static mut RNG: Option<XorShiftRng> = None; #[no_mangle] pub unsafe extern "C" fn a64l(s: *const c_char) -> c_long { @@ -375,8 +379,16 @@ pub extern "C" fn qsort( } #[no_mangle] -pub extern "C" fn rand() -> c_int { - unimplemented!(); +pub unsafe extern "C" fn rand() -> c_int { + match RNG { + Some(ref mut rng) => rng.gen_range::<c_int>(0, RAND_MAX), + None => { + let mut rng = XorShiftRng::from_seed([1; 16]); + let ret = rng.gen_range::<c_int>(0, RAND_MAX); + RNG = Some(rng); + ret + } + } } #[no_mangle] @@ -425,8 +437,8 @@ pub extern "C" fn setstate(state: *const c_char) -> *mut c_char { } #[no_mangle] -pub extern "C" fn srand(seed: c_uint) { - unimplemented!(); +pub unsafe extern "C" fn srand(seed: c_uint) { + RNG = Some(XorShiftRng::from_seed([seed as u8; 16])); } #[no_mangle] diff --git a/tests/.gitignore b/tests/.gitignore index 3fecd58cfb2de558a99705cebfaf23555bc5d035..28ee3728268142cc236e2e28c53481e466481a5b 100644 --- a/tests/.gitignore +++ b/tests/.gitignore @@ -27,6 +27,7 @@ /sprintf /stdlib/a64l /stdlib/bsearch +/stdlib/rand /stdlib/strtol /string/strchr /string/strcspn diff --git a/tests/Makefile b/tests/Makefile index 52983f3f6a8cce4b5fa5c5078ebdab452f6114e3..513235e8f899ee8a8e06faf171bd6bce13039ec4 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -23,6 +23,7 @@ EXPECT_BINS=\ stdlib/bsearch \ stdlib/strtol \ stdlib/a64l \ + stdlib/rand \ string/strncmp \ string/strcspn \ string/strchr \ diff --git a/tests/stdlib/rand.c b/tests/stdlib/rand.c new file mode 100644 index 0000000000000000000000000000000000000000..484b09906b4d3555280ef0a1b7b92fc41fb0b3a8 --- /dev/null +++ b/tests/stdlib/rand.c @@ -0,0 +1,8 @@ +#include <stdlib.h> +#include <stdio.h> + +int main(int argc, char** argv) { + printf("%d\n", rand()); + srand(259); + printf("%d\n", rand()); +}