2 Copyright 2017 The Kubernetes Authors.
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
8 http://www.apache.org/licenses/LICENSE-2.0
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.
17 // This file implements a heap data structure.
28 closedMsg = "heap is closed"
31 type LessFunc func(interface{}, interface{}) bool
32 type heapItem struct {
33 obj interface{} // The object which is stored in the heap.
34 index int // The index of the object's key in the Heap.queue.
37 type itemKeyValue struct {
42 // heapData is an internal struct that implements the standard heap interface
43 // and keeps the data stored in the heap.
44 type heapData struct {
45 // items is a map from key of the objects to the objects and their index.
46 // We depend on the property that items in the map are in the queue and vice versa.
47 items map[string]*heapItem
48 // queue implements a heap data structure and keeps the order of elements
49 // according to the heap invariant. The queue keeps the keys of objects stored
53 // keyFunc is used to make the key used for queued item insertion and retrieval, and
54 // should be deterministic.
56 // lessFunc is used to compare two objects in the heap.
61 _ = heap.Interface(&heapData{}) // heapData is a standard heap
64 // Less compares two objects and returns true if the first one should go
65 // in front of the second one in the heap.
66 func (h *heapData) Less(i, j int) bool {
67 if i > len(h.queue) || j > len(h.queue) {
70 itemi, ok := h.items[h.queue[i]]
74 itemj, ok := h.items[h.queue[j]]
78 return h.lessFunc(itemi.obj, itemj.obj)
81 // Len returns the number of items in the Heap.
82 func (h *heapData) Len() int { return len(h.queue) }
84 // Swap implements swapping of two elements in the heap. This is a part of standard
85 // heap interface and should never be called directly.
86 func (h *heapData) Swap(i, j int) {
87 h.queue[i], h.queue[j] = h.queue[j], h.queue[i]
88 item := h.items[h.queue[i]]
90 item = h.items[h.queue[j]]
94 // Push is supposed to be called by heap.Push only.
95 func (h *heapData) Push(kv interface{}) {
96 keyValue := kv.(*itemKeyValue)
98 h.items[keyValue.key] = &heapItem{keyValue.obj, n}
99 h.queue = append(h.queue, keyValue.key)
102 // Pop is supposed to be called by heap.Pop only.
103 func (h *heapData) Pop() interface{} {
104 key := h.queue[len(h.queue)-1]
105 h.queue = h.queue[0 : len(h.queue)-1]
106 item, ok := h.items[key]
115 // Heap is a thread-safe producer/consumer queue that implements a heap data structure.
116 // It can be used to implement priority queues and similar data structures.
121 // data stores objects and has a queue that keeps their ordering according
122 // to the heap invariant.
125 // closed indicates that the queue is closed.
126 // It is mainly used to let Pop() exit its control loop while waiting for an item.
130 // Close the Heap and signals condition variables that may be waiting to pop
131 // items from the heap.
132 func (h *Heap) Close() {
134 defer h.lock.Unlock()
139 // Add inserts an item, and puts it in the queue. The item is updated if it
141 func (h *Heap) Add(obj interface{}) error {
142 key, err := h.data.keyFunc(obj)
144 return KeyError{obj, err}
147 defer h.lock.Unlock()
149 return fmt.Errorf(closedMsg)
151 if _, exists := h.data.items[key]; exists {
152 h.data.items[key].obj = obj
153 heap.Fix(h.data, h.data.items[key].index)
155 h.addIfNotPresentLocked(key, obj)
161 // Adds all the items in the list to the queue and then signals the condition
162 // variable. It is useful when the caller would like to add all of the items
163 // to the queue before consumer starts processing them.
164 func (h *Heap) BulkAdd(list []interface{}) error {
166 defer h.lock.Unlock()
168 return fmt.Errorf(closedMsg)
170 for _, obj := range list {
171 key, err := h.data.keyFunc(obj)
173 return KeyError{obj, err}
175 if _, exists := h.data.items[key]; exists {
176 h.data.items[key].obj = obj
177 heap.Fix(h.data, h.data.items[key].index)
179 h.addIfNotPresentLocked(key, obj)
186 // AddIfNotPresent inserts an item, and puts it in the queue. If an item with
187 // the key is present in the map, no changes is made to the item.
189 // This is useful in a single producer/consumer scenario so that the consumer can
190 // safely retry items without contending with the producer and potentially enqueueing
192 func (h *Heap) AddIfNotPresent(obj interface{}) error {
193 id, err := h.data.keyFunc(obj)
195 return KeyError{obj, err}
198 defer h.lock.Unlock()
200 return fmt.Errorf(closedMsg)
202 h.addIfNotPresentLocked(id, obj)
207 // addIfNotPresentLocked assumes the lock is already held and adds the provided
208 // item to the queue if it does not already exist.
209 func (h *Heap) addIfNotPresentLocked(key string, obj interface{}) {
210 if _, exists := h.data.items[key]; exists {
213 heap.Push(h.data, &itemKeyValue{key, obj})
216 // Update is the same as Add in this implementation. When the item does not
217 // exist, it is added.
218 func (h *Heap) Update(obj interface{}) error {
222 // Delete removes an item.
223 func (h *Heap) Delete(obj interface{}) error {
224 key, err := h.data.keyFunc(obj)
226 return KeyError{obj, err}
229 defer h.lock.Unlock()
230 if item, ok := h.data.items[key]; ok {
231 heap.Remove(h.data, item.index)
234 return fmt.Errorf("object not found")
237 // Pop waits until an item is ready. If multiple items are
238 // ready, they are returned in the order given by Heap.data.lessFunc.
239 func (h *Heap) Pop() (interface{}, error) {
241 defer h.lock.Unlock()
242 for len(h.data.queue) == 0 {
243 // When the queue is empty, invocation of Pop() is blocked until new item is enqueued.
244 // When Close() is called, the h.closed is set and the condition is broadcast,
245 // which causes this loop to continue and return from the Pop().
247 return nil, fmt.Errorf("heap is closed")
251 obj := heap.Pop(h.data)
255 return nil, fmt.Errorf("object was removed from heap data")
259 // List returns a list of all the items.
260 func (h *Heap) List() []interface{} {
262 defer h.lock.RUnlock()
263 list := make([]interface{}, 0, len(h.data.items))
264 for _, item := range h.data.items {
265 list = append(list, item.obj)
270 // ListKeys returns a list of all the keys of the objects currently in the Heap.
271 func (h *Heap) ListKeys() []string {
273 defer h.lock.RUnlock()
274 list := make([]string, 0, len(h.data.items))
275 for key := range h.data.items {
276 list = append(list, key)
281 // Get returns the requested item, or sets exists=false.
282 func (h *Heap) Get(obj interface{}) (interface{}, bool, error) {
283 key, err := h.data.keyFunc(obj)
285 return nil, false, KeyError{obj, err}
287 return h.GetByKey(key)
290 // GetByKey returns the requested item, or sets exists=false.
291 func (h *Heap) GetByKey(key string) (interface{}, bool, error) {
293 defer h.lock.RUnlock()
294 item, exists := h.data.items[key]
296 return nil, false, nil
298 return item.obj, true, nil
301 // IsClosed returns true if the queue is closed.
302 func (h *Heap) IsClosed() bool {
304 defer h.lock.RUnlock()
311 // NewHeap returns a Heap which can be used to queue up items to process.
312 func NewHeap(keyFn KeyFunc, lessFn LessFunc) *Heap {
315 items: map[string]*heapItem{},