authorgravatar for justus@klausecker.deJustus Klausecker <justus@klausecker.de> 2025-11-14 10:34:23+01:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-11-23 09:52:43-08:00
loge5c2df9f17571136d0769580d6250db0b1a8d0ca
tree2e7349ec1ffe980f0cdac37fb9d045cdb1baa3b0
parent16fc083f2b5e542c0a35034debb058836e093b48

std.math.big.int: fix format functions


1 files changed, 35 insertions(+), 1 deletions(-)

lib/std/math/big/int.zig+35-1
......@@ -2032,7 +2032,11 @@ pub const Mutable = struct {
20322032 return formatNumber(self, w, .{});
20332033 }
20342034
2035 pub fn formatNumber(self: Const, w: *std.Io.Writer, n: std.fmt.Number) std.Io.Writer.Error!void {
2035 /// If the absolute value of integer is greater than or equal to `pow(2, 64 * @sizeOf(usize) * 8)`,
2036 /// this function will fail to print the string, printing "(BigInt)" instead of a number.
2037 /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory.
2038 /// See `Const.toString` and `Const.toStringAlloc` for a way to print big integers without failure.
2039 pub fn formatNumber(self: Mutable, w: *std.Io.Writer, n: std.fmt.Number) std.Io.Writer.Error!void {
20362040 return self.toConst().formatNumber(w, n);
20372041 }
20382042};
......@@ -2321,6 +2325,10 @@ pub const Const = struct {
23212325 return .{ normalized_res.reconstruct(if (self.positive) .positive else .negative), exactness };
23222326 }
23232327
2328 pub fn format(self: Const, w: *std.Io.Writer) std.Io.Writer.Error!void {
2329 return self.formatNumber(w, .{});
2330 }
2331
23242332 /// If the absolute value of integer is greater than or equal to `pow(2, 64 * @sizeOf(usize) * 8)`,
23252333 /// this function will fail to print the string, printing "(BigInt)" instead of a number.
23262334 /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory.
......@@ -4625,3 +4633,29 @@ fn testOneShiftCaseAliasing(func: fn ([]Limb, []const Limb, usize) usize, case:
46254633 try std.testing.expectEqualSlices(Limb, expected, r[base .. base + len]);
46264634 }
46274635}
4636
4637test "format" {
4638 var a: Managed = try .init(std.testing.allocator);
4639 defer a.deinit();
4640
4641 try a.set(123);
4642 try testFormat(a, "123");
4643
4644 try a.set(-123);
4645 try testFormat(a, "-123");
4646
4647 try a.set(20000000000000000000); // > maxInt(u64)
4648 try testFormat(a, "20000000000000000000");
4649
4650 try a.set(1 << 64 * @sizeOf(usize) * 8);
4651 try testFormat(a, "(BigInt)");
4652
4653 try a.set(-(1 << 64 * @sizeOf(usize) * 8));
4654 try testFormat(a, "(BigInt)");
4655}
4656
4657fn testFormat(a: Managed, expected: []const u8) !void {
4658 try std.testing.expectFmt(expected, "{f}", .{a});
4659 try std.testing.expectFmt(expected, "{f}", .{a.toMutable()});
4660 try std.testing.expectFmt(expected, "{f}", .{a.toConst()});
4661}