Comptime version:
// === [ Start of main.zig ] ===
pub fn main() !void {
const ca = comptime @import("custom_allocator.zig").init(.Arena);
const alloc = comptime ca.allocator();
defer ca.deinit();
var list = std.ArrayList(u8).empty;
defer list.deinit(alloc);
try list.append(alloc, 1);
std.debug.print("{any}\n", .{list.items});
}
// === [End of main.zig] ===
// === [ Start of custom_allocator.zig ] ===
const std = @import("std");
const mode = @import("builtin").mode;
const is_debug = mode == .Debug or mode == .ReleaseSafe;
var debug_allocator: std.heap.DebugAllocator(.{}) = .init;
const adaptive_allocator = if (is_debug) debug_allocator.allocator() else std.heap.smp_allocator;
var arena = std.heap.ArenaAllocator.init(adaptive_allocator);
const AllocatorType = enum { Adaptive, Arena };
pub fn init(comptime a_type: AllocatorType) type {
return struct {
pub fn allocator() std.mem.Allocator {
return switch (a_type) {
.Adaptive => adaptive_allocator,
.Arena => arena.allocator(),
};
}
pub fn deinit() void {
switch (a_type) {
.Arena => arena.deinit(),
else => {},
}
_ = if (is_debug) debug_allocator.deinit();
}
};
}
// === [ End of custom_allocator.zig ] ===