133 lines
2.1 KiB
C
133 lines
2.1 KiB
C
#include <string.h>
|
|
#include <stdlib.h>
|
|
#include "ucore/strvec.h"
|
|
|
|
void uc_strv_init(struct UCStrv *strv)
|
|
{
|
|
strv->cnt = 0;
|
|
strv->allocated = 0;
|
|
strv->strings = NULL;
|
|
}
|
|
|
|
int uc_strv_grow(struct UCStrv *strv, size_t cnt)
|
|
{
|
|
|
|
size_t allocate = strv->allocated + cnt;
|
|
void *tmp = realloc(strv->strings, sizeof *strv->strings * allocate);
|
|
|
|
if (tmp == NULL) {
|
|
return -1;
|
|
}
|
|
strv->strings = tmp;
|
|
strv->allocated = allocate;
|
|
|
|
return 0;
|
|
}
|
|
|
|
int uc_strv_expand(struct UCStrv *strv)
|
|
{
|
|
int rc = 0;
|
|
|
|
if (strv->cnt >= strv->allocated) {
|
|
//make some extra room
|
|
rc = uc_strv_grow(strv, 4);
|
|
}
|
|
|
|
return rc;
|
|
}
|
|
|
|
int uc_strv_append(struct UCStrv *strv, const char *str)
|
|
{
|
|
int rc;
|
|
char *dup;
|
|
|
|
rc = uc_strv_expand(strv);
|
|
if (rc != 0) {
|
|
return rc;
|
|
}
|
|
|
|
dup = strdup(str);
|
|
if (dup == NULL) {
|
|
return -2;
|
|
}
|
|
|
|
strv->strings[strv->cnt] = dup;
|
|
strv->cnt++;
|
|
|
|
return 0;
|
|
}
|
|
|
|
int uc_strv_append_nocopy(struct UCStrv *strv, char *str)
|
|
{
|
|
int rc;
|
|
rc = uc_strv_expand(strv);
|
|
|
|
if (rc != 0) {
|
|
return rc;
|
|
}
|
|
|
|
strv->strings[strv->cnt] = str;
|
|
strv->cnt++;
|
|
|
|
return 0;
|
|
}
|
|
|
|
int uc_strv_null_terminate(struct UCStrv *strv)
|
|
{
|
|
int rc;
|
|
|
|
rc = uc_strv_expand(strv);
|
|
if (rc != 0) {
|
|
return rc;
|
|
}
|
|
|
|
strv->strings[strv->cnt] = NULL;
|
|
|
|
return 0;
|
|
}
|
|
|
|
void uc_strv_clear(struct UCStrv *strv)
|
|
{
|
|
size_t i;
|
|
|
|
for (i = 0; i < strv->cnt; i++) {
|
|
free(strv->strings[i]);
|
|
strv->strings[i] = NULL;
|
|
}
|
|
|
|
strv->cnt = 0;
|
|
}
|
|
|
|
void uc_strv_destroy(struct UCStrv *strv)
|
|
{
|
|
uc_strv_clear(strv);
|
|
free(strv->strings);
|
|
strv->strings = NULL;
|
|
}
|
|
|
|
int uc_strv_append_all(struct UCStrv *a, struct UCStrv *b, int copy)
|
|
{
|
|
size_t i;
|
|
int rc;
|
|
|
|
rc = uc_strv_grow(a, a->allocated + b->cnt);
|
|
if (rc != 0) {
|
|
return rc;
|
|
}
|
|
|
|
for (i = 0; i < b->cnt; i++) {
|
|
if (copy) {
|
|
rc = uc_strv_append(a, b->strings[i]);
|
|
} else {
|
|
rc = uc_strv_append_nocopy(a, b->strings[i]);
|
|
}
|
|
|
|
if (rc != 0) {
|
|
return rc;
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|