strbuf.c: add `strbuf_insertf()` and `strbuf_vinsertf()`

Implement `strbuf_insertf()` and `strbuf_vinsertf()` to insert data using a printf format string. Original-idea-by: Johannes Schindelin <johannes.schindelin@gmx.de> Signed-off-by: Paul-Sebastian Ungureanu <ungureanupaulsebastian@gmail.com> Helped-by: Johannes Sixt <j6t@kdbg.org> Signed-off-by: Thomas Gummerer <t.gummerer@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Paul-Sebastian Ungureanu committed Feb 25, 2019 at 23:16 UTC 5ef264dbdbc48b44ad5fc37e7542f3dc70e3e8c5
2 files changed +45
strbuf.c
+36
@@ -249,6 +249,42 @@ void strbuf_insert(struct strbuf *sb, size_t pos, const void *data, size_t len)
249 strbuf_splice(sb, pos, 0, data, len);
250 }
251
252 +void strbuf_vinsertf(struct strbuf *sb, size_t pos, const char *fmt, va_list ap)
253 +{
254 + int len, len2;
255 + char save;
256 + va_list cp;
257 +
258 + if (pos > sb->len)
259 + die("`pos' is too far after the end of the buffer");
260 + va_copy(cp, ap);
261 + len = vsnprintf(sb->buf + sb->len, 0, fmt, cp);
262 + va_end(cp);
263 + if (len < 0)
264 + BUG("your vsnprintf is broken (returned %d)", len);
265 + if (!len)
266 + return; /* nothing to do */
267 + if (unsigned_add_overflows(sb->len, len))
268 + die("you want to use way too much memory");
269 + strbuf_grow(sb, len);
270 + memmove(sb->buf + pos + len, sb->buf + pos, sb->len - pos);
271 + /* vsnprintf() will append a NUL, overwriting one of our characters */
272 + save = sb->buf[pos + len];
273 + len2 = vsnprintf(sb->buf + pos, len + 1, fmt, ap);
274 + sb->buf[pos + len] = save;
275 + if (len2 != len)
276 + BUG("your vsnprintf is broken (returns inconsistent lengths)");
277 + strbuf_setlen(sb, sb->len + len);
278 +}
279 +
280 +void strbuf_insertf(struct strbuf *sb, size_t pos, const char *fmt, ...)
281 +{
282 + va_list ap;
283 + va_start(ap, fmt);
284 + strbuf_vinsertf(sb, pos, fmt, ap);
285 + va_end(ap);
286 +}
287 +
288 void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)
289 {
290 strbuf_splice(sb, pos, len, "", 0);
strbuf.h
+9
@@ -244,6 +244,15 @@ void strbuf_addchars(struct strbuf *sb, int c, size_t n);
244 */
245 void strbuf_insert(struct strbuf *sb, size_t pos, const void *, size_t);
246
247 +/**
248 + * Insert data to the given position of the buffer giving a printf format
249 + * string. The contents will be shifted, not overwritten.
250 + */
251 +void strbuf_vinsertf(struct strbuf *sb, size_t pos, const char *fmt,
252 + va_list ap);
253 +
254 +void strbuf_insertf(struct strbuf *sb, size_t pos, const char *fmt, ...);
255 +
256 /**
257 * Remove given amount of data from a given position of the buffer.
258 */