Skip to content

Commit 7cfbaa5

Browse files
ungpsdscho
authored andcommitted
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 <[email protected]> Signed-off-by: Paul-Sebastian Ungureanu <[email protected]> Helped-by: Johannes Sixt <[email protected]> Signed-off-by: Thomas Gummerer <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 3422bdc commit 7cfbaa5

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

strbuf.c

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,42 @@ void strbuf_insert(struct strbuf *sb, size_t pos, const void *data, size_t len)
249249
strbuf_splice(sb, pos, 0, data, len);
250250
}
251251

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+
252288
void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)
253289
{
254290
strbuf_splice(sb, pos, len, "", 0);

strbuf.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,15 @@ void strbuf_addchars(struct strbuf *sb, int c, size_t n);
244244
*/
245245
void strbuf_insert(struct strbuf *sb, size_t pos, const void *, size_t);
246246

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+
247256
/**
248257
* Remove given amount of data from a given position of the buffer.
249258
*/

0 commit comments

Comments
 (0)