authorgravatar for hemisputnik@proton.mehemisputnik <hemisputnik@proton.me> 2026-03-01 14:05:22+02:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-03-01 20:34:17+01:00
log74f361a5ce5212ce321fd0ebfa4c158468a161bb
tree3393ffb47774c585151d655bf2de33462d6e7b6c
parentda6d4e28eff7b65589b046d2772516a6d9fd25bc

std.math.big.int: address log2/log10 reviews

There were good reviews made after #31365 was merged, so this commit addresses them separately. 1. Assert that the number is greater than zero 2. Use `constants` instead of calculating constants manually 3. Use `Const.bitCountAbs` for log2

1 files changed, 7 insertions(+), 9 deletions(-)

lib/std/math/big/int.zig+7-9
......@@ -2678,7 +2678,9 @@ pub const Const = struct {
26782678
26792679 /// Calculate the base 2 logarithm, rounded down.
26802680 pub fn log2(a: Const) Limb {
2681 return a.limbs.len * @bitSizeOf(Limb) - 1 - @clz(a.limbs[a.limbs.len - 1]);
2681 assert(a.positive);
2682 assert(!a.eqlZero());
2683 return a.bitCountAbs() - 1;
26822684 }
26832685
26842686 /// Calculate the base 10 logarithm, rounded down.
......@@ -2695,13 +2697,9 @@ pub const Const = struct {
26952697 ///
26962698 /// `limbs_buffer` is used for temporary storage. The amount required is given by `calcLog10LimbsBufferLen`.
26972699 pub fn log10(a: Const, limbs_buffer: []Limb) Limb {
2698 const max_digits_per_limb = std.math.log10(std.math.maxInt(Limb));
2699 const limb_base = comptime calc: {
2700 var limb_base: comptime_int = 1;
2701 for (0..max_digits_per_limb) |_| limb_base *= 10;
2702 break :calc limb_base;
2703 };
2704 const limb_base_as_bigint: Const = .{ .limbs = &.{limb_base}, .positive = true };
2700 assert(a.positive);
2701 assert(!a.eqlZero());
2702 const limb_base_as_bigint: Const = .{ .limbs = &.{constants.big_bases[10]}, .positive = true };
27052703
27062704 var q: Mutable = .{
27072705 .limbs = limbs_buffer[0 .. a.limbs.len + 2],
......@@ -2721,7 +2719,7 @@ pub const Const = struct {
27212719 var num_digits: Limb = 0;
27222720 while (q.len >= 2) {
27232721 q.divTrunc(&remainder, q.toConst(), limb_base_as_bigint, division_buf);
2724 num_digits += max_digits_per_limb;
2722 num_digits += constants.digits_per_limb[10];
27252723 }
27262724 var remaining_limb = q.limbs[0];
27272725 while (remaining_limb != 0) {