forked from nutsdb/nutsdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lru.go
110 lines (88 loc) · 1.88 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
package nutsdb
import (
"container/list"
"sync"
)
// LRUCache is a least recently used (LRU) cache.
type LRUCache struct {
m map[interface{}]*list.Element
l *list.List
cap int
mu *sync.RWMutex
}
// New creates a new LRUCache with the specified capacity.
func NewLruCache(cap int) *LRUCache {
return &LRUCache{
m: make(map[interface{}]*list.Element),
l: list.New(),
cap: cap,
mu: &sync.RWMutex{},
}
}
// Add adds a new entry to the cache.
func (c *LRUCache) Add(key interface{}, value interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
if c.cap <= 0 {
return
}
if c.l.Len() >= c.cap {
c.removeOldest()
}
e := &LruEntry{
Key: key,
Value: value,
}
entry := c.l.PushFront(e)
c.m[key] = entry
}
// Get returns the entry associated with the given key, or nil if the key is not in the cache.
func (c *LRUCache) Get(key interface{}) interface{} {
c.mu.Lock()
defer c.mu.Unlock()
entry, ok := c.m[key]
if !ok {
return nil
}
c.l.MoveToFront(entry)
return entry.Value.(*LruEntry).Value
}
// Remove removes the entry associated with the given key from the cache.
func (c *LRUCache) Remove(key interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
entry, ok := c.m[key]
if !ok {
return
}
c.l.Remove(entry)
delete(c.m, key)
}
// Len returns the number of entries in the cache.
func (c *LRUCache) Len() int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.l.Len()
}
// Clear clears the cache.
func (c *LRUCache) Clear() {
c.mu.Lock()
defer c.mu.Unlock()
c.l.Init()
c.m = make(map[interface{}]*list.Element)
}
// removeOldest removes the oldest entry from the cache.
func (c *LRUCache) removeOldest() {
entry := c.l.Back()
if entry == nil {
return
}
key := entry.Value.(*LruEntry).Key
delete(c.m, key)
c.l.Remove(entry)
}
// LruEntry is a struct that represents an entry in the LRU cache.
type LruEntry struct {
Key interface{}
Value interface{}
}