[1/3] Add generic function to concatenate multiple strings

Message ID 20181203104307.19883-1-sbabic@denx.de
State New
Headers show
Series
  • [1/3] Add generic function to concatenate multiple strings
Related show

Commit Message

Stefano Babic Dec. 3, 2018, 10:43 a.m.
Signed-off-by: Stefano Babic <sbabic@denx.de>
---
 core/util.c    | 36 ++++++++++++++++++++++++++++++++++++
 include/util.h |  1 +
 2 files changed, 37 insertions(+)

Patch

diff --git a/core/util.c b/core/util.c
index 3ad0fd0..00d53e8 100644
--- a/core/util.c
+++ b/core/util.c
@@ -134,6 +134,42 @@  void freeargs (char **argv)
 	}
 }
 
+/*
+ * Concatente array of strings in a single string
+ * The allocated string must be freed by the caller
+ * delim can be used to separate substrings
+ */
+char *mstrcat(const char **nodes, const char *delim)
+{
+	const char **node;
+	char *dest = NULL, *buf = NULL;
+
+	if (!delim)
+		delim = "";
+	for (node = nodes; *node != NULL; node++) {
+		/* first run, just copy first entry */
+		if (!dest) {
+			dest = strdup(*node);
+			if (!dest)
+				return NULL;
+		} else {
+			if (asprintf(&buf, "%s%s%s", dest, delim, *node) ==
+				ENOMEM_ASPRINTF) {
+				ERROR("Path too long, OOM");
+				free(dest);
+				return NULL;
+			}
+
+			/*
+			 * Free previous concatenated string
+			 */
+			free(dest);
+			dest = buf;
+		}
+	}
+	return dest;
+}
+
 int openfileoutput(const char *filename)
 {
 	int fdout;
diff --git a/include/util.h b/include/util.h
index faf8aec..f09795a 100644
--- a/include/util.h
+++ b/include/util.h
@@ -172,6 +172,7 @@  void notify_init(void);
 int syslog_init(void);
 
 char **splitargs(char *args, int *argc);
+char *mstrcat(const char **nodes, const char *delim);
 char** string_split(const char* a_str, const char a_delim);
 void freeargs (char **argv);
 int get_hw_revision(struct hw_type *hw);