Using Show and Read in our prototype certainly made things easier on us when we were serializing and deserializing things, but that wasn’t the only benefit. It also meant that we didn’t have to think much about how users would interact with our library. Show and Read are both common type classes that have implementations for most basic types, and our users might already have them implemented for their own data.

Now that we’re going to be dropping these type classes in favor of something that works more reliably for our problem, we are going to need to ensure that we’re still giving users the ability to interact with our library using whatever types they happen to be using to represent their own file data. We’ll still handle this with type classes, but now instead of relying on preexisting type classes, we’ll define our own.

We’ll start with a class for encoding data into a bytestring:

​  ​ class ​ ​ Encode ​ a ​ where ​
​  encode :: a -> ​ ByteString ​

Let’s also create a type class for decoding things that we have encoded. You’ll build a complete decoder for file packs in the next chapter, but defining the type class now will give you something that you can use to test with as you work through this chapter:

​  ​ class ​ ​ Decode ​ a ​ where ​
​  decode :: ​ ByteString ​ -> ​ Either ​ ​ String ​ a

Now that we have defined a type class, we need to start creating some instances for it. Eventually we’ll want to create instances for things like FileData and FilePack , but we’ll start by creating instances for more basic types, so that we can re-use them when we’re implementing our bigger instances.

Creating Instances for Basic Types

Let’s start creating instances for our basic types with ByteString . Since we’re defining our own type classes for encoding and decoding things, we’re free to pick any approach that we want. We’re free to continue using base64 encoding for our fields, or to simply use the underlying bytestring directly. For now, let’s just make our encode and decode functions for ByteString preserve the input string unmodified:

​  ​ instance ​ ​ Encode ​ ​ ByteString ​ ​ where ​
​  encode = id
​  
​  ​ instance ​ ​ Decode ​ ​ ByteString ​ ​ where ​
​  decode = ​ Right ​ . id

We can create instances for Text and String with just a little bit more work. For Text we’ll use the encodeUtf8 and decodeUtf8 functions from Data.Text.Encoding to do the conversion for us:

​  ​ import ​ ​ Data.Text.Encoding ​ (​ encodeUtf8 ​, ​ decodeUtf8 ​)
​  
​  ​ instance ​ ​ Encode ​ ​ Text ​ ​ where ​
​  encode = encodeUtf8
​  
​  ​ instance ​ ​ Decode ​ ​ Text ​ ​ where ​
​  decode = ​ Right ​ . decodeUtf8

Similarly, our instances for String can simply re-use the work already done for us by pack and unpack from Data.ByteString.Char8 . We’ll need to add the FlexibleInstances extension for these instances. Without FlexibleInstances we’re not allowed to create an instance of a type class that specifies a particular value for a type parameter. Since String is an alias for [Char] , that means we wouldn’t ordinarily be allowed to create an instance for it. Instead, we’d need to create a more general instance for [a] . With FlexibleInstances we’re allowed to be more specific and restrict our instance to only [Char] :

