mirror of
https://codeberg.org/icewind/bitbuffer.git
synced 2026-06-03 16:44:06 +02:00
more efficient way of getting a usize from byte slice
This commit is contained in:
parent
5a188cb2c5
commit
1db817c70c
1 changed files with 21 additions and 21 deletions
|
|
@ -1,6 +1,6 @@
|
|||
use crate::{ReadError, Result};
|
||||
use crate::endianness::Endianness;
|
||||
use crate::is_signed::IsSigned;
|
||||
use crate::{ReadError, Result};
|
||||
use num_traits::{Float, PrimInt};
|
||||
use std::cmp::min;
|
||||
use std::marker::PhantomData;
|
||||
|
|
@ -63,7 +63,7 @@ impl IsPadded for Padded {
|
|||
/// let buffer = BitBuffer::from_padded_slice(bytes, 8, LittleEndian);
|
||||
/// ```
|
||||
pub struct BitBuffer<'a, E, S>
|
||||
where
|
||||
where
|
||||
E: Endianness,
|
||||
S: IsPadded,
|
||||
{
|
||||
|
|
@ -75,7 +75,7 @@ where
|
|||
}
|
||||
|
||||
impl<'a, E> BitBuffer<'a, E, NonPadded>
|
||||
where
|
||||
where
|
||||
E: Endianness,
|
||||
{
|
||||
/// Create a new BitBuffer from a byte slice
|
||||
|
|
@ -104,7 +104,7 @@ where
|
|||
}
|
||||
|
||||
impl<'a, E> BitBuffer<'a, E, Padded>
|
||||
where
|
||||
where
|
||||
E: Endianness,
|
||||
{
|
||||
/// Create a new BitBuffer from a byte slice with included padding
|
||||
|
|
@ -146,7 +146,7 @@ where
|
|||
}
|
||||
|
||||
impl<'a, E, S> BitBuffer<'a, E, S>
|
||||
where
|
||||
where
|
||||
E: Endianness,
|
||||
S: IsPadded,
|
||||
{
|
||||
|
|
@ -160,7 +160,6 @@ where
|
|||
self.byte_len
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_usize(&self, position: usize, count: usize) -> Result<usize> {
|
||||
if position + count > self.bit_len {
|
||||
return Err(ReadError::NotEnoughData {
|
||||
|
|
@ -173,14 +172,15 @@ where
|
|||
} else {
|
||||
min(position / 8, self.byte_len - USIZE_SIZE)
|
||||
};
|
||||
//let byte_index = position / 8;
|
||||
let bit_offset = position - byte_index * 8;
|
||||
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 raw_container: &usize = unsafe {
|
||||
// this is only safe for us because we're sure that there is enough data in the slice
|
||||
std::mem::transmute(self.bytes.as_ptr().offset(byte_index as isize))
|
||||
};
|
||||
let container = if E::is_le() {
|
||||
usize::from_le_bytes(bytes)
|
||||
usize::from_le(*raw_container)
|
||||
} else {
|
||||
usize::from_be_bytes(bytes)
|
||||
usize::from_be(*raw_container)
|
||||
};
|
||||
let shifted = if E::is_le() {
|
||||
container >> bit_offset
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue