packages feed

cache 0.1.1.2 → 0.1.2.0

raw patch · 3 files changed

+25/−1 lines, 3 filesPVP ok

version bump matches the API change (PVP)

API changes (from Hackage documentation)

+ Data.Cache: fetchWithCache :: (Eq k, Hashable k) => Cache k v -> k -> (k -> IO v) -> IO v

Files

cache.cabal view
@@ -1,5 +1,5 @@ name:           cache-version:        0.1.1.2+version:        0.1.2.0 synopsis:       An in-memory key/value store with expiration support homepage:       https://github.com/hverr/haskell-cache#readme license:        BSD3
src/Data/Cache.hs view
@@ -42,6 +42,8 @@   , deleteSTM   , purgeExpired   , purgeExpiredSTM+    -- ** Combined actions+  , fetchWithCache      -- * Cache information   , size@@ -198,6 +200,18 @@ -- the cache. insert :: (Eq k, Hashable k) => Cache k v -> k -> v -> IO () insert c = insert' c (defaultExpiration c)++-- | Get a value from cache. If not available from cache, use the provided action and update the cache.+-- Note that the cache check and conditional execution of the action is not one atomic action.+fetchWithCache :: (Eq k, Hashable k) => Cache k v -> k -> (k -> IO v) -> IO v+fetchWithCache c k f = do+  mv <- lookup c k+  case mv of+    Just v -> return v+    Nothing -> do+       v <- f k+       insert c k v+       return v  -- | STM variant of 'keys'. keysSTM :: Cache k v -> STM [k]
test/Data/CacheSpec.hs view
@@ -67,6 +67,13 @@         liftIO (size c) >>= (`shouldBe` 4)         _ <- liftIO $ purgeExpired c         liftIO (size c) >>= (`shouldBe` 3)+    it "should work with actions" $ do+        c <- liftIO $ defCache Nothing+        _ <- liftIO $ expire defExpiration+        liftIO (fetchWithCache c (fst ok) (const $ return 10))               >>= (`shouldBe` (snd ok))+        liftIO (fetchWithCache c (fst expired) (const $ return 10))          >>= (`shouldBe` 10)+        liftIO (fetchWithCache c (fst action) (const $ return (snd action))) >>= (`shouldBe` (snd action))+        liftIO (lookup' c (fst action) )                                     >>= (`shouldBe` Just (snd action))  defExpiration :: TimeSpec defExpiration = 1000000@@ -91,6 +98,9 @@  ok :: (String, Int) ok = ("ok", 3)++action :: (String, Int)+action = ("action", 6)  defCache :: Maybe TimeSpec -> IO (Cache String Int) defCache t = do