...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package v2store
16
17 import "container/heap"
18
19
20 type ttlKeyHeap struct {
21 array []*node
22 keyMap map[*node]int
23 }
24
25 func newTtlKeyHeap() *ttlKeyHeap {
26 h := &ttlKeyHeap{keyMap: make(map[*node]int)}
27 heap.Init(h)
28 return h
29 }
30
31 func (h ttlKeyHeap) Len() int {
32 return len(h.array)
33 }
34
35 func (h ttlKeyHeap) Less(i, j int) bool {
36 return h.array[i].ExpireTime.Before(h.array[j].ExpireTime)
37 }
38
39 func (h ttlKeyHeap) Swap(i, j int) {
40
41 h.array[i], h.array[j] = h.array[j], h.array[i]
42
43
44 h.keyMap[h.array[i]] = i
45 h.keyMap[h.array[j]] = j
46 }
47
48 func (h *ttlKeyHeap) Push(x interface{}) {
49 n, _ := x.(*node)
50 h.keyMap[n] = len(h.array)
51 h.array = append(h.array, n)
52 }
53
54 func (h *ttlKeyHeap) Pop() interface{} {
55 old := h.array
56 n := len(old)
57 x := old[n-1]
58
59
60
61 old[n-1] = nil
62 h.array = old[0 : n-1]
63 delete(h.keyMap, x)
64 return x
65 }
66
67 func (h *ttlKeyHeap) top() *node {
68 if h.Len() != 0 {
69 return h.array[0]
70 }
71 return nil
72 }
73
74 func (h *ttlKeyHeap) pop() *node {
75 x := heap.Pop(h)
76 n, _ := x.(*node)
77 return n
78 }
79
80 func (h *ttlKeyHeap) push(x interface{}) {
81 heap.Push(h, x)
82 }
83
84 func (h *ttlKeyHeap) update(n *node) {
85 index, ok := h.keyMap[n]
86 if ok {
87 heap.Remove(h, index)
88 heap.Push(h, n)
89 }
90 }
91
92 func (h *ttlKeyHeap) remove(n *node) {
93 index, ok := h.keyMap[n]
94 if ok {
95 heap.Remove(h, index)
96 }
97 }
98
View as plain text