artichoke/rand_mt

Replace hand-rolled chunks loop in `fill_bytes` with `chunks_exact_mut`

lopopolo opened this issue · 1 comments

Both Mt::fill_bytes and Mt64::fill_bytes use a handrolled implementation of [u8]::chunks_exact_mut.

Replace these while loops with use of the ChunksExactMut iterator.

rand_mt/src/mt.rs

Lines 306 to 317 in 7123536

let mut left = dest;
while left.len() >= CHUNK {
let (next, remainder) = left.split_at_mut(CHUNK);
left = remainder;
let chunk: [u8; CHUNK] = self.next_u32().to_le_bytes();
next.copy_from_slice(&chunk);
}
let n = left.len();
if n > 0 {
let chunk: [u8; CHUNK] = self.next_u32().to_le_bytes();
left.copy_from_slice(&chunk[..n]);
}

rand_mt/src/mt64.rs

Lines 289 to 300 in 7123536

let mut left = dest;
while left.len() >= CHUNK {
let (next, remainder) = left.split_at_mut(CHUNK);
left = remainder;
let chunk: [u8; CHUNK] = self.next_u64().to_le_bytes();
next.copy_from_slice(&chunk);
}
let n = left.len();
if n > 0 {
let chunk: [u8; CHUNK] = self.next_u64().to_le_bytes();
left.copy_from_slice(&chunk[..n]);
}

boba includes some code that uses chunks_exact which gives an example of how we'd be able to poke at the remainder slice:

https://github.com/artichoke/boba/blob/63b3b3fe5814d2b8641b1769c4ca61ceaaeed5ea/src/lib.rs#L192-L216