ttl_key_heap.go 1.3 KB

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