SafeAllocator

In my code for zig 0.15.2 I had this (incredibly ugly) code to define one global allocator.

pub const is_debug: bool = builtin.mode == .debug;
const DebugAllocator = std.heap.DebugAllocator(.{});
var da = if (is_debug) DebugAllocator.init else void;
pub const gpa: std.mem.Allocator = if (is_debug) da.allocator() else std.heap.smp_allocator;

But it works and reports memory leaks at deinit()..

Now moved to 0.17.1 and can’t get my head wrapped around the SafeAllocator.

How can I define my pub const gpa in the same way?
And how could I code it less ugly?
And is SafeAllocator actually a std.mem.Allocator? That I find difficult to read.

In 0.16+ you can get an allocator by using the juicy main like this:

pub fn main(init: std.process.Init) !void {
    const gpa = init.gpa;
    const io = init.io;
    // ...
}

The leak checking is then done automatically for you. There is also other stuff in there.

The gpa that is provided is determined as follows:

const gpa = if (use_safe_allocator)
        safe_allocator.allocator()
    else if (builtin.link_libc)
        std.heap.c_allocator
    else if (is_wasm)
        std.heap.wasm_allocator
    else if (!builtin.single_threaded)
        std.heap.smp_allocator
    else
        comptime unreachable;

The SafeAllocator is afaik basically like a light version of the DebugAllocator(which is similar to the old GeneralPurposeAllocator in before 0.14 times) that tracks a bit less.

You of course don’t have to use it and can just define the DebugAllocator like you did before. I just copy-pasted your snippet and it seemed to work.
Or you can define your own SafeAllocator:

var gpa_instance = std.heap.SafeAllocator.init(std.heap.page_allocator, .{});
pub const gpa = gpa_instance.allocator();