authorgravatar for candrewlee14@gmail.comAndrew Lee <candrewlee14@gmail.com> 2022-04-13 10:50:46-06:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-04-14 02:56:40-04:00
log9b82e7f558d5aa66ac1dc285af2345d46cc3d4d6
tree96024241498c9432a9f34041b1f6e4c9f772c0de
parent6ad9ac59e7461fa6bd906f7c4feb662509082c17

std/bounded_array.zig: Add Writer interface


1 files changed, 24 insertions(+), 0 deletions(-)

lib/std/bounded_array.zig+24
......@@ -239,6 +239,24 @@ pub fn BoundedArray(comptime T: type, comptime capacity: usize) type {
239239 assert(self.len <= capacity);
240240 mem.set(T, self.slice()[old_len..self.len], value);
241241 }
242
243 pub const Writer = if (T != u8)
244 @compileError("The Writer interface is only defined for BoundedArray(u8, ...) " ++
245 "but the given type is BoundedArray(" ++ @typeName(T) ++ ", ...)")
246 else
247 std.io.Writer(*Self, error{Overflow}, appendWrite);
248
249 /// Initializes a writer which will write into the array.
250 pub fn writer(self: *Self) Writer {
251 return .{ .context = self };
252 }
253
254 /// Same as `appendSlice` except it returns the number of bytes written, which is always the same
255 /// as `m.len`. The purpose of this function existing is to match `std.io.Writer` API.
256 fn appendWrite(self: *Self, m: []const u8) error{Overflow}!usize {
257 try self.appendSlice(m);
258 return m.len;
259 }
242260 };
243261}
244262
......@@ -336,4 +354,10 @@ test "BoundedArray" {
336354 const swapped = a.swapRemove(0);
337355 try testing.expectEqual(swapped, 0xdd);
338356 try testing.expectEqual(a.get(0), 0xee);
357
358 while (a.popOrNull()) |_| {}
359 const w = a.writer();
360 const s = "hello, this is a test string";
361 try w.writeAll(s);
362 try testing.expectEqualStrings(s, a.constSlice());
339363}