]> git.ipfire.org Git - thirdparty/git.git/blame - reftable/pq.c
Merge branch 'ps/reftable-iteration-perf-part2'
[thirdparty/git.git] / reftable / pq.c
CommitLineData
3b34f636
HWN
1/*
2Copyright 2020 Google LLC
3
4Use of this source code is governed by a BSD-style
5license that can be found in the LICENSE file or at
6https://developers.google.com/open-source/licenses/bsd
7*/
8
9#include "pq.h"
10
11#include "reftable-record.h"
12#include "system.h"
13#include "basics.h"
14
15int pq_less(struct pq_entry *a, struct pq_entry *b)
16{
bb2d6be4 17 int cmp = reftable_record_cmp(a->rec, b->rec);
3b34f636
HWN
18 if (cmp == 0)
19 return a->index > b->index;
3b34f636
HWN
20 return cmp < 0;
21}
22
3b34f636
HWN
23struct pq_entry merged_iter_pqueue_remove(struct merged_iter_pqueue *pq)
24{
25 int i = 0;
26 struct pq_entry e = pq->heap[0];
27 pq->heap[0] = pq->heap[pq->len - 1];
28 pq->len--;
29
30 i = 0;
31 while (i < pq->len) {
32 int min = i;
33 int j = 2 * i + 1;
34 int k = 2 * i + 2;
35 if (j < pq->len && pq_less(&pq->heap[j], &pq->heap[i])) {
36 min = j;
37 }
38 if (k < pq->len && pq_less(&pq->heap[k], &pq->heap[min])) {
39 min = k;
40 }
41
42 if (min == i) {
43 break;
44 }
45
46 SWAP(pq->heap[i], pq->heap[min]);
47 i = min;
48 }
49
50 return e;
51}
52
c18eecbe 53void merged_iter_pqueue_add(struct merged_iter_pqueue *pq, const struct pq_entry *e)
3b34f636
HWN
54{
55 int i = 0;
66c0daba 56
f6b58c1b 57 REFTABLE_ALLOC_GROW(pq->heap, pq->len + 1, pq->cap);
c18eecbe 58 pq->heap[pq->len++] = *e;
f6b58c1b 59
3b34f636
HWN
60 i = pq->len - 1;
61 while (i > 0) {
62 int j = (i - 1) / 2;
63 if (pq_less(&pq->heap[j], &pq->heap[i])) {
64 break;
65 }
66
67 SWAP(pq->heap[j], pq->heap[i]);
68
69 i = j;
70 }
71}
72
73void merged_iter_pqueue_release(struct merged_iter_pqueue *pq)
74{
3b34f636 75 FREE_AND_NULL(pq->heap);
bb2d6be4 76 memset(pq, 0, sizeof(*pq));
3b34f636 77}