From fc5f75bd4867f1cea5b1b742c418f4976b8650a7 Mon Sep 17 00:00:00 2001 From: "Edward Z. Yang" Date: Wed, 23 Jul 2014 20:29:30 +0100 Subject: [PATCH] Refactor decodeFileOrFail to have decodeGetFileOrFail, fixing #57. Signed-off-by: Edward Z. Yang --- src/Data/Binary.hs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/Data/Binary.hs b/src/Data/Binary.hs index d5a18585..82039501 100644 --- a/src/Data/Binary.hs +++ b/src/Data/Binary.hs @@ -68,6 +68,7 @@ module Data.Binary ( , encodeFile -- :: Binary a => FilePath -> a -> IO () , decodeFile -- :: Binary a => FilePath -> IO a , decodeFileOrFail + , decodeGetFileOrFail , module Data.Word -- useful @@ -215,9 +216,15 @@ decodeFile f = do -- in 'Right'. In case of decoder errors, the error message together with -- the byte offset will be returned. decodeFileOrFail :: Binary a => FilePath -> IO (Either (ByteOffset, String) a) -decodeFileOrFail f = +decodeFileOrFail f = decodeGetFileOrFail get f + +-- | Decode a value from a file using a 'Get' monad. In case of success, the +-- value will be returned in 'Right'. In case of decoder errors, the error +-- message together with the byte offset will be returned. +decodeGetFileOrFail :: Get a -> FilePath -> IO (Either (ByteOffset, String) a) +decodeGetFileOrFail g f = withBinaryFile f ReadMode $ \h -> do - feed (runGetIncremental get) h + feed (runGetIncremental g) h where -- TODO: put in Data.Binary.Get and name pushFromHandle? feed (Done _ _ x) _ = return (Right x) feed (Fail _ pos str) _ = return (Left (pos, str))