diff options
| author | Andrew Lee <candrewlee14@gmail.com> | 2022-04-13 10:50:46 -0600 |
|---|---|---|
| committer | Andrew Kelley <andrew@ziglang.org> | 2022-04-14 02:56:40 -0400 |
| commit | 9b82e7f558d5aa66ac1dc285af2345d46cc3d4d6 (patch) | |
| tree | 96024241498c9432a9f34041b1f6e4c9f772c0de /lib/std/bounded_array.zig | |
| parent | 6ad9ac59e7461fa6bd906f7c4feb662509082c17 (diff) | |
| download | zig-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.zig | 24 |
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()); } |
