Cache data

This commit is contained in:
Frederik Hanghøj Iversen 2020-11-14 13:37:37 +01:00
parent 7f0b3a166a
commit f06db720ea

27
Main.hs
View file

@ -1,5 +1,6 @@
{-# language TypeApplications #-} {-# language TypeApplications #-}
{-# language DataKinds #-} {-# language DataKinds #-}
{-# language LambdaCase #-}
{-# options_ghc -Wall -Werror #-} {-# options_ghc -Wall -Werror #-}
module Main (main) where module Main (main) where
@ -13,6 +14,7 @@ import qualified Data.ByteString.Lazy as ByteString
import System.Directory import System.Directory
import System.FilePath import System.FilePath
import System.Environment import System.Environment
import Control.Monad (guard)
main :: IO () main :: IO ()
main = do main = do
@ -25,24 +27,29 @@ main = do
cachedLoad :: IO (Bloom Size String) cachedLoad :: IO (Bloom Size String)
cachedLoad = do cachedLoad = do
cache <- getCachePath cache <- getCachePath
cacheExists <- doesFileExist cache load cache >>= \case
if cacheExists Nothing -> do
then load cache b <- build
else do ByteString.writeFile cache $ Binary.encode b
b <- build pure b
ByteString.writeFile cache $ Binary.encode b Just a -> pure a
pure b
getCachePath :: IO FilePath getCachePath :: IO FilePath
getCachePath = (</> "bloom-spell/words.bin") <$> getEnv "XDG_DATA_HOME" getCachePath = (</> "bloom-spell/words.bin") <$> getEnv "XDG_DATA_HOME"
load :: FilePath -> IO (Bloom Size String) load :: FilePath -> IO (Maybe (Bloom Size String))
load p = Binary.decode @(Bloom Size _) <$> ByteString.readFile p load p = do
cacheExists <- doesFileExist p
guard cacheExists
s <- ByteString.readFile p
case Binary.decodeOrFail @(Bloom Size _) s of
Left{} -> pure Nothing
Right (_, _, a) -> pure $ pure a
build :: IO (Bloom Size String) build :: IO (Bloom Size String)
build = fromList @(Bloom Size _) . lines <$> readFile dict build = fromList @(Bloom Size _) . lines <$> readFile dict
type Size = 0xfffff type Size = 0xffff0
dict :: FilePath dict :: FilePath
dict = "/usr/share/dict/words" dict = "/usr/share/dict/words"