-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcache.go
66 lines (53 loc) · 1.21 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
package logf
import (
"container/list"
)
// Cache is the simple implementation of LRU cache. The Cache is not
// goroutine safe.
type Cache struct {
m map[int32]*list.Element
l *list.List
limit int
}
// NewCache returns a new Cache with the given limit.
func NewCache(limit int) *Cache {
return &Cache{
m: make(map[int32]*list.Element, limit),
l: list.New(),
limit: limit,
}
}
// Set adds the given buffer with the given key to the cache or replaces
// the existing one with the same key.
func (c *Cache) Set(k int32, bytes []byte) {
e := c.l.PushFront(&element{k, bytes})
c.m[k] = e
if c.l.Len() > c.limit {
c.removeBack()
}
}
// Get returns cached buffer for the given key.
func (c *Cache) Get(k int32) ([]byte, bool) {
if e, ok := c.m[k]; ok {
c.l.MoveToFront(e)
return e.Value.(*element).bytes, true
}
return nil, false
}
// Len returns the count of cached buffers.
func (c *Cache) Len() int {
return len(c.m)
}
// Clean removes all buffers from the cache.
func (c *Cache) Clean() {
c.l = list.New()
c.m = make(map[int32]*list.Element, c.limit)
}
func (c *Cache) removeBack() {
e := c.l.Remove(c.l.Back())
delete(c.m, e.(*element).key)
}
type element struct {
key int32
bytes []byte
}