]> git.ipfire.org Git - pakfire.git/commitdiff
util: Commit forgotten pakfire_string_join function
authorMichael Tremer <michael.tremer@ipfire.org>
Fri, 23 Apr 2021 14:14:50 +0000 (14:14 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Fri, 23 Apr 2021 14:14:50 +0000 (14:14 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/libpakfire/util.c

index 4b9e06e73d9ce667d8933db51d92ae2a49247148..02a0047a8e8277405906b09aaa575df64794a381 100644 (file)
@@ -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 ",