diff --git a/Cargo.toml b/Cargo.toml index f754dd7..61813b8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "wyrand" -version = "0.2.0" +version = "0.2.1" edition = "2021" authors = ["Gonçalo Rica Pais da Silva "] description = "A fast & portable non-cryptographic pseudorandom number generator and hashing algorithm" @@ -35,6 +35,7 @@ serde = { version = "1.0", features = ["derive"], optional = true } [dev-dependencies] criterion = "0.5" serde_test = "1.0" +rand = "0.8" [[bench]] name = "rand_bench" diff --git a/benches/rand_bench.rs b/benches/rand_bench.rs index 4a5cf81..4fdcdcb 100644 --- a/benches/rand_bench.rs +++ b/benches/rand_bench.rs @@ -1,7 +1,8 @@ use criterion::{black_box, criterion_main, Criterion}; fn wyrand_benchmark(c: &mut Criterion) { - use rand_core::RngCore; + use rand::thread_rng; + use rand_core::{RngCore, SeedableRng}; use wyrand::WyRand; c.bench_function("rand", |b| { @@ -29,6 +30,10 @@ fn wyrand_benchmark(c: &mut Criterion) { criterion::BatchSize::LargeInput, ) }); + + c.bench_function("from_rng", |b| { + b.iter(|| black_box(WyRand::from_rng(thread_rng()))) + }); } #[cfg(feature = "wyhash")] diff --git a/src/final_v4_2/wyrand.rs b/src/final_v4_2/wyrand.rs index f5a03e7..e736dc7 100644 --- a/src/final_v4_2/wyrand.rs +++ b/src/final_v4_2/wyrand.rs @@ -92,9 +92,15 @@ impl RngCore for WyRand { impl SeedableRng for WyRand { type Seed = [u8; core::mem::size_of::()]; + #[inline] fn from_seed(seed: Self::Seed) -> Self { Self::new(u64::from_ne_bytes(seed)) } + + #[inline] + fn from_rng(mut rng: R) -> Result { + Ok(Self::new(rng.next_u64())) + } } #[cfg(test)] @@ -155,6 +161,16 @@ mod tests { assert_eq!(rand_dyn(&mut rng), 412_509_173); } + #[cfg(feature = "rand_core")] + #[test] + fn rand_core_from_rng() { + let mut source = WyRand::from_seed(Default::default()); + + let mut rng = WyRand::from_rng(&mut source).expect("from_rng should never fail here"); + + assert_eq!(rng.next_u32(), 844672934); + } + #[cfg(all(feature = "serde1", feature = "debug"))] #[test] fn serde_tokens() { diff --git a/src/legacy_final_v4/wyrand.rs b/src/legacy_final_v4/wyrand.rs index 0ab0a13..8213f62 100644 --- a/src/legacy_final_v4/wyrand.rs +++ b/src/legacy_final_v4/wyrand.rs @@ -92,9 +92,15 @@ impl RngCore for WyRandLegacy { impl SeedableRng for WyRandLegacy { type Seed = [u8; core::mem::size_of::()]; + #[inline] fn from_seed(seed: Self::Seed) -> Self { Self::new(u64::from_ne_bytes(seed)) } + + #[inline] + fn from_rng(mut rng: R) -> Result { + Ok(Self::new(rng.next_u64())) + } } #[cfg(test)] @@ -155,6 +161,16 @@ mod tests { assert_eq!(rand_dyn(&mut rng), 4_283_336_045); } + #[cfg(feature = "rand_core")] + #[test] + fn rand_core_from_rng() { + let mut source = WyRandLegacy::from_seed(Default::default()); + + let mut rng = WyRandLegacy::from_rng(&mut source).expect("from_rng should never fail here"); + + assert_eq!(rng.next_u32(), 4242651740); + } + #[cfg(all(feature = "serde1", feature = "debug"))] #[test] fn serde_tokens() {