{-# LANGUAGE CPP #-}
module Nix.Cache where
import qualified Data.ByteString.Lazy as BS
import Nix.Expr.Types.Annotated
#if defined (__linux__)
#define USE_COMPACT 1
#endif
#ifdef USE_COMPACT
import qualified Data.Compact as C
import qualified Data.Compact.Serialize as C
#endif
import qualified Codec.Serialise as S
readCache :: FilePath -> IO NExprLoc
readCache :: FilePath -> IO NExprLoc
readCache FilePath
path = do
#if USE_COMPACT
eres <- C.unsafeReadCompact path
either
(\ err -> fail $ "Error reading cache file: " <> err)
(\ expr -> pure $ C.getCompact expr)
eres
#else
Either DeserialiseFailure NExprLoc
eres <- ByteString -> Either DeserialiseFailure NExprLoc
forall a. Serialise a => ByteString -> Either DeserialiseFailure a
S.deserialiseOrFail (ByteString -> Either DeserialiseFailure NExprLoc)
-> IO ByteString -> IO (Either DeserialiseFailure NExprLoc)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FilePath -> IO ByteString
BS.readFile FilePath
path
(DeserialiseFailure -> IO NExprLoc)
-> (NExprLoc -> IO NExprLoc)
-> Either DeserialiseFailure NExprLoc
-> IO NExprLoc
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either
(\ DeserialiseFailure
err -> FilePath -> IO NExprLoc
forall (m :: * -> *) a. MonadFail m => FilePath -> m a
fail (FilePath -> IO NExprLoc) -> FilePath -> IO NExprLoc
forall a b. (a -> b) -> a -> b
$ FilePath
"Error reading cache file: " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> DeserialiseFailure -> FilePath
forall b a. (Show a, IsString b) => a -> b
show DeserialiseFailure
err)
NExprLoc -> IO NExprLoc
forall (f :: * -> *) a. Applicative f => a -> f a
pure
Either DeserialiseFailure NExprLoc
eres
#endif
writeCache :: FilePath -> NExprLoc -> IO ()
writeCache :: FilePath -> NExprLoc -> IO ()
writeCache FilePath
path NExprLoc
expr =
#ifdef USE_COMPACT
C.writeCompact path =<< C.compact expr
#else
FilePath -> ByteString -> IO ()
BS.writeFile FilePath
path (NExprLoc -> ByteString
forall a. Serialise a => a -> ByteString
S.serialise NExprLoc
expr)
#endif