From 2be61ba91bdbdfc60f0e2fc7f1f9f525ad13ab9e Mon Sep 17 00:00:00 2001 From: Panu Matilainen Date: Mon, 18 Feb 2013 10:44:40 +0200 Subject: [PATCH] A non-naive implementation of argvJoin() - The previous version was as naive as they get, for reasonable behavior with non-trivial amount of data precalculating string lengths and allocating at one go is necessary. (cherry picked from commit 11ba21e2ab67f14ad349252cfb890006a112867f) --- rpmio/argv.c | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/rpmio/argv.c b/rpmio/argv.c index f061f03..3508a9f 100644 --- a/rpmio/argv.c +++ b/rpmio/argv.c @@ -213,12 +213,32 @@ int argvSplit(ARGV_t * argvp, const char * str, const char * seps) char *argvJoin(ARGV_const_t argv, const char *sep) { + int argc = 0; + size_t argvlen = 0; char *dest = NULL; - char * const *arg; - for (arg = argv; arg && *arg; arg++) { - rstrscat(&dest, *arg, *(arg+1) ? sep : "", NULL); - } + if (argv) { + ARGV_const_t arg; + for (arg = argv; *arg; arg++) + argvlen += strlen(*arg); + argc = arg - argv; + } + + if (argc > 0) { + size_t seplen = (sep != NULL) ? strlen(sep) : 0; + char *p; + + dest = xmalloc(argvlen + (seplen * (argc - 1)) + 1); + + p = stpcpy(dest, argv[0]); + for (int i = 1; i < argc; i++) { + if (seplen) + p = stpcpy(p, sep); + p = stpcpy(p, argv[i]); + } + *p = '\0'; + } + return dest; } -- 2.7.4