LRU Bounded Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
module DoubleMap ( Map
                 , empty
                 , insert
                 , insertUnsafe
                 , member
                 , notMember
                 , lookup
                 , delete
                 , deleteAB
                 , deleteFindMaxA
                 , deleteFindMaxB
                 , view
                 , update
                 , updateKeyA
                 , updateKeyB
                 , size
                 , null
                 , valid
                 ) where

import qualified Data.Map.Strict as M
import Prelude hiding (lookup, null)
import Control.Applicative hiding (empty)
import Control.Monad.Writer
import Text.Printf

-- Map sorted and indexed by two different types of key (assumes both keys are
-- unique for each element)

data Map ka kb v = Map !(M.Map ka (kb, v))
                       !(M.Map kb (ka, v))
                       deriving (Show)

empty :: Map ka kb v
empty = Map M.empty M.empty

member :: (Ord ka, Ord kb) => Either ka kb -> Map ka kb v -> Bool
member k (Map ma mb) = case k of Left  ka -> M.member ka ma
                                 Right kb -> M.member kb mb

notMember :: (Ord ka, Ord kb) => Either ka kb -> Map ka kb v -> Bool
notMember k m = not $ member k m

-- This will leak orphaned entries when we overwrite existing entries with different
-- combinations of A/B keys, error should be detected by 'valid'
insertUnsafe :: (Ord ka, Ord kb) => ka -> kb -> v -> Map ka kb v -> Map ka kb v
insertUnsafe ka kb v (Map ma mb) = v `seq` Map (M.insert ka (kb, v) ma)
                                               (M.insert kb (ka, v) mb)

-- Unlike the normal insert of a standard map, this will leave the map unchanged if
-- any of the keys are already present in either map
insert :: (Ord ka, Ord kb) => ka -> kb -> v -> Map ka kb v -> Map ka kb v
insert ka kb v m =
    if   notMember (Left ka) m && notMember (Right kb) m
    then insertUnsafe ka kb v m
    else m

lookup :: (Ord ka, Ord kb) => Either ka kb -> Map ka kb v -> Maybe (ka, kb, v)
lookup k (Map ma mb) = case k of Left  ka -> (\(kb, v) -> (ka, kb, v)) <$> M.lookup ka ma
                                 Right kb -> (\(ka, v) -> (ka, kb, v)) <$> M.lookup kb mb

delete :: (Ord ka, Ord kb) => Either ka kb -> Map ka kb v -> Map ka kb v
delete k m = case lookup k m of
    Just (ka, kb, _) -> deleteAB ka kb m
    Nothing          -> m

-- Delete function for the case where we know both keys
deleteAB :: (Ord ka, Ord kb) => ka -> kb -> Map ka kb v -> Map ka kb v
deleteAB ka kb (Map ma mb) = Map (M.delete ka ma) (M.delete kb mb)

-- Find the largest key of A/B, delete it from the map and return it
deleteFindMaxA :: (Ord ka, Ord kb) => Map ka kb v -> (Map ka kb v, Maybe (ka, kb, v))
deleteFindMaxA m@(Map ma mb) = if   null m
                               then (m, Nothing)
                               else let ((delKeyA, (delKeyB, delVal)), delMapA) =
                                            M.deleteFindMax ma
                                    in  ( Map delMapA (M.delete delKeyB mb)
                                        , Just (delKeyA, delKeyB, delVal)
                                        )
deleteFindMaxB :: (Ord ka, Ord kb) => Map ka kb v -> (Map ka kb v, Maybe (ka, kb, v))
deleteFindMaxB m@(Map ma mb) = if   null m
                               then (m, Nothing)
                               else let ((delKeyB, (delKeyA, delVal)), delMapB) =
                                            M.deleteFindMax mb
                                    in  ( Map (M.delete delKeyA ma) delMapB
                                        , Just (delKeyA, delKeyB, delVal)
                                        )

view :: Map ka kb v -> (M.Map ka (kb, v), M.Map kb (ka, v))
view (Map ma mb) = (ma, mb)

