Andrew's git
/
gitweb.git
/ diff
summary
|
log
|
commit
| diff |
tree
commit
grep
author
committer
pickaxe
?
re
strbuf: add xstrfmt helper
author
Jeff King
<peff@peff.net>
Wed, 18 Jun 2014 20:01:34 +0000
(16:01 -0400)
committer
Junio C Hamano
<gitster@pobox.com>
Thu, 19 Jun 2014 19:25:17 +0000
(12:25 -0700)
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>
strbuf.c
patch
|
blob
|
history
strbuf.h
patch
|
blob
|
history
raw
|
patch
|
inline
| side by side (parent:
cb682f8
)
diff --git
a/strbuf.c
b/strbuf.c
index ac62982e672c22457468f601b35716dc9a52a81c..12c78656ca9ddb51fb62b95be29d18056911803f 100644
(file)
--- a/
strbuf.c
+++ b/
strbuf.c
@@
-600,3
+600,22
@@
char *xstrdup_tolower(const char *string)
result[i] = '\0';
return result;
}
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;
+}
diff --git
a/strbuf.h
b/strbuf.h
index e9ad03eabe72dc2ee6e7e0086baca71d343264ce..a594c24b2b0e9e82c16de1bb787758d561cb2e7b 100644
(file)
--- a/
strbuf.h
+++ b/
strbuf.h
@@
-187,4
+187,13
@@
extern int fprintf_ln(FILE *fp, const char *fmt, ...);
char *xstrdup_tolower(const char *);
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 */
#endif /* STRBUF_H */