-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathlru_cache.go
44 lines (39 loc) · 914 Bytes
/
lru_cache.go
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
package ldclient
import (
"container/list"
)
type lruCache struct {
values map[interface{}]*list.Element
lruList *list.List
capacity int
}
func newLruCache(capacity int) lruCache {
return lruCache{
values: make(map[interface{}]*list.Element),
lruList: list.New(),
capacity: capacity,
}
}
func (c *lruCache) clear() {
c.values = make(map[interface{}]*list.Element)
c.lruList.Init()
}
// Stores a value in the cache, returning true (and marking it as recently used) if it was
// already there, or false if it was newly added.
func (c *lruCache) add(value interface{}) bool {
if c.capacity == 0 {
return false
}
if e, ok := c.values[value]; ok {
c.lruList.MoveToFront(e)
return true
}
for len(c.values) >= c.capacity {
oldest := c.lruList.Back()
delete(c.values, oldest.Value)
c.lruList.Remove(oldest)
}
e := c.lruList.PushFront(value)
c.values[value] = e
return false
}