-
Notifications
You must be signed in to change notification settings - Fork 106
/
in_flight_pqueue.go
99 lines (88 loc) · 1.6 KB
/
in_flight_pqueue.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
package nsqd
type inFlightPqueue []*Message
func newInFlightPqueue(capacity int) inFlightPqueue {
return make(inFlightPqueue, 0, capacity)
}
func (pq inFlightPqueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
func (pq *inFlightPqueue) Push(x *Message) {
n := len(*pq)
c := cap(*pq)
if n+1 > c {
npq := make(inFlightPqueue, n, c*2)
copy(npq, *pq)
*pq = npq
}
*pq = (*pq)[0 : n+1]
x.index = n
(*pq)[n] = x
pq.up(n)
}
func (pq *inFlightPqueue) Pop() *Message {
n := len(*pq)
c := cap(*pq)
pq.Swap(0, n-1)
pq.down(0, n-1)
if n < (c/2) && c > 25 {
npq := make(inFlightPqueue, n, c/2)
copy(npq, *pq)
*pq = npq
}
x := (*pq)[n-1]
x.index = -1
*pq = (*pq)[0 : n-1]
return x
}
func (pq *inFlightPqueue) Remove(i int) *Message {
n := len(*pq)
if n-1 != i {
pq.Swap(i, n-1)
pq.down(i, n-1)
pq.up(i)
}
x := (*pq)[n-1]
x.index = -1
*pq = (*pq)[0 : n-1]
return x
}
func (pq *inFlightPqueue) PeekAndShift(max int64) (*Message, int64) {
if len(*pq) == 0 {
return nil, 0
}
x := (*pq)[0]
if x.pri > max {
return nil, x.pri - max
}
pq.Pop()
return x, 0
}
func (pq *inFlightPqueue) up(j int) {
for {
i := (j - 1) / 2 // parent
if i == j || (*pq)[j].pri >= (*pq)[i].pri {
break
}
pq.Swap(i, j)
j = i
}
}
func (pq *inFlightPqueue) down(i, n int) {
for {
j1 := 2*i + 1
if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
break
}
j := j1 // left child
if j2 := j1 + 1; j2 < n && (*pq)[j1].pri >= (*pq)[j2].pri {
j = j2 // = 2*i + 2 // right child
}
if (*pq)[j].pri >= (*pq)[i].pri {
break
}
pq.Swap(i, j)
i = j
}
}