Added string vector(argv like) functions

This commit is contained in:
Nils O. Selåsdal
2013-09-04 18:10:26 +02:00
parent a5b8d53177
commit 216dfe879d
4 changed files with 291 additions and 1 deletions
+107
View File
@@ -0,0 +1,107 @@
#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) {
rc = uc_strv_grow(strv, 1);
}
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;
strv->cnt++;
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;
}