Created
May 15, 2019 08:26
-
-
Save komuw/ed7392120c1b80381641ef763857ece6 to your computer and use it in GitHub Desktop.
we can print a buffer but not ArrayList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const warn = std.debug.warn; | |
pub fn main() !void { | |
// 1. This works | |
var buf = try std.Buffer.init(std.debug.global_allocator, ""); | |
defer buf.deinit(); | |
try buf.append("hello"); | |
warn("buffer:\n\t {}", buf); | |
// 2. But this does NOT work | |
var list = std.ArrayList(i32).init(std.debug.global_allocator); | |
defer list.deinit(); | |
try list.append(1); | |
warn("list:\n\t {}", list); | |
} |
if we were to create a custom format method for std.ArrayList
it would do almost what we want;
pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
return struct {
const Self = @This();
// Custom format method
pub fn format(
self: Self,
comptime fmt: []const u8,
context: var,
comptime Errors: type,
output: fn (@typeOf(context), []const u8) Errors!void,
) Errors!void {
return std.fmt.format(context, Errors, output, "ArrayList: .capacity: {}, .len: {}, .allocator: {}", self.capacity(), self.len, self.allocator);
}
...
...
pub fn main() !void {
var list = ArrayList(i32).init(std.debug.global_allocator);
defer list.deinit();
try list.append(131);
try list.append(12424);
try list.append(12);
warn("\n\nlist:\n\t {}", list);
}
zig fmt . && zig build-exe main.zig && ./main
list:
ArrayList: .capacity: 8, .len: 3, .allocator: Allocator{ .reallocFn = fn(*std.mem.Allocator, []u8, u29, usize, u29) std.mem.Error![]u8@1065f8fd0, .shrinkFn = fn(*std.mem.Allocator, []u8, u29, usize, u29) []u8@1065f9210 }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Answer from IRC:
the
std.Buffer
contains astd.ArrayList(u8)
while the second bit usesstd.ArrayList(i32)
, bytes are printable