[PATCH 046/112] commands: time: refactor into new strjoin

Ahmad Fatoum a.fatoum at pengutronix.de
Wed Jan 3 10:12:06 PST 2024


time concatenates all its remaining arguments with a space in-between
and then passes that to the command executor. This can be useful
elsewhere as well, so factor it out into a new strjoin function.

No functional change.

Signed-off-by: Ahmad Fatoum <a.fatoum at pengutronix.de>
---
 commands/time.c  | 11 +----------
 include/string.h |  2 ++
 lib/string.c     | 23 +++++++++++++++++++++++
 3 files changed, 26 insertions(+), 10 deletions(-)

diff --git a/commands/time.c b/commands/time.c
index 5b8933ea6553..336128f6a9be 100644
--- a/commands/time.c
+++ b/commands/time.c
@@ -12,26 +12,17 @@ static int do_time(int argc, char *argv[])
 	unsigned char *buf;
 	u64 start, end, diff64;
 	bool nanoseconds = false;
-	int len = 1; /* '\0' */
 
 	if (argc < 2)
 		return COMMAND_ERROR_USAGE;
 
-	for (i = 1; i < argc; i++)
-		len += strlen(argv[i]) + 1;
-
-	buf = xzalloc(len);
-
 	i = 1;
 	if (!strcmp(argv[i], "-n")) {
 		nanoseconds = true;
 		i++;
 	}
 
-	for (; i < argc; i++) {
-		strcat(buf, argv[i]);
-		strcat(buf, " ");
-	}
+	buf = strjoin(" ", &argv[i], argc - i);
 
 	start = get_time_ns();
 
diff --git a/include/string.h b/include/string.h
index 71810180b5ba..2f2af85b554f 100644
--- a/include/string.h
+++ b/include/string.h
@@ -21,6 +21,8 @@ char *parse_assignment(char *str);
 
 int strverscmp(const char *a, const char *b);
 
+char *strjoin(const char *separator, char **array, size_t len);
+
 static inline int strcmp_ptr(const char *a, const char *b)
 {
 	return a && b ? strcmp(a, b) : compare3(a, b);
diff --git a/lib/string.c b/lib/string.c
index bf0f0455ab3f..d8e5edd40648 100644
--- a/lib/string.c
+++ b/lib/string.c
@@ -1000,3 +1000,26 @@ char *parse_assignment(char *str)
 
 	return value;
 }
+
+char *strjoin(const char *separator, char **arr, size_t arrlen)
+{
+	size_t separatorlen;
+	int len = 1; /* '\0' */
+	char *buf;
+	int i;
+
+	separatorlen = strlen(separator);
+
+	for (i = 0; i < arrlen; i++)
+		len += strlen(arr[i]) + separatorlen;
+
+	buf = xzalloc(len);
+
+	for (i = 0; i < arrlen; i++) {
+		strcat(buf, arr[i]);
+		strcat(buf, separator);
+	}
+
+	return buf;
+}
+EXPORT_SYMBOL(strjoin);
-- 
2.39.2




More information about the barebox mailing list