update :: (Ord ka, Ord kb) => Either ka kb -> v -> Map ka kb v -> Map ka kb v
update k v m@(Map ma mb) = case lookup k m of
    Just (ka, kb, _) -> Map (M.update (\_ -> Just (kb, v)) ka ma)
                            (M.update (\_ -> Just (ka, v)) kb mb)
    Nothing          -> m

updateKeyA :: (Ord ka, Ord kb) => ka -> ka -> Map ka kb v -> Map ka kb v
updateKeyA ka ka' m@(Map ma mb) = case lookup (Left ka) m of
    Just (_, kb, v) -> Map (M.insert ka' (kb, v) $ M.delete ka ma)
                           (M.update (\_ -> Just (ka', v)) kb mb)
    Nothing         -> m

updateKeyB :: (Ord ka, Ord kb) => kb -> kb -> Map ka kb v -> Map ka kb v
updateKeyB kb kb' m@(Map ma mb) = case lookup (Right kb) m of
    Just (ka, _, v) -> Map (M.update (\_ -> Just (kb', v)) ka ma)
                           (M.insert kb' (ka, v) $ M.delete kb mb)
    Nothing         -> m

size :: Map ka kb v -> Int
size (Map ma _) = M.size ma

null :: Map ka kb v -> Bool
null (Map ma _) = M.null ma

valid :: (Show ka, Show kb, Ord ka, Ord kb) => Map ka kb v -> Maybe String
valid (Map ma mb) = 
    let w = execWriter $ do
            unless (M.valid ma) $ tell "inner map A not valid\n"
            unless (M.valid mb) $ tell "inner map B not valid\n"
            when (M.size ma /= M.size mb) . tell $
                printf "A / B map size mismatch (%i / %i)\n" (M.size ma) (M.size mb)
            forM_ (M.toList ma) $ \(ka, (kb, _)) ->
                case M.lookup kb mb of Just (ka', _) ->
                                           when (ka /= ka') . tell $ printf
                                               "bad A <- B back reference ('%s' <- '%s')\n"
                                               (show ka )
                                               (show ka')
                                       Nothing ->
                                           tell $ printf
                                                      "bad A -> B reference ('%s' not in B)\n"
                                                      (show kb)
            forM_ (M.toList mb) $ \(kb, (ka, _)) ->
                case M.lookup ka ma of Just (kb', _) ->
                                          when (kb /= kb') . tell $ printf
                                               "bad B <- A back reference ('%s' <- '%s')\n"
                                               (show kb )
                                               (show kb')
                                       Nothing ->
                                           tell $ printf
                                                      "bad B -> A reference ('%s' not in A)\n"
                                                      (show ka)
    in  case w of [] -> Nothing
                  xs -> Just xs

module LRUBoundedMap ( Map
                     , empty
                     , insert
                     , insertUnsafe
                     , member
                     , notMember
                     , lookup
                     , delete
                     , deleteFindNewest
                     , update
                     , size
                     , view
                     , valid
                     ) where

import Prelude hiding (lookup)
import Data.Word
import Control.Applicative hiding (empty)
import Control.Monad.Writer
import Text.Printf

import qualified DoubleMap as DM
import qualified Data.Map.Strict as M

-- Bounded map maintaining a separate map for access history to drop the least
-- recently used element once the specified element limit is reached

data Map k v = Map !(DM.Map k Word64 v)
                   !Word64 -- We use a 'tick', which we keep incrementing, to keep track of how
                           -- old elements are relative to each other
                   !Int
                   deriving (Show)

empty :: Int -> Map k v
empty limit | limit >= 1 = Map DM.empty 0 limit
            | otherwise  = error "limit for LRUBoundedMap needs to be >= 1"

-- Insert a new element into the map, return the new map and the truncated
-- element (if over the limit)
insertInternal :: Ord k
               => (k -> Word64 -> v -> DM.Map k Word64 v -> DM.Map k Word64 v) -- DM insert
               -> k
               -> v
               -> Map k v
               -> (Map k v, Maybe (k, v))
insertInternal fins k v (Map m tick limit) =
    let inserted         = fins k tick v m
        (truncE, truncM) = if   DM.size inserted > limit
                           then let (lruKB, (lruKA, lruV)) = M.findMin (snd $ DM.view inserted)
                                in  (Just (lruKA, lruV), DM.deleteAB lruKA lruKB inserted)
                           else (Nothing, inserted)
    in  (Map truncM (tick + 1) limit, truncE)
insert :: Ord k => k -> v -> Map k v -> (Map k v, Maybe (k, v)) 
insert = insertInternal DM.insert
insertUnsafe :: Ord k => k -> v -> Map k v -> (Map k v, Maybe (k, v)) 
insertUnsafe = insertInternal DM.insertUnsafe

member :: Ord k => k -> Map k v -> Bool
member k (Map m _ _) = DM.member (Left k) m

notMember :: Ord k => k -> Map k v -> Bool
notMember k (Map m _ _) = DM.notMember (Left k) m

-- Lookup element, also update LRU time
lookup :: Ord k => k -> Map k v -> (Map k v, Maybe v)
lookup k bm@(Map m tick limit) = case DM.lookup (Left k) m of
    Just (_, kb, v) -> (Map (DM.updateKeyB kb tick m) (tick + 1) limit, Just v)
    Nothing         -> (bm, Nothing)

delete :: Ord k => k -> Map k v -> Map k v
delete k (Map m tick limit) = Map (DM.delete (Left k) m) tick limit

-- Remove and return most recently used element
deleteFindNewest :: Ord k => Map k v -> (Map k v, Maybe (k, v))
deleteFindNewest (Map m tick limit) = let (delMap, delVal) = DM.deleteFindMaxB m
                                      in  ( Map delMap tick limit
                                          , (\(ka, _, v) -> (ka, v)) <$> delVal
                                          )

-- Update value, don't touch LRU time
update :: Ord k => k -> v -> Map k v -> Map k v
update k v (Map m tick limit) = Map (DM.update (Left k) v m) tick limit

size :: Map k v -> (Int, Int)
size (Map m _ limit) = (DM.size m, limit)

view :: Map ka v -> (M.Map ka (Word64, v), M.Map Word64 (ka, v))
view (Map m _ _) = DM.view m

valid :: (Show k, Ord k) => Map k v -> Maybe String
valid (Map m tick limit) =
    let w = execWriter $ do
                when (limit < 1) $ tell "limit < 1\n"
                let (_, mb) = DM.view m
                forM_ (M.toList mb) $ \(kb, _) ->
                   when (kb >= tick) . tell $ printf "invalid tick in B map (%i > %i)\n" kb tick
                case DM.valid m of
                    Just xs -> tell xs
                    Nothing -> return ()
    in  case w of [] -> Nothing
                  xs -> Just xs

module LRUBoundedHashMap ( Map
                         , empty
                         , insert
                         , update
                         , member
                         , notMember
                         , lookup
                         , delete
                         , pop
                         , size
                         , view
                         , valid
                         ) where

import qualified Data.HashMap.Strict as HM
import Prelude hiding (lookup, last)
import Control.Monad.Writer
import Data.Hashable
import Data.Maybe

-- Map dropping least recently used item when growing over a specified limit
--
-- Implementation based on Data.Cache.LRU / lrucache, main difference is basing
-- the code on HashMap instead of Map and the insert function returning the
-- truncated element.
--
-- TODO: Map.size is O(1) while HashMap.size is O(n), maybe cache the size?

data Map k v = Map { mFirst :: !(Maybe k)
                   , mLast  :: !(Maybe k)
                   , mLimit :: !Int
                   , mMap   :: !(HM.HashMap k (Link k v))
                   }

data Link k v = Link { lPrev :: !(Maybe k)
                     , lNext :: !(Maybe k)
                     , lVal  :: v
                     }

empty :: Int -> Map k v
empty limit | limit >= 1 = Map { mFirst = Nothing
                               , mLast  = Nothing
                               , mLimit = limit
                               , mMap   = HM.empty
                               }
            | otherwise  = error "limit for LRUBoundedMap needs to be >= 1"

size :: Map k v -> (Int, Int)
size (Map _ _ limit content) = (HM.size content, limit)

member :: (Eq k, Hashable k) => k -> Map k v -> Bool
member k = HM.member k . mMap

notMember :: (Eq k, Hashable k) => k -> Map k v -> Bool
notMember k = not . HM.member k . mMap

view :: Map k v -> [(k, v)]
view = map (\(k, lnk) -> (k, lVal lnk)) . HM.toList . mMap

-- Lookup element, also update LRU
lookup :: (Eq k, Hashable k) => k -> Map k v -> (Map k v, Maybe v)
lookup k m =
    case HM.lookup k $ mMap m of
        Nothing  -> (m, Nothing)
        Just lnk -> (hit k m, Just $ lVal lnk)

-- Move the passed key to the front of the list (most recently used). Note that this
-- function assumes the key is actually in the map
{-# INLINE hit #-}
hit :: (Eq k, Hashable k) => k -> Map k v -> Map k v
hit k m@(Map first last limit content) =
    let Just firstK   = first
        Just lastK    = last
        Just lastLnk  = HM.lookup lastK content
        adjFront      = HM.adjust (\v -> v { lPrev = Just k }) firstK .
                        HM.adjust (\v -> v { lPrev = Nothing
                                           , lNext = first
                                           }
                                  ) k
        Just prevLast = lPrev lastLnk
        Just kL       = HM.lookup k content
        Just prevK    = lPrev kL
        Just nextK    = lNext kL
    in  case () of _ | k == firstK -> m -- Already at the front
                     | k == lastK  -> -- Move up last
                                      Map (Just k)
                                          (lPrev lastLnk)
                                          limit
                                          -- Second last now last, having no next
                                          . HM.adjust (\v -> v { lNext = Nothing })
                                                      prevLast
                                                      . adjFront $ content -- Update the new first
                     | otherwise   -> -- Move to front from the middle
                                      Map (Just k)
                                          last
                                          limit
                                          -- Remove key from the middle
                                          . HM.adjust (\v -> v { lNext = Just nextK }) prevK
                                          . HM.adjust (\v -> v { lPrev = Just prevK }) nextK
                                          . adjFront $ content -- Update the new first

delete :: (Eq k, Hashable k) => k -> Map k v -> (Map k v, Maybe v)
delete k m@(Map first last limit content) =
    let Just firstK    = first
        Just lastK     = last
        Just nextK     = lNext kL
        Just prevK     = lPrev kL
        (deleted, mKL) = -- TODO: Map had updateLookupWithKey, now we need 2x O(log n)
                         case HM.lookup k $ mMap m of
                             Just v  -> (HM.delete k content, Just v)
                             Nothing -> (content, Nothing)
        Just kL        = mKL
        mKLV           = Just $ lVal kL
    in  case () of _ | isNothing mKL        -> -- Key not in map
                                               (m, Nothing)
                     | HM.size content == 1 -> -- Just drop the remaining item
                                               ( Map Nothing Nothing limit deleted
                                               , mKLV
                                               )
                     | k == firstK          -> -- Remove first
                                               ( Map (lNext kL)
                                                      last
                                                      limit
                                                      . HM.adjust (\v -> v { lPrev = Nothing })
                                                                  nextK
                                                                  $ deleted
                                               , mKLV
                                               )
                     | k == lastK           -> -- Remove last
                                               ( Map first
                                                     (lPrev kL)
                                                     limit
                                                     . HM.adjust (\v -> v { lNext = Nothing })
                                                                 prevK
                                                                 $ deleted
                                               , mKLV
                                               )
                                               
                     | otherwise            -> -- Remove from the middle, first / last unchanged
                                               ( Map first
                                                     last
                                                     limit
                                                     . HM.adjust
                                                           (\v -> v { lNext = lNext kL }) prevK
                                                     . HM.adjust
                                                           (\v -> v { lPrev = lPrev kL }) nextK
                                                     $ deleted
                                               , mKLV
                                               )

-- Delete and return most recently used item
pop :: (Eq k, Hashable k) => Map k v -> (Map k v, Maybe (k, v))
pop m =
    if   (fst $ size m) == 0
    then (m, Nothing)
    else let (m', Just v) = delete first m
             Just first   = mFirst m
         in  (m', Just (first, v))

update :: (Eq k, Hashable k) => k -> v -> Map k v -> Map k v
update k v m =
    case insertInternal True k v m of
        (m', Nothing) -> m'
        _             -> error "LRUBoundedMap.update: insertInternal truncated with updateOnly"

-- Insert a new element into the map, return the new map and the truncated
-- element (if over the limit)
insert ::  (Eq k, Hashable k) => k -> v -> Map k v -> (Map k v, Maybe (k, v))
insert = insertInternal False

insertInternal :: (Eq k, Hashable k) => Bool -> k -> v -> Map k v -> (Map k v, Maybe (k, v))
insertInternal updateOnly k v m@(Map first last limit content) =
    let insertEmpty  = Map (Just k)
                           (Just k)
                           limit
                           (HM.insert k (Link Nothing Nothing v) content)
        insertUpdate = ( hit k $ m { mMap = HM.adjust (\v' -> v' { lVal = v }) k content }
                       , Nothing
                       )
        insertAdd    = if   HM.size content == limit
                       then addFull
                       else (add, Nothing)
        -- Add to the front
        inserted     = HM.insert k firstL
                           . HM.adjust (\v' -> v' { lPrev = Just k })
                                       firstK
                                       $ content
        add          = m { mFirst = Just k
                         , mMap   = inserted
                         }
        Just firstK  = first
        firstL       = Link Nothing (Just firstK) v
        -- Delete last
        addFull      = case delete lastK add of (m', Nothing) -> (m', Nothing         )
                                                (m', Just v') -> (m', Just (lastK, v'))
        Just lastK   = last
    -- We can have an empty or a non-empty list, the item can be already in the
    -- map or not, and we can be in insert or update mode, handle all cases below
    in  case () of _ | HM.null content && (not updateOnly) -> (insertEmpty, Nothing)
                     | HM.member k content                 -> insertUpdate
                     | not updateOnly                      -> insertAdd
                     | otherwise                           -> (m, Nothing)

valid :: (Eq k, Hashable k) => Map k v -> Maybe String
valid (Map first last limit content) =
    let w = execWriter $ do
                when (limit < 1)               $ tell "limit < 1\n"
                when (HM.size content > limit) $ tell "Size over the limit\n"
                when (length keysForwards /= HM.size content) $
                    tell "Map / linked-list size mismatch\n"
                when (keysForwards /= reverse keysBackwards) $
                    tell "Forwards and backwards traversal gives different lists\n"
                when (not $ all (`HM.member` content) keysForwards) $
                    tell "Not all keys from the linked-list present in the map\n"
        keysForwards           = traverse (lNext) first
        keysBackwards          = traverse (lPrev) last
        traverse _ Nothing     = []
        traverse step (Just k) = let Just nextK = HM.lookup k content
                                 in  k : (traverse (step) $ step nextK)
    in  case w of [] -> Nothing
                  xs -> Just xs

module Main where

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import Data.List
import Control.Monad

import qualified LRUBoundedMap as LRU
-- import qualified LRUBoundedHashMap as LRU

main :: IO ()
main = do
    let testData = map (\x -> (B8.pack . show $ x, x)) [1..1024]
        testMap  = foldl' (\r (k, v) -> fst $ LRU.insert k v r) (LRU.empty 1024) testData

    let tmp = foldl' (\r (k, v) -> fst . LRU.lookup k $ r) testMap .
              concat . replicate 2000 $ testData

    print $ LRU.valid tmp

    return ()