diff options
author | evuez <julien@mulga.net> | 2024-04-01 15:17:30 +0200 |
---|---|---|
committer | evuez <julien@mulga.net> | 2024-04-03 22:45:36 +0200 |
commit | 985974c264804ff788b3b5242fef707d4b7fa9a6 (patch) | |
tree | d80f83db178c3fd1b83b3b749793d47236dde35d /src/Cache.hs | |
download | webmaild-985974c264804ff788b3b5242fef707d4b7fa9a6.tar.gz |
Initial commit
Diffstat (limited to 'src/Cache.hs')
-rw-r--r-- | src/Cache.hs | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/Cache.hs b/src/Cache.hs new file mode 100644 index 0000000..b009770 --- /dev/null +++ b/src/Cache.hs @@ -0,0 +1,46 @@ +module Cache (newInMemory, start, CacheM, getInbox) where + +import Control.Concurrent.STM + ( TVar + , atomically + , newTVarIO + , readTVar + , readTVarIO + , writeTVar + ) +import Intro +import qualified Mail as M +import qualified Queue as Q + +data Cache = Cache + { count :: Int + , inbox :: [M.Mail] + } + +type CacheM = TVar Cache + +newInMemory :: IO CacheM +newInMemory = newTVarIO newCache + +start :: Q.QueueM M.Mail -> CacheM -> IO () +start queue cache = go + where + go :: IO () + go = do + mail <- Q.pull queue + updateCache cache (`addMail` mail) + go + +getInbox :: CacheM -> IO [M.Mail] +getInbox c = inbox <$> readTVarIO c + +newCache :: Cache +newCache = Cache 0 [] + +addMail :: Cache -> M.Mail -> Cache +addMail cache mail = cache{count = count cache + 1, inbox = mail : inbox cache} + +updateCache :: CacheM -> (Cache -> Cache) -> IO () +updateCache c f = atomically $ do + cache <- readTVar c + writeTVar c (f cache) |