authorgravatar for benjamin.feng@glassdoor.comBenjamin Feng <benjamin.feng@glassdoor.com> 2020-02-29 15:16:04-06:00
committergravatar for benjamin.feng@glassdoor.comBenjamin Feng <benjamin.feng@glassdoor.com> 2020-03-12 10:26:27-05:00
logd2e4aafd64184017dc1f152a4b46eeafca94bbd8
treeb92a4cd5ccdc29b43833666e5c34fd4d77c50080
parent1c18ab01a44bf3cbef356ff215e97dfe2788265b

Fixup allocPrint


1 files changed, 17 insertions(+), 19 deletions(-)

lib/std/fmtstream.zig+17-19
......@@ -1088,25 +1088,23 @@ pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: var) BufPrintError![]
10881088 return buf[0..fbs.pos];
10891089}
10901090
1091// pub const AllocPrintError = error{OutOfMemory};
1092
1093// pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![]u8 {
1094// var size: usize = 0;
1095// format(&size, error{}, countSize, fmt, args) catch |err| switch (err) {};
1096// const buf = try allocator.alloc(u8, size);
1097// return bufPrint(buf, fmt, args) catch |err| switch (err) {
1098// error.BufferTooSmall => unreachable, // we just counted the size above
1099// };
1100// }
1101
1102// fn countSize(size: *usize, bytes: []const u8) (error{}!void) {
1103// size.* += bytes.len;
1104// }
1105
1106// pub fn allocPrint0(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![:0]u8 {
1107// const result = try allocPrint(allocator, fmt ++ "\x00", args);
1108// return result[0 .. result.len - 1 :0];
1109// }
1091pub const AllocPrintError = error{OutOfMemory};
1092
1093pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![]u8 {
1094 // Count the characters we need to preallocate
1095 var counting_stream = std.io.countingOutStream(std.io.null_out_stream);
1096 format(counting_stream.outStream(), fmt, args) catch |err| switch (err) {};
1097
1098 const buf = try allocator.alloc(u8, counting_stream.bytes_written);
1099 return bufPrint(buf, fmt, args) catch |err| switch (err) {
1100 error.BufferTooSmall => unreachable, // we just counted the size above
1101 };
1102}
1103
1104pub fn allocPrint0(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![:0]u8 {
1105 const result = try allocPrint(allocator, fmt ++ "\x00", args);
1106 return result[0 .. result.len - 1 :0];
1107}
11101108
11111109test "bufPrintInt" {
11121110 var buffer: [100]u8 = undefined;