Re: [PATCH 1/4] strbuf: add strbuf_add_uint()
- From
Jeff King <peff@peff.net>
- Date
- May 12, 2026, 18:42 UTC
- Message-ID
- <20260512184238.GC70851@coredump.intra.peff.net>
- In-Reply-To
- <20260512115603.80780-2-l.s.r@web.de>
On Tue, May 12, 2026 at 01:56:00PM +0200, René Scharfe wrote:
> 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.
Cute. The naive obvious question here is: why not just grow the strbuf and format it there directly?
And the answer is that it's much easier to format numbers right-to-left, and then you know how many digits you need. ;)
You can compute the number of digits needed up front, of course, but it's log-10. You might be able to do it quickly based on the size of the leading bit, but there are a lot of off-by-one gotchas.
So probably the extra memcpy() is not that big a deal.
-Peff