-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcache.go
80 lines (63 loc) · 1.23 KB
/
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
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
package cmap
import (
"sync"
)
type Cache interface {
Lock()
Unlock()
RLock()
RUnlock()
Set(string, interface{})
Get(string) (interface{}, bool)
Remove(string) (interface{}, bool)
Len() int
Keys() []string
}
// compile check
var (
_ Cache = (*defaultCache)(nil)
)
type defaultCache struct {
mutex *sync.RWMutex
values map[string]interface{}
}
func (c *defaultCache) Lock() {
c.mutex.Lock()
}
func (c *defaultCache) RLock() {
c.mutex.RLock()
}
func (c *defaultCache) Unlock() {
c.mutex.Unlock()
}
func (c *defaultCache) RUnlock() {
c.mutex.RUnlock()
}
func (c *defaultCache) Set(key string, value interface{}) {
c.values[key] = value
}
func (c *defaultCache) Get(key string) (interface{}, bool) {
v, ok := c.values[key]
return v, ok
}
func (c *defaultCache) Remove(key string) (interface{}, bool) {
v, ok := c.values[key]
delete(c.values, key)
return v, ok
}
func (c *defaultCache) Len() int {
return len(c.values)
}
func (c *defaultCache) Keys() []string {
keys := make([]string, 0, len(c.values))
for k, _ := range c.values {
keys = append(keys, k)
}
return keys
}
func newDefaultCache(size int) *defaultCache {
return &defaultCache{
mutex: new(sync.RWMutex),
values: make(map[string]interface{}, size),
}
}