github.com/amazechain/amc@v0.1.3/internal/p2p/leaky-bucket/heap.go (about) 1 package leakybucket 2 3 import "fmt" 4 5 // Based on the example implementation of priority queue found in the 6 // container/heap package docs: https://golang.org/pkg/container/heap/ 7 type priorityQueue []*LeakyBucket 8 9 func (pq priorityQueue) Len() int { 10 return len(pq) 11 } 12 13 func (pq priorityQueue) Peak() *LeakyBucket { 14 if len(pq) <= 0 { 15 return nil 16 } 17 return pq[0] 18 } 19 20 func (pq priorityQueue) Less(i, j int) bool { 21 return pq[i].p.Before(pq[j].p) 22 } 23 24 func (pq priorityQueue) Swap(i, j int) { 25 pq[i], pq[j] = pq[j], pq[i] 26 pq[i].index = i 27 pq[j].index = j 28 } 29 30 func (pq *priorityQueue) Push(x interface{}) { 31 n := len(*pq) 32 b, ok := x.(*LeakyBucket) 33 if !ok { 34 panic(fmt.Sprintf("%T", x)) 35 } 36 b.index = n 37 *pq = append(*pq, b) 38 } 39 40 func (pq *priorityQueue) Pop() interface{} { 41 old := *pq 42 n := len(old) 43 b := old[n-1] 44 b.index = -1 // for safety 45 *pq = old[0 : n-1] 46 return b 47 }