-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqueue.go
127 lines (99 loc) · 2.21 KB
/
queue.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package congestion
import (
"container/heap"
)
const maxInt = int((^uint(0)) >> 1)
// rendezvouz is for returning context to the calling goroutine
type rendezvouz struct {
priority int
index int
errChan chan error
}
func (r rendezvouz) Drop() {
select {
case r.errChan <- Dropped:
default:
}
}
func (r rendezvouz) Signal() {
close(r.errChan)
}
type queue []*rendezvouz
func (pq queue) Len() int { return len(pq) }
func (pq queue) 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 queue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
func (pq *queue) Push(x interface{}) {
n := len(*pq)
item := x.(*rendezvouz)
item.index = n
*pq = append(*pq, item)
}
func (pq *queue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
item.index = -1 // for safety
*pq = old[0 : n-1]
return item
}
type priorityQueue queue
func newQueue(capacity int) priorityQueue {
return priorityQueue(make([]*rendezvouz, 0, capacity))
}
func (pq *priorityQueue) Len() int {
return len(*pq)
}
func (pq *priorityQueue) Cap() int {
return cap(*pq)
}
func (pq *priorityQueue) push(r *rendezvouz) {
heap.Push((*queue)(pq), r)
}
func (pq *priorityQueue) Push(r *rendezvouz) bool {
// If we're under capacity, push it to the queue
if pq.Len() < pq.Cap() {
pq.push(r)
return true
}
// otherwise, we need to check if this takes priority over the lowest element
old := *pq
n := len(old)
index := n / 2
lowestIndex := index
priority := maxInt
for i := index; i < n; i++ {
if old[i].priority < priority {
lowestIndex = i
priority = old[i].priority
}
}
last := (*pq)[lowestIndex]
if last.priority < r.priority {
(*pq)[lowestIndex] = r
// Fix index
r.index = lowestIndex
heap.Fix((*queue)(pq), lowestIndex)
// For safety
last.index = -1
last.Drop()
return true
}
return false
}
func (pq *priorityQueue) Empty() bool {
return (*queue)(pq).Len() <= 0
}
func (pq *priorityQueue) Pop() rendezvouz {
ret := heap.Pop((*queue)(pq)).(*rendezvouz)
return *ret
}
func (pq *priorityQueue) Remove(r *rendezvouz) {
heap.Remove((*queue)(pq), r.index)
}