aboutsummaryrefslogtreecommitdiff
path: root/util.c
diff options
context:
space:
mode:
Diffstat (limited to 'util.c')
-rw-r--r--util.c53
1 files changed, 53 insertions, 0 deletions
diff --git a/util.c b/util.c
index ccc8c19..d07899f 100644
--- a/util.c
+++ b/util.c
@@ -1,5 +1,58 @@
+#include <stdlib.h>
+#include <string.h>
#include "util.h"
+struct string_list *string_split(const char *string, char delim) {
+ const char *loc = string;
+ int size = 2; /* rest of string, NULL terminator */
+ int index = 0;
+ char delims[2] = {0};
+ char *saveptr = NULL;
+ struct string_list *list = calloc(1, sizeof(struct string_list));
+
+ if (!list)
+ goto finish;
+
+ list->source = strdup(string);
+ if (!list->source)
+ goto finish;
+
+ while((loc = strchr(loc, delim))) {
+ size++;
+ while (*loc && *loc == delim) loc++;
+ }
+
+ list->list = calloc(size, sizeof(char *));
+ if (!list->list)
+ goto finish;
+
+ delims[0] = delim;
+
+ while((loc = strtok_r(index == 0 ? list->source : NULL, delims, &saveptr))) {
+ list->list[index++] = loc;
+ if (index >= size)
+ break;
+ }
+
+finish:
+ return list;
+}
+
+void string_list_free(struct string_list *list) {
+ if (list) {
+ if (list->list) {
+ free(list->list);
+ list->list = NULL;
+ }
+ if (list->source) {
+ free(list->source);
+ list->source = NULL;
+ }
+
+ free(list);
+ }
+}
+
void string_truncate(char *string, size_t max_len) {
size_t len = strlen(string) + 1;
if (len <= max_len) return;