summaryrefslogtreecommitdiff
path: root/mld/strtab.c
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--mld/strtab.c56
1 files changed, 56 insertions, 0 deletions
diff --git a/mld/strtab.c b/mld/strtab.c
new file mode 100644
index 0000000..c31889b
--- /dev/null
+++ b/mld/strtab.c
@@ -0,0 +1,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;
+}