From: Michael Tremer Date: Fri, 23 Apr 2021 14:14:50 +0000 (+0000) Subject: util: Commit forgotten pakfire_string_join function X-Git-Tag: 0.9.28~1285^2~252 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=b03e11277c49a6c0da4fcf14c5abefc043f3fb5b;p=pakfire.git util: Commit forgotten pakfire_string_join function Signed-off-by: Michael Tremer --- diff --git a/src/libpakfire/util.c b/src/libpakfire/util.c index 4b9e06e73..02a0047a8 100644 --- a/src/libpakfire/util.c +++ b/src/libpakfire/util.c @@ -226,6 +226,55 @@ char** pakfire_split_string(const char* s, char delim) { return ret; } +char* pakfire_string_join(char** list, const char* delim) { + if (!list) + return NULL; + + size_t length = 0; + unsigned int elements = 0; + + // Count the number of elements and the total length + for (char** item = list; *item; item++) { + length += strlen(*item); + elements++; + } + + // Empty list? + if (!elements) + return NULL; + + // Add the delimiters + length += strlen(delim) * (elements - 1); + + // Allocate the result string + char* string = malloc(length + 1); + if (!string) + return NULL; + + // Pointer to where we are writing + char* p = string; + + size_t bytes_left = length; + size_t bytes_written; + + for (char** item = list; *item; item++) { + bytes_written = snprintf(p, bytes_left, "%s", *item); + + bytes_left -= bytes_written; + p += bytes_written; + + // Write the delimiter + if (bytes_left) { + bytes_written = snprintf(p, bytes_left, "%s", delim); + + bytes_left -= bytes_written; + p += bytes_written; + } + } + + return string; +} + int pakfire_format_size(char* dst, size_t length, double value) { const char* units[] = { "%4.0f ",