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

unalligned fallback

This commit is contained in:
Robin Appelman 2021-07-27 16:58:50 +02:00
commit ed249331e1
2 changed files with 22 additions and 15 deletions

View file

@ -294,12 +294,22 @@ macro_rules! impl_into_bytes {
#[inline(always)]
fn into_u16(self) -> Self::U16Iter {
use std::convert::TryInto;
use std::mem::align_of;
let bytes = self.to_le_bytes();
let (head, aligned, tail) = unsafe { bytes[..].align_to::<u16>() };
debug_assert_eq!(0, head.len());
debug_assert_eq!(0, tail.len());
Self::U16Iter::new(aligned.try_into().unwrap())
if align_of::<Self>() >= align_of::<u16>() {
let (head, aligned, tail) = unsafe { bytes[..].align_to::<u16>() };
debug_assert_eq!(0, head.len());
debug_assert_eq!(0, tail.len());
Self::U16Iter::new(aligned.try_into().unwrap())
} else {
let mut shorts = [0; $shorts];
let mut chunks = bytes.chunks(2).zip(shorts.iter_mut());
while let Some((&[a, b], short)) = chunks.next() {
*short = (b as u16) << 8 | a as u16;
}
Self::U16Iter::new(shorts)
}
}
}
};

View file

@ -106,18 +106,15 @@ impl<'a, E: Endianness> WriteBuffer<'a, E> {
pub fn push_bool(&mut self, val: bool) {
let val = val as u8;
let bit_offset = self.bit_len() % 8;
if E::is_le() {
if bit_offset == 0 {
self.bytes.push(val);
} else {
*self.bytes.last_mut().unwrap() |= val << bit_offset;
}
let shift = if E::is_le() {
bit_offset
} else {
if bit_offset == 0 {
self.bytes.push(val << 7);
} else {
*self.bytes.last_mut().unwrap() |= val << (7 - bit_offset);
}
7 - bit_offset
};
if bit_offset == 0 {
self.bytes.push(val << shift);
} else {
*self.bytes.last_mut().unwrap() |= val << shift;
}
self.bit_len += 1;
}