{-# LANGUAGE CPP #-}
{-# LANGUAGE PatternSynonyms #-}

module Distribution.Compat.Binary
       ( decodeOrFailIO
       , decodeFileOrFail'
       , module Data.Binary
       ) where

import Control.Exception (ErrorCall (..), catch, evaluate)
import Data.ByteString.Lazy (ByteString)

import Data.Binary

-- | Lazily reconstruct a value previously written to a file.
decodeFileOrFail' :: Binary a => FilePath -> IO (Either String a)
decodeFileOrFail' :: forall a. Binary a => FilePath -> IO (Either FilePath a)
decodeFileOrFail' FilePath
f = ((ByteOffset, FilePath) -> Either FilePath a)
-> (a -> Either FilePath a)
-> Either (ByteOffset, FilePath) a
-> Either FilePath a
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (FilePath -> Either FilePath a
forall a b. a -> Either a b
Left (FilePath -> Either FilePath a)
-> ((ByteOffset, FilePath) -> FilePath)
-> (ByteOffset, FilePath)
-> Either FilePath a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ByteOffset, FilePath) -> FilePath
forall a b. (a, b) -> b
snd) a -> Either FilePath a
forall a b. b -> Either a b
Right (Either (ByteOffset, FilePath) a -> Either FilePath a)
-> IO (Either (ByteOffset, FilePath) a) -> IO (Either FilePath a)
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` FilePath -> IO (Either (ByteOffset, FilePath) a)
forall a.
Binary a =>
FilePath -> IO (Either (ByteOffset, FilePath) a)
decodeFileOrFail FilePath
f

decodeOrFailIO :: Binary a => ByteString -> IO (Either String a)
decodeOrFailIO :: forall a. Binary a => ByteString -> IO (Either FilePath a)
decodeOrFailIO ByteString
bs =
    IO (Either FilePath a)
-> (ErrorCall -> IO (Either FilePath a)) -> IO (Either FilePath a)
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
catch (a -> IO a
forall a. a -> IO a
evaluate (ByteString -> a
forall a. Binary a => ByteString -> a
decode ByteString
bs) IO a -> (a -> IO (Either FilePath a)) -> IO (Either FilePath a)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Either FilePath a -> IO (Either FilePath a)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either FilePath a -> IO (Either FilePath a))
-> (a -> Either FilePath a) -> a -> IO (Either FilePath a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Either FilePath a
forall a b. b -> Either a b
Right) ErrorCall -> IO (Either FilePath a)
forall {m :: * -> *} {b}.
Monad m =>
ErrorCall -> m (Either FilePath b)
handler
  where
    handler :: ErrorCall -> m (Either FilePath b)
handler (ErrorCallWithLocation FilePath
str FilePath
_) = Either FilePath b -> m (Either FilePath b)
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either FilePath b -> m (Either FilePath b))
-> Either FilePath b -> m (Either FilePath b)
forall a b. (a -> b) -> a -> b
$ FilePath -> Either FilePath b
forall a b. a -> Either a b
Left FilePath
str