| ... | @@ -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 | } |
| 164 | | 164 | |
| 165 | /// Same as `append` except it returns the number of bytes written, which is always the same | 165 | 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 | } | | |
| 172 | | 167 | |
| 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 | }; |
| 178 | | 183 | |
| 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 | |
| | 703 | test "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 | } |