mirror of
https://codeberg.org/icewind/bitbuffer.git
synced 2026-06-04 00:54: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(test)]
|
||||||
|
#![feature(try_from)]
|
||||||
#![warn(missing_docs)]
|
#![warn(missing_docs)]
|
||||||
|
|
||||||
//! Tools for reading integers of arbitrary bit length and non byte-aligned integers and other data types
|
//! 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,
|
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>();
|
const USIZE_SIZE: usize = size_of::<usize>();
|
||||||
|
|
||||||
impl<'a> BitBuffer<'a> {
|
impl<'a> BitBuffer<'a> {
|
||||||
|
|
@ -121,11 +105,11 @@ impl<'a> BitBuffer<'a> {
|
||||||
}
|
}
|
||||||
let byte_index = position / 8;
|
let byte_index = position / 8;
|
||||||
let bit_offset = position & 7;
|
let bit_offset = position & 7;
|
||||||
let bytes: &[u8; USIZE_SIZE] = array_ref!(self.bytes, byte_index, USIZE_SIZE);
|
let slice = &self.bytes[byte_index..byte_index + USIZE_SIZE];
|
||||||
let container_le = unsafe {
|
let bytes: [u8; USIZE_SIZE] = unsafe {
|
||||||
std::mem::transmute::<[u8; USIZE_SIZE], usize>(*bytes)
|
*(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 shifted = container >> bit_offset;
|
||||||
let mask = !(usize::max_value() << count);
|
let mask = !(usize::max_value() << count);
|
||||||
Ok(shifted & mask)
|
Ok(shifted & mask)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue