diff options
| author | Mitchell Hashimoto <m@mitchellh.com> | 2025-09-24 10:19:13 -0700 |
|---|---|---|
| committer | Mitchell Hashimoto <m@mitchellh.com> | 2025-09-24 10:30:13 -0700 |
| commit | 2c78ad8889dee68e4fd06a975593d0c8fc476210 (patch) | |
| tree | 102784eb3221f9f20e7ff01fa94e70429a7dedfa /src/lib | |
| parent | de013148d3c2c6b59c5dd035a3a72dd6132445c0 (diff) | |
lib-vt: setup a default allocator if null
Diffstat (limited to 'src/lib')
| -rw-r--r-- | src/lib/allocator.zig | 16 |
1 files changed, 16 insertions, 0 deletions
diff --git a/src/lib/allocator.zig b/src/lib/allocator.zig index ef296f23d..de1453dbe 100644 --- a/src/lib/allocator.zig +++ b/src/lib/allocator.zig @@ -13,6 +13,22 @@ pub const VTable = extern struct { free: *const fn (*anyopaque, memory: [*]u8, memory_len: usize, alignment: u8, ret_addr: usize) callconv(.c) void, }; +/// Returns an allocator to use for the given possibly-null C allocator, +/// ensuring some allocator is always returned. +pub fn default(c_alloc_: ?*const Allocator) std.mem.Allocator { + // If we're given an allocator, use it. + if (c_alloc_) |c_alloc| return c_alloc.zig(); + + // If we have libc, use that. We prefer libc if we have it because + // its generally fast but also lets the embedder easily override + // malloc/free with custom allocators like mimalloc or something. + if (comptime builtin.link_libc) return std.heap.c_allocator; + + // No libc, use the preferred allocator for releases which is the + // Zig SMP allocator. + return std.heap.smp_allocator; +} + /// The Allocator interface for custom memory allocation strategies /// within C libghostty APIs. /// |
