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{...@@ -1986,7 +1986,10 @@ pub const BufPrintError = error{
1986/// Returns a slice of the bytes printed to.1986/// Returns a slice of the bytes printed to.
1987pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: anytype) BufPrintError![]u8 {1987pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: anytype) BufPrintError![]u8 {
1988 var fbs = std.io.fixedBufferStream(buf);1988 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 };
1990 return fbs.getWritten();1993 return fbs.getWritten();
1991}1994}
19921995
...@@ -1998,7 +2001,7 @@ pub fn bufPrintZ(buf: []u8, comptime fmt: []const u8, args: anytype) BufPrintErr...@@ -1998,7 +2001,7 @@ pub fn bufPrintZ(buf: []u8, comptime fmt: []const u8, args: anytype) BufPrintErr
1998/// Count the characters needed for format. Useful for preallocating memory2001/// Count the characters needed for format. Useful for preallocating memory
1999pub fn count(comptime fmt: []const u8, args: anytype) u64 {2002pub fn count(comptime fmt: []const u8, args: anytype) u64 {
2000 var counting_writer = std.io.countingWriter(std.io.null_writer);2003 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;
2002 return counting_writer.bytes_written;2005 return counting_writer.bytes_written;
2003}2006}
20042007