-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstorage.go
96 lines (82 loc) · 1.36 KB
/
storage.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 main
type node struct {
prev *node
key string
data *paste
next *node
}
type LinkedHashMap struct {
table map[string]*node
head *node
tail *node
cap int
}
func NewLHM(length int) *LinkedHashMap {
return &LinkedHashMap{
table: make(map[string]*node, length),
head: nil,
tail: nil,
cap: length,
}
}
func (l *LinkedHashMap) Add(key string, data *paste) {
tmp := &node{
prev: l.tail,
key: key,
data: data,
next: nil,
}
if l.cap <= 0 {
l.Delete(l.head.key)
}
l.cap--
l.table[key] = tmp
if l.head == nil && l.tail == nil {
l.head = tmp
l.tail = tmp
} else {
l.appendToTail(tmp)
}
}
func (l *LinkedHashMap) Delete(key string) bool {
tmp, ok := l.table[key]
if !ok {
return ok
}
delete(l.table, key)
l.remove(tmp)
l.cap++
return ok
}
func (l *LinkedHashMap) Get(key string) (*paste, bool) {
tmp, ok := l.table[key]
if !ok {
return nil, ok
}
if tmp != l.tail {
l.remove(tmp)
l.appendToTail(tmp)
}
return tmp.data, ok
}
func (l *LinkedHashMap) remove(n *node) {
if l.head == l.tail {
l.head = nil
l.tail = nil
} else if n == l.head {
l.head = n.next
l.head.prev = nil
} else if n == l.tail {
l.tail = n.prev
l.tail.next = nil
} else {
n.prev.next = n.next
n.next.prev = n.prev
}
}
func (l *LinkedHashMap) appendToTail(n *node) {
n.prev = l.tail
n.next = nil
l.tail.next = n
l.tail = n
}