authorgravatar for benjamin.feng@glassdoor.comBenjamin Feng <benjamin.feng@glassdoor.com> 2020-02-29 21:43:54-06:00
committergravatar for benjamin.feng@glassdoor.comBenjamin Feng <benjamin.feng@glassdoor.com> 2020-03-12 10:41:09-05:00
log8dd078b99a31f49194c07af93b0f555f2c7260dc
tree32cbbfcf0fa6d35a69d1d9fe0462369ca631fab5
parent2429fdd73bc2405034805893f169ae58c1c34c56

Convert Buffer to use fmtstream


2 files changed, 11 insertions(+), 14 deletions(-)

lib/std/buffer.zig+3-9
......@@ -65,15 +65,9 @@ pub const Buffer = struct {
6565 }
6666
6767 pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: var) !Buffer {
68 const countSize = struct {
69 fn countSize(size: *usize, bytes: []const u8) (error{}!void) {
70 size.* += bytes.len;
71 }
72 }.countSize;
73 var size: usize = 0;
74 std.fmt.format(&size, error{}, countSize, format, args) catch |err| switch (err) {};
68 const size = std.fmtstream.count(format, args);
7569 var self = try Buffer.initSize(allocator, size);
76 assert((std.fmt.bufPrint(self.list.items, format, args) catch unreachable).len == size);
70 assert((std.fmtstream.bufPrint(self.list.items, format, args) catch unreachable).len == size);
7771 return self;
7872 }
7973
......@@ -155,7 +149,7 @@ pub const Buffer = struct {
155149 }
156150
157151 pub fn print(self: *Buffer, comptime fmt: []const u8, args: var) !void {
158 return std.fmt.format(self, error{OutOfMemory}, Buffer.append, fmt, args);
152 return self.outStream().print(fmt, args);
159153 }
160154
161155 pub fn outStream(self: *Buffer) std.io.OutStream(*Buffer, error{OutOfMemory}, appendWrite) {
lib/std/fmtstream.zig+8-5
......@@ -1080,14 +1080,17 @@ pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: var) BufPrintError![]
10801080 return buf[0..fbs.pos];
10811081}
10821082
1083pub const AllocPrintError = error{OutOfMemory};
1084
1085pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![]u8 {
1086 // Count the characters we need to preallocate
1083// Count the characters needed for format. Useful for preallocating memory
1084pub fn count(comptime fmt: []const u8, args: var) usize {
10871085 var counting_stream = std.io.countingOutStream(std.io.null_out_stream);
10881086 format(counting_stream.outStream(), fmt, args) catch |err| switch (err) {};
1087 return counting_stream.bytes_written;
1088}
10891089
1090 const buf = try allocator.alloc(u8, counting_stream.bytes_written);
1090pub const AllocPrintError = error{OutOfMemory};
1091
1092pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![]u8 {
1093 const buf = try allocator.alloc(u8, count(fmt, args));
10911094 return bufPrint(buf, fmt, args) catch |err| switch (err) {
10921095 error.BufferTooSmall => unreachable, // we just counted the size above
10931096 };