worktree: use 'worktree' over 'working tree'
[git/debian.git] / reftable / pq.c
blobefc474017a22d7e65e0aaa9fc78ded3ffc5075de
1 /*
2 Copyright 2020 Google LLC
4 Use of this source code is governed by a BSD-style
5 license that can be found in the LICENSE file or at
6 https://developers.google.com/open-source/licenses/bsd
7 */
9 #include "pq.h"
11 #include "reftable-record.h"
12 #include "system.h"
13 #include "basics.h"
15 int pq_less(struct pq_entry *a, struct pq_entry *b)
17 struct strbuf ak = STRBUF_INIT;
18 struct strbuf bk = STRBUF_INIT;
19 int cmp = 0;
20 reftable_record_key(&a->rec, &ak);
21 reftable_record_key(&b->rec, &bk);
23 cmp = strbuf_cmp(&ak, &bk);
25 strbuf_release(&ak);
26 strbuf_release(&bk);
28 if (cmp == 0)
29 return a->index > b->index;
31 return cmp < 0;
34 struct pq_entry merged_iter_pqueue_top(struct merged_iter_pqueue pq)
36 return pq.heap[0];
39 int merged_iter_pqueue_is_empty(struct merged_iter_pqueue pq)
41 return pq.len == 0;
44 struct pq_entry merged_iter_pqueue_remove(struct merged_iter_pqueue *pq)
46 int i = 0;
47 struct pq_entry e = pq->heap[0];
48 pq->heap[0] = pq->heap[pq->len - 1];
49 pq->len--;
51 i = 0;
52 while (i < pq->len) {
53 int min = i;
54 int j = 2 * i + 1;
55 int k = 2 * i + 2;
56 if (j < pq->len && pq_less(&pq->heap[j], &pq->heap[i])) {
57 min = j;
59 if (k < pq->len && pq_less(&pq->heap[k], &pq->heap[min])) {
60 min = k;
63 if (min == i) {
64 break;
67 SWAP(pq->heap[i], pq->heap[min]);
68 i = min;
71 return e;
74 void merged_iter_pqueue_add(struct merged_iter_pqueue *pq, struct pq_entry e)
76 int i = 0;
77 if (pq->len == pq->cap) {
78 pq->cap = 2 * pq->cap + 1;
79 pq->heap = reftable_realloc(pq->heap,
80 pq->cap * sizeof(struct pq_entry));
83 pq->heap[pq->len++] = e;
84 i = pq->len - 1;
85 while (i > 0) {
86 int j = (i - 1) / 2;
87 if (pq_less(&pq->heap[j], &pq->heap[i])) {
88 break;
91 SWAP(pq->heap[j], pq->heap[i]);
93 i = j;
97 void merged_iter_pqueue_release(struct merged_iter_pqueue *pq)
99 int i = 0;
100 for (i = 0; i < pq->len; i++) {
101 reftable_record_destroy(&pq->heap[i].rec);
103 FREE_AND_NULL(pq->heap);
104 pq->len = pq->cap = 0;