This patch adds a function which realloc()s a string and prints to the end of
it. Useful for building up strings when you don't know how large a buffer to
allocate beforehand.
I've also added the format(printf) __attribute__ to this and the other *printf
functions.
- Andrew
diff --git a/src/include/gnunet_common.h b/src/include/gnunet_common.h
index 2a0ca33..ada13f6 100644
--- a/src/include/gnunet_common.h
+++ b/src/include/gnunet_common.h
@@ -826,9 +826,21 @@ GNUNET_ntoh_double (double d);
* @param ... data for format string
* @return number of bytes written to buf or negative value on error
*/
-int
+int __attribute__((format (printf, 3, 4)))
GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
+/**
+ * @ingroup memory
+ * Append to the end of a string. realloc()s its argument to be large enough
+ * to fit the complete string and aborts if insufficient memory.
+ *
+ * @param buf pointer to the string to append to
+ * @param format format string
+ * @param ... data for format string
+ * @return number of bytes writter to end of string excluding 0-terminator.
+ */
+int __attribute__((format (printf, 2, 3)))
+GNUNET_append_sprintf (char **buf, const char *format, ...);
/**
* @ingroup memory
@@ -839,7 +851,7 @@ GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
* @param ... data for format string
* @return number of bytes in "*buf" excluding 0-termination
*/
-int
+int __attribute__((format (printf, 2, 3)))
GNUNET_asprintf (char **buf, const char *format, ...);
diff --git a/src/util/common_allocation.c b/src/util/common_allocation.c
index b547367..156774f 100644
--- a/src/util/common_allocation.c
+++ b/src/util/common_allocation.c
@@ -342,6 +342,39 @@ GNUNET_xgrow_ (void **old, size_t elementSize, unsigned int *oldCount,
*oldCount = newCount;
}
+/**
+ * @ingroup memory
+ * Append to the end of a string. realloc()s its argument to be large enough
+ * to fit the complete string and aborts if insufficient memory.
+ *
+ * @param buf pointer to the string to append to
+ * @param format format string
+ * @param ... data for format string
+ * @return number of bytes writter to end of string excluding 0-terminator.
+ */
+int
+GNUNET_append_sprintf (char **buf, const char *format, ...)
+{
+ int ret;
+ int len;
+ va_list args;
+
+ if (*buf)
+ len = strlen(*buf);
+ else
+ len = 0;
+
+ va_start (args, format);
+ ret = VSNPRINTF (NULL, 0, format, args);
+ va_end (args);
+
+ *buf = GNUNET_realloc (*buf, len + ret + 1);
+ va_start (args, format);
+ VSNPRINTF (*buf + len, ret, format, args);
+ va_end (args);
+
+ return ret;
+}
/**
* Like asprintf, just portable.
_______________________________________________
GNUnet-developers mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/gnunet-developers