mirror of
https://codeberg.org/icewind/bitbuffer.git
synced 2026-06-03 08:34:07 +02:00
cleanup reading a bit
This commit is contained in:
parent
64f24a2921
commit
348fbb851b
1 changed files with 5 additions and 21 deletions
26
src/lib.rs
26
src/lib.rs
|
|
@ -1,4 +1,5 @@
|
|||
#![feature(test)]
|
||||
#![feature(try_from)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
//! Tools for reading integers of arbitrary bit length and non byte-aligned integers and other data types
|
||||
|
|
@ -44,23 +45,6 @@ pub struct BitBuffer<'a> {
|
|||
byte_len: usize,
|
||||
}
|
||||
|
||||
macro_rules! array_ref {
|
||||
($arr:expr, $offset:expr, $len:expr) => {{
|
||||
{
|
||||
#[inline]
|
||||
unsafe fn as_array<T>(slice: &[T]) -> &[T; $len] {
|
||||
&*(slice.as_ptr() as *const [_; $len])
|
||||
}
|
||||
let offset = $offset;
|
||||
let slice = & $arr[offset..offset + $len];
|
||||
#[allow(unused_unsafe)]
|
||||
unsafe {
|
||||
as_array(slice)
|
||||
}
|
||||
}
|
||||
}}
|
||||
}
|
||||
|
||||
const USIZE_SIZE: usize = size_of::<usize>();
|
||||
|
||||
impl<'a> BitBuffer<'a> {
|
||||
|
|
@ -121,11 +105,11 @@ impl<'a> BitBuffer<'a> {
|
|||
}
|
||||
let byte_index = position / 8;
|
||||
let bit_offset = position & 7;
|
||||
let bytes: &[u8; USIZE_SIZE] = array_ref!(self.bytes, byte_index, USIZE_SIZE);
|
||||
let container_le = unsafe {
|
||||
std::mem::transmute::<[u8; USIZE_SIZE], usize>(*bytes)
|
||||
let slice = &self.bytes[byte_index..byte_index + USIZE_SIZE];
|
||||
let bytes: [u8; USIZE_SIZE] = unsafe {
|
||||
*(slice.as_ptr() as *const [u8; USIZE_SIZE])
|
||||
};
|
||||
let container = usize::from_le(container_le);
|
||||
let container = usize::from_le_bytes(bytes);
|
||||
let shifted = container >> bit_offset;
|
||||
let mask = !(usize::max_value() << count);
|
||||
Ok(shifted & mask)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue