module Game.LambdaHack.Utils.File
( encodeEOF, strictDecodeEOF
) where
import System.IO
import Data.Binary
import qualified Data.ByteString.Lazy as LBS
import qualified Codec.Compression.Zlib as Z
encodeData :: Binary a => FilePath -> a -> IO ()
encodeData f = LBS.writeFile f . Z.compress . encode
encodeEOF :: Binary a => FilePath -> a -> IO ()
encodeEOF f a = encodeData f (a, "OK")
strictReadSerialized :: FilePath -> IO LBS.ByteString
strictReadSerialized f =
withBinaryFile f ReadMode $ \ h -> do
c <- LBS.hGetContents h
let d = Z.decompress c
LBS.length d `seq` return d
strictDecodeData :: Binary a => FilePath -> IO a
strictDecodeData = fmap decode . strictReadSerialized
strictDecodeEOF :: Binary a => FilePath -> IO a
strictDecodeEOF f = do
(a, n) <- strictDecodeData f
if n == "OK"
then return a
else error $ "Fatal error: corrupted file " ++ f