github.com/wzbox/go-ethereum@v1.9.2/p2p/util.go (about) 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 17 package p2p 18 19 import ( 20 "container/heap" 21 "time" 22 ) 23 24 // expHeap tracks strings and their expiry time. 25 type expHeap []expItem 26 27 // expItem is an entry in addrHistory. 28 type expItem struct { 29 item string 30 exp time.Time 31 } 32 33 // nextExpiry returns the next expiry time. 34 func (h *expHeap) nextExpiry() time.Time { 35 return (*h)[0].exp 36 } 37 38 // add adds an item and sets its expiry time. 39 func (h *expHeap) add(item string, exp time.Time) { 40 heap.Push(h, expItem{item, exp}) 41 } 42 43 // remove removes an item. 44 func (h *expHeap) remove(item string) bool { 45 for i, v := range *h { 46 if v.item == item { 47 heap.Remove(h, i) 48 return true 49 } 50 } 51 return false 52 } 53 54 // contains checks whether an item is present. 55 func (h expHeap) contains(item string) bool { 56 for _, v := range h { 57 if v.item == item { 58 return true 59 } 60 } 61 return false 62 } 63 64 // expire removes items with expiry time before 'now'. 65 func (h *expHeap) expire(now time.Time) { 66 for h.Len() > 0 && h.nextExpiry().Before(now) { 67 heap.Pop(h) 68 } 69 } 70 71 // heap.Interface boilerplate 72 func (h expHeap) Len() int { return len(h) } 73 func (h expHeap) Less(i, j int) bool { return h[i].exp.Before(h[j].exp) } 74 func (h expHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } 75 func (h *expHeap) Push(x interface{}) { *h = append(*h, x.(expItem)) } 76 func (h *expHeap) Pop() interface{} { 77 old := *h 78 n := len(old) 79 x := old[n-1] 80 *h = old[0 : n-1] 81 return x 82 }