I started learning zig this week and reading through the standard library I stumbled upon the Parsed struct. I love how simple the pattern is, but I have been trying to understand why store a pointer to the allocator and not the arena allocator itself.
What's the reason behind creating the arena allocator in the heap using it's underlying allocator?
(from https://ziglang.org/documentation/0.12.0/std/#src/std/json/static.zig)
pub fn Parsed(comptime T: type) type {
return struct {
arena: *ArenaAllocator,
value: T,
pub fn deinit(self: @This()) void {
const allocator = self.arena.child_allocator;
self.arena.deinit();
allocator.destroy(self.arena);
}
};
}
// ... and used ...
var parsed = Parsed(T){
.arena = try allocator.create(ArenaAllocator),
.value = undefined,
};
errdefer allocator.destroy(parsed.arena);
parsed.arena.* = ArenaAllocator.init(allocator);
errdefer parsed.arena.deinit();
Why not embed the arena allocator in Parsed and avoid an indirection?
pub fn Parsed(comptime T: type) type {
return struct {
arena: ArenaAllocator,
value: T,
pub fn deinit(self: @This()) void {
self.arena.deinit();
}
};
}
Maybe I'm overthinking this, but I'm sure there is a thought process behind it that I'm missing.