#Am I using comptime right?

1 messages · Page 1 of 1 (latest)

pastel furnace
#

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 ] ===
#

Non-comptime version:

// === [ Start of main.zig ] ===
pub fn main() !void {
    const custom_allocator = @import("custom_allocator.zig");
    const alloc = custom_allocator.init(.Adaptive);
    defer custom_allocator.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 CustomAllocatorType = enum { Adaptive, Arena };
var chosen_type: CustomAllocatorType = undefined;
pub fn init(ca_type: CustomAllocatorType) std.mem.Allocator {
    chosen_type = ca_type;
    return switch (ca_type) {
        .Adaptive => adaptive_allocator,
        .Arena => arena.allocator(),
    };
}
pub fn deinit() void {
    switch (chosen_type) {
        .Arena => arena.deinit(),
        else => {},
    }
    _ = if (is_debug) debug_allocator.deinit();
}
// === [ End of custom_allocator.zig ] ===