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); | |
} |
Initially I thought that std.Buffer
is able to be printed because maybe it declares a custom format
method but it doesn't;
https://github.com/ziglang/zig/blob/master/std/buffer.zig
Answer from IRC:
the std.Buffer
contains a std.ArrayList(u8)
while the second bit uses std.ArrayList(i32)
, bytes are printable
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
ie
warn("buffer:\n\t {}", buf);
printshowever,
warn("list:\n\t {}", list);
results in;