-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmost_recently_used.go
48 lines (40 loc) · 1.09 KB
/
most_recently_used.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
package cache_replacement_policies
import "time"
// The most recently used item will be evicted
type mruCachePolicy struct {
lastUsedAt map[string]int64
mostRecentlyUsedKey string
}
func NewMRUCachePolicy() CachePolicy {
return &mruCachePolicy{lastUsedAt: map[string]int64{}}
}
func (cp mruCachePolicy) PickKeyToEvict() string {
return cp.mostRecentlyUsedKey
}
func (cp *mruCachePolicy) OnKeySet(key string) {
if cp.mostRecentlyUsedKey == "" {
cp.mostRecentlyUsedKey = key
}
cp.lastUsedAt[key] = time.Now().Unix()
}
func (cp *mruCachePolicy) OnKeyGet(key string) {
if cp.mostRecentlyUsedKey == "" {
cp.mostRecentlyUsedKey = key
}
cp.lastUsedAt[key] = time.Now().Unix()
}
func (cp *mruCachePolicy) OnKeyEviction(key string) error {
delete(cp.lastUsedAt, key)
mostRecentlyUsed := struct {
key string
timestamp int64
}{timestamp: time.Now().Unix()}
for key, timestamp := range cp.lastUsedAt {
if timestamp > mostRecentlyUsed.timestamp {
mostRecentlyUsed.timestamp = timestamp
mostRecentlyUsed.key = key
}
}
cp.mostRecentlyUsedKey = mostRecentlyUsed.key
return nil
}