From 404a78943d75dda7573d3324431a21918dbe526f Mon Sep 17 00:00:00 2001 From: Christoffer Lerno Date: Thu, 27 Nov 2025 12:14:59 +0100 Subject: [PATCH] - Somewhat faster BigInt output. --- lib/std/math/bigint.c3 | 45 ++++++++++++++++++++++++++++++++++++++---- releasenotes.md | 1 + 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/lib/std/math/bigint.c3 b/lib/std/math/bigint.c3 index a08e5d4a4..feb6b8b98 100644 --- a/lib/std/math/bigint.c3 +++ b/lib/std/math/bigint.c3 @@ -508,10 +508,47 @@ fn BigInt BigInt.abs(&self) fn usz? BigInt.to_format(&self, Formatter* format) @dynamic { - @stack_mem(4100; Allocator mem) + if (self.is_zero()) { - return format.print(self.to_string_with_radix(10, mem)); - }; + format.print("0")!; + return 1; + } + BigInt a = *self; + bool negative = self.is_negative(); + usz len; + if (negative) + { + format.out('-')!; + len++; + a.negate(); + } + uint[280] chunks; + int chunk_count; + + const BASE10_9 = 1000000000; + foreach_r(d : self.data) + { + ulong carry = d; + for (int i = 0; i < chunk_count; i++) + { + ulong v = chunks[i] * 4294967296ULL + carry; + carry = v / BASE10_9; + chunks[i] = (uint)(v - carry * BASE10_9); + } + if (carry) + { + ulong new_carry = carry / BASE10_9; + chunks[chunk_count++] = (uint)(carry - new_carry * BASE10_9); + if (new_carry) chunks[chunk_count++] = (uint)new_carry; + } + } + int ms = chunk_count - 1; + len += format.printf("%d", chunks[ms])!; + foreach_r (c : chunks[:ms]) + { + len += format.printf("%09d", c)!; + } + return len; } fn String BigInt.to_string(&self, Allocator allocator) @dynamic @@ -527,7 +564,7 @@ fn String BigInt.to_string_with_radix(&self, int radix, Allocator allocator) if (self.is_zero()) return "0".copy(allocator); const char[*] CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - @stack_mem(4100; Allocator mem) + @stack_mem(4120; Allocator mem) { BigInt a = *self; DString str; diff --git a/releasenotes.md b/releasenotes.md index 149d23d9f..d76791c5d 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -57,6 +57,7 @@ - Make printing typeids give some helpful typeid data. - Add `NSApplicationTerminateReply` to ns module (macOS). - Add `registerClassPair` function to objc module (macOS). +- Somewhat faster BigInt output. ## 0.7.7 Change list