config: pass 'repo' directly to 'config_with_options()'
[alt-git.git] / prio-queue.c
blobdc2476be53a30a6e9c682d934f620422dd855ada
1 #include "git-compat-util.h"
2 #include "alloc.h"
3 #include "prio-queue.h"
5 static inline int compare(struct prio_queue *queue, int i, int j)
7 int cmp = queue->compare(queue->array[i].data, queue->array[j].data,
8 queue->cb_data);
9 if (!cmp)
10 cmp = queue->array[i].ctr - queue->array[j].ctr;
11 return cmp;
14 static inline void swap(struct prio_queue *queue, int i, int j)
16 SWAP(queue->array[i], queue->array[j]);
19 void prio_queue_reverse(struct prio_queue *queue)
21 int i, j;
23 if (queue->compare)
24 BUG("prio_queue_reverse() on non-LIFO queue");
25 for (i = 0; i < (j = (queue->nr - 1) - i); i++)
26 swap(queue, i, j);
29 void clear_prio_queue(struct prio_queue *queue)
31 FREE_AND_NULL(queue->array);
32 queue->nr = 0;
33 queue->alloc = 0;
34 queue->insertion_ctr = 0;
37 void prio_queue_put(struct prio_queue *queue, void *thing)
39 int ix, parent;
41 /* Append at the end */
42 ALLOC_GROW(queue->array, queue->nr + 1, queue->alloc);
43 queue->array[queue->nr].ctr = queue->insertion_ctr++;
44 queue->array[queue->nr].data = thing;
45 queue->nr++;
46 if (!queue->compare)
47 return; /* LIFO */
49 /* Bubble up the new one */
50 for (ix = queue->nr - 1; ix; ix = parent) {
51 parent = (ix - 1) / 2;
52 if (compare(queue, parent, ix) <= 0)
53 break;
55 swap(queue, parent, ix);
59 void *prio_queue_get(struct prio_queue *queue)
61 void *result;
62 int ix, child;
64 if (!queue->nr)
65 return NULL;
66 if (!queue->compare)
67 return queue->array[--queue->nr].data; /* LIFO */
69 result = queue->array[0].data;
70 if (!--queue->nr)
71 return result;
73 queue->array[0] = queue->array[queue->nr];
75 /* Push down the one at the root */
76 for (ix = 0; ix * 2 + 1 < queue->nr; ix = child) {
77 child = ix * 2 + 1; /* left */
78 if (child + 1 < queue->nr &&
79 compare(queue, child, child + 1) >= 0)
80 child++; /* use right child */
82 if (compare(queue, ix, child) <= 0)
83 break;
85 swap(queue, child, ix);
87 return result;
90 void *prio_queue_peek(struct prio_queue *queue)
92 if (!queue->nr)
93 return NULL;
94 if (!queue->compare)
95 return queue->array[queue->nr - 1].data;
96 return queue->array[0].data;