summaryrefslogtreecommitdiff
path: root/masm/strtbl.c
blob: b01bb925f8ef112d6fda921f23805e92126ccecd (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
#include <merror.h>
#include <string.h>
#include <stdlib.h>

#include "asm.h"

int strtbl_get_str(struct str_table *str_tbl, const char *str, size_t *res)
{
        for (size_t i = 0; i < str_tbl->size; i ++) {
                if (strcmp(str_tbl->ptr + i, str) == 0) {
                        if (res != NULL)
                                *res = i;
                        return M_SUCCESS;
                }
        }

        return M_ERROR;
}

int strtbl_write_str(struct str_table *str_tbl, const char *str, size_t *res)
{
        if (strtbl_get_str(str_tbl, str, res) == M_SUCCESS)
                return M_SUCCESS;

        size_t len = strlen(str);
        char *new = realloc(str_tbl->ptr, str_tbl->size + len + 1);
        if (new == NULL)
                return M_ERROR;
        str_tbl->ptr = new;
        memcpy(str_tbl->ptr + str_tbl->size, str, len + 1);

        if (res != NULL)
                *res = str_tbl->size;

        str_tbl->size += len + 1;
        return M_SUCCESS;
}

void strtbl_init(struct str_table *str_tbl)
{
        str_tbl->size = 1;
        str_tbl->ptr = malloc(1);
        *str_tbl->ptr = '\0';
}

void strtbl_free(struct str_table *str_tbl)
{
        free(str_tbl->ptr);
}