prio-queue.c 2.01 KB
Newer Older
1 2 3
#include "cache.h"
#include "prio-queue.h"

4 5
static inline int compare(struct prio_queue *queue, int i, int j)
{
6
	int cmp = queue->compare(queue->array[i].data, queue->array[j].data,
7
				 queue->cb_data);
8 9
	if (!cmp)
		cmp = queue->array[i].ctr - queue->array[j].ctr;
10 11 12 13 14
	return cmp;
}

static inline void swap(struct prio_queue *queue, int i, int j)
{
René Scharfe's avatar
René Scharfe committed
15
	SWAP(queue->array[i], queue->array[j]);
16 17
}

18 19 20 21 22
void prio_queue_reverse(struct prio_queue *queue)
{
	int i, j;

	if (queue->compare != NULL)
23
		BUG("prio_queue_reverse() on non-LIFO queue");
24
	for (i = 0; i < (j = (queue->nr - 1) - i); i++)
25
		swap(queue, i, j);
26 27
}

28 29
void clear_prio_queue(struct prio_queue *queue)
{
30
	FREE_AND_NULL(queue->array);
31 32
	queue->nr = 0;
	queue->alloc = 0;
33
	queue->insertion_ctr = 0;
34 35 36 37 38 39 40 41
}

void prio_queue_put(struct prio_queue *queue, void *thing)
{
	int ix, parent;

	/* Append at the end */
	ALLOC_GROW(queue->array, queue->nr + 1, queue->alloc);
42 43 44
	queue->array[queue->nr].ctr = queue->insertion_ctr++;
	queue->array[queue->nr].data = thing;
	queue->nr++;
45
	if (!queue->compare)
46 47 48 49 50
		return; /* LIFO */

	/* Bubble up the new one */
	for (ix = queue->nr - 1; ix; ix = parent) {
		parent = (ix - 1) / 2;
51
		if (compare(queue, parent, ix) <= 0)
52 53
			break;

54
		swap(queue, parent, ix);
55 56 57 58 59
	}
}

void *prio_queue_get(struct prio_queue *queue)
{
60
	void *result;
61 62 63 64
	int ix, child;

	if (!queue->nr)
		return NULL;
65
	if (!queue->compare)
66
		return queue->array[--queue->nr].data; /* LIFO */
67

68
	result = queue->array[0].data;
69 70 71 72 73 74 75 76
	if (!--queue->nr)
		return result;

	queue->array[0] = queue->array[queue->nr];

	/* Push down the one at the root */
	for (ix = 0; ix * 2 + 1 < queue->nr; ix = child) {
		child = ix * 2 + 1; /* left */
77 78
		if (child + 1 < queue->nr &&
		    compare(queue, child, child + 1) >= 0)
79 80
			child++; /* use right child */

81
		if (compare(queue, ix, child) <= 0)
82 83
			break;

84
		swap(queue, child, ix);
85 86 87
	}
	return result;
}
88 89 90 91 92 93 94 95 96

void *prio_queue_peek(struct prio_queue *queue)
{
	if (!queue->nr)
		return NULL;
	if (!queue->compare)
		return queue->array[queue->nr - 1].data;
	return queue->array[0].data;
}