Hello!
I created my own cursor for reading values fro Vec<u8>
.
I need to optimize it. How do it? Any ideas?
#[derive(PartialEq, Debug)]
/// The cursor for reading a low-level data
pub struct ReadCursor<'a, 'b> {
data: &'a Vec<u8>,
data_types: &'b Vec<DataType>,
bit_pos: usize,
byte_pos: usize,
data_types_index: usize,
byte_order: ByteOrdering,
}
impl<'a, 'b> ReadCursor<'a, 'b> {
pub fn new(data: &'a Vec<u8>, data_types: &'b Vec<DataType>, byte_order: ByteOrdering) -> Self {
ReadCursor {
data,
data_types,
bit_pos: 0,
byte_pos: 0,
data_types_index: 0,
byte_order,
}
}
fn get_bit_lsb0(data: u8, index: usize) -> bool {
(data >> index & 1) == 1
}
fn read_bool(&mut self) -> Option<bool> {
let data = self.data.get(self.byte_pos)?;
let bit_value = Self::get_bit_lsb0(*data, self.bit_pos);
if self.bit_pos == BIT_LAST_INDEX {
self.bit_pos = BIT_FIRST_INDEX;
self.byte_pos += 1;
} else {
self.bit_pos += 1;
}
Some(bit_value)
}
fn read_u8(&mut self) -> Option<u8> {
if self.bit_pos != BIT_FIRST_INDEX {
self.bit_pos = BIT_FIRST_INDEX;
self.byte_pos += 1;
}
let data = self.data.get(self.byte_pos)?;
self.byte_pos += 1;
Some(*data)
}
pub fn read_next(&mut self) -> Option<Value> {
let dt = self.data_types.get(self.data_types_index)?;
self.data_types_index += 1;
let value = match dt {
DataType::BOOL => Value::BOOL(self.read_bool()?),
DataType::U8 => Value::U8(self.read_u8()?),
_ => {
return None;
}
};
Some(value)
}
}
Full Example: Playground