Its very simple, do you need to use the Arraylist before turning it into a writer? Then use fromArrayList if not, use init preferably initCapacity if you have at least a reasonable assumption required space.
But, checking the code, Allocating.sendFile creates a new ArrayList each time it is called, so it seems to me that .init is less efficient compared to .fromArrayList.
Update: this is incorrect, since the ArrayList is replaced with empty. Still not sure when you need to use .fromArrayList or .empty.
Here is the diff with the new code using Io.Writer.Allocating.
The doctest.zig is from the current master.
diff --git a/tools/doctest.zig b/tools/doctest.zig
index a762b8d0b9..266aa2143f 100644
--- a/tools/doctest.zig
+++ b/tools/doctest.zig
@@ -1011,10 +1011,16 @@ fn termColor(allocator: Allocator, input: []const u8) ![]u8 {
const supported_sgr_colors = [_]u8{ 31, 32, 36 };
const supported_sgr_numbers = [_]u8{ 0, 1, 2 };
- var buf = std.array_list.Managed(u8).init(allocator);
- defer buf.deinit();
+ //var buf = std.array_list.Managed(u8).init(allocator);
+ //defer buf.deinit();
+ //
+ //var out = buf.writer();
+
+ var buf: std.ArrayList(u8) = .empty;
+ var a: std.Io.Writer.Allocating = .fromArrayList(allocator, &buf);
+ defer a.deinit();
+ const out = &a.writer;
- var out = buf.writer();
var sgr_param_start_index: usize = undefined;
var sgr_num: u8 = undefined;
var sgr_color: u8 = undefined;
@@ -1118,7 +1124,7 @@ fn termColor(allocator: Allocator, input: []const u8) ![]u8 {
},
}
}
- return try buf.toOwnedSlice();
+ return try buf.toOwnedSlice(allocator);
}
// Returns true if number is in slice.
I used .fromArrayList due to the code constraint.
When running zig test tool/doctest.zig, the test fails because the termColor function returns an empty string.
Probably I’m doing something wrong, but I have no idea about
how to fix it.