go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/mql/internal/queue.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package internal
     5  
     6  // An Item is something we manage in a priority queue.
     7  type Item struct {
     8  	receiver NodeID
     9  	sender   NodeID
    10  	priority int // The priority of the item in the queue.
    11  }
    12  
    13  // A PriorityQueue implements heap.Interface and holds Items.
    14  type PriorityQueue []*Item
    15  
    16  func (pq PriorityQueue) Len() int { return len(pq) }
    17  
    18  func (pq PriorityQueue) Less(i, j int) bool {
    19  	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
    20  	return pq[i].priority > pq[j].priority
    21  }
    22  
    23  func (pq PriorityQueue) Swap(i, j int) {
    24  	pq[i], pq[j] = pq[j], pq[i]
    25  }
    26  
    27  func (pq *PriorityQueue) Push(x interface{}) {
    28  	item := x.(*Item)
    29  	*pq = append(*pq, item)
    30  }
    31  
    32  func (pq *PriorityQueue) Pop() interface{} {
    33  	old := *pq
    34  	n := len(old)
    35  	item := old[n-1]
    36  	old[n-1] = nil // avoid memory leak
    37  	*pq = old[0 : n-1]
    38  	return item
    39  }