]> git.ipfire.org Git - thirdparty/git.git/commitdiff
strbuf: add strbuf_add_uint()
authorRené Scharfe <l.s.r@web.de>
Tue, 12 May 2026 11:56:00 +0000 (13:56 +0200)
committerJunio C Hamano <gitster@pobox.com>
Tue, 12 May 2026 15:48:42 +0000 (00:48 +0900)
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>
strbuf.c
strbuf.h

index 3e04addc22febb60cc79fbdfc42257336b86809d..9731ecdc1feb9787b060fa500131aca095fa8e23 100644 (file)
--- a/strbuf.c
+++ b/strbuf.c
@@ -361,6 +361,18 @@ void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
        va_end(ap);
 }
 
+void strbuf_add_uint(struct strbuf *sb, uintmax_t value)
+{
+       char buf[DIV_ROUND_UP(bitsizeof(value) * 10, 33)];
+       char *end = buf + sizeof(buf);
+       char *p = end;
+
+       do
+               *--p = "0123456789"[value % 10];
+       while (value /= 10);
+       strbuf_add(sb, p, end - p);
+}
+
 static void add_lines(struct strbuf *out,
                        const char *prefix,
                        const char *buf, size_t size,
index 06e284f9cca445cbe8a5ee9ec8c25fc74e18ff46..1089ae687bda95f7f044dd5eef62a9667090dfe8 100644 (file)
--- a/strbuf.h
+++ b/strbuf.h
@@ -410,6 +410,12 @@ void strbuf_humanise_rate(struct strbuf *buf, off_t bytes);
 __attribute__((format (printf,2,3)))
 void strbuf_addf(struct strbuf *sb, const char *fmt, ...);
 
+
+/**
+ * Add an unsigned decimal number.
+ */
+void strbuf_add_uint(struct strbuf *sb, uintmax_t value);
+
 /**
  * Add a formatted string prepended by a comment character and a
  * blank to the buffer.