Skip to content

Commit 642c3ce

Browse files
dhardyvks
authored andcommitted
Replace zerocopy::IntoBytes::as_mut_bytes with unsafe slice::from_raw_parts_mut
Mostly code gen appears equivalent, though it affects inlining of u32x4 gen with SmallRng. Benchmarks are not significantly affected.
1 parent 8783420 commit 642c3ce

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

src/rng.rs

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212
use crate::distr::uniform::{SampleRange, SampleUniform};
1313
use crate::distr::{self, Distribution, StandardUniform};
1414
use core::num::Wrapping;
15+
use core::{mem, slice};
1516
use rand_core::RngCore;
16-
use zerocopy::IntoBytes;
1717

1818
/// User-level interface for RNGs
1919
///
@@ -393,13 +393,20 @@ impl Fill for [u8] {
393393
}
394394
}
395395

396-
macro_rules! impl_fill {
396+
// This macro is unsafe to call: target types must support transmute from
397+
// random bits (i.e. all bit representations are valid).
398+
macro_rules! unsafe_impl_fill {
397399
() => {};
398400
($t:ty) => {
399401
impl Fill for [$t] {
400402
fn fill<R: Rng + ?Sized>(&mut self, rng: &mut R) {
401403
if self.len() > 0 {
402-
rng.fill_bytes(self.as_mut_bytes());
404+
rng.fill_bytes(unsafe {
405+
slice::from_raw_parts_mut(self.as_mut_ptr()
406+
as *mut u8,
407+
mem::size_of_val(self)
408+
)
409+
});
403410
for x in self {
404411
*x = x.to_le();
405412
}
@@ -410,24 +417,29 @@ macro_rules! impl_fill {
410417
impl Fill for [Wrapping<$t>] {
411418
fn fill<R: Rng + ?Sized>(&mut self, rng: &mut R) {
412419
if self.len() > 0 {
413-
rng.fill_bytes(self.as_mut_bytes());
420+
rng.fill_bytes(unsafe {
421+
slice::from_raw_parts_mut(self.as_mut_ptr()
422+
as *mut u8,
423+
self.len() * mem::size_of::<$t>()
424+
)
425+
});
414426
for x in self {
415-
*x = Wrapping(x.0.to_le());
427+
*x = Wrapping(x.0.to_le());
416428
}
417429
}
418430
}
419431
}
420432
};
421433
($t:ty, $($tt:ty,)*) => {
422-
impl_fill!($t);
434+
unsafe_impl_fill!($t);
423435
// TODO: this could replace above impl once Rust #32463 is fixed
424-
// impl_fill!(Wrapping<$t>);
425-
impl_fill!($($tt,)*);
436+
// unsafe_impl_fill!(Wrapping<$t>);
437+
unsafe_impl_fill!($($tt,)*);
426438
}
427439
}
428440

429-
impl_fill!(u16, u32, u64, u128,);
430-
impl_fill!(i8, i16, i32, i64, i128,);
441+
unsafe_impl_fill!(u16, u32, u64, u128,);
442+
unsafe_impl_fill!(i8, i16, i32, i64, i128,);
431443

432444
impl<T, const N: usize> Fill for [T; N]
433445
where

0 commit comments

Comments
 (0)