Skip to content

core::rand - adding task local lazily initialized rng, as per #3439 #3639

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
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/libcore/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,33 @@ pub fn seeded_xorshift(x: u32, y: u32, z: u32, w: u32) -> Rng {
{mut x: x, mut y: y, mut z: z, mut w: w} as Rng
}


// used to make space in TLS for a random number generator
fn tls_rng_state(+_v: @RandRes) {}

/**
* Gives back a lazily initialized task-local random number generator,
* seeded by the system. Intended to be used in method chaining style, ie
* task_rng().gen_int().
*/
pub fn task_rng() -> Rng {
let r : Option<@RandRes>;
unsafe {
r = task::local_data::local_data_get(tls_rng_state);
}
match r {
None => {
let rng = @RandRes(rustrt::rand_new());
unsafe {
task::local_data::local_data_set(tls_rng_state, rng);
}
rng as Rng
}
Some(rng) => rng as Rng
}
}


#[cfg(test)]
pub mod tests {
#[test]
Expand Down Expand Up @@ -460,6 +487,14 @@ pub mod tests {
assert r.shuffle(~[]) == empty;
assert r.shuffle(~[1, 1, 1]) == ~[1, 1, 1];
}

#[test]
pub fn task_rng() {
let r = rand::task_rng();
r.gen_int();
assert r.shuffle(~[1, 1, 1]) == ~[1, 1, 1];
assert r.gen_uint_range(0u, 1u) == 0u;
}
}


Expand Down