util.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2019 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package p2p
  17. import (
  18. "container/heap"
  19. "github.com/ethereum/go-ethereum/common/mclock"
  20. )
  21. // expHeap tracks strings and their expiry time.
  22. type expHeap []expItem
  23. // expItem is an entry in addrHistory.
  24. type expItem struct {
  25. item string
  26. exp mclock.AbsTime
  27. }
  28. // nextExpiry returns the next expiry time.
  29. func (h *expHeap) nextExpiry() mclock.AbsTime {
  30. return (*h)[0].exp
  31. }
  32. // add adds an item and sets its expiry time.
  33. func (h *expHeap) add(item string, exp mclock.AbsTime) {
  34. heap.Push(h, expItem{item, exp})
  35. }
  36. // contains checks whether an item is present.
  37. func (h expHeap) contains(item string) bool {
  38. for _, v := range h {
  39. if v.item == item {
  40. return true
  41. }
  42. }
  43. return false
  44. }
  45. // expire removes items with expiry time before 'now'.
  46. func (h *expHeap) expire(now mclock.AbsTime, onExp func(string)) {
  47. for h.Len() > 0 && h.nextExpiry() < now {
  48. item := heap.Pop(h)
  49. if onExp != nil {
  50. onExp(item.(expItem).item)
  51. }
  52. }
  53. }
  54. // heap.Interface boilerplate
  55. func (h expHeap) Len() int { return len(h) }
  56. func (h expHeap) Less(i, j int) bool { return h[i].exp < h[j].exp }
  57. func (h expHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  58. func (h *expHeap) Push(x interface{}) { *h = append(*h, x.(expItem)) }
  59. func (h *expHeap) Pop() interface{} {
  60. old := *h
  61. n := len(old)
  62. x := old[n-1]
  63. *h = old[0 : n-1]
  64. return x
  65. }