-
Notifications
You must be signed in to change notification settings - Fork 24
/
lru.go
96 lines (82 loc) · 1.57 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
package lru
import (
"sync"
"time"
)
type Cache struct {
cache *cacheBase
lock sync.Mutex
noSync bool
}
func New(size int, options ...func(*Cache)) *Cache {
c := &Cache{cache: newCacheBase(size)}
for _, option := range options {
option(c)
}
return c
}
func WithExpiry(expiry time.Duration) func(c *Cache) {
return func(c *Cache) {
c.cache.Expiry = expiry
}
}
func WithEvictionCallback(onEvicted func(key string, value interface{})) func(c *Cache) {
return func(c *Cache) {
c.cache.OnEvicted = onEvicted
}
}
func WithoutSync() func(c *Cache) {
return func(c *Cache) {
c.noSync = true
}
}
func (c *Cache) Add(key string, value interface{}) {
if !c.noSync {
c.lock.Lock()
defer c.lock.Unlock()
}
c.cache.Add(key, value)
}
func (c *Cache) Get(key string) (value interface{}, ok bool) {
if !c.noSync {
c.lock.Lock()
defer c.lock.Unlock()
}
return c.cache.Get(key)
}
// Updates element's value without updating its "Least-Recently-Used" status
func (c *Cache) UpdateElement(key string, value interface{}) {
if !c.noSync {
c.lock.Lock()
defer c.lock.Unlock()
}
c.cache.UpdateElement(key, value)
}
func (c *Cache) Remove(key string) {
if !c.noSync {
c.lock.Lock()
defer c.lock.Unlock()
}
c.cache.Remove(key)
}
func (c *Cache) RemoveOldest() {
if !c.noSync {
c.lock.Lock()
defer c.lock.Unlock()
}
c.cache.RemoveOldest()
}
func (c *Cache) Len() int {
if !c.noSync {
c.lock.Lock()
defer c.lock.Unlock()
}
return c.cache.Len()
}
func (c *Cache) Clear() {
if !c.noSync {
c.lock.Lock()
defer c.lock.Unlock()
}
c.cache.Clear()
}