Skip to content

Instantly share code, notes, and snippets.

@dhardy
Created January 10, 2018 12:47
Show Gist options
  • Save dhardy/8d4e4213dd5aa21ccdc58a80a362cfe1 to your computer and use it in GitHub Desktop.
Save dhardy/8d4e4213dd5aa21ccdc58a80a362cfe1 to your computer and use it in GitHub Desktop.
read_u32 & unaligned reads
/// Read a `u32` from a byte sequence, in litte-endian order
///
/// Consider usage with the `arrayref` crate.
pub fn read_u32(bytes: &[u8; 4]) -> u32 {
// TODO: check; also isn't the only code difference the read type?
// TODO: but since this is unused we could just remove it!
// On platforms where unaligned reads are safe, do a simple read
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
unsafe{ *(bytes as *const [u8; 4] as *const u32) }.to_le()
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
unsafe {
let mut v: u32 = mem::uninitialized();
ptr::copy_nonoverlapping(
bytes.as_ptr(),
&mut v as *mut u32 as *mut u8,
mem::size_of::<u32>());
v.to_le()
}
}
/// Read a `u64` from a byte sequence, in litte-endian order
///
/// Consider usage with the `arrayref` crate.
pub fn read_u64(bytes: &[u8; 8]) -> u64 {
// TODO: as read_u32
unsafe{ *(bytes as *const [u8; 8] as *const u64) }.to_le()
}
@dhardy
Copy link
Author

dhardy commented Jan 10, 2018

@pitdicker what do you think — the original (as read_u64 here) is potentially unsafe?

Also, I checked dhardy/master and found only one use (MockAddRng), and it's possible to use the slice versions instead anyway, so shall we just remove these functions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment