Before we can start unpacking an entire archive we need to think smaller. A filepack archive is made up of one or more different FileData values, and each of those FileData values are in turn made up of all of the individual values in the overall record. If we want to unpack a FileData , we’ll need to start by being able to unpack each of the individual types that make up a FileData record.
Let’s start by decoding Word32 values. Not only do we need to decode these because they are one of the types that make up a FileData record, but we’re also going to need to deal with the Word32 size field prefixes that we added to help us encode compound values more easily.
We already have a Decode instance for Word32 that makes use of the bytestringToWord32 function that we built earlier to help us test our code. We’ll keep using those functions, but we’re going to need to do a little bit of extra work to extract an actual Word32 value our of our file pack. The first thing we need to account for is the fact that we’re not just encoding the Word32 values directly into our FilePack . All of the data that we encoded was prefixed with an additional Word32 that told us the size of the next fields. Let’s start by writing a function, naiveDecodeWord32 , that will help us get a Word32 field:
| | naiveDecodeWord32 :: ByteString -> Either String Word32 |
| | naiveDecodeWord32 inputString = |
| | decode ( BS .drop 4 inputString) |
In this very naive version of our decoding function, we’re simply dropping the first four bytes of our input string and then using our existing Word32 decode instance to try to parse the rest of it. We can try it out in ghci and see that it works not only to successfully parse a correctly encoded value, but it also gives us some degree of error handling against bad values:
| | λ naiveDecodeWord32 (encodeWithSize @ Word32 255) |
| | Right 255 |
| | λ naiveDecodeWord32 (encode @ Word32 255) |
| | Left "Expecting 4 bytes but got 0" |
| | λ naiveDecodeWord32 (encode @ String "Greetings" ) |
| | Left "Expecting 4 bytes but got 5" |
This is a pretty good starting spot, and works well for a naive function. The biggest problem with our current implementation is that we discard any of the input that we’re not using to parse our Word32 . It would be nice if that were all we had to do for our decoders, and in fact we’ll get there in the end, but for now we can’t rely on our upstream callers to know implementation details like how much data we need to decode our number. Instead, we should take what we need to parse a value from the input, and return the rest of it to be used for the next thing that needs to be parsed.
Sticking with our most naive possible implementation, we can do this by first dropping the four-byte size prefix, and then splitting the rest of the string into two parts: the encoded word that we want to parse, and everything else. The splitAt function from Data.ByteString does this for us, so it’s pretty easy:
| | naiveDecodeWord32 :: ByteString -> Either String ( Word32 , ByteString ) |
| | naiveDecodeWord32 inputString = |
| | let |
| | (encodedWord, rest) = BS .splitAt 4 ( BS .drop 4 inputString) |
| | in do |
| | decodedWord <- decode encodedWord |
| | pure (decodedWord, rest) |
This is starting to look a bit better—we still have some error handling for free thanks to the Decode instance we wrote for Word32 , and now we’re returning the remainder of the string for additional parsing. This implementation is still a bit rough around the edges though. For one thing, our error messages could be better. We don’t make it clear to the user the error is referring to the number of bytes after the size prefix, and we don’t differentiate at all between the case where we didn’t even get enough bytes for the size prefix, or where we did get enough for the prefix but didn’t have enough leftover to parse the word. We’re also making a blanket assumption the size prefix will always be four bytes. It’s true it should always be four bytes if the input we’re getting is indeed a correctly encoded Word32 , but if our function is being called with some other kind of data then our user is probably already having a hard enough time and we can make their day a little easier by differentiating this error case from the others. In fact, all these improved error messages can go a long way toward helping a user who is trying to debug an encoder or decoder, or to troubleshoot why some data they want to parse isn’t getting parsed as they expect.
Let’s take one more pass at our function by adding more robust error handling for all of these edge cases:
| | import Control.Monad ( when ) |
| | |
| | naiveDecodeWord32 :: ByteString -> Either String ( Word32 , ByteString ) |
| | naiveDecodeWord32 inputString = do |
| | when ( BS .length inputString < 4) $ |
| | Left "Error, not enough data to get the size of the next field" |
| | let (encodedSizePrefix, rest) = BS .splitAt 4 inputString |
| | sizePrefix <- fromIntegral <$> bytestringToWord32 encodedSizePrefix |
| | when (sizePrefix /= 4) $ |
| | Left "the field size of a word should be 4" |
| | when ( BS .length rest < fromIntegral sizePrefix) $ |
| | Left "Not enough data for the next field size" |
| | let (encodedWord, rest') = BS .splitAt sizePrefix rest |
| | decodedWord <- decode encodedWord |
| | pure (decodedWord, rest') |
The when Function
The when function in this example comes from the Control.Monad module, which is part of base . This function is quite useful when we’re writing procedural style code in a do block as we’ve done here, since it lets us conditionally run some action without having to put the rest of our code into an if or case expression. In this example, we’re only evaluating Left if the field size isn’t what we expect. Since a Left value will terminate our Either action, it can be used as a way to early-abort on errors.
Now that we can decode Word32 values effectively, let’s move on to strings. Once again, we’ll aim to provide useful error messages when we can, and we’ll return the remainder of the data that we didn’t consume with our parsing.
Let’s start by looking at the implementation for a naive String decoder:
| | naiveDecodedString :: ByteString -> Either String ( String , ByteString ) |
| | naiveDecodedString inputString = do |
| | when ( BS .length inputString < 4) $ |
| | Left "Error, not enough data to get the size of the next field" |
| | let (encodedSizePrefix, rest) = BS .splitAt 4 inputString |
| | sizePrefix <- fromIntegral <$> bytestringToWord32 encodedSizePrefix |
| | when ( BS .length rest < fromIntegral sizePrefix) $ |
| | Left "Not enough data for the next field size" |
| | let (encodedString, rest') = BS .splitAt sizePrefix rest |
| | decodedString <- decode encodedString |
| | pure (decodedString, rest') |
Do you notice anything? We’ve renamed a couple of things since we’re working with strings instead of words now, and we’ve removed the check to verify the size of the field should always be exactly four bytes. Otherwise, these two functions are nearly identical. If we continued to implement other decoders, we could keep using the same pattern, but we’re hiding almost all the interesting logic behind the same repetitive bits of code to deal with the mechanics of how we’ve encoded the format. It seems like it might be time to do a bit of refactoring to break this function up into some re-usable components.
One of the most fundamental things we’re going to be doing with all of our decoding functions is taking some bytes out of the input string to parse, and returning the rest of the data unmodified. Let’s start refactoring by writing a function to handle this for us:
| | extractBytes |
| | :: Int |
| | -> ByteString |
| | -> Either String ( ByteString , ByteString ) |
| | extractBytes n byteString = do |
| | when ( BS .length byteString < n) $ |
| | Left $ "Error, extract bytes needs at least " <> show n <> " bytes" |
| | pure $ BS .splitAt n byteString |
Another thing we’ll want to do regularly is to look at the size of the next block of data by reading the size prefix at the start of the current input to figure out how much data we should extract for the next segment of input. We can re-use the extractBytes function that we just wrote to make that easier:
| | nextSegmentSize :: ByteString -> Either String ( Word32 , ByteString ) |
| | nextSegmentSize byteString = do |
| | (nextSegmentStr, rest) <- extractBytes 4 byteString |
| | parsedSegmentSize <- bytestringToWord32 nextSegmentStr |
| | pure (parsedSegmentSize, rest) |
Most of the time when we want to parse a field, we’re going to follow a pattern: first we’ll get the size of the next segment, then we’ll take however many bytes we need from the input string again. We can also write a function to do all of this for us and just give us the next segment of data that we need to decode:
| | nextSegment :: ByteString -> Either String ( ByteString , ByteString ) |
| | nextSegment byteString = do |
| | (segmentSize, rest) <- nextSegmentSize byteString |
| | extractBytes (fromIntegral segmentSize) rest |
Something still doesn’t feel right here. We’ve refactored our code into very small functions, and yet in all of these examples, the majority of the code that we’re writing is bookkeeping. We’re still manually dealing with pattern matching out the value we care about and the remainder of the ByteString frequently. The work that we’re doing to re-use our functions is starting to get a little tedious.
It turns out that we still have a significant refactoring opportunity that can greatly reduce the tedium of writing code like this for both us and users who want to use our parsing library: refactoring our ad hoc parser into a monadic parser .