Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic serialization in Haskell

I'm getting this error when I try to deserialize an object.

Amy64.hs: GetException "too few bytes\nFrom:\tdemandInput\n\n"

The output file is created, and looks like this:

00000000  1f 8b 08 00 00 00 00 00  04 03 63 60 00 03 56 a7  |..........c`..V.|
00000010  d2 f4 e2 4a 00 be b2 38  41 0d 00 00 00           |...J...8A....|

I suspect I'm using the new generics stuff incorrectly. Here is my code. By the way, if I delete lines 9, 22, and 23, I get the same result. And if I remove the gzip/ungzip stuff, I get the same result.

{-# LANGUAGE DeriveGeneric #-}

import Data.Conduit (runResourceT, ($$), (=$))
import Data.Conduit.Binary (sinkFile, sourceFile)
import Data.Conduit.Cereal (sinkGet, sourcePut)
import Data.Conduit.Zlib (gzip, ungzip)
import qualified Data.Serialize as DS (Serialize, get, put)
import GHC.Generics (Generic)
import Data.Serialize.Derive (derivePut, deriveGet) -- line 9

readBug :: FilePath -> IO (Either String Bug)
readBug f = 
  runResourceT $ sourceFile f $$ ungzip =$ sinkGet (DS.get)

writeBug :: FilePath -> Bug -> IO ()
writeBug f t = 
  runResourceT $ sourcePut (DS.put t) $$ gzip =$ sinkFile f

data Bug = Bug String deriving (Show, Generic)

instance DS.Serialize Bug where
  put = derivePut -- line 22
  get = deriveGet -- line 23

main = do
  let a = Bug "Bugsy"
  writeBug "x.dat" a
  (Right b) <- readBug "x.dat" :: IO (Either String Bug)
  print b
like image 574
mhwombat Avatar asked Oct 17 '12 13:10

mhwombat


1 Answers

It turned out that my mistake had nothing to do with Generics per se. A bad type signature on the readBug function was causing it to try to read an Either String Bug instead of just a Bug.

{-# LANGUAGE DeriveGeneric #-}

import Data.Conduit (runResourceT, ($$), (=$))
import Data.Conduit.Binary (sinkFile, sourceFile)
import Data.Conduit.Cereal (sinkGet, sourcePut)
import Data.Conduit.Zlib (gzip, ungzip)
import qualified Data.Serialize as DS (Serialize, get, put)
import GHC.Generics (Generic)
import Data.Serialize.Derive (derivePut, deriveGet) -- line 9

readBug :: FilePath -> IO Bug
readBug f = 
  runResourceT $ sourceFile f $$ ungzip =$ sinkGet DS.get

writeBug :: FilePath -> Bug -> IO ()
writeBug f t = 
  runResourceT $ sourcePut (DS.put t) $$ gzip =$ sinkFile f

data Bug = Bug String deriving (Show, Generic)

instance DS.Serialize Bug where
  put = derivePut -- line 22
  get = deriveGet -- line 23

main :: IO ()
main = do
  let a = Bug "Bugsy"
  writeBug "x.dat" a
  b <- readBug "x.dat" :: IO Bug
  print b
like image 126
mhwombat Avatar answered Nov 24 '22 19:11

mhwombat