/
heap.go
42 lines (35 loc) · 808 Bytes
/
heap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package leakybucket
// Based on the example implementation of priority queue found in the
// container/heap package docs: https://golang.org/pkg/container/heap/
type priorityQueue []*LeakyBucket
func (pq priorityQueue) Len() int {
return len(pq)
}
func (pq priorityQueue) Peak() *LeakyBucket {
if len(pq) <= 0 {
return nil
}
return pq[0]
}
func (pq priorityQueue) Less(i, j int) bool {
return pq[i].p.Before(pq[j].p)
}
func (pq priorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
func (pq *priorityQueue) Push(x interface{}) {
n := len(*pq)
b := x.(*LeakyBucket)
b.index = n
*pq = append(*pq, b)
}
func (pq *priorityQueue) Pop() interface{} {
old := *pq
n := len(old)
b := old[n-1]
b.index = -1 // for safety
*pq = old[0 : n-1]
return b
}