Skip to content

Add formatted printing directly into std.Buffer #4385

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/std/buffer.zig
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,16 @@ pub const Buffer = struct {
try self.resize(m.len);
mem.copy(u8, self.list.toSlice(), m);
}

pub fn print(self: *Buffer, comptime fmt: []const u8, args: var) !void {
try std.fmt.format(
self,
@typeInfo(@TypeOf(Buffer.append)).Fn.return_type.?.ErrorSet,
Buffer.append,
fmt,
args,
);
}
};

test "simple Buffer" {
Expand Down Expand Up @@ -190,3 +200,11 @@ test "Buffer.initCapacity" {
testing.expect(buf.capacity() == old_cap);
testing.expect(mem.eql(u8, buf.toSliceConst(), "hello"));
}

test "Buffer.print" {
var buf = try Buffer.init(testing.allocator, "");
defer buf.deinit();

try buf.print("Hello {} the {}", .{ 2, "world" });
testing.expect(buf.eql("Hello 2 the world"));
}