ggunzip - A Bit More : Yr golygfa o Hescwm Uchaf, rhif 35

At the end of our last video, Andy and I had worked up the Biterator, a little Iterator wrapper around a byte stream that lets you take a single bit at a time.

It looked like this. If, like me, you’ve only limited Rust knowledge, it’s still pretty much as you expected.

use std::io::{self, Read};

pub struct Biterator<'a> {     (1)
    /// 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) {
        self.bit_count = 0;
    }

    fn read_byte(&mut self) -> Result<u8, io::Error> {
        let mut buf = vec![0u8; 1];
        self.byte_stream.read_exact(&mut buf)?;
        Ok(buf[0])
    }
}

impl<'a> Iterator for Biterator<'a> {
type Item = Result<u8, io::Error>; // Will always be 0 or 1

    fn next(&mut self) -> Option<Self::Item> {
        if self.bit_count == 0 {
            match self.read_byte() {
                Ok(b) => {
                    self.current_byte = b;
                }
                Err(e) => match e.kind() {   (2)
                    io::ErrorKind::UnexpectedEof => return None,
                    _ => return Some(Err(e)),
                },
            }
        }

        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 += 1;

        if self.bit_count > 7 {
            // We have exhausted the current byte - need to read a new one
            self.bit_count = 0;
        }

        Some(Ok(ret))
    }
}
  1. I’ve managed to avoid lifetime specifiers in my Rust code so far, but we need one here to indicate that the Biterator can not outlive the stream it is wrapping.

  2. If read_byte fails that might actually be not be an error. Consequently we have to unpick the error and look inside it. If it is an UnexpectedEof then we’ve reached the end of the iteration and return None. Anything else really is an error, which we pass up.

If you’ve got a byte stream, some kind of & mut dyn Read, you can create a Biterator around it, and then read off a single bit at a time. Rust, like all sensible languages, doesn’t have a bit type, so we chose to return a byte instead. We could have returned a boolean, but that feels icky even if a bit and a boolean are essentially equivalent.

We chose to put together an iterator because it’s quite an easy thing to implement. Rust’s Iterator trait has only a single required method, fn next(&mut self) → Option<Self::Item>. There’s pretty straightforward, even if that return type can be a bit tricksy when, as it does here, the Option wraps a Result.

More Bits

Iterators are great if you just want to sit in a loop and keep pulling items until there’s nothing left, but can be unwieldy in other situations.

The Deflate algorithm, for example, says

Each block of compressed data begins with 3 header bits containing the following data:
    first bit - BFINAL
    next two bites - BTYPE

At the end of our stream, the code we had to read and check these three bits was something of a monster.

// ....
let mut bits = Biterator::new(f);

let Some(b_final) = bits.next() else {
    // Unexpected end of stream
    return Err(BadDeflate::UnknownCompressionScheme);
};
let b_final = b_final.map_err(|_| BadDeflate::UnknownCompressionScheme)?;

let Some(type_1) = bits.next() else {
    // Unexpected end of stream
    return Err(BadDeflate::UnknownCompressionScheme);
};
let type_1 = type_1.map_err(|_| BadDeflate::UnknownCompressionScheme)?;
let Some(type_2) = bits.next() else {
    // Unexpected end of stream
    return Err(BadDeflate::UnknownCompressionScheme);
};
let type_2 = type_2.map_err(|_| BadDeflate::UnknownCompressionScheme)?;

if type_1 != 0 || type_2 != 0 {
    // Actually is and unknown compression scheme
    return Err(BadDeflate::UnknownCompressionScheme);
}

// ...

There’s lots of repetition to eliminate, but the whole affair would be much easier if we could simply read more than one bit at a time.

To that end, I extended our Biterator with a couple of additional methods

  • read_bit() → Result<u8, Error>, which reads a single bit, but returns a Result<u8, Error>, rather than the Option<Result<u8, Error>> that next() returns.

  • read_bits(count: u8) → Result<u8, Error>, which reads up to 8 bits at a time.

Using these methods, our code above melts away.

// ...
let b_final = bits.read_bit().or(Err(BadDeflate::EndOfFile))?;

inflate_block(&mut bits, of)?;
// ....

fn inflate_block(
    mut bits: &mut Biterator,
    of: &mut dyn Write,
) -> Result<(), BadDeflate> {
    let type_bits = bits.read_bits(2).or(Err(BadDeflate::EndOfFile))?;

    match type_bits {
        0b00 => read_uncompressed_block(&mut bits, of),
        _ => Err(BadDeflate::UnknownCompressionScheme),
    }
}

Really rather happy with this, and how the code is firming up generally.

I’ve dabbled with extension traits elsewhere in ggunzip, and perhaps the .or(Err(…​)) error handling mouthful is a candidate for a local extension. Andy and I may differ philosophically on this though, so I’m leaving it until we next get together.


Biterator, extended with read_bit and read_bits
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))
}

Tagged rust, code, and ggunzip
« prev
June Linkfarm
next »
July Linkfarm


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired



Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired