[PATCH 3/6] string: reduce strjoin runtime, drop trailing separator

Ahmad Fatoum a.fatoum at pengutronix.de
Tue Oct 25 23:42:02 PDT 2022


The implementation of strjoin is a bit suboptimal. The destination
string is traversed from the beginning due to strcat and we have a
left-over separator at the end, while it should only be in-between.

Fix this.

Signed-off-by: Ahmad Fatoum <a.fatoum at pengutronix.de>
---
 include/string.h |  1 +
 lib/string.c     | 15 +++++++++++----
 2 files changed, 12 insertions(+), 4 deletions(-)

diff --git a/include/string.h b/include/string.h
index 2cc727fd1d7a..596440ca8164 100644
--- a/include/string.h
+++ b/include/string.h
@@ -4,6 +4,7 @@
 
 #include <linux/string.h>
 
+void *mempcpy(void *dest, const void *src, size_t count);
 int strtobool(const char *str, int *val);
 char *strsep_unescaped(char **, const char *);
 char *stpcpy(char *dest, const char *src);
diff --git a/lib/string.c b/lib/string.c
index a500e8a3d1ba..edd36da4d4f2 100644
--- a/lib/string.c
+++ b/lib/string.c
@@ -603,6 +603,11 @@ void *__memcpy(void * dest, const void *src, size_t count)
 	__alias(__default_memcpy);
 #endif
 
+void *mempcpy(void *dest, const void *src, size_t count)
+{
+	return memcpy(dest, src, count) + count;
+}
+EXPORT_SYMBOL(mempcpy);
 
 #ifndef __HAVE_ARCH_MEMMOVE
 /**
@@ -943,7 +948,7 @@ char *strjoin(const char *separator, char **arr, size_t arrlen)
 {
 	size_t separatorlen;
 	int len = 1; /* '\0' */
-	char *buf;
+	char *buf, *p;
 	int i;
 
 	separatorlen = strlen(separator);
@@ -951,12 +956,14 @@ char *strjoin(const char *separator, char **arr, size_t arrlen)
 	for (i = 0; i < arrlen; i++)
 		len += strlen(arr[i]) + separatorlen;
 
-	buf = xzalloc(len);
+	p = buf = xmalloc(len);
 
 	for (i = 0; i < arrlen; i++) {
-		strcat(buf, arr[i]);
-		strcat(buf, separator);
+		p = stpcpy(p, arr[i]);
+		p = mempcpy(p, separator, separatorlen);
 	}
 
+	p[-separatorlen] = '\0';
+
 	return buf;
 }
-- 
2.30.2




More information about the barebox mailing list