authorgravatar for johnnymarler@gmail.comJonathan Marler <johnnymarler@gmail.com> 2020-06-13 11:35:18-06:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-06-16 18:26:54-04:00
logf0b8791da75d2cb9c73424b8270da81e7d0ec333
tree7ae1100c0dd1628be3d60b89e782171ff6e758d5
parent593db7e8d0a5ad3cc1693944503f718ee96bda38

ArrayList(u8) support writer interface


1 files changed, 29 insertions(+), 12 deletions(-)

lib/std/array_list.zig+29-12
...@@ -162,19 +162,24 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {...@@ -162,19 +162,24 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
162 mem.copy(T, self.items[oldlen..], items);162 mem.copy(T, self.items[oldlen..], items);
163 }163 }
164164
165 /// Same as `append` except it returns the number of bytes written, which is always the same165 pub usingnamespace if (T != u8) struct { } else struct {
166 /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API.166 pub const Writer = std.io.Writer(*Self, error{OutOfMemory}, appendWrite);
167 /// This function may be called only when `T` is `u8`.
168 fn appendWrite(self: *Self, m: []const u8) !usize {
169 try self.appendSlice(m);
170 return m.len;
171 }
172167
173 /// Initializes an OutStream which will append to the list.168 /// Initializes a Writer which will append to the list.
174 /// This function may be called only when `T` is `u8`.169 pub fn writer(self: *Self) Writer {
175 pub fn outStream(self: *Self) std.io.OutStream(*Self, error{OutOfMemory}, appendWrite) {170 return .{ .context = self };
176 return .{ .context = self };171 }
177 }172
173 /// Deprecated: use `writer`
174 pub const outStream = writer;
175
176 /// Same as `append` except it returns the number of bytes written, which is always the same
177 /// as `m.len`. The purpose of this function existing is to match `std.io.Writer` API.
178 fn appendWrite(self: *Self, m: []const u8) !usize {
179 try self.appendSlice(m);
180 return m.len;
181 }
182 };
178183
179 /// Append a value to the list `n` times.184 /// Append a value to the list `n` times.
180 /// Allocates more memory as necessary.185 /// Allocates more memory as necessary.
...@@ -694,3 +699,15 @@ test "std.ArrayList.shrink still sets length on error.OutOfMemory" {...@@ -694,3 +699,15 @@ test "std.ArrayList.shrink still sets length on error.OutOfMemory" {
694 list.shrink(1);699 list.shrink(1);
695 testing.expect(list.items.len == 1);700 testing.expect(list.items.len == 1);
696}701}
702
703test "std.ArrayList.writer" {
704 var list = ArrayList(u8).init(std.testing.allocator);
705 defer list.deinit();
706
707 const writer = list.writer();
708 try writer.writeAll("a");
709 try writer.writeAll("bc");
710 try writer.writeAll("d");
711 try writer.writeAll("efg");
712 testing.expectEqualSlices(u8, list.items, "abcdefg");
713}