]> git.ipfire.org Git - thirdparty/git.git/blame - prio-queue.c
apply: use SWAP macro
[thirdparty/git.git] / prio-queue.c
CommitLineData
b4b594a3 1#include "cache.h"
b4b594a3
JH
2#include "prio-queue.h"
3
6d63baa4
JK
4static inline int compare(struct prio_queue *queue, int i, int j)
5{
e8f91e3d 6 int cmp = queue->compare(queue->array[i].data, queue->array[j].data,
6d63baa4 7 queue->cb_data);
e8f91e3d
JK
8 if (!cmp)
9 cmp = queue->array[i].ctr - queue->array[j].ctr;
6d63baa4
JK
10 return cmp;
11}
12
13static inline void swap(struct prio_queue *queue, int i, int j)
14{
e8f91e3d 15 struct prio_queue_entry tmp = queue->array[i];
6d63baa4
JK
16 queue->array[i] = queue->array[j];
17 queue->array[j] = tmp;
18}
19
da24b104
JH
20void prio_queue_reverse(struct prio_queue *queue)
21{
22 int i, j;
23
24 if (queue->compare != NULL)
25 die("BUG: prio_queue_reverse() on non-LIFO queue");
6d63baa4
JK
26 for (i = 0; i <= (j = (queue->nr - 1) - i); i++)
27 swap(queue, i, j);
da24b104
JH
28}
29
b4b594a3
JH
30void clear_prio_queue(struct prio_queue *queue)
31{
32 free(queue->array);
33 queue->nr = 0;
34 queue->alloc = 0;
35 queue->array = NULL;
e8f91e3d 36 queue->insertion_ctr = 0;
b4b594a3
JH
37}
38
39void prio_queue_put(struct prio_queue *queue, void *thing)
40{
b4b594a3
JH
41 int ix, parent;
42
43 /* Append at the end */
44 ALLOC_GROW(queue->array, queue->nr + 1, queue->alloc);
e8f91e3d
JK
45 queue->array[queue->nr].ctr = queue->insertion_ctr++;
46 queue->array[queue->nr].data = thing;
47 queue->nr++;
6d63baa4 48 if (!queue->compare)
b4b594a3
JH
49 return; /* LIFO */
50
51 /* Bubble up the new one */
52 for (ix = queue->nr - 1; ix; ix = parent) {
53 parent = (ix - 1) / 2;
6d63baa4 54 if (compare(queue, parent, ix) <= 0)
b4b594a3
JH
55 break;
56
6d63baa4 57 swap(queue, parent, ix);
b4b594a3
JH
58 }
59}
60
61void *prio_queue_get(struct prio_queue *queue)
62{
6d63baa4 63 void *result;
b4b594a3 64 int ix, child;
b4b594a3
JH
65
66 if (!queue->nr)
67 return NULL;
6d63baa4 68 if (!queue->compare)
e8f91e3d 69 return queue->array[--queue->nr].data; /* LIFO */
b4b594a3 70
e8f91e3d 71 result = queue->array[0].data;
b4b594a3
JH
72 if (!--queue->nr)
73 return result;
74
75 queue->array[0] = queue->array[queue->nr];
76
77 /* Push down the one at the root */
78 for (ix = 0; ix * 2 + 1 < queue->nr; ix = child) {
79 child = ix * 2 + 1; /* left */
6d63baa4
JK
80 if (child + 1 < queue->nr &&
81 compare(queue, child, child + 1) >= 0)
b4b594a3
JH
82 child++; /* use right child */
83
6d63baa4 84 if (compare(queue, ix, child) <= 0)
b4b594a3
JH
85 break;
86
6d63baa4 87 swap(queue, child, ix);
b4b594a3
JH
88 }
89 return result;
90}