summaryrefslogtreecommitdiff
path: root/mld/strtab.c
blob: c31889b36fdae7f9052fcd90da0aa47e09826066 (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
#include <merror.h>
#include <stdlib.h>

#include "link.h"

int strtab_init(struct string_table *strtab)
{
	strtab->len = 1;
	strtab->data = malloc(1);

	if (strtab->data == NULL) {
		PERROR("cannot alloc");
		return M_ERROR;
	}

	strtab->data[0] = '\0';
	return M_SUCCESS;
}

void strtab_free(struct string_table *strtab)
{
	free(strtab->data);
}

int strtab_push(struct string_table *strtab, const char *str, size_t *res)
{
	if (strtab_get(strtab, str, res) == M_SUCCESS)
		return M_SUCCESS;

	size_t len = strlen(str);
	char *new = realloc(strtab->data, strtab->len + len + 1);
	if (new == NULL) {
		PERROR("cannot realloc");
		return M_ERROR;
	}
	strtab->data = new;
	memcpy(strtab->data + strtab->len, str, len + 1);

	if (res != NULL)
		*res = strtab->len;
	strtab->len += len + 1;

	return M_SUCCESS;
}

int strtab_get(struct string_table *strtab, const char *str, size_t *res)
{
	for (size_t i = 0; i < strtab->len; i++) {
		if (strcmp(strtab->data + i, str) == 0) {
			if (res != NULL)
				*res = i;
			return M_SUCCESS;
		}
	}
	return M_ERROR;
}