summaryrefslogtreecommitdiff
path: root/tests/str_table.c
blob: e185cec4cf435f1729b91b5b12a285f7f7cc8054 (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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * str_table.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "config.h"

#include "str_table.h"
#include "compat.h"
#include "test.h"

static char *strings[1000];

static int read_strings(void)
{
	ssize_t ret;
	char *line;
	size_t n;
	FILE *fp;
	int i;

	fp = test_open_read("words.txt");

	for (i = 0; i < 1000; ++i) {
		line = NULL;
		n = 0;

		ret = getline(&line, &n, fp);
		if (ret < 0) {
			perror("reading words");
			goto fail;
		}

		strings[i] = line;
	}

	fclose(fp);
	return 0;
fail:
	for (i = 0; i < 1000; ++i)
		free(strings[i]);
	fclose(fp);
	return -1;
}

int main(void)
{
	str_table_t table;
	size_t i, j, idx;
	const char *str;

	TEST_ASSERT(chdir(TEST_PATH) == 0);

	if (read_strings())
		return EXIT_FAILURE;

	TEST_ASSERT(str_table_init(&table, 64) == 0);

	for (i = 0; i < 1000; ++i) {
		TEST_ASSERT(str_table_get_index(&table, strings[i], &idx) == 0);

		TEST_EQUAL_UI(idx, i);

		for (j = 0; j <= i; ++j) {
			str = str_table_get_string(&table, j);

			TEST_NOT_NULL(str);
			TEST_ASSERT(str != strings[i]);
			TEST_STR_EQUAL(str, strings[j]);
		}

		for (; j < 1000; ++j)
			TEST_NULL(str_table_get_string(&table, j));
	}

	for (i = 0; i < 1000; ++i) {
		TEST_ASSERT(str_table_get_index(&table, strings[i], &idx) == 0);
		TEST_EQUAL_UI(idx, i);

		str = str_table_get_string(&table, i);

		TEST_NOT_NULL(str);
		TEST_ASSERT(str != strings[i]);
		TEST_STR_EQUAL(str, strings[i]);
	}

	str_table_cleanup(&table);

	for (i = 0; i < 1000; ++i)
		free(strings[i]);

	return EXIT_SUCCESS;
}