summaryrefslogtreecommitdiffstats
path: root/src/mergesort.c
blob: 2562d9d4f8455d7520035c8f6f00385f0a8cdca9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* SPDX-License-Identifier: LGPL-2.1-only */

/* Copyright (C) 2020 Gediminas Jakutis */

#include <errno.h>
#include <stdlib.h>
#include "defs.h"
#include "mergesort.h"

int merge(struct stream * const dest, struct stream * const A, struct stream * const B)
{
	int ret;
	struct entry_l *a;
	struct entry_l *b;

	try(A->parent != B->parent, err, EINVAL, "cannot merge blocks: uncommon parent!");

	a = get(A);
	b = get(B);

	while (a || b) {
		if (a && (!b || a->val <= b->val)) {
			put(dest, a);
			a = get(A);
		} else {
			put(dest, b);
			b = get(B);
		}
	}

err:
	return ret;
}