Skip to content

Commit

Permalink
Implement Rng::fill
Browse files Browse the repository at this point in the history
Fills a byte slice with random data.

Benchmarks:

  test fill             ... bench:          29 ns/iter (+/- 5)
  test fill_naive       ... bench:         343 ns/iter (+/- 33)

Remove `bytes`
  • Loading branch information
cloudhead committed Sep 10, 2022
1 parent f53d813 commit 992fae3
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
23 changes: 23 additions & 0 deletions benches/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,26 @@ fn u32_fastrand(b: &mut Bencher) {
sum
})
}

#[bench]
fn fill(b: &mut Bencher) {
let rng = fastrand::Rng::new();
b.iter(|| {
// Pick a size that isn't divisble by 8.
let mut bytes = [0u8; 367];
rng.fill(&mut bytes);
bytes
})
}

#[bench]
fn fill_naive(b: &mut Bencher) {
let rng = fastrand::Rng::new();
b.iter(|| {
let mut bytes = [0u8; 367];
for item in &mut bytes {
*item = rng.u8(..);
}
bytes
})
}
16 changes: 16 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,22 @@ impl Rng {
}
}

/// Fill a byte slice with random data.
#[inline]
pub fn fill(&self, slice: &mut [u8]) {
// Filling the buffer in chunks of 8 is much faster.
let mut chunks = slice.chunks_exact_mut(8);
for items in chunks.by_ref() {
let r = self.u64(..);
items.copy_from_slice(&r.to_le_bytes());
}

let remainder = chunks.into_remainder();
for item in remainder {
*item = self.u8(..);
}
}

rng_integer!(
u8,
u8,
Expand Down
13 changes: 13 additions & 0 deletions tests/smoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,19 @@ fn u128() {
}
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn fill() {
let r = fastrand::Rng::new();
let mut a = [0u8; 64];
let mut b = [0u8; 64];

r.fill(&mut a);
r.fill(&mut b);

assert_ne!(a, b);
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn rng() {
Expand Down

0 comments on commit 992fae3

Please sign in to comment.