| 1 |
-- from https://jaspervdj.be/posts/2015-02-24-lru-cache.html |
| 2 |
module Network.Wai.Middleware.Push.Referer.LRU ( |
| 3 |
Cache(..) |
| 4 |
, Priority |
| 5 |
, empty |
| 6 |
, insert |
| 7 |
, lookup |
| 8 |
) where |
| 9 |
|
| 10 |
import Data.OrdPSQ (OrdPSQ) |
| 11 |
import qualified Data.OrdPSQ as PSQ |
| 12 |
import Data.Int (Int64) |
| 13 |
import Prelude hiding (lookup) |
| 14 |
|
| 15 |
import Network.Wai.Middleware.Push.Referer.Multi (Multi) |
| 16 |
import qualified Network.Wai.Middleware.Push.Referer.Multi as M |
| 17 |
|
| 18 |
type Priority = Int64 |
| 19 |
|
| 20 |
data Cache k v = Cache { |
| 21 |
cCapacity :: Int -- ^ The maximum number of elements in the queue |
| 22 |
, cSize :: Int -- ^ The current number of elements in the queue |
| 23 |
, cValLimit :: Int |
| 24 |
, cTick :: Priority -- ^ The next logical time |
| 25 |
, cQueue :: OrdPSQ k Priority (Multi v) |
| 26 |
} deriving (Eq, Show) |
| 27 |
|
| 28 |
empty :: Int -> Int -> Cache k v |
| 29 |
empty capacity valLimit |
| 30 |
| capacity < 1 = error "Cache.empty: capacity < 1" |
| 31 |
| otherwise = Cache { |
| 32 |
cCapacity = capacity |
| 33 |
, cSize = 0 |
| 34 |
, cValLimit = valLimit |
| 35 |
, cTick = 0 |
| 36 |
, cQueue = PSQ.empty |
| 37 |
} |
| 38 |
|
| 39 |
trim :: Ord k => Cache k v -> Cache k v |
| 40 |
trim c |
| 41 |
| cTick c == maxBound = empty (cCapacity c) (cValLimit c) |
| 42 |
| cSize c > cCapacity c = c { |
| 43 |
cSize = cSize c - 1 |
| 44 |
, cQueue = PSQ.deleteMin (cQueue c) |
| 45 |
} |
| 46 |
| otherwise = c |
| 47 |
|
| 48 |
insert :: (Ord k, Ord v) => k -> v -> Cache k v -> Cache k v |
| 49 |
insert k v c = case PSQ.alter lookupAndBump k (cQueue c) of |
| 50 |
(True, q) -> trim $ c { cTick = cTick c + 1, cQueue = q, cSize = cSize c + 1} |
| 51 |
(False, q) -> trim $ c { cTick = cTick c + 1, cQueue = q } |
| 52 |
where |
| 53 |
lookupAndBump Nothing = (True, Just (cTick c, M.singleton (cValLimit c) v)) |
| 54 |
lookupAndBump (Just (_, x)) = (False, Just (cTick c, M.insert v x)) |
| 55 |
|
| 56 |
lookup :: Ord k => k -> Cache k v -> (Cache k v, [v]) |
| 57 |
lookup k c = case PSQ.alter lookupAndBump k (cQueue c) of |
| 58 |
(Nothing, _) -> (c, []) |
| 59 |
(Just x, q) -> let c' = trim $ c { cTick = cTick c + 1, cQueue = q } |
| 60 |
xs = M.list x |
| 61 |
in (c', xs) |
| 62 |
where |
| 63 |
lookupAndBump Nothing = (Nothing, Nothing) |
| 64 |
lookupAndBump (Just (_, x)) = (Just x, Just (cTick c, x)) |