-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.go
45 lines (37 loc) · 1023 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
43
44
45
package tcp
import (
"container/heap"
)
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*TcpPacketItem
func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
// We want Pop to give us the highest, not lowest, Priority so we use greater than here.
return pq[i].Priority < pq[j].Priority
}
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 any) {
n := len(*pq)
item := x.(*TcpPacketItem)
item.Index = n
*pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() any {
old := *pq
n := len(old)
item := old[n-1]
old[n-1] = nil // avoid memory leak
item.Index = -1 // for safety
*pq = old[0 : n-1]
return item
}
// update modifies the Priority and Value of an Item in the queue.
func (pq *PriorityQueue) Update(item *TcpPacketItem, Value *TcpPacket, Priority int) {
item.Value = Value
item.Priority = Priority
heap.Fix(pq, item.Index)
}