ttl_key_heap.go 2.1 KB

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