summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohannes Weiner <hannes@cmpxchg.org>2009-11-23 22:51:59 +0100
committerJohannes Weiner <hannes@cmpxchg.org>2009-11-23 22:51:59 +0100
commitc2add4dbc639f2970722e9913de455d7d320f7be (patch)
tree83269d70f7313afc05b3c7bc29d07f55a13f1b98
parentc69a89e24853454c2813fe5e96ad1c5470f20b03 (diff)
util: add sheep_addprintf()
Simple, auto-resizing, concatenative sprintf(). Signed-off-by: Johannes Weiner <hannes@cmpxchg.org>
-rw-r--r--include/sheep/util.h1
-rw-r--r--sheep/util.c31
2 files changed, 32 insertions, 0 deletions
diff --git a/include/sheep/util.h b/include/sheep/util.h
index 7df60cb..ba8023c 100644
--- a/include/sheep/util.h
+++ b/include/sheep/util.h
@@ -20,6 +20,7 @@ void *sheep_zalloc(size_t);
void *sheep_realloc(void *, size_t);
char *sheep_strdup(const char *);
void sheep_free(const void *);
+int sheep_addprintf(char **, size_t *, const char *, ...);
void __noreturn sheep_bug(const char *, ...);
diff --git a/sheep/util.c b/sheep/util.c
index a6f862e..395586c 100644
--- a/sheep/util.c
+++ b/sheep/util.c
@@ -44,6 +44,37 @@ void sheep_free(const void *mem)
free((void *)mem);
}
+#define DEFAULT_BUF 64
+
+int sheep_addprintf(char **bufp, size_t *pos, const char *fmt, ...)
+{
+ va_list ap;
+ int len;
+
+ *bufp = sheep_realloc(*bufp, *pos + DEFAULT_BUF);
+
+ va_start(ap, fmt);
+ len = vsnprintf(*bufp + *pos, DEFAULT_BUF, fmt, ap);
+ va_end(ap);
+
+ sheep_bug_on(len < 0);
+
+ if (len >= DEFAULT_BUF) {
+ int bytes = len + 1;
+
+ *bufp = sheep_realloc(*bufp, *pos + bytes);
+
+ va_start(ap, fmt);
+ len = vsnprintf(*bufp + *pos, bytes, fmt, ap);
+ va_end(ap);
+
+ sheep_bug_on(len < 0);
+ sheep_bug_on(len > bytes - 1);
+ }
+ *pos += len;
+ return len;
+}
+
void sheep_bug(const char *fmt, ...)
{
va_list ap;