summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMichael Elkins <me@sigpipe.org>2010-08-08 10:40:38 -0700
committerMichael Elkins <me@sigpipe.org>2010-08-08 10:40:38 -0700
commit9b1cf33b613b3b61ccd10f30773b34c6dda56af2 (patch)
tree5aa8b24629b0839c9abc9c81399ddf3eaef22cfd
parent306406f6713c22e6c9e82cc533f9255f379af5f4 (diff)
add a malloc+sprintf combo function
-rw-r--r--lib.c31
-rw-r--r--lib.h1
2 files changed, 32 insertions, 0 deletions
diff --git a/lib.c b/lib.c
index 17cc5160..0d829154 100644
--- a/lib.c
+++ b/lib.c
@@ -1082,3 +1082,34 @@ int mutt_atol (const char *str, long *dst)
return -1;
return 0;
}
+
+/* Allocate a C-string large enough to contain the formatted string.
+ * This is essentially malloc+sprintf in one.
+ */
+char *mutt_sprintf (const char *fmt, ...)
+{
+ size_t rlen = STRING;
+ char *r = safe_malloc (rlen);
+ for (;;)
+ {
+ va_list ap;
+ va_start (ap, fmt);
+ size_t n = vsnprintf (r, rlen, fmt, ap);
+ va_end (ap);
+ if (n < rlen)
+ {
+ /* reduce space to just that which was used. note that 'n' does not
+ * include the terminal nul char.
+ */
+ if (n == 0) /* convention is to use NULL for zero-length strings. */
+ FREE (&r);
+ else if (n != rlen - 1)
+ safe_realloc (&r, n + 1);
+ return r;
+ }
+ /* increase size and try again */
+ rlen = n + 1;
+ safe_realloc(&r, rlen);
+ }
+ /* not reached */
+}
diff --git a/lib.h b/lib.h
index e13e1a24..b08f909d 100644
--- a/lib.h
+++ b/lib.h
@@ -153,6 +153,7 @@ char *mutt_concatn_path (char *, size_t, const char *, size_t, const char *, siz
char *mutt_concat_path (char *, const char *, const char *, size_t);
char *mutt_read_line (char *, size_t *, FILE *, int *, int);
char *mutt_skip_whitespace (char *);
+char *mutt_sprintf (const char *, ...);
char *mutt_strlower (char *);
char *mutt_substrcpy (char *, const char *, const char *, size_t);
char *mutt_substrdup (const char *, const char *);