Here is the code:
// Constants for parsing and buffer size
const SIZE_PARSING: u8 = 3;
const SIZE_BUFFER: u8 = 8;
fn main() {
// Test data for parsing
let arr_n: [u8; 12] = [
0b101, 0b001, 0b111, 0b001, 0b111, 0b000, 0b001, 0b010, 0b001, 0b011, 0b111, 0b001,
];
// Length of the input data
let len = arr_n.len();
// Buffer-related variables
let mut buf: u8 = 0;
let mut bitwise_location: u8 = SIZE_BUFFER;
let mut bit_left: u8 = 0;
let mut bit_fill_left: u8 = 0;
let mut buf_cycle: u8 = 0;
let mut buf_full = false;
// Variable to store the last value of `i` outside the loop
let mut last_i = 0;
// Iterate through each byte of the input array
for i in 0..len {
// If the buffer is not full and buf_cycle is less than SIZE_PARSING,
// update the buffer with the current byte
if buf_cycle < SIZE_PARSING && buf_full {
buf |= arr_n[i - 1] << bitwise_location;
}
// If the remaining space in the buffer is less than SIZE_PARSING,
// update the buffer and related variables
if bitwise_location < SIZE_PARSING {
println!("Im here! \t");
buf_full = true;
buf_cycle += 1;
bit_left = bitwise_location;
bit_fill_left = arr_n[i] >> (SIZE_PARSING - bit_left);
buf |= bit_fill_left;
println!("Value: {}", buf);
// Reset the buffer and update the bitwise_location
buf = 0;
bitwise_location = SIZE_BUFFER - (SIZE_PARSING - bit_left);
// Reset buf_cycle if it's a multiple of SIZE_PARSING
if buf_cycle % SIZE_PARSING == 0 {
buf_cycle = 0;
}
} else {
// Update the buffer and bitwise_location
bitwise_location -= SIZE_PARSING;
buf |= arr_n[i] << bitwise_location;
buf_full = false;
}
// Store the last value of `i`
last_i = i;
}
// If there are any remaining bits in the last byte, shift them into the buffer
if buf_cycle % SIZE_PARSING != 0 {
let i = last_i;
buf |= arr_n[i] << bitwise_location;
println!("Value: {}", buf);
}
}