From a4b92602156fcbc729dd383050c270cf4fd1b004 Mon Sep 17 00:00:00 2001 From: DualFroz Date: Sun, 6 Sep 2026 19:32:19 +0200 Subject: [PATCH] feat: add compareNodes and prioqInit --- src/prioq.c | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/prioq.c diff --git a/src/prioq.c b/src/prioq.c new file mode 100644 index 0000000..bd6c2b5 --- /dev/null +++ b/src/prioq.c @@ -0,0 +1,55 @@ +#include "prioq.h" + +static int compareNodes(const RbtNode* a, const RbtNode* b) +{ + const PrioQNode* pa = rbtEntry(a, PrioQNode, node); + const PrioQNode* pb = rbtEntry(b, PrioQNode, node); + + if (pa->vruntime != pb->vruntime) + return pa->vruntime < pb->vruntime ? -1 : 1; + if (pa->id != pb->id) + return pa->id < pb->id ? -1 : 1; + return 0; +} + +void prioqInit(PrioQueue* q) +{ + rbtInit(&q->tree); +} + +void prioqInsert(PrioQueue* q, PrioQNode* n, uint64 vruntime, uint32 id) +{ + n->vruntime = vruntime; + n->id = id; + bool inserted = rbtInsert(&q->tree, &n->node, compareNodes); + (void)inserted; /* unique id guarantees the key can never already exist */ +} + +PrioQNode* prioqPeekMin(const PrioQueue* q) +{ + RbtNode* n = rbtFirst(&q->tree); + return n ? rbtEntry(n, PrioQNode, node) : nullptr; +} + +PrioQNode* prioqPopMin(PrioQueue* q) +{ + PrioQNode* min = prioqPeekMin(q); + if (min) + rbtRemove(&q->tree, &min->node); + return min; +} + +void prioqRemove(PrioQueue* q, PrioQNode* n) +{ + rbtRemove(&q->tree, &n->node); +} + +usize prioqCount(const PrioQueue* q) +{ + return rbtCount(&q->tree); +} + +bool prioqIsEmpty(const PrioQueue* q) +{ + return rbtIsEmpty(&q->tree); +}