authorgravatar for quae@daurnimator.comdaurnimator <quae@daurnimator.com> 2020-03-01 19:13:26+11:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-04-01 10:36:38-04:00
log0ee2462a3116020013f8c55e830182df0fa369f2
tree64cddc256c5a06df16099a6296bfe659b3578d74
parente8a1e2a1d8f2903d5951339f7d3e0dbdfc85704c
signaturelock-open Commit is signed but in an unrecognized format.

std: add std.ArrayList(u8).outStream()


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

lib/std/array_list.zig+27
......@@ -189,6 +189,22 @@ pub fn AlignedArrayList(comptime T: type, comptime alignment: ?u29) type {
189189 self.len += items.len;
190190 }
191191
192 pub usingnamespace if (T == u8)
193 struct {
194 /// Same as `append` except it returns the number of bytes written, which is always the same
195 /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API.
196 fn appendWrite(self: *Self, m: []const u8) !usize {
197 try self.appendSlice(m);
198 return m.len;
199 }
200
201 pub fn outStream(self: *Self) std.io.OutStream(*Self, error{OutOfMemory}, appendWrite) {
202 return .{ .context = self };
203 }
204 }
205 else
206 struct {};
207
192208 /// Append a value to the list `n` times. Allocates more memory
193209 /// as necessary.
194210 pub fn appendNTimes(self: *Self, value: T, n: usize) !void {
......@@ -479,3 +495,14 @@ test "std.ArrayList: ArrayList(T) of struct T" {
479495 try root.sub_items.append(Item{ .integer = 42, .sub_items = ArrayList(Item).init(testing.allocator) });
480496 testing.expect(root.sub_items.items[0].integer == 42);
481497}
498
499test "std.ArrayList(u8) implements outStream" {
500 var buffer = ArrayList(u8).init(std.testing.allocator);
501 defer buffer.deinit();
502
503 const x: i32 = 42;
504 const y: i32 = 1234;
505 try buffer.outStream().print("x: {}\ny: {}\n", .{ x, y });
506
507 testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.span());
508}