...
1 package ldevents
2
3 import (
4 "container/list"
5 )
6
7 type lruCache struct {
8 values map[interface{}]*list.Element
9 lruList *list.List
10 capacity int
11 }
12
13 func newLruCache(capacity int) lruCache {
14 return lruCache{
15 values: make(map[interface{}]*list.Element),
16 lruList: list.New(),
17 capacity: capacity,
18 }
19 }
20
21 func (c *lruCache) clear() {
22 c.values = make(map[interface{}]*list.Element)
23 c.lruList.Init()
24 }
25
26
27
28 func (c *lruCache) add(value interface{}) bool {
29 if c.capacity == 0 {
30 return false
31 }
32 if e, ok := c.values[value]; ok {
33 c.lruList.MoveToFront(e)
34 return true
35 }
36 for len(c.values) >= c.capacity {
37 oldest := c.lruList.Back()
38 delete(c.values, oldest.Value)
39 c.lruList.Remove(oldest)
40 }
41 e := c.lruList.PushFront(value)
42 c.values[value] = e
43 return false
44 }
45
View as plain text