From c339278ff709752633b32791f68a238e01161b91 Mon Sep 17 00:00:00 2001 From: Christoffer Lerno Date: Thu, 28 Aug 2025 12:12:22 +0200 Subject: [PATCH] `String.bformat` has reduced overhead. --- lib/std/core/string.c3 | 17 +++++++++++++---- releasenotes.md | 1 + 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/lib/std/core/string.c3 b/lib/std/core/string.c3 index 14f19237d..7ffb8e7e7 100644 --- a/lib/std/core/string.c3 +++ b/lib/std/core/string.c3 @@ -109,16 +109,25 @@ fn String format(Allocator allocator, String fmt, args...) @format(1) => @pool() } <* - Return a new String created using the formatting function. + Return a new String created using the formatting function, the resulting string must fit the buffer. @param [inout] buffer : `The buffer to use` @param [in] fmt : `The formatting string` *> fn String bformat(char[] buffer, String fmt, args...) @format(1) { - DString str = dstring::new_with_capacity(allocator::wrap(buffer), fmt.len + args.len * 8); - str.appendf(fmt, ...args); - return str.str_view(); + Formatter f; + OutputFn format_fn = fn void?(void* buf, char c) { + char[]* buffer_ref = buf; + char[] buffer = *buffer_ref; + if (buffer.len == 0) return io::BUFFER_EXCEEDED?; + buffer[0] = c; + *buffer_ref = buffer[1..]; + }; + char[] buffer_copy = buffer; + f.init(format_fn, &buffer_copy); + usz len = f.vprintf(fmt, args)!!; + return (String)buffer[:len]; } <* diff --git a/releasenotes.md b/releasenotes.md index 2b34b952e..3c8de2134 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -103,6 +103,7 @@ - Added `AsciiCharset` for matching ascii characters quickly. - Added `String.trim_charset`. - Added array `@reduce`, `@filter`, `@any`, `@all`, `@sum`, `@product`, and `@indices_of` macros. +- `String.bformat` has reduced overhead. ## 0.7.4 Change list