authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-02-20 03:16:02-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-02-23 02:37:11-07:00
log9129fb28dcc3c94a709cefd8040f41b9125693ee
treeb42589f8b298bde542e8caf807949e773b5a2408
parent2df3de1e209076cb27d6573a0cdd2bed075d88b3

std.ArrayList: add writerAssumeCapacity

Useful when you want to use an ArrayList to operate on a static buffer.

1 files changed, 19 insertions(+), 2 deletions(-)

lib/std/array_list.zig+19-2
...@@ -937,14 +937,31 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ...@@ -937,14 +937,31 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
937 return .{ .context = .{ .self = self, .allocator = allocator } };937 return .{ .context = .{ .self = self, .allocator = allocator } };
938 }938 }
939939
940 /// Same as `append` except it returns the number of bytes written, which is always the same940 /// Same as `append` except it returns the number of bytes written,
941 /// as `m.len`. The purpose of this function existing is to match `std.io.Writer` API.941 /// which is always the same as `m.len`. The purpose of this function
942 /// existing is to match `std.io.Writer` API.
942 /// Invalidates element pointers if additional memory is needed.943 /// Invalidates element pointers if additional memory is needed.
943 fn appendWrite(context: WriterContext, m: []const u8) Allocator.Error!usize {944 fn appendWrite(context: WriterContext, m: []const u8) Allocator.Error!usize {
944 try context.self.appendSlice(context.allocator, m);945 try context.self.appendSlice(context.allocator, m);
945 return m.len;946 return m.len;
946 }947 }
947948
949 pub const WriterAssumeCapacity = std.io.Writer(*Self, error{}, appendWriteAssumeCapacity);
950
951 /// Initializes a Writer which will append to the list, asserting the
952 /// list can hold the additional bytes.
953 pub fn writerAssumeCapacity(self: *Self) WriterAssumeCapacity {
954 return .{ .context = self };
955 }
956
957 /// Same as `appendSliceAssumeCapacity` except it returns the number of bytes written,
958 /// which is always the same as `m.len`. The purpose of this function
959 /// existing is to match `std.io.Writer` API.
960 fn appendWriteAssumeCapacity(self: *Self, m: []const u8) error{}!usize {
961 self.appendSliceAssumeCapacity(m);
962 return m.len;
963 }
964
948 /// Append a value to the list `n` times.965 /// Append a value to the list `n` times.
949 /// Allocates more memory as necessary.966 /// Allocates more memory as necessary.
950 /// Invalidates element pointers if additional memory is needed.967 /// Invalidates element pointers if additional memory is needed.