aboutsummaryrefslogtreecommitdiff
path: root/lib/std/buffer.zig
diff options
context:
space:
mode:
authorAndrew Kelley <andrew@ziglang.org>2020-03-11 18:54:52 -0400
committerGitHub <noreply@github.com>2020-03-11 18:54:52 -0400
commit895f67cc6dfe3ade4b635c4c2168843b022edee7 (patch)
tree78f817084e76780c1b3eaab961657b168736e4d3 /lib/std/buffer.zig
parent571f3ed161455074be5f296b39b24cba554da8e0 (diff)
parent06d2f53ece7328e6beedd5c846a5b25798ba74e3 (diff)
downloadzig-895f67cc6dfe3ade4b635c4c2168843b022edee7.tar.gz
zig-895f67cc6dfe3ade4b635c4c2168843b022edee7.zip
Merge pull request #4710 from ziglang/io-stream-iface
rework I/O stream abstractions
Diffstat (limited to 'lib/std/buffer.zig')
-rw-r--r--lib/std/buffer.zig23
1 files changed, 23 insertions, 0 deletions
diff --git a/lib/std/buffer.zig b/lib/std/buffer.zig
index 9bf024191e..28ce2a5610 100644
--- a/lib/std/buffer.zig
+++ b/lib/std/buffer.zig
@@ -157,6 +157,17 @@ pub const Buffer = struct {
pub fn print(self: *Buffer, comptime fmt: []const u8, args: var) !void {
return std.fmt.format(self, error{OutOfMemory}, Buffer.append, fmt, args);
}
+
+ pub fn outStream(self: *Buffer) std.io.OutStream(*Buffer, error{OutOfMemory}, appendWrite) {
+ return .{ .context = self };
+ }
+
+ /// Same as `append` except it returns the number of bytes written, which is always the same
+ /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API.
+ pub fn appendWrite(self: *Buffer, m: []const u8) !usize {
+ try self.append(m);
+ return m.len;
+ }
};
test "simple Buffer" {
@@ -208,3 +219,15 @@ test "Buffer.print" {
try buf.print("Hello {} the {}", .{ 2, "world" });
testing.expect(buf.eql("Hello 2 the world"));
}
+
+test "Buffer.outStream" {
+ var buffer = try Buffer.initSize(testing.allocator, 0);
+ defer buffer.deinit();
+ const buf_stream = buffer.outStream();
+
+ const x: i32 = 42;
+ const y: i32 = 1234;
+ try buf_stream.print("x: {}\ny: {}\n", .{ x, y });
+
+ testing.expect(mem.eql(u8, buffer.toSlice(), "x: 42\ny: 1234\n"));
+}