Haskell中的通用序列化

时间:2012-10-17 13:19:09

标签: haskell serialization deserialization

当我尝试反序列化对象时,我收到此错误。

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

创建输出文件,如下所示:

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....|

我怀疑我错误地使用了新的泛型内容。这是我的代码。顺便说一句,如果我删除第9,22和23行,我会得到相同的结果。如果我删除gzip / ungzip的东西,我会得到相同的结果。

{-# 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

1 个答案:

答案 0 :(得分:2)

事实证明,我的错误与泛型本身无关。 readBug函数上的错误类型签名导致其尝试阅读Either String Bug而非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