add printf-like primitive to the buffers.
[apps/madmutt.git] / lib-lib / buffer.c
index f186bfd..71f31b4 100644 (file)
 
 #include "lib-lib.h"
 
+#define BUFSIZ_INCREMENT  1024
+
+void buffer_resize(buffer_t *buf, ssize_t newsize)
+{
+    if (newsize >= buf->size) {
+        /* rounds newsize to the 1024 multiple just after newsize+1 */
+        newsize = (newsize + BUFSIZ_INCREMENT) & ~(BUFSIZ_INCREMENT - 1);
+        p_realloc(&buf->data, newsize);
+    }
+}
+
+
+
+
+/****** LEGACY BUFFERS *******/
+
 /*
  * Creates and initializes a BUFFER*. If passed an existing BUFFER*,
  * just initializes. Frees anything already in the buffer.
@@ -91,3 +107,33 @@ void mutt_buffer_add(BUFFER *buf, const char *s, ssize_t len)
     *buf->dptr = '\0';
 }
 
+ssize_t buffer_addvf(buffer_t *buf, const char *fmt, va_list args)
+{
+    ssize_t len;
+    va_list ap;
+
+    va_copy(ap, args);
+    buffer_ensure(buf, BUFSIZ);
+
+    len = vsnprintf(buf->data + buf->len, buf->size - buf->len, fmt, args);
+    if (len < 0) {
+        len = 0;
+    }
+    if (len >= buf->size - buf->len) {
+        buffer_ensure(buf, len);
+        vsnprintf(buf->data + buf->len, buf->size - buf->len, fmt, ap);
+    }
+    buf->len += len;
+    buf->data[buf->len] = '\0';
+
+    return len;
+}
+
+ssize_t buffer_addf(buffer_t *buf, const char *fmt, ...) {
+    ssize_t res;
+    va_list args;
+    va_start(args, fmt);
+    res = buffer_addvf(buf, fmt, args);
+    va_end(args);
+    return res;
+}