aboutsummaryrefslogtreecommitdiff
path: root/lib/std/bounded_array.zig
diff options
context:
space:
mode:
authorAndrew Lee <candrewlee14@gmail.com>2022-04-13 10:50:46 -0600
committerAndrew Kelley <andrew@ziglang.org>2022-04-14 02:56:40 -0400
commit9b82e7f558d5aa66ac1dc285af2345d46cc3d4d6 (patch)
tree96024241498c9432a9f34041b1f6e4c9f772c0de /lib/std/bounded_array.zig
parent6ad9ac59e7461fa6bd906f7c4feb662509082c17 (diff)
downloadzig-9b82e7f558d5aa66ac1dc285af2345d46cc3d4d6.tar.gz
zig-9b82e7f558d5aa66ac1dc285af2345d46cc3d4d6.zip
std/bounded_array.zig: Add Writer interface
Diffstat (limited to 'lib/std/bounded_array.zig')
-rw-r--r--lib/std/bounded_array.zig24
1 files changed, 24 insertions, 0 deletions
diff --git a/lib/std/bounded_array.zig b/lib/std/bounded_array.zig
index 7c562b7c84..0b0efc55e4 100644
--- a/lib/std/bounded_array.zig
+++ b/lib/std/bounded_array.zig
@@ -239,6 +239,24 @@ pub fn BoundedArray(comptime T: type, comptime capacity: usize) type {
assert(self.len <= capacity);
mem.set(T, self.slice()[old_len..self.len], value);
}
+
+ pub const Writer = if (T != u8)
+ @compileError("The Writer interface is only defined for BoundedArray(u8, ...) " ++
+ "but the given type is BoundedArray(" ++ @typeName(T) ++ ", ...)")
+ else
+ std.io.Writer(*Self, error{Overflow}, appendWrite);
+
+ /// Initializes a writer which will write into the array.
+ pub fn writer(self: *Self) Writer {
+ return .{ .context = self };
+ }
+
+ /// Same as `appendSlice` 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.Writer` API.
+ fn appendWrite(self: *Self, m: []const u8) error{Overflow}!usize {
+ try self.appendSlice(m);
+ return m.len;
+ }
};
}
@@ -336,4 +354,10 @@ test "BoundedArray" {
const swapped = a.swapRemove(0);
try testing.expectEqual(swapped, 0xdd);
try testing.expectEqual(a.get(0), 0xee);
+
+ while (a.popOrNull()) |_| {}
+ const w = a.writer();
+ const s = "hello, this is a test string";
+ try w.writeAll(s);
+ try testing.expectEqualStrings(s, a.constSlice());
}