-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.go
58 lines (48 loc) · 1012 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
46
47
48
49
50
51
52
53
54
55
56
57
58
package maatq
import (
"bytes"
"container/heap"
"encoding/json"
)
// minHeap to hold peroidic messages, minHeap implements
// container/heap.Interface
type minHeap struct {
Items *[]*PriorityMessage
}
func (h minHeap) String() string {
b := bytes.Buffer{}
if err := json.NewEncoder(&b).Encode(h.Items); err != nil {
return err.Error()
}
return b.String()
}
func (h minHeap) Len() int {
if h.Items == nil {
return 0
}
return len(*h.Items)
}
func (h minHeap) Less(i, j int) bool {
return (*h.Items)[i].T < (*h.Items)[j].T
}
func (h minHeap) Swap(i, j int) {
(*h.Items)[i], (*h.Items)[j] = (*h.Items)[j], (*h.Items)[i]
}
func (h minHeap) Push(x interface{}) {
*h.Items = append(*h.Items, x.(*PriorityMessage))
}
func (h minHeap) Pop() interface{} {
n := len(*h.Items) - 1
v := (*h.Items)[n]
*h.Items = (*h.Items)[0:n]
return v
}
// newHeap get a pointer of minHeap
func newHeap() *minHeap {
s := make([]*PriorityMessage, 0)
h := &minHeap{
Items: &s,
}
heap.Init(h)
return h
}