From f06db720ea2df4336b78a7041ce03213f9b5562f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederik=20Hangh=C3=B8j=20Iversen?= Date: Sat, 14 Nov 2020 13:37:37 +0100 Subject: [PATCH] Cache data --- Main.hs | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/Main.hs b/Main.hs index 5b97373..8abbf91 100644 --- a/Main.hs +++ b/Main.hs @@ -1,5 +1,6 @@ {-# language TypeApplications #-} {-# language DataKinds #-} +{-# language LambdaCase #-} {-# options_ghc -Wall -Werror #-} module Main (main) where @@ -13,6 +14,7 @@ import qualified Data.ByteString.Lazy as ByteString import System.Directory import System.FilePath import System.Environment +import Control.Monad (guard) main :: IO () main = do @@ -25,24 +27,29 @@ main = do cachedLoad :: IO (Bloom Size String) cachedLoad = do cache <- getCachePath - cacheExists <- doesFileExist cache - if cacheExists - then load cache - else do - b <- build - ByteString.writeFile cache $ Binary.encode b - pure b + load cache >>= \case + Nothing -> do + b <- build + ByteString.writeFile cache $ Binary.encode b + pure b + Just a -> pure a getCachePath :: IO FilePath getCachePath = ( "bloom-spell/words.bin") <$> getEnv "XDG_DATA_HOME" -load :: FilePath -> IO (Bloom Size String) -load p = Binary.decode @(Bloom Size _) <$> ByteString.readFile p +load :: FilePath -> IO (Maybe (Bloom Size String)) +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 = fromList @(Bloom Size _) . lines <$> readFile dict -type Size = 0xfffff +type Size = 0xffff0 dict :: FilePath dict = "/usr/share/dict/words"