| ... | ... | @@ -1081,16 +1081,20 @@ pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: var) BufPrintError![] |
| 1081 | 1081 | } |
| 1082 | 1082 | |
| 1083 | 1083 | // Count the characters needed for format. Useful for preallocating memory |
| 1084 | | pub fn count(comptime fmt: []const u8, args: var) usize { |
| 1084 | pub fn count(comptime fmt: []const u8, args: var) !usize { |
| 1085 | 1085 | var counting_stream = std.io.countingOutStream(std.io.null_out_stream); |
| 1086 | 1086 | format(counting_stream.outStream(), fmt, args) catch |err| switch (err) {}; |
| 1087 | | return counting_stream.bytes_written; |
| 1087 | return std.math.cast(usize, counting_stream.bytes_written); |
| 1088 | 1088 | } |
| 1089 | 1089 | |
| 1090 | 1090 | pub const AllocPrintError = error{OutOfMemory}; |
| 1091 | 1091 | |
| 1092 | 1092 | pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![]u8 { |
| 1093 | | const buf = try allocator.alloc(u8, count(fmt, args)); |
| 1093 | const size = count(fmt, args) catch |err| switch (err) { |
| 1094 | // Output too long. Can't possibly allocate enough memory to display it. |
| 1095 | error.Overflow => return error.OutOfMemory, |
| 1096 | }; |
| 1097 | const buf = try allocator.alloc(u8, size); |
| 1094 | 1098 | return bufPrint(buf, fmt, args) catch |err| switch (err) { |
| 1095 | 1099 | error.BufferTooSmall => unreachable, // we just counted the size above |
| 1096 | 1100 | }; |