Skip to content

Commit cc1ec4c

Browse files
committed
prio-queue: add 'peek' operation
When consuming a priority queue, it can be convenient to inspect the next object that will be dequeued without actually dequeueing it. Our existing library did not have such a 'peek' operation, so add it as prio_queue_peek(). Add a reference-level comparison in t/helper/test-prio-queue.c so this method is exercised by t0009-prio-queue.sh. Signed-off-by: Derrick Stolee <[email protected]>
1 parent 2d3b1c5 commit cc1ec4c

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed

prio-queue.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,12 @@ void *prio_queue_get(struct prio_queue *queue)
8585
}
8686
return result;
8787
}
88+
89+
void *prio_queue_peek(struct prio_queue *queue)
90+
{
91+
if (!queue->nr)
92+
return NULL;
93+
if (!queue->compare)
94+
return queue->array[queue->nr - 1].data;
95+
return queue->array[0].data;
96+
}

prio-queue.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@ extern void prio_queue_put(struct prio_queue *, void *thing);
4646
*/
4747
extern void *prio_queue_get(struct prio_queue *);
4848

49+
/*
50+
* Gain access to the "thing" that would be returned by
51+
* prio_queue_get, but do not remove it from the queue.
52+
*/
53+
extern void *prio_queue_peek(struct prio_queue *);
54+
4955
extern void clear_prio_queue(struct prio_queue *);
5056

5157
/* Reverse the LIFO elements */

t/helper/test-prio-queue.c

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,13 @@ int cmd__prio_queue(int argc, const char **argv)
2222
struct prio_queue pq = { intcmp };
2323

2424
while (*++argv) {
25-
if (!strcmp(*argv, "get"))
26-
show(prio_queue_get(&pq));
27-
else if (!strcmp(*argv, "dump")) {
25+
if (!strcmp(*argv, "get")) {
26+
void *peek = prio_queue_peek(&pq);
27+
void *get = prio_queue_get(&pq);
28+
if (peek != get)
29+
BUG("peek and get results do not match");
30+
show(get);
31+
} else if (!strcmp(*argv, "dump")) {
2832
int *v;
2933
while ((v = prio_queue_get(&pq)))
3034
show(v);

0 commit comments

Comments
 (0)