-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
96 lines (80 loc) · 1.33 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package golib
import (
"container/list"
"sync"
)
// Cache ...
type Cache interface {
Get(int64) interface{}
Put(int64, interface{}) bool
Reset()
}
// Options ...
type options struct {
size int
}
// cache ...
type cache struct {
options *options
mutex sync.Mutex
list *list.List
items map[int64]*list.Element
}
// record ...
type record struct {
key int64
value interface{}
}
// NewCache ...
func NewCache(size int) Cache {
c := &cache{
options: &options{
size: size,
},
}
c.Reset()
return c
}
// Get ...
func (c *cache) Get(key int64) interface{} {
c.mutex.Lock()
defer c.mutex.Unlock()
if e, ok := c.items[key]; ok {
c.list.MoveToFront(e)
return e.Value.(record).value
}
return nil
}
// Put ...
func (c *cache) Put(key int64, value interface{}) bool {
if value == nil {
return false
}
c.mutex.Lock()
defer c.mutex.Unlock()
if e, ok := c.items[key]; ok {
c.list.MoveToFront(e)
return true
}
item := c.list.PushFront(record{
key: key,
value: value,
})
c.items[key] = item
if c.list.Len() > c.options.size {
e := c.list.Back()
if e != nil {
c.list.Remove(e)
k := e.Value.(record).key
delete(c.items, k)
}
}
return true
}
// Reset ...
func (c *cache) Reset() {
c.mutex.Lock()
defer c.mutex.Unlock()
c.items = make(map[int64]*list.Element)
c.list = list.New()
}