mirror of
https://codeberg.org/icewind/bitbuffer.git
synced 2026-06-03 08:34:07 +02:00
fix read_bytes in BE mode
This commit is contained in:
parent
5e7a68a57e
commit
ea2640655b
2 changed files with 26 additions and 4 deletions
|
|
@ -275,15 +275,23 @@ where
|
|||
///
|
||||
/// [`ReadError::NotEnoughData`]: enum.ReadError.html#variant.NotEnoughData
|
||||
pub fn read_bytes(&self, position: usize, byte_count: usize) -> Result<Vec<u8>> {
|
||||
let mut data = vec![];
|
||||
data.reserve_exact(byte_count);
|
||||
let mut data = Vec::with_capacity(byte_count);
|
||||
let mut byte_left = byte_count;
|
||||
let max_read = size_of::<usize>() - 1;
|
||||
let mut read_pos = position;
|
||||
while byte_left > 0 {
|
||||
let read = min(byte_left, max_read);
|
||||
let bytes: [u8; USIZE_SIZE] = self.read_usize(read_pos, read * 8)?.to_le_bytes();
|
||||
let usable_bytes = &bytes[0..read];
|
||||
let raw_bytes = self.read_usize(read_pos, read * 8)?;
|
||||
let bytes: [u8; USIZE_SIZE] = if E::is_le() {
|
||||
raw_bytes.to_le_bytes()
|
||||
} else {
|
||||
raw_bytes.to_be_bytes()
|
||||
};
|
||||
let usable_bytes = if E::is_le() {
|
||||
&bytes[0..read]
|
||||
} else {
|
||||
&bytes[8-read..8]
|
||||
};
|
||||
data.extend_from_slice(usable_bytes);
|
||||
byte_left -= read;
|
||||
read_pos += read * 8;
|
||||
|
|
|
|||
|
|
@ -234,6 +234,20 @@ fn test_from() {
|
|||
let _: BitStream<LittleEndian> = BitStream::from(BYTES.to_vec());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_read_str_be() {
|
||||
let bytes = vec![
|
||||
0x48, 0x65, 0x6c, 0x6c,
|
||||
0x6f, 0x20, 0x77, 0x6f,
|
||||
0x72, 0x6c, 0x64, 0,
|
||||
0, 0, 0, 0
|
||||
];
|
||||
let buffer = BitBuffer::new(bytes, BigEndian);
|
||||
assert_eq!(buffer.read_string(0, Some(13)).unwrap(), "Hello world".to_owned());
|
||||
assert_eq!(buffer.read_string(0, Some(16)).unwrap(), "Hello world".to_owned());
|
||||
assert_eq!(buffer.read_string(0, None).unwrap(), "Hello world".to_owned());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_trait() {
|
||||
let buffer = BitBuffer::new(BYTES.to_vec(), BigEndian);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue