volcano.sh/volcano@v1.9.0/pkg/scheduler/util/priority_queue.go (about) 1 /* 2 Copyright 2017 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package util 18 19 import ( 20 "container/heap" 21 22 "volcano.sh/volcano/pkg/scheduler/api" 23 ) 24 25 // PriorityQueue implements a scheduling queue. 26 type PriorityQueue struct { 27 queue priorityQueue 28 } 29 30 type priorityQueue struct { 31 items []interface{} 32 lessFn api.LessFn 33 } 34 35 // NewPriorityQueue returns a PriorityQueue 36 func NewPriorityQueue(lessFn api.LessFn) *PriorityQueue { 37 return &PriorityQueue{ 38 queue: priorityQueue{ 39 items: make([]interface{}, 0), 40 lessFn: lessFn, 41 }, 42 } 43 } 44 45 // Push pushes element in the priority Queue 46 func (q *PriorityQueue) Push(it interface{}) { 47 heap.Push(&q.queue, it) 48 } 49 50 // Pop pops element in the priority Queue 51 func (q *PriorityQueue) Pop() interface{} { 52 if q.Len() == 0 { 53 return nil 54 } 55 56 return heap.Pop(&q.queue) 57 } 58 59 // Empty check if queue is empty 60 func (q *PriorityQueue) Empty() bool { 61 return q.queue.Len() == 0 62 } 63 64 // Len returns Len of the priority queue 65 func (q *PriorityQueue) Len() int { 66 return q.queue.Len() 67 } 68 69 func (pq *priorityQueue) Len() int { return len(pq.items) } 70 71 func (pq *priorityQueue) Less(i, j int) bool { 72 if pq.lessFn == nil { 73 return i < j 74 } 75 76 // We want Pop to give us the highest, not lowest, priority so we use greater than here. 77 return pq.lessFn(pq.items[i], pq.items[j]) 78 } 79 80 func (pq priorityQueue) Swap(i, j int) { 81 pq.items[i], pq.items[j] = pq.items[j], pq.items[i] 82 } 83 84 func (pq *priorityQueue) Push(x interface{}) { 85 (*pq).items = append((*pq).items, x) 86 } 87 88 func (pq *priorityQueue) Pop() interface{} { 89 old := (*pq).items 90 n := len(old) 91 item := old[n-1] 92 (*pq).items = old[0 : n-1] 93 return item 94 }