summaryrefslogtreecommitdiffstats
path: root/lib/libdvec/src/test.c
blob: af0ee241a75e387153334ae0163124f1911c291f (plain) (blame)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "allocator.h"
#include "dvec.h"

#include <err.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static const char *dvec_err[] = {
	DVEC_STRERR_INIT
};

bool
str_sort_order(const void *p1, const void *p2, const void *user)
{
	const char *s1 = *(const char **)p1;
	const char *s2 = *(const char **)p2;

	return strcmp(s1, s2) <= 0;
}

int
str_search(const void *p, const void *user)
{
	const char *str = *(const char **)p, *cmp = user;

	return strcmp(cmp, str);
}

int
main(int argc, const char **argv)
{
	struct dvec dvec, *fused;
	ssize_t below, above, on;
	const char **val, *tmp;
	int i, rc;

	rc = dvec_init(&dvec, sizeof(const char *), 16, &stdlib_heap_allocator);
	if (rc) DVEC_ERR(dvec_err, rc);

	for (i = 1; i < argc; i++) {
		rc = dvec_add_back(&dvec, 1);
		if (rc) DVEC_ERR(dvec_err, rc);
		val = dvec_back(&dvec);
		*val = argv[i];
	}

	rc = dvec_quick_sort_ex(&dvec, &stdlib_heap_allocator, &tmp,
		false, str_sort_order, NULL);
	if (rc < 0) DVEC_ERR(dvec_err, rc);

	on = dvec_binary_search(&dvec, str_search, "abc", &below, &above);

	for (DVEC_ITER(&dvec, val))
		printf("%s\n", *val);

	printf("dvec len: %lu\n", dvec.len);

	printf("\n");
	printf("below: %li\n", below);
	printf("on: %li\n", on);
	printf("above: %li\n", above);
	printf("\n");

	fused = dvec_alloc_fused(sizeof(const char *), 0,
		&stdlib_heap_allocator, &rc);
	if (!fused) DVEC_ERR(dvec_err, rc);

	printf("fused: %p %p (+%li)\n", (void *) fused,
		fused->data, fused->data - (uint8_t *) fused);

	rc = dvec_free(fused);
	if (rc) DVEC_ERR(dvec_err, rc);

	dvec_deinit(&dvec);
}