56 lines
1 KiB
C
56 lines
1 KiB
C
#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;
|
|
}
|