Skip to content

Commit 30a0ddb

Browse files
peffgitster
authored andcommitted
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 <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent cb682f8 commit 30a0ddb

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

strbuf.c

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,3 +600,22 @@ char *xstrdup_tolower(const char *string)
600600
result[i] = '\0';
601601
return result;
602602
}
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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,4 +187,13 @@ extern int fprintf_ln(FILE *fp, const char *fmt, ...);
187187

188188
char *xstrdup_tolower(const char *);
189189

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+
190199
#endif /* STRBUF_H */

0 commit comments

Comments
 (0)