​  ​ {-# LANGUAGE FlexibleInstances #-} ​
​  
​  ​ instance ​ ​ Encode ​ ​ String ​ ​ where ​
​  encode = ​ BC ​.pack
​  
​  ​ instance ​ ​ Decode ​ ​ String ​ ​ where ​
​  decode = ​ Right ​ . ​ BC ​.unpack

With our various string types accounted for, let’s turn our attention to a type that has a more interesting instance: Word32 .

Serializing Word32

The Word32 type represents an unsigned four-byte (32-bit) number. Word32 is the first major departure from our serialization pattern so far, because it’s not string data but instead raw binary data. Although we might naively choose to convert our number to a string and encode that string the same way we encoded Text and String values, in this example, we’ll stick to our chosen approach of avoiding show and read and instead encoding the data ourselves. As you’ll see later on in this chapter, the choice to encode the raw binary data now will end up paying dividends to us later when it’s time to deserialize our files.

Thankfully, as its name implies, ByteString works under the hood with raw binary data. Specifically, raw individual bytes. Until now we’ve ignored the “binary-ness” of ByteString and worked with them through interfaces that let us think of them as textual string data, but we are perfectly free to skip these interfaces and work directly with the underlying bytes that make up a ByteString .

Earlier, when we wrote our Encode and Decode instances for String we used the pack and unpack functions from Data.ByteString.Char8 . The pack function takes a list of characters and returns a new ByteString , and unpack takes a ByteString and returns a list of characters.

If we want to work with the underlying bytes instead of character strings, all we need to do is to use the pack and unpack functions from Data.ByteString instead of Data.ByteString.Char8 :

​  ​ λ ​ :​ type ​ ​ BS ​.pack
​  ​ BS ​.pack :: [​ Word8 ​] -> ​ ByteString ​
​  ​ λ ​ :​ type ​ ​ BS ​.unpack
​  ​ BS ​.unpack :: ​ ByteString ​ -> [​ Word8 ​]

This is pretty convenient, but the difficulty we’re going to run into is that we’re dealing with a four-byte Word32 value, and somehow we need to convert that to four one-byte Word8 values instead.

Let’s write a function called Word32ToBytes that will handle the conversion for us. It’ll have the type:

​  word32ToBytes :: ​ Word32 ​ -> (​ Word8 ​, ​ Word8 ​, ​ Word8 ​, ​ Word8 ​)

We’ll start our implementation by importing Data.Bits from base . This will give us access to some useful bitwise operators that we can use to split up our Word32 : The bitwise-and operator (.&.) , the bitwise-or operator (.|.) , and the bitwise shift function.

​  ​ import ​ ​ Data.Bits ​ ((.&.), (.|.), ​ shift ​)
Bit Twiddling

| images/aside-icons/important.png | If you haven’t worked with bitwise operations in a while, you might find some of the examples in this section hard to follow. In that case, you should use ghci to experiment with the operations before you move forward. You can use the printf function from Text.Printf to easily display values in binary to make this easier: showBinary = printf "%b\n" . |

The implementation of our function makes use of some bit twiddling to get the underlying bytes out of our Word32 value:

​  word32ToBytes :: ​ Word32 ​ -> (​ Word8 ​, ​ Word8 ​, ​ Word8 ​, ​ Word8 ​)
​  word32ToBytes word =
​  ​ let ​ a = fromIntegral $ 255 .&. word
​  b = fromIntegral $ 255 .&. (shift word (-8))
​  c = fromIntegral $ 255 .&. (shift word (-16))
​  d = fromIntegral $ 255 .&. (shift word (-24))
​  ​ in ​ (a,b,c,d)

In this function, we take one-byte sections out of our Word32 one at a time by shifting the value to the right and then using 255 .&. to take only the lower byte of the shifted value. In the end, we’ll have gotten each of the bytes one-by-one. If you haven’t encountered this sort of bit twiddling before, or don’t remember much about it, you don’t need to worry. We’ll revisit this one more time later on in this section when we reconstruct the values, and afterwards we won’t need to return to the details of this function again.

We can get a better idea of how this works by writing a quick function in ghci to help us visualize this. We’ll need to import Text.Printf so that we can easily print out hex digits, and then we can create a small helper function, printBytes , which takes a four-tuple of bytes and prints them out:

​  ​ λ ​ ​ import ​ ​ Text.Printf ​
​  ​ λ ​ printBytes (a,b,c,d) = printf ​ "%02x %02x %02x %02x ​​ \n ​​ " ​ a b c d

And now we can print out some values:

​  ​ λ ​ printBytes $ word32ToBytes 0xAABBCCDD
​  dd cc bb aa
​  ​ λ ​ printBytes $ word32ToBytes 255
​  ff 00 00 00
​  ​ λ ​ printBytes $ word32ToBytes 65535
​  ff ff 00 00
​  ​ λ ​ printBytes $ word32ToBytes 0xffff0000
​  00 00 ff ff

The order of bytes in the output will depend on the native byte order (or “endianness”) of your system. The previous examples are from a little endian x86-64 system, which puts the least significant bytes first.

Since we’re not going to be working directly with the bytes in our application, other than encoding and decoding them, we don’t need to be immediately concerned with the byte order in our data. We would, however, need to consider byte order if we were going to try to make our application work with files that were created on systems with a potentially different byte ordering.

Now that we have a way to get the individual bytes out of a Word32 , we can pack them into a bytestring without too much extra work. We’ll start by building a function that will let us create a new ByteString from a Word32 :

​  word32ToByteString :: ​ Word32 ​ -> ​ ByteString ​
​  word32ToByteString word =
​  ​ let ​ (a,b,c,d) = word32ToBytes word
​  ​ in ​ ​ BS ​.pack [a,b,c,d]

We can also create a function that will let us add a Word32 to the beginning of an existing bytestring. This will come in handy later as we start to serialize our data:

​  consWord32 :: ​ Word32 ​ -> ​ ByteString ​ -> ​ ByteString ​
​  consWord32 word bytestring =
​  ​ let ​ packedWord = word32ToByteString word
​  ​ in ​ packedWord <> bytestring

Now that we have a way to turn a Word32 into a ByteString we can encode one by calling word32ToByteString :

​  ​ instance ​ ​ Encode ​ ​ Word32 ​ ​ where ​
​  encode = word32ToByteString

Now that we have a working encoder, let’s turn our attention toward decoding a value. Our decoder function needs to turn a bytestring back into a single Word32 by putting the individual bytes in the word back together. Before we start dealing with the ByteString data, let’s first write a simpler function that will start with the raw bytes and put them back together into a Word32 :

​  word32FromBytes :: (​ Word8 ​, ​ Word8 ​, ​ Word8 ​, ​ Word8 ​) -> ​ Word32 ​
​  word32FromBytes (a,b,c,d) =
​  ​ let ​
​  a' = fromIntegral a
​  b' = shift (fromIntegral b) 8
​  c' = shift (fromIntegral c) 16
​  d' = shift (fromIntegral d) 24
​  ​ in ​ a' .|. b' .|. c' .|. d'

This function is the inverse of our previous word32ToBytes function. Each value was originally shifted to the right by 0, 1, 2, or 3 bytes, so we shift them back to their correct position and then use bitwise-or ( .|. ) to combine them back into a single value.

Once you’ve written this function, you can validate that it’s correct by writing a function to test Word32 values to ensure that converting a value to bytes and back returns the original value.

Turning a ByteString into a Word32 using our new word32FromBytes function isn’t going to be very hard, but it does have the potential to fail. Unlike when we were created a ByteString , we now have to consider the possibility of failure. A Word32 must be made up of precisely four bytes, so we need to check the size of our input and return an error if we get more or less data than we expect.

We’ll handle this by unpacking our bytestring and pattern matching on the resulting list. If we get exactly four bytes, we can convert them into a Word32 and otherwise we’ll report an error:

​  bytestringToWord32 :: ​ ByteString ​ -> ​ Either ​ ​ String ​ ​ Word32 ​
​  bytestringToWord32 bytestring =
​  ​ case ​ ​ BS ​.unpack bytestring ​ of ​
​  [a,b,c,d] -> ​ Right ​ $ word32FromBytes (a,b,c,d)
​  _otherwise ->
​  ​ let ​ l = show $ ​ BS ​.length bytestring
​  ​ in ​ ​ Left ​ (​ "Expecting 4 bytes but got " ​ <> l)

Finally, we can write our Decode instance for Word32 by directly calling bytestringToWord32 :

​  ​ instance ​ ​ Decode ​ ​ Word32 ​ ​ where ​
​  decode = bytestringToWord32

Serializing FileMode

A FileMode is an alias for CMode , which is itself a newtype wrapper around Word32 . This means we can easily re-use the work we’ve just done with Word32 to serialize and deserialize FileMode too:

​  ​ instance ​ ​ Encode ​ ​ FileMode ​ ​ where ​
​  encode (​ CMode ​ fMode) = encode fMode
​  
​  ​ instance ​ ​ Decode ​ ​ FileMode ​ ​ where ​
​  decode = fmap ​ CMode ​ . decode

Serializing FileData

Now that we’ve written instances to let us serialize all of the types that we’re using inside of FileData , we can move on to serializing a FileData value itself. As a first step, let’s refactor FileData . Instead using a sum type like FileContents to list a small set of supported files, we’ll add a type parameter to keep track of the type of the contents in our file:

​  ​ data ​ ​ FileData ​ a = ​ FileData ​
​  { fileName :: ​ FilePath ​
​  , fileSize :: ​ Word32 ​
​  , filePermissions :: ​ FileMode ​
​  , fileData :: a
​  } ​ deriving ​ (​ Eq ​, ​ Read ​, ​ Show ​)
​  
​  ​ newtype ​ ​ FilePack ​ a =
​  ​ FilePack ​ {getPackedFiles :: [​ FileData ​ a]}
​  ​ deriving ​ (​ Eq ​, ​ Read ​, ​ Show ​)

Next, let’s move on to writing an Encode instance for FileData . Unlike our earlier examples, FileData is a record that has several values that will need to be packed together. Let’s start with a relatively simple attempt at encoding file data:

​  ​ instance ​ ​ Encode ​ a => ​ Encode ​ (​ FileData ​ a) ​ where ​
​  encode ​ FileData ​{..} =
​  encode fileName
​  <> encode fileSize
​  <> encode filePermissions
​  <> encode fileData

In this example, we’re depending on the Encode instance for whatever type we’re using to store the contents of the file. We already have instances defined for the types we’re using to store metadata. This is enough to let us encode each individual field in the record, and from there we can concatenate them together to get encoded file data. This approach will compile, and we can see it working to encode data in ghci . Now that we can support several different content types, we’ll use a type application to tell the compiler what kind of contents we’re intending to use:

​  ​ λ ​ encode $ ​ FileData ​ @​ String ​ ​ "testPath" ​ 0 0 ​ "Foo" ​
​  ​ "testPath ​​ \NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL ​​ Foo" ​

Unfortunately, we’ve created a problem for ourselves when we want to decode a value. If we try to implement an equally straightforward decoder we’ll quickly see what happened:

​  ​ instance ​ ​ Decode ​ a => ​ Decode ​ (​ FileData ​ a) ​ where ​
​  decode encodedFileData =
​  ​ case ​ decode encodedFileData ​ of ​
​  ​ -- ... ​

Do you see the problem yet? We get a single ByteString in as input, and the first thing that we try to decode will consume our entire bytestring. If all of our fields were of a fixed size, then we could just take enough data out of the bytestring for each field and decode that, but we’re dealing with both string data from FilePath and unknown data with the field our user provides.

We need some way to separate out the individual fields so that we can decode them effectively. We could add a separator to our strings so that we can mark the end of one section of data and the start of another, but since we might be storing arbitrary data, there aren’t any separators that we could use that couldn’t also occur naturally in the data that we’re encoding.

We can avoid this problem by prefixing each field with the size, in bytes, of the field. Then, when we’re decoding things, we can always just take the exact amount of the string that we need and decode it.

To support adding size information to everything that we encode, let’s add a second function to our Encode type class called encodeWithSize :

​  ​ class ​ ​ Encode ​ a ​ where ​
​  encode :: a -> ​ ByteString ​
​  encodeWithSize :: a -> ​ ByteString ​

Of course, if we have a definition of encode we can always come up with a reasonable definition of encodeWithSize by looking at the length of the encoded value, so we can add a default implementation:

​  encodeWithSize :: a -> ​ ByteString ​
​  encodeWithSize a =
​  ​ let ​ s = encode a
​  l = fromIntegral $ ​ BS ​.length s
​  ​ in ​ word32ToByteString l <> s

On the other hand, if we’re provided a valid implementation of encodeWithSize , we can come up with a valid implementation of decode by dropping off the leading size field. So, we can add a default implementation for it as well:

​  encode :: a -> ​ ByteString ​
​  encode = ​ BS ​.drop 4 . encodeWithSize

As a last step, let’s add a MINIMAL pragma to let our users know that they need to provide an implementation of at least one of these two functions. With that, our final type class definition will be:

​  ​ class ​ ​ Encode ​ a ​ where ​
​  encode :: a -> ​ ByteString ​
​  encode =
​  ​ BS ​.drop 4 . encodeWithSize
​  
​  encodeWithSize :: a -> ​ ByteString ​
​  encodeWithSize a =
​  ​ let ​ s = encode a
​  l = fromIntegral $ ​ BS ​.length s
​  ​ in ​ word32ToByteString l <> s
​  ​ {- MINIMAL encode | encodeWithSize #-} ​

We’ve already implemented encode for all of our values, so we could move on. For most of our instances, there’s no way that we can do better than our default encodeWithSize implementation, so we only need to update our Word32 instance.

Since we know that Word32 will always take up four bytes when it’s encoded, we don’t need to look at the length of the encoded string at all. We can save some effort and hard-code the size ahead of time:

​  ​ instance ​ ​ Encode ​ ​ Word32 ​ ​ where ​
​  encode = word32ToByteString
​  encodeWithSize w =
​  ​ let ​ (a, b, c, d) = word32ToBytes w
​  ​ in ​ ​ BS ​.pack [ 4, 0, 0, 0
​  , a, b, c, d]

This implementation should be significantly more efficient since we’re only constructing a single ByteString .

Now that we have a way to keep track of the size of each field in FileData , we can return to our instance implementation. We’ll use our new function to encode each of our fields with their size. We’ll also encode the entire thing together as a single bytestring so we keep all the internal pieces together:

​  ​ instance ​ ​ Encode ​ a => ​ Encode ​ (​ FileData ​ a) ​ where ​
​  encode ​ FileData ​{..} =
​  ​ let ​
​  encodedFileName = encodeWithSize fileName
​  encodedFileSize = encodeWithSize fileSize
​  encodedFilePermissions = encodeWithSize filePermissions
​  encodedFileData = encodeWithSize fileData
​  encodedData =
​  encodedFileName
​  <> encodedFileSize
​  <> encodedFilePermissions
​  <> encodedFileData
​  ​ in ​ encode encodedData

For the moment we’ll skip implementing Decode for our FileData . Later on in this chapter, we’ll return to the subject of decoding records and other compound value types.

Serializing Tuples and Lists

Before we finish up with this section on serializing data, let’s add two more instances that will come in handy later on in the chapter. As with FileData , we’ll serialize them now, and add Decode instances later on.

We’ll start by serializing tuples. As with FileData , we’ll make use of encodeWithSize to let us differentiate between our first and second fields:

​  ​ instance ​ (​ Encode ​ a, ​ Encode ​ b) => ​ Encode ​ (a,b) ​ where ​
​  encode (a,b) =
​  encode $ encodeWithSize a <> encodeWithSize b

Next, we’ll add an instance that will let us encode any list of encodable values. We don’t know ahead of time how many elements we’ll be processing, but we can still apply our pattern of encoding to every element of our list with its size, concatenating them together, and encoding the final result.

We’ll use the foldMap function to do this. foldMap , like the name implies, is a combination of a fold and a map. It applies a function to each element in a list and combines the results with (<>) :

​  ​ instance ​ ​ Encode ​ a => ​ Encode ​ [a] ​ where ​
​  encode = encode . foldMap encodeWithSize

Unfortunately, this instance doesn’t work! If we try to compile it we’ll get an error. Your error might look a bit different, but it should resemble this one:

​  FilePack.hs:49:10: error:
​  • Overlapping instances for Encode String
​  arising from a use of ‘FilePack.$dmencodeWithSize’
​  Matching instances:
​  instance Encode String -- Defined at FilePack.hs:49:10
​  instance Encode a => Encode [a] -- Defined at FilePack.hs:85:10
​  • In the expression: FilePack.$dmencodeWithSize @(String)
​  In an equation for ‘encodeWithSize’:
​  encodeWithSize = FilePack.$dmencodeWithSize @(String)
​  In the instance declaration for ‘Encode String’
​  |
​  49 | instance Encode String where
​  | ^^^^^^^^^^^^^

The important part here is the part that says Overlapping instances .

The problem is we’ve told the compiler to do the same thing in two different ways. In the instance we just wrote, we told it for any list it should use that instance’s version of encode . When we created an instance for String we also told it to use that instance any time it had a list of characters. So the compiler throws up its arms, and an error, and refuses to compile our program.

Of course, to us it’s obvious what we’d like to happen. We want our special case of String to be used when it can be, and we want to fall back to our general case of [a] otherwise. We can tell the compiler to do just that by telling it that our new instance is OVERLAPPABLE . The OVERLAPPABLE pragma is a way that we can tell GHC to always prefer a different instance if there happens to be a conflict.

With the pragma in place our instance now looks like this:

​  ​ instance ​ ​ {-# OVERLAPPABLE #-} ​ ​ Encode ​ a => ​ Encode ​ [a] ​ where ​
​  encode = encode . foldMap encodeWithSize

And with the conflict resolved, GHC will happily compile our code again and work as we’d like.

Overlapping instances are a common problem. If you run into them you can use the OVERLAPPABLE instance as we’ve done here to specify an instance that should not be chosen if there is a conflict, or you can use the OVERLAPS pragma to provide one that should be authoritative.

The OverlappingInstances extension enables overlapping on all instances without the pragma, but this extension is deprecated and you should not use it in new code.