Skip to content
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

make rng seed extendable #26

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
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
7 changes: 4 additions & 3 deletions benches/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ extern crate test;
use rand::prelude::*;
use test::Bencher;
use wyhash::WyRng;
use fastrand::CellSeed;

#[bench]
fn shuffle_wyhash(b: &mut Bencher) {
Expand All @@ -18,7 +19,7 @@ fn shuffle_wyhash(b: &mut Bencher) {

#[bench]
fn shuffle_fastrand(b: &mut Bencher) {
let rng = fastrand::Rng::new();
let rng = fastrand::Rng::<CellSeed>::new();
let mut x = (0..100).collect::<Vec<usize>>();
b.iter(|| {
rng.shuffle(&mut x);
Expand All @@ -40,7 +41,7 @@ fn u8_wyhash(b: &mut Bencher) {

#[bench]
fn u8_fastrand(b: &mut Bencher) {
let rng = fastrand::Rng::new();
let rng = fastrand::Rng::<CellSeed>::new();
b.iter(|| {
let mut sum = 0u8;
for _ in 0..10_000 {
Expand All @@ -64,7 +65,7 @@ fn u32_wyhash(b: &mut Bencher) {

#[bench]
fn u32_fastrand(b: &mut Bencher) {
let rng = fastrand::Rng::new();
let rng = fastrand::Rng::<CellSeed>::new();
b.iter(|| {
let mut sum = 0u32;
for _ in 0..10_000 {
Expand Down
54 changes: 38 additions & 16 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,38 @@ use instant::Instant;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;

pub trait Seed {
fn with_seed(seed: u64) -> Rng<Self> where Self: Sized;
fn get(&self) -> u64;
fn set(&self, new_seed: u64);
}

// Seed abstraction, so users can specify their own
#[derive(Debug, PartialEq, Eq)]
pub struct CellSeed(Cell<u64>);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think the new-type struct abstraction is necessary, it imo should be omitted. It might be a good idea to replace it with a type alias.

pub type CellSeed = Cell<u64>;


impl Seed for CellSeed {
fn with_seed(seed: u64) -> Rng<CellSeed> {
let rng = Rng(CellSeed(Cell::new(0)));
rng.seed(seed);
rng
}
fn get(&self) -> u64 { self.0.get() }
fn set(&self, new_seed: u64) { self.0.set(new_seed); }
}

/// A random number generator.
#[derive(Debug, PartialEq, Eq)]
pub struct Rng(Cell<u64>);
pub struct Rng<T: Seed>(T);

impl Default for Rng {
impl<T: Seed> Default for Rng<T> {
#[inline]
fn default() -> Rng {
fn default() -> Self {
Rng::new()
}
}

impl Clone for Rng {
impl<S: Seed + Clone> Clone for Rng<S> {
/// Clones the generator by deterministically deriving a new generator based on the initial
/// seed.
///
Expand All @@ -111,12 +131,12 @@ impl Clone for Rng {
///
/// assert_eq!(rng1.u64(..), rng2.u64(..), "the cloned generators are identical");
/// ```
fn clone(&self) -> Rng {
Rng::with_seed(self.gen_u64())
fn clone(&self) -> Rng<S> {
S::with_seed(self.gen_u64())
}
}

impl Rng {
impl<S: Seed> Rng<S> {
/// Generates a random `u32`.
#[inline]
fn gen_u32(&self) -> u32 {
Expand Down Expand Up @@ -194,13 +214,13 @@ impl Rng {
}

thread_local! {
static RNG: Rng = Rng(Cell::new({
static RNG: Rng<CellSeed> = Rng(CellSeed(Cell::new({
let mut hasher = DefaultHasher::new();
Instant::now().hash(&mut hasher);
thread::current().id().hash(&mut hasher);
let hash = hasher.finish();
(hash << 1) | 1
}));
})));
}

/// Computes `(a * b) >> 32`.
Expand Down Expand Up @@ -269,23 +289,25 @@ macro_rules! rng_integer {
};
}

impl Rng {
impl<S: Seed> Rng<S> {
/// Creates a new random number generator.
#[inline]
pub fn new() -> Rng {
Rng::with_seed(
pub fn new() -> Self {
S::with_seed(
RNG.try_with(|rng| rng.u64(..))
.unwrap_or(0x4d595df4d0f33173),
)
}

#[inline]
pub fn from(seed: S) -> Rng<S> {
Rng(seed)
}

/// Creates a new random number generator with the initial seed.
#[inline]
pub fn with_seed(seed: u64) -> Self {
let rng = Rng(Cell::new(0));

rng.seed(seed);
rng
S::with_seed(seed)
}

/// Generates a random `char` in ranges a-z and A-Z.
Expand Down
68 changes: 63 additions & 5 deletions tests/smoke.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::*;
use fastrand::CellSeed;

#[cfg(target_arch = "wasm32")]
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
Expand Down Expand Up @@ -84,7 +85,7 @@ fn u128() {
#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn rng() {
let r = fastrand::Rng::new();
let r = fastrand::Rng::<CellSeed>::new();

assert_ne!(r.u64(..), r.u64(..));

Expand All @@ -98,8 +99,8 @@ fn rng() {
#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn rng_init() {
let a = fastrand::Rng::new();
let b = fastrand::Rng::new();
let a = fastrand::Rng::<CellSeed>::new();
let b = fastrand::Rng::<CellSeed>::new();
assert_ne!(a.u64(..), b.u64(..));

a.seed(7);
Expand All @@ -110,8 +111,65 @@ fn rng_init() {
#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn with_seed() {
let a = fastrand::Rng::with_seed(7);
let b = fastrand::Rng::new();
let a = fastrand::Rng::<CellSeed>::with_seed(7);
let b = fastrand::Rng::<CellSeed>::new();
b.seed(7);
assert_eq!(a.u64(..), b.u64(..));
}



mod atomic {
use std::sync::atomic::{AtomicU64, Ordering};
use fastrand::{Rng, Seed};

struct AtomicSeed(AtomicU64);
impl Seed for AtomicSeed {
fn with_seed(seed: u64) -> Rng<Self> where Self: Sized {
Rng::from(AtomicSeed(AtomicU64::new(seed)))
}

fn get(&self) -> u64 {
self.0.load(Ordering::Relaxed)
}

fn set(&self, new_seed: u64) {
self.0.store(new_seed, Ordering::Relaxed)
}
Comment on lines +128 to +138
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If thread B reads a value between the time thread A reads it and the time it stores the value, thread A and thread B will get the same value from rng. I guess there are both use cases where that is ok and use cases where it is not ok, but I'm not positive about having an API that is easy to misuse.

(If you want to create atomic rng, I think you need to replace get/set in gen_u64 with fetch_add)

}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn rng_atomic() {
let r = fastrand::Rng::<AtomicSeed>::new();

assert_ne!(r.u64(..), r.u64(..));

r.seed(7);
let a = r.u64(..);
r.seed(7);
let b = r.u64(..);
assert_eq!(a, b);
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn rng_init_atomic() {
let a = fastrand::Rng::<AtomicSeed>::new();
let b = fastrand::Rng::<AtomicSeed>::new();
assert_ne!(a.u64(..), b.u64(..));

a.seed(7);
b.seed(7);
assert_eq!(a.u64(..), b.u64(..));
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn with_seed_atomic() {
let a = fastrand::Rng::<AtomicSeed>::with_seed(7);
let b = fastrand::Rng::<AtomicSeed>::new();
b.seed(7);
assert_eq!(a.u64(..), b.u64(..));
}
}