format_config: simplify buffer handling
When formatting a config value into a strbuf, we may end up stringifying it into a fixed-size buffer using sprintf, and then copying that buffer into the strbuf. We can eliminate the middle-man (and drop some calls to sprintf!) by writing directly to the strbuf. The reason it was written this way in the first place is that we need to know before writing the value whether to insert a delimiter. Instead of delaying the write of the value, we speculatively write the delimiter, and roll it back in the single case that cares. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Jeff King committed
Aug 20, 2015 at 10:47 UTC
f2259877531ed2a58ec04aeaeb6beb5183f81f92
1 file changed
+16
-22
builtin/config.c
+16
-22
@@ -111,41 +111,35 @@ static int format_config(struct strbuf *buf, const char *key_, const char *value
111
if (show_keys)
112
strbuf_addstr(buf, key_);
113
if (!omit_values) {
114
- int must_free_vptr = 0;
115
- int must_add_delim = show_keys;
116
- char value[256];
117
- const char *vptr = value;
114
+ if (show_keys)
115
+ strbuf_addch(buf, key_delim);
116
117
if (types == TYPE_INT)
120
- sprintf(value, "%"PRId64,
121
- git_config_int64(key_, value_ ? value_ : ""));
118
+ strbuf_addf(buf, "%"PRId64,
119
+ git_config_int64(key_, value_ ? value_ : ""));
120
else if (types == TYPE_BOOL)
123
- vptr = git_config_bool(key_, value_) ? "true" : "false";
121
+ strbuf_addstr(buf, git_config_bool(key_, value_) ?
122
+ "true" : "false");
123
else if (types == TYPE_BOOL_OR_INT) {
124
int is_bool, v;
125
v = git_config_bool_or_int(key_, value_, &is_bool);
126
if (is_bool)
128
- vptr = v ? "true" : "false";
127
+ strbuf_addstr(buf, v ? "true" : "false");
128
else
130
- sprintf(value, "%d", v);
129
+ strbuf_addf(buf, "%d", v);
130
} else if (types == TYPE_PATH) {
132
- if (git_config_pathname(&vptr, key_, value_) < 0)
131
+ const char *v;
132
+ if (git_config_pathname(&v, key_, value_) < 0)
133
return -1;
134
- must_free_vptr = 1;
134
+ strbuf_addstr(buf, v);
135
+ free((char *)v);
136
} else if (value_) {
136
- vptr = value_;
137
+ strbuf_addstr(buf, value_);
138
} else {
138
- /* Just show the key name */
139
- vptr = "";
140
- must_add_delim = 0;
139
+ /* Just show the key name; back out delimiter */
140
+ if (show_keys)
141
+ strbuf_setlen(buf, buf->len - 1);
142
}
142
-
143
- if (must_add_delim)
144
- strbuf_addch(buf, key_delim);
145
- strbuf_addstr(buf, vptr);
146
-
147
- if (must_free_vptr)
148
- free((char *)vptr);
143
}
144
strbuf_addch(buf, term);
145
return 0;