github.com/ghodss/etcd@v0.3.1-0.20140417172404-cc329bfa55cb/store/ttl_key_heap.go (about) 1 package store 2 3 import ( 4 "container/heap" 5 ) 6 7 // An TTLKeyHeap is a min-heap of TTLKeys order by expiration time 8 type ttlKeyHeap struct { 9 array []*node 10 keyMap map[*node]int 11 } 12 13 func newTtlKeyHeap() *ttlKeyHeap { 14 h := &ttlKeyHeap{keyMap: make(map[*node]int)} 15 heap.Init(h) 16 return h 17 } 18 19 func (h ttlKeyHeap) Len() int { 20 return len(h.array) 21 } 22 23 func (h ttlKeyHeap) Less(i, j int) bool { 24 return h.array[i].ExpireTime.Before(h.array[j].ExpireTime) 25 } 26 27 func (h ttlKeyHeap) Swap(i, j int) { 28 // swap node 29 h.array[i], h.array[j] = h.array[j], h.array[i] 30 31 // update map 32 h.keyMap[h.array[i]] = i 33 h.keyMap[h.array[j]] = j 34 } 35 36 func (h *ttlKeyHeap) Push(x interface{}) { 37 n, _ := x.(*node) 38 h.keyMap[n] = len(h.array) 39 h.array = append(h.array, n) 40 } 41 42 func (h *ttlKeyHeap) Pop() interface{} { 43 old := h.array 44 n := len(old) 45 x := old[n-1] 46 h.array = old[0 : n-1] 47 delete(h.keyMap, x) 48 return x 49 } 50 51 func (h *ttlKeyHeap) top() *node { 52 if h.Len() != 0 { 53 return h.array[0] 54 } 55 return nil 56 } 57 58 func (h *ttlKeyHeap) pop() *node { 59 x := heap.Pop(h) 60 n, _ := x.(*node) 61 return n 62 } 63 64 func (h *ttlKeyHeap) push(x interface{}) { 65 heap.Push(h, x) 66 } 67 68 func (h *ttlKeyHeap) update(n *node) { 69 index, ok := h.keyMap[n] 70 if ok { 71 heap.Remove(h, index) 72 heap.Push(h, n) 73 } 74 } 75 76 func (h *ttlKeyHeap) remove(n *node) { 77 index, ok := h.keyMap[n] 78 if ok { 79 heap.Remove(h, index) 80 } 81 }