strbuf: add xstrfmt helper

You can use a strbuf to build up a string from parts, and then detach it. In the general case, you might use multiple strbuf_add* functions to do the building. However, in many cases, a single strbuf_addf is sufficient, and we end up with: struct strbuf buf = STRBUF_INIT; ... strbuf_addf(&buf, fmt, some, args); str = strbuf_detach(&buf, NULL); We can make this much more readable (and avoid introducing an extra variable, which can clutter the code) by introducing a convenience function: str = xstrfmt(fmt, some, args); Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Jun 18, 2014 at 16:01 UTC 30a0ddb705678d512185e359831479a6b3567147
2 files changed +28
strbuf.c
+19
@@ -600,3 +600,22 @@ char *xstrdup_tolower(const char *string)
600 result[i] = '\0';
601 return result;
602 }
603 +
604 +char *xstrvfmt(const char *fmt, va_list ap)
605 +{
606 + struct strbuf buf = STRBUF_INIT;
607 + strbuf_vaddf(&buf, fmt, ap);
608 + return strbuf_detach(&buf, NULL);
609 +}
610 +
611 +char *xstrfmt(const char *fmt, ...)
612 +{
613 + va_list ap;
614 + char *ret;
615 +
616 + va_start(ap, fmt);
617 + ret = xstrvfmt(fmt, ap);
618 + va_end(ap);
619 +
620 + return ret;
621 +}
strbuf.h
+9
@@ -187,4 +187,13 @@ extern int fprintf_ln(FILE *fp, const char *fmt, ...);
187
188 char *xstrdup_tolower(const char *);
189
190 +/*
191 + * Create a newly allocated string using printf format. You can do this easily
192 + * with a strbuf, but this provides a shortcut to save a few lines.
193 + */
194 +__attribute__((format (printf, 1, 0)))
195 +char *xstrvfmt(const char *fmt, va_list ap);
196 +__attribute__((format (printf, 1, 2)))
197 +char *xstrfmt(const char *fmt, ...);
198 +
199 #endif /* STRBUF_H */