-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
87 lines (74 loc) · 1.44 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
package cache
type Data []byte
type Node struct {
key int
data *Data
next *Node
prev *Node
}
type NodeList struct {
header *Node
footer *Node
capacity int
}
func NewNodeList() *NodeList {
return &NodeList{}
}
func (c *NodeList) Get(key int) *Data {
if c.header == nil {
return nil
}
for node := c.header; node != nil; node = node.next {
if node.key == key {
return node.data
}
}
return nil
}
func (c *NodeList) Remove(key int) {
if c.header == nil {
return
}
for node := c.header; ; node = node.next {
if node.key == key {
prev := node.prev
next := node.next
prev.next = next
next.prev = prev
c.capacity--
return
}
}
}
func (c *NodeList) Put(key int, value *Data) {
node := Node{key: key, data: value}
c.capacity++
if c.header == nil {
c.header = &node
c.footer = &node
return
}
node.prev = c.footer
c.footer.next = &node
c.footer = &node
}
type Cache struct {
capacity int
pool []NodeList
}
func NewCache(capacity int) *Cache {
pool := make([]NodeList, capacity)
return &Cache{capacity: capacity, pool: pool}
}
func (c *Cache) id(key int) int {
return key % c.capacity
}
func (c *Cache) Get(key int) *Data {
return c.pool[c.id(key)].Get(key)
}
func (c *Cache) Remove(key int) {
c.pool[c.id(key)].Remove(key)
}
func (c *Cache) Put(key int, value *Data) {
c.pool[c.id(key)].Put(key, value)
}