From 3e96ed44e8c5b63bd0cef1e263e7991ac16c21e3 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Tue, 17 Jan 2023 10:47:14 -0700 Subject: lib: Add a function to split a string into substrings Some environment variables provide a space-separated list of strings. It is easier to process these when they are broken out into an array of strings. Add a utility function to handle this. Signed-off-by: Simon Glass --- lib/strto.c | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'lib') diff --git a/lib/strto.c b/lib/strto.c index 6462d4fddf..154921165c 100644 --- a/lib/strto.c +++ b/lib/strto.c @@ -11,6 +11,7 @@ #include #include +#include #include /* from lib/kstrtox.c */ @@ -222,3 +223,43 @@ void str_to_upper(const char *in, char *out, size_t len) if (len) *out = '\0'; } + +const char **str_to_list(const char *instr) +{ + const char **ptr; + char *str, *p; + int count, i; + + /* don't allocate if the string is empty */ + str = *instr ? strdup(instr) : (char *)instr; + if (!str) + return NULL; + + /* count the number of space-separated strings */ + for (count = *str != '\0', p = str; *p; p++) { + if (*p == ' ') { + count++; + *p = '\0'; + } + } + + /* allocate the pointer array, allowing for a NULL terminator */ + ptr = calloc(count + 1, sizeof(char *)); + if (!ptr) { + if (*str) + free(str); + return NULL; + } + + for (i = 0, p = str; i < count; p += strlen(p) + 1, i++) + ptr[i] = p; + + return ptr; +} + +void str_free_list(const char **ptr) +{ + if (ptr) + free((char *)ptr[0]); + free(ptr); +} -- cgit v1.2.3