-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru.go
75 lines (65 loc) · 1.11 KB
/
lru.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
/**
* User: [email protected]
* Date: 2023/9/5
* Time: 12:13
*/
package vaedb
import (
"container/list"
"sync"
)
const DefaultSize = 1 << 16
type LruCache struct {
cache map[string]*list.Element
size int
list *list.List
mux sync.Mutex
}
type CacheItem struct {
key string
val []byte
}
func DefaultLruCache() *LruCache {
return NewLruCache(DefaultSize)
}
// size = 0 表示无限制
func NewLruCache(size int) *LruCache {
return &LruCache{
cache: make(map[string]*list.Element),
size: size,
list: list.New(),
}
}
func (l *LruCache) isFull() bool {
if l.size == 0 {
return false
}
return l.list.Len() >= l.size
}
func (l *LruCache) Set(key string, val []byte) {
l.mux.Lock()
defer l.mux.Unlock()
e, ok := l.cache[key]
if !ok {
if l.isFull() {
l.list.Remove(l.list.Back())
}
} else {
l.list.Remove(e)
}
newEle := l.list.PushFront(&CacheItem{
key: key,
val: val,
})
l.cache[key] = newEle
}
func (l *LruCache) Get(key string) *CacheItem {
l.mux.Lock()
defer l.mux.Unlock()
e, ok := l.cache[key]
if ok {
l.list.MoveToFront(e)
return e.Value.(*CacheItem)
}
return nil
}