use crate::read_bytes::ReadBytes;
use std::error;
use std::io::{Error, ErrorKind, Read};
pub struct Biterator<'a> {
/// Underlying stream of bytes
byte_stream: &'a mut dyn Read,
// Cached byte we are working on now. This gets gradually right-shifted, so
// the next bit is always the least significant.
current_byte: u8,
// How many bits of this byte we have already returned
bit_count: u8,
}
impl<'a> Biterator<'a> {
pub fn new(byte_stream: &'a mut dyn Read) -> Self {
Self {
byte_stream,
current_byte: 0,
bit_count: 0,
}
}
pub fn skip_to_next_byte_boundary(&mut self) -> &mut dyn Read {
self.bit_count = 0;
self.byte_stream
}
pub fn read_bit(&mut self) -> Result<u8, Error> {
let Some(bit) = self.next() else {
// Unexpected end of stream
return error(ErrorKind::UnexpectedEof, "Unexpected EOF");
};
bit
}
pub fn read_bits(&mut self, count: u8) -> Result<u8, Error> {
if count == 0 || count > 8 {
return error(
ErrorKind::InvalidData,
format!("Can not read {} bits", count),
);
}
let mut bits: u8 = 0b0;
for _ in 0..count {
bits <<= 1;
bits += self.read_bit()?
}
Ok(bits)
}
}
impl<'a> Iterator for Biterator<'a> {
type Item = Result<u8, Error>; // Will always be 0 or 1
fn next(&mut self) -> Option<Self::Item> {
if self.bit_count == 0 {
match self.byte_stream.read_byte() {
Ok(b) => self.current_byte = b,
Err(e) => return end_or_error(e),
}
}
// pick off lsb
let ret = self.current_byte & 0b00000001;
// Next time, we will want the bit to the left of the one we just
// returned, so shift them right.
self.current_byte >>= 1;
self.bit_count = (self.bit_count + 1) % 8;
Some(Ok(ret))
}
}
fn end_or_error(e: Error) -> Option<Result<u8, Error>> {
match e.kind() {
ErrorKind::UnexpectedEof => None,
_ => Some(Err(e)),
}
}
fn error<E>(kind: ErrorKind, msg: E) -> Result<u8, Error>
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
Err(Error::new(kind, msg))
}