Debian Codegraph @

src/Data/Cache/LRU/Internal.hs

raw
1 {-# OPTIONS_HADDOCK not-home #-}
2 {-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor,
3 DeriveFoldable, DeriveTraversable #-}
4
5 -- | This module provides access to all the internals use by the LRU
6 -- type. This can be used to create data structures that violate the
7 -- invariants the public interface maintains. Be careful when using
8 -- this module. The 'valid' function can be used to check if an LRU
9 -- structure satisfies the invariants the public interface maintains.
10 --
11 -- If this degree of control isn't needed, consider using
12 -- "Data.Cache.LRU" instead.
13 module Data.Cache.LRU.Internal where
14
15 import Control.Applicative (Applicative, pure, liftA2)
16 import Data.Traversable (Traversable(traverse), foldMapDefault)
17 import Data.Foldable (Foldable(foldMap), traverse_)
18
19 import Prelude hiding (last, lookup)
20
21 import Data.Map ( Map )
22 import qualified Data.Map as Map
23 #if MIN_VERSION_containers(0,5,0)
24 import qualified Data.Map.Strict as MapStrict
25 #endif
26
27 import Data.Data (Data)
28 import Data.Typeable (Typeable)
29
30 import Data.Functor.Contravariant (Contravariant((>$)))
31
32 -- | Stores the information that makes up an LRU cache
33 data LRU key val = LRU {
34 first :: !(Maybe key) -- ^ the key of the most recently accessed entry
35 , last :: !(Maybe key) -- ^ the key of the least recently accessed entry
36 , maxSize :: !(Maybe Integer) -- ^ the maximum size of the LRU cache
37 , content :: !(Map key (LinkedVal key val)) -- ^ the backing 'Map'
38 } deriving (Eq, Data, Typeable, Functor)
39
40 instance (Ord key) => Traversable (LRU key) where
41 traverse f l = fmap (fromList $ maxSize l) . go $ toList l
42 where
43 go [] = pure []
44 go (x:xs) = liftA2 (:) (g x) (go xs)
45 g (a, b) = fmap ((,) a) $ f b
46
47 instance (Ord key) => Foldable (LRU key) where
48 foldMap = foldMapDefault
49
50 instance (Ord key, Show key, Show val) => Show (LRU key val) where
51 show lru = "fromList " ++ show (toList lru)
52
53 -- | The values stored in the Map of the LRU cache. They embed a
54 -- doubly-linked list through the values of the 'Map'.
55 data LinkedVal key val = Link {
56 value :: val -- ^ The actual value
57 , prev :: !(Maybe key) -- ^ the key of the value before this one
58 , next :: !(Maybe key) -- ^ the key of the value after this one
59 } deriving (Eq, Data, Typeable, Functor, Foldable, Traversable)
60
61 -- | Make an LRU. If a size limit is specified, the LRU is guaranteed
62 -- to not grow above the specified number of entries.
63 newLRU :: (Ord key) => Maybe Integer -- ^ the optional maximum size of the LRU
64 -> LRU key val
65 newLRU (Just s) | s <= 0 = error "non-positive size LRU"
66 newLRU s = LRU Nothing Nothing s Map.empty
67
68 -- | Build a new LRU from the given maximum size and list of contents,
69 -- in order from most recently accessed to least recently accessed.
70 fromList :: Ord key => Maybe Integer -- ^ the optional maximum size of the LRU
71 -> [(key, val)] -> LRU key val
72 fromList s l = appendAll $ newLRU s
73 where appendAll = foldr ins id l
74 ins (k, v) = (insert k v .)
75
76 -- | Retrieve a list view of an LRU. The items are returned in
77 -- order from most recently accessed to least recently accessed.
78 toList :: Ord key => LRU key val -> [(key, val)]
79 toList lru = maybe [] (listLinks . content $ lru) $ first lru
80 where
81 listLinks m key =
82 let Just lv = Map.lookup key m
83 keyval = (key, value lv)
84 in case next lv of
85 Nothing -> [keyval]
86 Just nk -> keyval : listLinks m nk
87
88 -- | Traverse the (key, value) pairs of the LRU, in a read-only
89 -- way. This is a 'Fold' in the sense used by the
90 -- <https://hackage.haskell.org/package/lens lens package>. It must be
91 -- read-only because alterations could break the underlying 'Map'
92 -- structure.
93 pairs :: (Ord key, Applicative f, Contravariant f)
94 => ((key, val) -> f (key, val))
95 -> LRU key val -> f (LRU key val)
96 pairs f l = () >$ (traverse_ f $ toList l)
97
98 -- | Traverse the keys of the LRU, in a read-only
99 -- way. This is a 'Fold' in the sense used by the
100 -- <https://hackage.haskell.org/package/lens lens package>. It must be
101 -- read-only because alterations could break the underlying 'Map'
102 -- structure.
103 keys :: (Ord key, Applicative f, Contravariant f)
104 => (key -> f key)
105 -> LRU key val -> f (LRU key val)
106 keys f l = () >$ (traverse_ (f . fst) $ toList l)
107
108 -- | Add an item to an LRU. If the key was already present in the
109 -- LRU, the value is changed to the new value passed in. The
110 -- item added is marked as the most recently accessed item in the
111 -- LRU returned.
112 --
113 -- If this would cause the LRU to exceed its maximum size, the
114 -- least recently used item is dropped from the cache.
115 insert :: Ord key => key -> val -> LRU key val -> LRU key val
116 insert key val lru = fst (insertInforming key val lru)
117
118 -- | Same as 'insert', but also returns element which was dropped from
119 -- cache, if any.
120 insertInforming :: Ord key => key -> val -> LRU key val
121 -> (LRU key val, Maybe (key, val))
122 insertInforming key val lru = maybe emptyCase nonEmptyCase $ first lru
123 where
124 contents = content lru
125 full = maybe False (fromIntegral (Map.size contents) ==) $ maxSize lru
126 present = key `Map.member` contents
127
128 -- this is the case for adding to an empty LRU Cache
129 emptyCase = (LRU fl fl (maxSize lru) m', Nothing)
130 where
131 fl = Just key
132 lv = Link val Nothing Nothing
133 m' = Map.insert key lv contents
134
135 nonEmptyCase firstKey = if present then (hitSet, Nothing)
136 else add firstKey
137
138 -- this updates the value stored with the key, then marks it as
139 -- the most recently accessed
140 hitSet = hit' key lru'
141 where lru' = lru { content = contents' }
142 contents' = adjust' (\v -> v {value = val}) key contents
143
144 -- create a new LRU with a new first item, and
145 -- conditionally dropping the last item
146 add firstKey = if full then (lru'', Just (lastKey, value lastLV))
147 else (lru', Nothing)
148 where
149 -- add a new first item
150 firstLV' = Link val Nothing $ Just firstKey
151 contents' = Map.insert key firstLV' .
152 adjust' (\v -> v { prev = Just key }) firstKey $
153 contents
154 lru' = lru { first = Just key, content = contents' }
155
156 -- remove the last item
157 Just lastKey = last lru'
158 Just lastLV = Map.lookup lastKey contents'
159 contents'' = Map.delete lastKey contents'
160 lru'' = delete' lastKey lru' contents'' lastLV
161
162 -- | Look up an item in an LRU. If it was present, it is marked as
163 -- the most recently accesed in the returned LRU.
164 lookup :: Ord key => key -> LRU key val -> (LRU key val, Maybe val)
165 lookup key lru = case Map.lookup key $ content lru of
166 Nothing -> (lru, Nothing)
167 Just lv -> (hit' key lru, Just . value $ lv)
168
169 -- | Remove an item from an LRU. Returns the new LRU, and the value
170 -- removed if the key was present.
171 delete :: Ord key => key -> LRU key val -> (LRU key val, Maybe val)
172 delete key lru = maybe (lru, Nothing) delete'' mLV
173 where
174 delete'' lv = (delete' key lru cont' lv, Just $ value lv)
175 (mLV, cont') = Map.updateLookupWithKey (\_ _ -> Nothing) key $ content lru
176
177 -- | Removes the least-recently accessed element from the LRU.
178 -- Returns the new LRU, and the key and value from the least-recently
179 -- used element, if there was one.
180 pop :: Ord key => LRU key val -> (LRU key val, Maybe (key, val))
181 pop lru = if size lru == 0 then (lru, Nothing) else (lru', Just pair)
182 where
183 Just lastKey = last lru
184 (lru', Just lastVal) = delete lastKey lru
185 pair = (lastKey, lastVal)
186
187 -- | Returns the number of elements the LRU currently contains.
188 size :: LRU key val -> Int
189 size = Map.size . content
190
191 -- | Internal function. The key passed in must be present in the
192 -- LRU. Moves the item associated with that key to the most
193 -- recently accessed position.
194 hit' :: Ord key => key -> LRU key val -> LRU key val
195 hit' key lru = if key == firstKey then lru else notFirst
196 where Just firstKey = first lru
197 Just lastKey = last lru
198 Just lastLV = Map.lookup lastKey conts
199 conts = content lru
200
201 -- key wasn't already the head of the list. Some alteration
202 -- will be needed
203 notFirst = if key == lastKey then replaceLast else replaceMiddle
204
205 adjFront = adjust' (\v -> v { prev = Just key}) firstKey .
206 adjust' (\v -> v { prev = Nothing
207 , next = first lru }) key
208
209 -- key was the last entry in the list
210 replaceLast = lru { first = Just key
211 , last = prev lastLV
212 , content = cLast
213 }
214 Just pKey = prev lastLV
215 cLast = adjust' (\v -> v { next = Nothing }) pKey . adjFront $ conts
216
217 -- the key wasn't the first or last key
218 replaceMiddle = lru { first = Just key
219 , content = cMid
220 }
221 Just keyLV = Map.lookup key conts
222 Just prevKey = prev keyLV
223 Just nextKey = next keyLV
224 cMid = adjust' (\v -> v { next = Just nextKey }) prevKey .
225 adjust' (\v -> v { prev = Just prevKey }) nextKey .
226 adjFront $ conts
227
228 -- | An internal function used by 'insert' (when the cache is full)
229 -- and 'delete'. This function has strict requirements on its
230 -- arguments in order to work properly.
231 --
232 -- As this is intended to be an internal function, the arguments were
233 -- chosen to avoid repeated computation, rather than for simplicity of
234 -- calling this function.
235 delete' :: Ord key => key -- ^ The key must be present in the provided 'LRU'
236 -> LRU key val -- ^ This is the 'LRU' to modify
237 -> Map key (LinkedVal key val) -- ^ this is the 'Map' from the
238 -- previous argument, but with
239 -- the key already removed from
240 -- it. This isn't consistent
241 -- yet, as it still might
242 -- contain LinkedVals with
243 -- pointers to the removed key.
244 -> LinkedVal key val -- ^ This is the 'LinkedVal' that
245 -- corresponds to the key in the passed
246 -- in LRU. It is absent from the passed
247 -- in map.
248 -> LRU key val
249 delete' key lru cont' lv = if Map.null cont' then deleteOnly else deleteOne
250 where
251 -- delete the only item in the cache
252 deleteOnly = lru { first = Nothing
253 , last = Nothing
254 , content = cont'
255 }
256
257 -- delete an item that isn't the only item
258 Just firstKey = first lru
259 deleteOne = if firstKey == key then deleteFirst else deleteNotFirst
260
261 -- delete the first item
262 deleteFirst = lru { first = next lv
263 , content = contFirst
264 }
265 Just nKey = next lv
266 contFirst = adjust' (\v -> v { prev = Nothing }) nKey cont'
267
268 -- delete an item other than the first
269 Just lastKey = last lru
270 deleteNotFirst = if lastKey == key then deleteLast else deleteMid
271
272 -- delete the last item
273 deleteLast = lru { last = prev lv
274 , content = contLast
275 }
276 Just pKey = prev lv
277 contLast = adjust' (\v -> v { next = Nothing}) pKey cont'
278
279 -- delete an item in the middle
280 deleteMid = lru { content = contMid }
281 contMid = adjust' (\v -> v { next = next lv }) pKey .
282 adjust' (\v -> v { prev = prev lv }) nKey $
283 cont'
284
285 -- | Internal function. This is very similar to 'Map.adjust', with
286 -- two major differences. First, it's strict in the application of
287 -- the function, which is a huge win when working with this structure.
288 --
289 -- Second, it requires that the key be present in order to work. If
290 -- the key isn't present, 'undefined' will be inserted into the 'Map',
291 -- which will cause problems later.
292 adjust' :: Ord k => (a -> a) -> k -> Map k a -> Map k a
293 #if MIN_VERSION_containers(0,5,0)
294 adjust' = MapStrict.adjust
295 #else
296 adjust' f k m = Map.insertWith' (\_ o -> f o) k (error "adjust' used wrongly") m
297 #endif
298
299 -- | Internal function. This checks the four structural invariants
300 -- of the LRU cache structure:
301 --
302 -- 1. The cache's size does not exceed the specified max size.
303 --
304 -- 2. The linked list through the nodes is consistent in both directions.
305 --
306 -- 3. The linked list contains the same number of nodes as the cache.
307 --
308 -- 4. Every key in the linked list is in the 'Map'.
309 valid :: Ord key => LRU key val -> Bool
310 valid lru = maybe True (fromIntegral (size lru) <=) (maxSize lru) &&
311 reverse orderedKeys == reverseKeys &&
312 size lru == length orderedKeys &&
313 all (`Map.member` contents) orderedKeys
314 where contents = content lru
315 orderedKeys = walk next . first $ lru
316 walk _ Nothing = []
317 walk f (Just k) = let Just k' = Map.lookup k contents
318 in k : (walk f . f $ k')
319 reverseKeys = walk prev . last $ lru