ttl_key_heap.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // 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. package v2store
  15. import "container/heap"
  16. // An TTLKeyHeap is a min-heap of TTLKeys order by expiration time
  17. type ttlKeyHeap struct {
  18. array []*node
  19. keyMap map[*node]int
  20. }
  21. func newTtlKeyHeap() *ttlKeyHeap {
  22. h := &ttlKeyHeap{keyMap: make(map[*node]int)}
  23. heap.Init(h)
  24. return h
  25. }
  26. func (h ttlKeyHeap) Len() int {
  27. return len(h.array)
  28. }
  29. func (h ttlKeyHeap) Less(i, j int) bool {
  30. return h.array[i].ExpireTime.Before(h.array[j].ExpireTime)
  31. }
  32. func (h ttlKeyHeap) Swap(i, j int) {
  33. // swap node
  34. h.array[i], h.array[j] = h.array[j], h.array[i]
  35. // update map
  36. h.keyMap[h.array[i]] = i
  37. h.keyMap[h.array[j]] = j
  38. }
  39. func (h *ttlKeyHeap) Push(x interface{}) {
  40. n, _ := x.(*node)
  41. h.keyMap[n] = len(h.array)
  42. h.array = append(h.array, n)
  43. }
  44. func (h *ttlKeyHeap) Pop() interface{} {
  45. old := h.array
  46. n := len(old)
  47. x := old[n-1]
  48. // Set slice element to nil, so GC can recycle the node.
  49. // This is due to golang GC doesn't support partial recycling:
  50. // https://github.com/golang/go/issues/9618
  51. old[n-1] = nil
  52. h.array = old[0 : n-1]
  53. delete(h.keyMap, x)
  54. return x
  55. }
  56. func (h *ttlKeyHeap) top() *node {
  57. if h.Len() != 0 {
  58. return h.array[0]
  59. }
  60. return nil
  61. }
  62. func (h *ttlKeyHeap) pop() *node {
  63. x := heap.Pop(h)
  64. n, _ := x.(*node)
  65. return n
  66. }
  67. func (h *ttlKeyHeap) push(x interface{}) {
  68. heap.Push(h, x)
  69. }
  70. func (h *ttlKeyHeap) update(n *node) {
  71. index, ok := h.keyMap[n]
  72. if ok {
  73. heap.Remove(h, index)
  74. heap.Push(h, n)
  75. }
  76. }
  77. func (h *ttlKeyHeap) remove(n *node) {
  78. index, ok := h.keyMap[n]
  79. if ok {
  80. heap.Remove(h, index)
  81. }
  82. }