In the last chapter, you built a tool to encode a file archive as raw binary data. One of the biggest challenges that we ran into as we were developing that project was the fact that we wanted to support files with different types in a single archive. We were able to do this by using existential types to erase the information about a specific type but keep the important information that it had an Encode instance.
The fundamental reason that this approach worked for encoding was that, at some point, the user of our library had to create values that were loaded into a FilePack , and those values had to have instances that said how the data should be encoded. Our existential type allowed us to forget the other information about that type, but we still carried the particular implementation of encode that each type used along with its data. That meant that when it came time to call encode on the entire FilePack , our program was able to figure out which particular encode function it needed to call for every single piece of data.
Decoding a FilePack is going to bring in a new wrinkle: when we’re loading in a new file archive and decoding it, all we have is some raw binary data. We don’t know what type it should be, so we have no idea which Decode instance we should use to extract the data.
In order to extract data, we’ll need the user to tell us what kind of data they want to extract, and then we can make a best effort at extracting the data into that type using the binary data we have. Of course, the user might be trying to deserialize some corrupt data, or might be wrong about the way the data was encoded originally, so we’ll need to be able to report errors to them as well.
You might recognize that what we’re talking about here is a parsing problem. Deserializing data, especially in the general way that we want to support for FilePack usually comes down to a parsing problem. We’ll approach the problem of extracting our encoded data as a parsing problem. This means that as you work through this chapter, keep in mind that the techniques you’re using here will apply equally well to parsing other types of data, like JSON or XML data, binary file formats, or text input you receive directly from a user.