forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
53 lines (46 loc) · 993 Bytes
/
cache.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
package server
import "sync"
type cache struct {
data map[string]interface{}
keylist []string
idx int
maxSize int
mtx sync.RWMutex
}
func newCache(maxSize int) *cache {
return &cache{
data: map[string]interface{}{},
keylist: []string{},
maxSize: maxSize,
}
}
func (c *cache) Get(k string) (interface{}, bool) {
c.mtx.RLock()
v, ok := c.data[k]
c.mtx.RUnlock()
return v, ok
}
func (c *cache) Insert(k string, v interface{}) {
// Short path if its already in the cache
_, ok := c.Get(k)
if ok {
return
}
// Slow path, grab the write lock and insert
c.mtx.Lock()
_, ok = c.data[k]
if !ok {
c.data[k] = v
if len(c.keylist) < c.maxSize {
// Haven't reached max size yet, keep adding keys.
c.keylist = append(c.keylist, k)
} else {
// Start recycling spots in the key list and
// dropping cache entries for them.
delete(c.data, c.keylist[c.idx])
c.keylist[c.idx] = k
c.idx = (c.idx + 1) % c.maxSize
}
}
c.mtx.Unlock()
}