github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/network/queue/priorityQueue.go (about) 1 package queue 2 3 import "time" 4 5 type item struct { 6 message interface{} 7 priority int // The priority of the item in the queue. 8 // The index is needed by update and is maintained by the heap.Interface methods. 9 index int // The index of the item in the heap. 10 timestamp time.Time // timestamp to maintain insertions order for items with the same priority and for telemetry 11 12 } 13 14 // A priorityQueue implements heap.Interface and holds Items. 15 type priorityQueue []*item 16 17 func (pq priorityQueue) Len() int { return len(pq) } 18 19 func (pq priorityQueue) Less(i, j int) bool { 20 // We want Pop to give us the highest, not lowest, priority so we use greater than here. 21 if pq[i].priority > pq[j].priority { 22 return true 23 } 24 if pq[i].priority < pq[j].priority { 25 return false 26 } 27 // if both items have the same priority, then pop the oldest 28 return pq[i].timestamp.Before(pq[j].timestamp) 29 } 30 31 func (pq priorityQueue) Swap(i, j int) { 32 pq[i], pq[j] = pq[j], pq[i] 33 pq[i].index = i 34 pq[j].index = j 35 } 36 37 func (pq *priorityQueue) Push(x interface{}) { 38 n := len(*pq) 39 item, ok := x.(*item) 40 if !ok { 41 return 42 } 43 item.index = n 44 *pq = append(*pq, item) 45 } 46 47 func (pq *priorityQueue) Pop() interface{} { 48 old := *pq 49 n := len(old) 50 item := old[n-1] 51 old[n-1] = nil // avoid memory leak 52 item.index = -1 // for safety 53 *pq = old[0 : n-1] 54 return item 55 }