Cleared up issue with parsing ints

+ Endianness was all out of whack
+ Everything is currently handled as little endian, easy to add a config for endianness later
+ num-bigint comes in clutch, it now handles the shifting of bits
This commit is contained in:
joeyahines committed 2021-10-09 13:58:41 -06:00
1 parent 6daf3a55f2
commit bb6f331c75
3 files changed
+31 -26

No files matched your search

+10 -16
View File
@@ -1,4 +1,5 @@
use std::fmt::{Display, Formatter};
use num_bigint::BigUint;
#[derive(Clone, Debug)]
pub enum ByteStreamError {
@@ -32,13 +33,14 @@ pub struct ByteStream {
data: Vec<u8>,
}
impl ByteStream {
pub fn get_bytes(&self, bit_ndx: usize, bit_count: usize) -> Result<Vec<u8>, ByteStreamError> {
let byte_ndx = bit_ndx / 8;
let bits_before = (bit_ndx % 8) as u8;
let bits_in_last_byte = ((bit_ndx + bit_count - bits_before as usize) % 8) as u8;
let byte_count = if bit_count >= 8 { bit_count / 8 } else { 1 };
let bytes_needed = if bits_before != 0 {
let byte_count = ((bit_count as f32) / (8.0)).ceil() as usize;
let bytes_needed = if (bits_before as usize + bit_count) % 8 != 0 && !(bits_before as usize + bit_count < 8){
byte_count + 1
} else {
byte_count
@@ -48,21 +50,13 @@ impl ByteStream {
return Err(ByteStreamError::OutOfRange);
}
let mut byte_stream = self.data[byte_ndx..byte_ndx + bytes_needed].to_vec();
let byte_stream = self.data[byte_ndx..byte_ndx + bytes_needed].to_vec();
if bits_before != 0 {
let mut carry: u8 = 0;
for _ in 0..bits_before {
for k in (0..bytes_needed).rev() {
let next: u8 = (byte_stream[k] & 0x01) << 7;
byte_stream[k] = (byte_stream[k] >> 1) | carry;
let number = BigUint::from_bytes_le(&byte_stream) >> bits_before;
carry = next;
}
}
}
let mut byte_stream = number.to_bytes_le();
if bytes_needed > byte_count {
if bytes_needed > byte_count && bytes_needed == byte_stream.len() {
byte_stream.pop();
}
@@ -105,11 +99,11 @@ mod tests {
#[test]
fn test_get_bytes_with_shift_in_byte() {
let bytes: Vec<u8> = vec![0xff, 0x00, 0x55];
let bytes: Vec<u8> = vec![0x5f, 0x00, 0x55];
let bit_stream = ByteStream::from(bytes.clone());
let new_bytes = bit_stream.get_bytes(4, 4).unwrap();
assert_eq!(vec![0x0f], new_bytes);
assert_eq!(vec![0x05], new_bytes);
}
#[test]