summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorSimon Glass <sjg@chromium.org>2023-01-17 10:47:14 -0700
committerTom Rini <trini@konsulko.com>2023-01-23 18:11:39 -0500
commit3e96ed44e8c5b63bd0cef1e263e7991ac16c21e3 (patch)
treeed9bae7e827fd7b3db39fe675b1c3c541e61e4ba /lib
parenta0fb9de60d2fe64107ebadc85e73000e84a963ea (diff)
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.c41
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);
+}