blob: 477d2b9f3aa1c6bbf1a8822c31d2ea729b714ad4 [file] [log] [blame]
khenaidoo59ce9dd2019-11-11 13:05:32 -05001// Copyright 2015 The etcd Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package v2store
16
17import "container/heap"
18
19// An TTLKeyHeap is a min-heap of TTLKeys order by expiration time
20type ttlKeyHeap struct {
21 array []*node
22 keyMap map[*node]int
23}
24
25func newTtlKeyHeap() *ttlKeyHeap {
26 h := &ttlKeyHeap{keyMap: make(map[*node]int)}
27 heap.Init(h)
28 return h
29}
30
31func (h ttlKeyHeap) Len() int {
32 return len(h.array)
33}
34
35func (h ttlKeyHeap) Less(i, j int) bool {
36 return h.array[i].ExpireTime.Before(h.array[j].ExpireTime)
37}
38
39func (h ttlKeyHeap) Swap(i, j int) {
40 // swap node
41 h.array[i], h.array[j] = h.array[j], h.array[i]
42
43 // update map
44 h.keyMap[h.array[i]] = i
45 h.keyMap[h.array[j]] = j
46}
47
48func (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
54func (h *ttlKeyHeap) Pop() interface{} {
55 old := h.array
56 n := len(old)
57 x := old[n-1]
58 // Set slice element to nil, so GC can recycle the node.
59 // This is due to golang GC doesn't support partial recycling:
60 // https://github.com/golang/go/issues/9618
61 old[n-1] = nil
62 h.array = old[0 : n-1]
63 delete(h.keyMap, x)
64 return x
65}
66
67func (h *ttlKeyHeap) top() *node {
68 if h.Len() != 0 {
69 return h.array[0]
70 }
71 return nil
72}
73
74func (h *ttlKeyHeap) pop() *node {
75 x := heap.Pop(h)
76 n, _ := x.(*node)
77 return n
78}
79
80func (h *ttlKeyHeap) push(x interface{}) {
81 heap.Push(h, x)
82}
83
84func (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
92func (h *ttlKeyHeap) remove(n *node) {
93 index, ok := h.keyMap[n]
94 if ok {
95 heap.Remove(h, index)
96 }
97}