From 2f8e66080580c1ef3814cc4e2f27ae418d8d6e0c Mon Sep 17 00:00:00 2001 From: hemisputnik Date: Wed, 25 Feb 2026 10:48:24 +0200 Subject: [PATCH] std.math.log10: handle comptime_int inputs correctly also add a few tests for comptime types fixes #31333 --- lib/std/math/log10.zig | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/std/math/log10.zig b/lib/std/math/log10.zig index e55ac46849242b9514638528ad2514c4b9e36ca8..4c1bb412a0dac7500b11226f327ceca0d7578168 100644 --- a/lib/std/math/log10.zig +++ b/lib/std/math/log10.zig @@ -17,7 +17,12 @@ pub fn log10(x: anytype) @TypeOf(x) { }, .float => return @log10(x), .comptime_int => { - return @as(comptime_int, @floor(@log10(@as(f64, x)))); + const Int = @Int( + if (x < 0) .signed else .unsigned, + // We let log10_int check if x is 0, for a nicer error message. + @max(16, if (x == 0) 0 else 1 + std.math.log2(x)), + ); + return @as(comptime_int, log10_int(@as(Int, x))); }, .int => |IntType| switch (IntType.signedness) { .signed => @compileError("log10 not implemented for signed integers"), @@ -156,3 +161,10 @@ test log10_int { try testing.expectEqual(max_exponent, log10_int(@as(T, std.math.maxInt(T)))); } } + +test "log10 with comptime types" { + try testing.expectEqual(0, log10(2)); + try testing.expectEqual(2.0, log10(100.0)); + try testing.expectEqual(2, log10(123)); + try testing.expectEqual(3.0, log10(1000.0)); +} -- 2.54.0