Relicence all source and header files included in LGPL code
[lttng-tools.git] / src / common / string-utils / string-utils.cpp
index 3051644f34adf1a77853a7c63e2d3096318b6ff0..8e6a76adc4ca097940a8d4c1600357dee4e86353 100644 (file)
@@ -1,15 +1,19 @@
 /*
  * Copyright (C) 2017 Philippe Proulx <pproulx@efficios.com>
  *
- * SPDX-License-Identifier: GPL-2.0-only
+ * SPDX-License-Identifier: LGPL-2.1-only
  *
  */
 
 #define _LGPL_SOURCE
 #include <stdlib.h>
+#include <stdio.h>
 #include <string.h>
 #include <stdbool.h>
 #include <type_traits>
+#include <assert.h>
+#include <errno.h>
+#include <stdarg.h>
 
 #include "string-utils.h"
 #include "../macros.h"
@@ -373,3 +377,69 @@ size_t strutils_array_of_strings_len(char * const *array)
 
        return count;
 }
+
+int strutils_append_str(char **s, const char *append)
+{
+       char *old = *s;
+       char *new_str;
+       size_t oldlen = (old == NULL) ? 0 : strlen(old);
+       size_t appendlen = strlen(append);
+
+       new_str = (char *) zmalloc(oldlen + appendlen + 1);
+       if (!new_str) {
+               return -ENOMEM;
+       }
+       if (oldlen) {
+               strcpy(new_str, old);
+       }
+       strcat(new_str, append);
+       *s = new_str;
+       free(old);
+       return 0;
+}
+
+int strutils_appendf(char **s, const char *fmt, ...)
+{
+       char *new_str;
+       size_t oldlen = (*s) ? strlen(*s) : 0;
+       int ret;
+       va_list args;
+
+       /* Compute length of formatted string we append. */
+       va_start(args, fmt);
+       ret = vsnprintf(NULL, 0, fmt, args);
+       va_end(args);
+
+       if (ret == -1) {
+               goto end;
+       }
+
+       /* Allocate space for old string + new string + \0. */
+       new_str = (char *) zmalloc(oldlen + ret + 1);
+       if (!new_str) {
+               ret = -ENOMEM;
+               goto end;
+       }
+
+       /* Copy old string, if there was one. */
+       if (oldlen) {
+               strcpy(new_str, *s);
+       }
+
+       /* Format new string in-place. */
+       va_start(args, fmt);
+       ret = vsprintf(&new_str[oldlen], fmt, args); 
+       va_end(args);
+
+       if (ret == -1) {
+               ret = -1;
+               goto end;
+       }
+
+       free(*s);
+       *s = new_str;
+       new_str = NULL;
+
+end:
+       return ret;
+}
This page took 0.023825 seconds and 4 git commands to generate.