1
0
Fork 0
mirror of https://codeberg.org/icewind/bitbuffer.git synced 2026-06-03 16:44:06 +02:00

dont read unalligned usize

This commit is contained in:
Robin Appelman 2019-12-25 15:38:14 +01:00
commit 8147ae1988

View file

@ -103,32 +103,26 @@ where
let bit_offset = position & 7; let bit_offset = position & 7;
let usize_bit_size = size_of::<usize>() * 8; let usize_bit_size = size_of::<usize>() * 8;
let container = if cfg!(feature = "unsafe") { let bytes: [u8; USIZE_SIZE] = if cfg!(feature = "unsafe") {
use std::mem::transmute; use std::mem::transmute;
// panic instead of accessing out of bounds data when the caller didn't do it's job bounds checking // panic instead of accessing out of bounds data when the caller didn't do it's job bounds checking
// due to the magic of branch prediction and this check "always" passing, the cost for this // due to the magic of branch prediction and this check "always" passing, the cost for this
// is below the point of being measurable by `cargo bench` // is below the point of being measurable by `cargo bench`
assert!(position + count <= self.bit_len()); assert!(position + count <= self.bit_len());
let raw_container: &usize = unsafe { unsafe {
// this is safe here because we already have checks that we don't read past the slice // this is safe here because we already have checks that we don't read past the slice
let ptr = self.bytes.as_ptr().add(byte_index); let ptr = self.bytes.as_ptr().add(byte_index);
transmute(ptr) *transmute::<_, &[u8; USIZE_SIZE]>(ptr)
};
if E::is_le() {
usize::from_le(*raw_container)
} else {
usize::from_be(*raw_container)
} }
} else { } else {
let bytes = self.read_usize_bytes(byte_index); self.read_usize_bytes(byte_index)
};
if E::is_le() { let container = if E::is_le() {
usize::from_le_bytes(bytes) usize::from_le_bytes(bytes)
} else { } else {
usize::from_be_bytes(bytes) usize::from_be_bytes(bytes)
}
}; };
let shifted = if E::is_le() { let shifted = if E::is_le() {