authorgravatar for ian@ianjohnson.devIan Johnson <ian@ianjohnson.dev> 2023-10-27 20:29:17-04:00
committergravatar for ian@ianjohnson.devIan Johnson <ian@ianjohnson.dev> 2024-01-29 19:02:18-05:00
logcc25756b3f33578774b557bdf09dcc9e918c1e5a
treee713795cfeaa0674321003bf2b6d7d847cf6a89c
parente392c1a0b33e69156c36234e6584be306caf16ef

Eliminate generic duplication in `allocPrint`

Since `bufPrint` and `count` both control the writers used internally, they can leverage type-erased writers while maintaining correct error handling. This reduces generic instantiations when using `allocPrint`, which calls both `count` and `bufPrint` internally.

1 files changed, 5 insertions(+), 2 deletions(-)

lib/std/fmt.zig+5-2
......@@ -1986,7 +1986,10 @@ pub const BufPrintError = error{
19861986/// Returns a slice of the bytes printed to.
19871987pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: anytype) BufPrintError![]u8 {
19881988 var fbs = std.io.fixedBufferStream(buf);
1989 try format(fbs.writer(), fmt, args);
1989 format(fbs.writer().any(), fmt, args) catch |err| switch (err) {
1990 error.NoSpaceLeft => return error.NoSpaceLeft,
1991 else => unreachable,
1992 };
19901993 return fbs.getWritten();
19911994}
19921995
......@@ -1998,7 +2001,7 @@ pub fn bufPrintZ(buf: []u8, comptime fmt: []const u8, args: anytype) BufPrintErr
19982001/// Count the characters needed for format. Useful for preallocating memory
19992002pub fn count(comptime fmt: []const u8, args: anytype) u64 {
20002003 var counting_writer = std.io.countingWriter(std.io.null_writer);
2001 format(counting_writer.writer(), fmt, args) catch |err| switch (err) {};
2004 format(counting_writer.writer().any(), fmt, args) catch unreachable;
20022005 return counting_writer.bytes_written;
20032006}
20042007