-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
88 lines (80 loc) · 1.2 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
package bezier
import (
"fmt"
)
type Cache struct {
Cap int
Size int
head *node
data []*node
}
type node struct {
Value KV
Key string
next *node
}
type KV interface {
Key() string
}
func NewCache(capacity int) *Cache {
ca := &Cache{
Cap: capacity,
Size: -1,
head: nil,
data: make([]*node, capacity),
}
for i := 0; i < capacity; i++ {
ca.data[i] = &node{}
}
return ca
}
func (c *Cache) Put(i KV) {
c.Size++
if c.head == nil {
c.head = c.data[0]
c.head.Value = i
c.head.Key = i.Key()
c.head.next = nil
return
}
loc := (c.Size) % c.Cap
cur := c.head
newHead := c.data[loc]
newHead.Value = i
newHead.Key = i.Key()
newHead.next = cur
c.head = newHead
}
func (c *Cache) Get(key string) KV {
cur := c.head
start := cur
for cur != nil {
if cur.Key == key {
return cur.Value
}
cur = cur.next
if start == cur {
break
}
}
return nil
}
func (c *Cache) String() string {
ret := ""
size := c.Size + 1
if size >= c.Cap {
size = c.Cap
}
ret += fmt.Sprintf("cap:%d, size:%d\n", c.Cap, size)
cur := c.head
start := cur
for cur != nil {
ret += fmt.Sprintf("%+v -> ", cur.Key)
cur = cur.next
if start == cur {
break
}
}
ret += "\n"
return ret
}