diff options
author | Simon Glass <sjg@chromium.org> | 2023-01-17 20:47:14 +0300 |
---|---|---|
committer | Tom Rini <trini@konsulko.com> | 2023-01-24 02:11:39 +0300 |
commit | 3e96ed44e8c5b63bd0cef1e263e7991ac16c21e3 (patch) | |
tree | ed9bae7e827fd7b3db39fe675b1c3c541e61e4ba /lib | |
parent | a0fb9de60d2fe64107ebadc85e73000e84a963ea (diff) | |
download | u-boot-3e96ed44e8c5b63bd0cef1e263e7991ac16c21e3.tar.xz |
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 <sjg@chromium.org>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/strto.c | 41 |
1 files changed, 41 insertions, 0 deletions
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 <common.h> #include <errno.h> +#include <malloc.h> #include <linux/ctype.h> /* 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); +} |