github.com/core-coin/go-core/v2@v2.1.9/p2p/util.go (about) 1 // Copyright 2019 by the Authors 2 // This file is part of the go-core library. 3 // 4 // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>. 16 17 package p2p 18 19 import ( 20 "container/heap" 21 22 "github.com/core-coin/go-core/v2/common/mclock" 23 ) 24 25 // expHeap tracks strings and their expiry time. 26 type expHeap []expItem 27 28 // expItem is an entry in addrHistory. 29 type expItem struct { 30 item string 31 exp mclock.AbsTime 32 } 33 34 // nextExpiry returns the next expiry time. 35 func (h *expHeap) nextExpiry() mclock.AbsTime { 36 return (*h)[0].exp 37 } 38 39 // add adds an item and sets its expiry time. 40 func (h *expHeap) add(item string, exp mclock.AbsTime) { 41 heap.Push(h, expItem{item, exp}) 42 } 43 44 // contains checks whether an item is present. 45 func (h expHeap) contains(item string) bool { 46 for _, v := range h { 47 if v.item == item { 48 return true 49 } 50 } 51 return false 52 } 53 54 // expire removes items with expiry time before 'now'. 55 func (h *expHeap) expire(now mclock.AbsTime, onExp func(string)) { 56 for h.Len() > 0 && h.nextExpiry() < now { 57 item := heap.Pop(h) 58 if onExp != nil { 59 onExp(item.(expItem).item) 60 } 61 } 62 } 63 64 // heap.Interface boilerplate 65 func (h expHeap) Len() int { return len(h) } 66 func (h expHeap) Less(i, j int) bool { return h[i].exp < h[j].exp } 67 func (h expHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } 68 func (h *expHeap) Push(x interface{}) { *h = append(*h, x.(expItem)) } 69 func (h *expHeap) Pop() interface{} { 70 old := *h 71 n := len(old) 72 x := old[n-1] 73 *h = old[0 : n-1] 74 return x 75 }