{-# language CPP #-}
module Nix.Cache where
import Nix.Prelude
import qualified Data.ByteString.Lazy as BSL
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 :: Path -> IO NExprLoc
readCache :: Path -> IO NExprLoc
readCache Path
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
BSL.readFile (Path -> FilePath
coerce Path
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 :: Path -> NExprLoc -> IO ()
writeCache :: Path -> NExprLoc -> IO ()
writeCache Path
path NExprLoc
expr =
#ifdef USE_COMPACT
C.writeCompact path =<< C.compact expr
#else
FilePath -> ByteString -> IO ()
BSL.writeFile (Path -> FilePath
coerce Path
path) (NExprLoc -> ByteString
forall a. Serialise a => a -> ByteString
S.serialise NExprLoc
expr)
#endif