ttl_key_heap.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package store
  14. import (
  15. "container/heap"
  16. )
  17. // An TTLKeyHeap is a min-heap of TTLKeys order by expiration time
  18. type ttlKeyHeap struct {
  19. array []*node
  20. keyMap map[*node]int
  21. }
  22. func newTtlKeyHeap() *ttlKeyHeap {
  23. h := &ttlKeyHeap{keyMap: make(map[*node]int)}
  24. heap.Init(h)
  25. return h
  26. }
  27. func (h ttlKeyHeap) Len() int {
  28. return len(h.array)
  29. }
  30. func (h ttlKeyHeap) Less(i, j int) bool {
  31. return h.array[i].ExpireTime.Before(h.array[j].ExpireTime)
  32. }
  33. func (h ttlKeyHeap) Swap(i, j int) {
  34. // swap node
  35. h.array[i], h.array[j] = h.array[j], h.array[i]
  36. // update map
  37. h.keyMap[h.array[i]] = i
  38. h.keyMap[h.array[j]] = j
  39. }
  40. func (h *ttlKeyHeap) Push(x interface{}) {
  41. n, _ := x.(*node)
  42. h.keyMap[n] = len(h.array)
  43. h.array = append(h.array, n)
  44. }
  45. func (h *ttlKeyHeap) Pop() interface{} {
  46. old := h.array
  47. n := len(old)
  48. x := old[n-1]
  49. h.array = old[0 : n-1]
  50. delete(h.keyMap, x)
  51. return x
  52. }
  53. func (h *ttlKeyHeap) top() *node {
  54. if h.Len() != 0 {
  55. return h.array[0]
  56. }
  57. return nil
  58. }
  59. func (h *ttlKeyHeap) pop() *node {
  60. x := heap.Pop(h)
  61. n, _ := x.(*node)
  62. return n
  63. }
  64. func (h *ttlKeyHeap) push(x interface{}) {
  65. heap.Push(h, x)
  66. }
  67. func (h *ttlKeyHeap) update(n *node) {
  68. index, ok := h.keyMap[n]
  69. if ok {
  70. heap.Remove(h, index)
  71. heap.Push(h, n)
  72. }
  73. }
  74. func (h *ttlKeyHeap) remove(n *node) {
  75. index, ok := h.keyMap[n]
  76. if ok {
  77. heap.Remove(h, index)
  78. }
  79. }