File: priority_queue.go

package info (click to toggle)
golang-github-vbauerster-mpb 8.8.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,044 kB
  • sloc: sh: 7; makefile: 3
file content (37 lines) | stat: -rw-r--r-- 701 bytes parent folder | download | duplicates (3)
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
package mpb

import "container/heap"

var _ heap.Interface = (*priorityQueue)(nil)

type priorityQueue []*Bar

func (pq priorityQueue) Len() int { return len(pq) }

func (pq priorityQueue) Less(i, j int) bool {
	// greater priority pops first
	return pq[i].priority > pq[j].priority
}

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 interface{}) {
	n := len(*pq)
	bar := x.(*Bar)
	bar.index = n
	*pq = append(*pq, bar)
}

func (pq *priorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	bar := old[n-1]
	old[n-1] = nil // avoid memory leak
	bar.index = -1 // for safety
	*pq = old[:n-1]
	return bar
}