Can we have a std.DefaultAllocator()

UPDATE:

already exists

I’m not understanding the question. This is the current state of std.mem.Allocator. Most users select an allocator, and there is typically a single allocator for the entire application (though this is not a requirement, they nest fairly easily):

const std = @import("std");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    // continue on using your allocator in your application...
}

std.Io is analogous to std.mem.Allocator (they are structs containing vtables, so-called “interfaces”).

There are implementations, like GeneralPurposeAllocator, or ThreadPool, or GreenThreads or whatever the implementers of the std.Io interface will be, that expose a method that returns the interface.

Example of std.Io usage:

const std = @import("std");
const Io = std.Io;

fn saveData(io: Io, data: []const u8) !void {
   var a_future = io.async(saveFile, .{io, data, "saveA.txt"});
   var b_future = io.async(saveFile, .{io, data, "saveB.txt"});

   const a_result = a_future.await(io);
   const b_result = b_future.await(io);

   try a_result;
   try b_result;

   const out: Io.File = .stdout();
   try out.writeAll(io, "save complete");
}

fn saveFile(io: Io, data: []const u8, name: []const u8) !void {
   const file = try Io.Dir.cwd().createFile(io, name, .{});
   defer file.close(io);
   try file.writeAll(io, data);
}

You can see that std.Io already contains default (or solely) Io implementation.

In the same manner std.Allocator will contain default Allocator.

I updated post

Here is the gist referrenced in Andrew’s talk:

pub fn main() !void {
    var debug_allocator: std.heap.DebugAllocator(.{}) = .init;
    const gpa = debug_allocator.allocator();
    //const gpa = std.heap.smp_allocator;

    var thread_pool: std.Io.ThreadPool = undefined;
    try thread_pool.init(.{
        .allocator = gpa,
        .n_jobs = std.Thread.getCpuCount() catch 1,
    });
    defer thread_pool.deinit();

    const io = thread_pool.io();

then you need to call your functions with io:

saveData(io, "hello world!");

In a similar manner that you can pick different allocator implementations (DebugAllocator vs smp_allocator). You can choose different io implementations ThreadPool vs GreenThreads vs SingleThreaded etc).

There is no “default” Io implementation. The user still has to pick one. By default, perhaps the author meant to express that there will be some implementations already provided in the standard library that are reasonable choices generally.

I got the point, thank you
Post was updated

Related:

2 Likes

thank you
post updated

1 Like

The concept of std.heap.DebugAllocator was proposed when SmpAllocator was introduced.
https://github.com/ziglang/zig/issues/12484