str_talloc: make strjoin much more efficient.
authorRusty Russell <rusty@rustcorp.com.au>
Tue, 19 Apr 2011 10:53:59 +0000 (20:23 +0930)
committerRusty Russell <rusty@rustcorp.com.au>
Tue, 19 Apr 2011 11:00:08 +0000 (20:30 +0930)
Inspired by patch from Volker.

ccan/str_talloc/str_talloc.c

index 3bcb1f2a9cf3f7836603bfa9cbed7524f98c87ff..88e02ef2edfc58bab2a33c1abad4b9000a19fc61 100644 (file)
@@ -38,11 +38,17 @@ char *strjoin(const void *ctx, char *strings[], const char *delim)
 {
        unsigned int i;
        char *ret = talloc_strdup(ctx, "");
+       size_t totlen = 0, dlen = strlen(delim);
 
        for (i = 0; strings[i]; i++) {
-               ret = talloc_append_string(ret, strings[i]);
-               ret = talloc_append_string(ret, delim);
+               size_t len = strlen(strings[i]);
+               ret = talloc_realloc(ctx, ret, char, totlen + len + dlen + 1);
+               memcpy(ret + totlen, strings[i], len);
+               totlen += len;
+               memcpy(ret + totlen, delim, dlen);
+               totlen += dlen;
        }
+       ret[totlen] = '\0';
        return ret;
 }