diff options
author | George Abbott <george@gabbott.dev> | 2023-12-25 19:38:14 +0000 |
---|---|---|
committer | George Abbott <george@gabbott.dev> | 2023-12-25 19:38:14 +0000 |
commit | e88dbc79302eeba614488c9c5cbc6b00fe66df4e (patch) | |
tree | 6311cb19e3ed22ee194a0cb0a38ca4ee70d1b565 |
Added initial code
-rw-r--r-- | strarr.h | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/strarr.h b/strarr.h new file mode 100644 index 0000000..69ae4a4 --- /dev/null +++ b/strarr.h @@ -0,0 +1,64 @@ +#ifndef STRARR_H +#define STRARR_H +#include <stddef.h> +#include <string.h> +#include <stdlib.h> + + +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 |