Throughout this chapter, you’ll work through building a library for a tool called filepack . The FilePack library that we build will allow users to create archives of files that can be saved to disk, stored in a database, or sent over the internet. The examples you build as you work through this chapter will only support the programmatic creation and extraction of archives, but you are encouraged to create a complete application around this library as an additional example.
For maximum compatibility with third-party systems and tooling, we’ll store the contents of our files as base64 encoded string data. Base64 encoding is a well-known approach to encoding binary data in plain ASCII text so that it can be handled in systems that assume they are dealing with plain text. Rather than implementing the base64 encoding algorithm ourselves, we’ll import the base64-bytestring package. This package provides the Data.Byte String>Base64 module that we’ll be using throughout the chapter.
Exploring the Base64 Encoding Package
We can see some examples of base64 encoding and decoding in ghci . We’ll start by turning on the OverloadedStrings extension so that we can easily type ByteString literals, and we’ll import both Data.ByteString and Data.ByteString.Base64 :
| | λ :set - XOverloadedStrings |
| | λ import qualified Data.ByteString as BS |
| | λ import Data.ByteString.Base64 ( encode , decode ) |
The two functions we’ll be most interested in from the module are encode and decode , which allow us to encode a ByteString as base64, or decode it from base64 respectively. We can look at the types in ghci :
| | λ : type encode |
| | encode :: BS . ByteString -> BS . ByteString |
| | λ : type decode |
| | decode :: BS . ByteString -> Either String BS . ByteString |
To encode a ByteString we pass it to encode. The ByteString that we get back out will look nothing like the input. You can try running a few examples to see what base64 encoded strings look like:
| | λ encode "Hello, World" |
| | "SGVsbG8sIFdvcmxk" |
| | λ encode "String To Encode" |
| | "U3RyaW5nIFRvIEVuY29kZQ==" |
Decoding a string could fail if we pass in a value that isn’t a valid base64 string. If the value is a valid base64 string, we should always get back precisely the same string that we originally encoded:
| | λ decode (encode "Hello, World" ) |
| | Right "Hello, World" |
| | |
| | λ decode "Hello, World" |
| | Left "invalid character at offset: 5" |
Creating the Basic Application
We’ll start by creating a new project with cabal and adding a new module, FilePack , to the library. In this example, we’re going to need to add the OverloadedStrings extension. Since we know that we’re going to need them, we’ll also go ahead and import the ByteString and Base64 encoding modules:
| | {-# LANGUAGE OverloadedStrings #-} |
| | |
| | module FilePack where |
| | |
| | import Data.ByteString ( ByteString ) |
| | import qualified Data.ByteString as BS |
| | import qualified Data.ByteString.Char8 as BC |
| | import qualified Data.ByteString.Base64 as B64 |
| | import Data.Word |
| | import System.Posix.Types ( FileMode , CMode (..)) |
| | import Text.Read ( readEither ) |
A file pack is really nothing more than a collection of files, so the next thing we need to figure out is how we want to represent an individual file. For now, let’s start with something minimal, and we’ll expand on what we can do with it throughout the chapter.
We’ll create a new record, FileData , to store information about a file. We’ll have four fields in our record:
- fileName will hold the name of the file on disk.
- fileSize will hold the size of the unpacked file.
- filePermissions will store the file’s permissions.
- fileData will store the actual contents of the file.
Since a file size can never be negative, we’ll store the size as a Word32 . The Word types, from Data.Word , allow us to store unsigned numeric values.
| System Dependent Code Ahead |
|---|
|
| In this chapter, we’ll assume that a CMode is an alias for Word32 . CMode might alias other numeric types depending on your operating system. In that case, you may need to define some additional type class instances to fully support your operating system. |
We’ll store the permissions using the CMode type from System.Posix.Types . This type will let us store a numeric representation of the file permissions in normal Unix permissions style as a three-digit octal number. We’ll also bring in FileMode , which is an alias for CMode that has a more easily understandable name.
Finally, we’ll store the contents of our file as a ByteString . This will make our lives easier since it is the native type that our base64 encoder wants to use, and can represent arbitrary binary data.
With these fields in place, we can create our new FileData record:
| | data FileData = FileData |
| | { fileName :: FilePath |
| | , fileSize :: Word32 |
| | , filePermissions :: FileMode |
| | , fileData :: ByteString |
| | } deriving ( Eq , Read , Show ) |
The FileData record represents a single file. A FilePack is a collection of files that should be stored in an archive. We’ll use a newtype wrapper for our file pack:
| | newtype FilePack = |
| | FilePack {getPackedFiles :: [ FileData ]} deriving ( Eq , Read , Show ) |
Now we’re ready to serialize our file pack into an archive. Sticking with the theme of starting with a minimal implementation, we’ll use Show to serialize our file pack into a String , then BS.pack to convert the String into a ByteString , and finally we’ll call B64.encode to generate the final archive:
| | packFiles :: FilePack -> ByteString |
| | packFiles filePack = |
| | B64 .encode . BC .pack . show $ filePack |
We need to do a bit more work to unpack our file, but not too much. We’ll start by importing another module from bytestring , Data.ByteString.Char8 . This module has most of the same functions that are available in Data.ByteString , but they work with String and Char values rather than lists of bytes. Data.ByteString.Char8 re-exports the same ByteString type that is exported by Data.ByteString , so you don’t need to worry about converting between Data.ByteString.ByteString and Data.ByteString.Char8.ByteString .
Next, we’ll need to try to decode the serialialized data that we’ve gotten. If that fails we can give up, because there’s nothing more that we can do. On the other hand, if we do get a decoded value, then we can try to use our Read instance to convert that value back to a FilePack .
We can’t just call read though. There are two issues we’ll need to solve. First, read might fail at runtime. It would be nice if we could get some better error reporting if something goes wrong. To do that, we can use the readEither function from Text.Read in base . This function works like read but returns an Either value rather than failing at runtime.
The other issue is that readEither and other similar functions all work with String values rather than bytestrings, so we’ll call BC.unpack to convert our ByteString into a string before trying to parse it.
With all of that in place, here’s what our unpack function looks like:
| | unpackFiles :: ByteString -> Either String FilePack |
| | unpackFiles serializedData = |
| | B64 .decode serializedData >>= readEither . BC .unpack |
As a general rule, using Show and Read for important serialization work as we’ve done in this example is a bad idea. Both read and show are quite closely tied to the specific implementation of a record. The strings generated by show include the names of all of the record fields, in the order they are written in the code. Similarly, read will fail if any fields have been added, removed, renamed, or the order of fields in a record have changed. Later on in this chapter we’ll stop depending on these and implement serialization and deserialization ourselves, but for now we’ll keep using these as a quick way to develop our first prototype.
Writing In-Line Tests
As we’re working through the development of our library, it’ll be nice to test our code in ghci , but it can start to get a little annoying to rewrite the tests we want to run repeatedly. In cases like that, one handy approach is to add some tests in our module that will be available to run interactively each time we load the code into ghci . Once you’ve finished active work on the feature, you can delete your test code or use them as the foundation for unit tests.
| | testPackFile :: ByteString |
| | testPackFile = |
| | packFiles sampleFilePack |
| | |
| | testUnpackFile :: Either String FilePack |
| | testUnpackFile = unpackFiles testPackFile |
| | |
| | testRoundTrip :: FilePack -> Bool |
| | testRoundTrip pack = |
| | ( Right pack) == (unpackFiles $ packFiles pack) |
These test functions will now let us look at the result of packing and unpacking FilePack values, as well as verifying that we can round-trip our data by ensuring that decoding some encoded data gives us back what we started with.
| | λ testRoundTrip |
| | True |
Supporting Multiple File Types
Our simple version of FilePack works remarkably well for being such a small library, but there are a few drawbacks to the approach that we’ve taken. The most immediate one is we’re requiring our users to do the hard work of turning their data into a ByteString before they can ever create a file. It’d be nice if we could allow users to instead work with whatever types they are already using to represent their file data, but pack those files directly into a file pack.
The next incremental step that we could take to giving our users more flexibility in how they represent their data is to make use of a sum type. Instead of taking a ByteString to serialize data, we can take any of several different types of data that could represent the file.
For the moment, let’s consider a couple of other popular ways to represent Haskell data. ByteString will allow us to easily support binary data, so next, let’s add support for Text to support text content. We’ll also add support for text stored as a String so that users who are working with strings don’t need to pack and unpack their data.
We’ve already added bytestring into our cabal dependencies, and String support comes from base . We’ll also need to add text as a dependency in our cabal file.
Next, we need to import a couple of modules. Data.Text will give us access to Text types. The Text type is an efficient way to represent and work with Unicode text data:
| | import Data.Text ( Text ) |
| | import qualified Data.Text as Text |
With our imports in place, we can move on to defining a type to represent our file contents. Since we have three different formats to choose from, we’ll create a new sum type , FileContents :
| | data FileContents |
| | = StringFileContents String |
| | | TextFileContents Text |
| | | ByteStringFileContents ByteString |
| | deriving ( Eq , Read , Show ) |
And next, let’s update our our FileData record to use FileContents :
| | data FileData = FileData |
| | { fileName :: FilePath |
| | , fileSize :: Word32 |
| | , filePermissions :: FileMode |
| | , fileData :: FileContents |
| | } deriving ( Eq , Read , Show ) |
Finally, we need to update our sampleFilePack to select a particular encoding of our data:
| | sampleFilePack :: FilePack |
| | sampleFilePack = FilePack $ |
| | [ FileData "stringFile" 0 0 $ StringFileContents "hello string" |
| | , FileData "textFile" 0 0 $ TextFileContents "hello text" |
| | , FileData "binaryFile" 0 0 $ ByteStringFileContents "hello bytestring" |
| | ] |
Using a sum type here allows us to create a slightly more flexible API while having to write minimal code. In cases where you know ahead of time that you’ll only need to support a few specific input types, making use of a sum type to represent all of the options is often the easiest way forward.
In the case of our file packer, however, we want to allow users of our library to package any sort of data into files without restricting them to a particular set of representations.