Use zerocopy to replace some unsafe code#1349
Conversation
| let mut buf = [0_u8; mem::size_of::<$intrinsic>()]; | ||
| rng.fill_bytes(&mut buf); | ||
| // x86 is little endian so no need for conversion | ||
| // SAFETY: we know [u8; N] and $intrinsic have the same size | ||
| unsafe { mem::transmute_copy(&buf) } | ||
| zerocopy::transmute!(buf) |
There was a problem hiding this comment.
Here's another option if this would be preferred. I opted not to go this route since it messes with code that's been verified to compile to SIMD instructions (although I expect the same would work here):
let mut val = $intrinsic::new_zeroed();
// On proper hardware, this should compile to SIMD instructions
// Verified on x86 Haswell with __m128i, __m256i
//
// x86 is little endian so no need for conversion
rng.fill_bytes(&mut val.as_bytes_mut());
val|
The key point here is the adoption of |
|
The main contender would be |
With the obvious caveat that I'm biased as the author, and focusing specifically on this use case (rather than comparing the crates across all use cases), I would advocate for zerocopy in this case for a few reasons:
That said, the uses introduced in this PR are pretty small, the panic paths in bytemuck's solutions might be optimized out, and there's probably not a huge difference either way. |
|
In future it also may be worth to (optionally) use |
No description provided.