strbuf: add strbuf_add_uint()
strbuf_addf() calls vsnprintf(3) underneath, which supports a plethora of formatting options. We can avoid its overhead in basic cases by providing specialized functions like strbuf_addstr() for strings. Add another one, strbuf_add_uint(), for unsigned integers. Prepare the number string in a temporary buffer. Make it big enough for any unsigned integer value: A decimal digit can represent ln(10)/ln(2) ≈ 3.32 bits; dividing the number of bits of uintmax_t by 3.3 and rounding up gives a sufficiently close conservative size estimate. Signed-off-by: René Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>
René Scharfe committed
May 12, 2026 at 13:56 UTC
cdeef283bcf8529fc858cfe7d18a7522294519c4
2 files changed
+18
strbuf.c
+12
@@ -361,6 +361,18 @@ void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
361
va_end(ap);
362
}
363
364
+void strbuf_add_uint(struct strbuf *sb, uintmax_t value)
365
+{
366
+ char buf[DIV_ROUND_UP(bitsizeof(value) * 10, 33)];
367
+ char *end = buf + sizeof(buf);
368
+ char *p = end;
369
+
370
+ do
371
+ *--p = "0123456789"[value % 10];
372
+ while (value /= 10);
373
+ strbuf_add(sb, p, end - p);
374
+}
375
+
376
static void add_lines(struct strbuf *out,
377
const char *prefix,
378
const char *buf, size_t size,
strbuf.h
+6
@@ -410,6 +410,12 @@ void strbuf_humanise_rate(struct strbuf *buf, off_t bytes);
410
__attribute__((format (printf,2,3)))
411
void strbuf_addf(struct strbuf *sb, const char *fmt, ...);
412
413
+
414
+/**
415
+ * Add an unsigned decimal number.
416
+ */
417
+void strbuf_add_uint(struct strbuf *sb, uintmax_t value);
418
+
419
/**
420
* Add a formatted string prepended by a comment character and a
421
* blank to the buffer.