Created
January 10, 2018 12:47
-
-
Save dhardy/8d4e4213dd5aa21ccdc58a80a362cfe1 to your computer and use it in GitHub Desktop.
read_u32 & unaligned reads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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?