During our conversation, I said there’s a clear future direction for this function, which is to load the various headers into a little data structure. It could be, I said, "an exercise for the viewer".
Friends, I am that viewer.
Looking at the gzip header definition, you can probably cast it into code using the language of your choice. Here, of course, we’re using Rust.
struct Header
struct Header {
flags: Flags,
timestamp: Option<u32>,
extra_flag: ExtraFlag,
filesystem: Filesystem,
extra_field: Option<Vec<u8>>,
filename: Option<String>,
comment: Option<String>,
crc16: Option<u16>,
}
You can probably also see the general shape of the code to populate the header. Read the first few bytes to populate the flag members, then check those flags to determine which of the optional fields to populate.
And that’s just what I did.
In the minimal code above, we already have near repetition reading the bytes and checking their values. That was my initial hook. I extracted out a function verify_gzip_magic_number, followed by verify_compression_scheme. I then worried away at those to reduce them down. Kent Beck’s technique, which comes to me via Ron Jeffries, of making things more similar in order to enable duplication to be eliminated was my go-to here.
I’ll spare you the full ins and outs but after a few rounds, I had these little helper functions.
fn verify_gzip_magic_number<R: Read + ?Sized>(
f: &mut R,
) -> Result<(), BadHeader> {
verify_byte_sequence(f, &[0x1F, 0x8B], BadHeader::BadMagicNumber)
}
fn verify_compression_scheme<R: Read + ?Sized>(
f: &mut R,
) -> Result<(), BadHeader> {
verify_byte_sequence(f, &[0x08], BadHeader::UnknownCompressionScheme)
}
fn verify_byte_sequence<R: Read + ?Sized>(
f: &mut R,
expected: &[u8],
error: BadHeader,
) -> Result<(), BadHeader> {
let cs_buf = read_bytes(f, expected.len())?;
if cs_buf == expected {
Ok(())
} else {
Err(error)
}
}
fn read_bytes<R: Read + ?Sized>(
f: &mut R,
len: usize,
) -> Result<Vec<u8>, BadHeader> {
let mut buf = vec![0u8; len]; (1)
f.read_exact(&mut buf).or(Err(BadHeader::EndOfFile))?; (2)
Ok(buf)
}
-
The initial code used fixed sized buffers. This code uses a Vector, because we’re specifying the size at runtime.
-
If read_exact fails, it returns an io::Error. We’re using or to instead return an error of our own.
You might well be thinking that looks like quite a lot more code. Well, yes it is, and no it isn’t. I’ve broken the code out into several functions, which always carries a certain amount of overhead. The code here also does more, covering error cases the original code ignores. But let’s have a look at where these functions are called from.
Compare verify_gzip_header before and after. Even when squashed down into a narrow column, after is easier on the eye. It’s shorter, has expressive names, and straight through control flow.