Skip to content

Commit

Permalink
strbuf: add xstrfmt helper
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
Jeff King authored and Junio C Hamano committed Jun 19, 2014
1 parent cb682f8 commit 30a0ddb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
19 changes: 19 additions & 0 deletions strbuf.c
Original file line number Diff line number Diff line change
Expand Up @@ -600,3 +600,22 @@ char *xstrdup_tolower(const char *string)
result[i] = '\0';
return result;
}

char *xstrvfmt(const char *fmt, va_list ap)
{
struct strbuf buf = STRBUF_INIT;
strbuf_vaddf(&buf, fmt, ap);
return strbuf_detach(&buf, NULL);
}

char *xstrfmt(const char *fmt, ...)
{
va_list ap;
char *ret;

va_start(ap, fmt);
ret = xstrvfmt(fmt, ap);
va_end(ap);

return ret;
}
9 changes: 9 additions & 0 deletions strbuf.h
Original file line number Diff line number Diff line change
Expand Up @@ -187,4 +187,13 @@ extern int fprintf_ln(FILE *fp, const char *fmt, ...);

char *xstrdup_tolower(const char *);

/*
* Create a newly allocated string using printf format. You can do this easily
* with a strbuf, but this provides a shortcut to save a few lines.
*/
__attribute__((format (printf, 1, 0)))
char *xstrvfmt(const char *fmt, va_list ap);
__attribute__((format (printf, 1, 2)))
char *xstrfmt(const char *fmt, ...);

#endif /* STRBUF_H */

0 comments on commit 30a0ddb

Please sign in to comment.