summaryrefslogtreecommitdiffstats
path: root/membuffer.c
diff options
context:
space:
mode:
Diffstat (limited to 'membuffer.c')
-rw-r--r--membuffer.c59
1 files changed, 57 insertions, 2 deletions
diff --git a/membuffer.c b/membuffer.c
index c8a06662f..2889a0cdc 100644
--- a/membuffer.c
+++ b/membuffer.c
@@ -6,12 +6,18 @@
#include "dive.h"
#include "membuffer.h"
-void free_buffer(struct membuffer *b)
+char *detach_buffer(struct membuffer *b)
{
- free(b->buffer);
+ char *result = b->buffer;
b->buffer = NULL;
b->len = 0;
b->alloc = 0;
+ return result;
+}
+
+void free_buffer(struct membuffer *b)
+{
+ free(detach_buffer(b));
}
void flush_buffer(struct membuffer *b, FILE *f)
@@ -100,6 +106,26 @@ void put_vformat(struct membuffer *b, const char *fmt, va_list args)
}
}
+/* Silly helper using membuffer */
+char *vformat_string(const char *fmt, va_list args)
+{
+ struct membuffer mb = { 0 };
+ put_vformat(&mb, fmt, args);
+ mb_cstring(&mb);
+ return detach_buffer(&mb);
+}
+
+char *format_string(const char *fmt, ...)
+{
+ va_list args;
+ char *result;
+
+ va_start(args, fmt);
+ result = vformat_string(fmt, args);
+ va_end(args);
+ return result;
+}
+
void put_format(struct membuffer *b, const char *fmt, ...)
{
va_list args;
@@ -228,3 +254,32 @@ void put_quoted(struct membuffer *b, const char *text, int is_attribute, int is_
text = p;
}
}
+
+char *add_to_string_va(const char *old, const char *fmt, va_list args)
+{
+ char *res;
+ struct membuffer o = { 0 }, n = { 0 };
+ put_vformat(&n, fmt, args);
+ put_format(&o, "%s\n%s", old ?: "", mb_cstring(&n));
+ res = strdup(mb_cstring(&o));
+ free_buffer(&o);
+ free_buffer(&n);
+ free((void *)old);
+ return res;
+}
+
+/* this is a convenience function that cleverly adds text to a string, using our membuffer
+ * infrastructure.
+ * WARNING - this will free(old), the intended pattern is
+ * string = add_to_string(string, fmt, ...)
+ */
+char *add_to_string(const char *old, const char *fmt, ...)
+{
+ char *res;
+ va_list args;
+
+ va_start(args, fmt);
+ res = add_to_string_va(old, fmt, args);
+ va_end(args);
+ return res;
+}