-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathpriorityQueue.go
More file actions
55 lines (46 loc) · 1.29 KB
/
priorityQueue.go
File metadata and controls
55 lines (46 loc) · 1.29 KB
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
46
47
48
49
50
51
52
53
54
55
package queue
import "time"
type item struct {
message any
priority int // The priority of the item in the queue.
// The index is needed by update and is maintained by the heap.Interface methods.
index int // The index of the item in the heap.
timestamp time.Time // timestamp to maintain insertions order for items with the same priority and for telemetry
}
// A priorityQueue implements heap.Interface and holds Items.
type priorityQueue []*item
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.
if pq[i].priority > pq[j].priority {
return true
}
if pq[i].priority < pq[j].priority {
return false
}
// if both items have the same priority, then pop the oldest
return pq[i].timestamp.Before(pq[j].timestamp)
}
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, ok := x.(*item)
if !ok {
return
}
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
}