#ifndef STRARR_H #define STRARR_H #include #include #include typedef struct strarr { char *data; /* the underlying data */ size_t len; /* the amount of string entries */ size_t used; /* the total bytes used of the capacity for the strings, incl NULL */ size_t cap; /* the total bytes allocated to the buffer, incl NULL */ } strarr; void strarr_init_empty(strarr *sa, size_t cap) { sa->len = 0; sa->used = 0; sa->cap = cap; sa->data = (char*) malloc(cap); } void strarr_init_from_str_split(strarr *sa, const char *str, char del) { size_t len = strlen(str); char* data = (char*) malloc(len + 1); /* include the NULL terminator */ sa->data = data; sa->cap = len + 1; memcpy(sa->data, str, len); /* There are at minimum one entries. */ sa->len = 1; /* Swap all `del` for '\0'. */ for (size_t i = 0; i < sa->cap; ++i) { if (sa->data[i] == del) { sa->data[i] = '\0'; sa->len++; } } } /* Copy string into strarr, appending it in the process. */ void strarr_app(strarr *sa, char *str) { size_t len = strlen(str); strcpy(&sa->data[sa->used], str); sa->len++; sa->used += len; sa->cap += len; } #endif