-
Notifications
You must be signed in to change notification settings - Fork 0
/
lru.go
136 lines (116 loc) · 2.4 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
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
package mcache
import (
"container/list"
"context"
"sync"
"time"
)
type LruCache struct {
clock Clock
items map[string]*list.Element
evictList *list.List
cap int
sync.Mutex
}
func (c *LruCache) Init(clock Clock, capacity int) {
c.clock = clock
c.items = make(map[string]*list.Element, capacity+1)
c.evictList = list.New()
c.cap = capacity
}
func (c *LruCache) Set(ctx context.Context, key string, val interface{}, ttl time.Duration) error {
c.Lock()
defer c.Unlock()
value := deref(val)
it, ok := c.items[key]
if ok {
item := it.Value.(*lfuItem)
item.value = value
if ttl > 0 {
item.expireAt = c.clock.Now().Add(ttl)
} else {
item.expireAt = c.clock.Now().Add(defaultExpiredAt)
}
c.evictList.MoveToFront(it)
} else {
c.evict(ctx, 1)
item := lruItem{
key: key,
value: value,
}
if ttl > 0 {
item.expireAt = c.clock.Now().Add(ttl)
} else {
item.expireAt = c.clock.Now().Add(defaultExpiredAt)
}
c.items[key] = c.evictList.PushFront(&item)
}
return nil
}
func (c *LruCache) Get(ctx context.Context, key string) (interface{}, error) {
c.Lock()
defer c.Unlock()
item, ok := c.items[key]
if ok {
it := item.Value.(*lruItem)
if !it.IsExpired(c.clock) {
c.evictList.MoveToFront(item)
return it.value, nil
}
c.removeElement(item)
}
return nil, KeyNotFoundError
}
func (c *LruCache) Exists(ctx context.Context, key string) bool {
c.Lock()
defer c.Unlock()
item, ok := c.items[key]
if !ok {
return false
}
if item.Value.(*lruItem).IsExpired(c.clock) {
c.removeElement(item)
return false
}
return true
}
func (c *LruCache) Remove(ctx context.Context, key string) bool {
c.Lock()
defer c.Unlock()
if ent, ok := c.items[key]; ok {
c.removeElement(ent)
return true
}
return false
}
func (c *LruCache) Evict(ctx context.Context, count int) {
c.Lock()
defer c.Unlock()
c.evict(ctx, count)
}
func (c *LruCache) evict(ctx context.Context, count int) {
if c.evictList.Len() < c.cap {
return
}
for i := 0; i < count; i++ {
ent := c.evictList.Back()
if ent == nil {
return
} else {
c.removeElement(ent)
}
}
}
func (c *LruCache) removeElement(e *list.Element) {
c.evictList.Remove(e)
entry := e.Value.(*lruItem)
delete(c.items, entry.key)
}
type lruItem struct {
key string
value interface{}
expireAt time.Time
}
func (it *lruItem) IsExpired(clock Clock) bool {
return it.expireAt.Before(clock.Now())
}