forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lru_cache.go
136 lines (108 loc) · 2.33 KB
/
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
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
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package cache
import (
"container/list"
"sync"
)
const minCacheSize = 32
var _ Cacher = &LRU{}
type entry struct {
Key interface{}
Value interface{}
}
// LRU is a key value store with bounded size. If the size is attempted to be
// exceeded, then an element is removed from the cache before the insertion is
// done, based on evicting the least recently used value.
type LRU struct {
lock sync.Mutex
entryMap map[interface{}]*list.Element
entryList *list.List
Size int
}
func (c *LRU) Put(key, value interface{}) {
c.lock.Lock()
defer c.lock.Unlock()
c.put(key, value)
}
func (c *LRU) Get(key interface{}) (interface{}, bool) {
c.lock.Lock()
defer c.lock.Unlock()
return c.get(key)
}
func (c *LRU) Evict(key interface{}) {
c.lock.Lock()
defer c.lock.Unlock()
c.evict(key)
}
func (c *LRU) Flush() {
c.lock.Lock()
defer c.lock.Unlock()
c.flush()
}
func (c *LRU) init() {
if c.entryMap == nil {
c.entryMap = make(map[interface{}]*list.Element, minCacheSize)
}
if c.entryList == nil {
c.entryList = list.New()
}
if c.Size <= 0 {
c.Size = 1
}
}
func (c *LRU) resize() {
for c.entryList.Len() > c.Size {
e := c.entryList.Front()
c.entryList.Remove(e)
val := e.Value.(*entry)
delete(c.entryMap, val.Key)
}
}
func (c *LRU) put(key, value interface{}) {
c.init()
c.resize()
if e, ok := c.entryMap[key]; !ok {
if c.entryList.Len() >= c.Size {
e = c.entryList.Front()
c.entryList.MoveToBack(e)
val := e.Value.(*entry)
delete(c.entryMap, val.Key)
val.Key = key
val.Value = value
} else {
e = c.entryList.PushBack(&entry{
Key: key,
Value: value,
})
}
c.entryMap[key] = e
} else {
c.entryList.MoveToBack(e)
val := e.Value.(*entry)
val.Value = value
}
}
func (c *LRU) get(key interface{}) (interface{}, bool) {
c.init()
c.resize()
if e, ok := c.entryMap[key]; ok {
c.entryList.MoveToBack(e)
val := e.Value.(*entry)
return val.Value, true
}
return struct{}{}, false
}
func (c *LRU) evict(key interface{}) {
c.init()
c.resize()
if e, ok := c.entryMap[key]; ok {
c.entryList.Remove(e)
delete(c.entryMap, key)
}
}
func (c *LRU) flush() {
c.init()
c.entryMap = make(map[interface{}]*list.Element, minCacheSize)
c.entryList = list.New()
}