|
| 1 | +// This file makes the glue between mimalloc heap allocation and libdom memory |
| 2 | +// management. |
| 3 | +// We replace the libdom default usage of allocations with mimalloc heap |
| 4 | +// allocation to be able to free all memory used at once, like an arena usage. |
| 5 | + |
| 6 | +const std = @import("std"); |
| 7 | +const c = @cImport({ |
| 8 | + @cInclude("mimalloc.h"); |
| 9 | +}); |
| 10 | + |
| 11 | +const Error = error{ |
| 12 | + HeapNotNull, |
| 13 | + HeapNull, |
| 14 | +}; |
| 15 | + |
| 16 | +var heap: ?*c.mi_heap_t = null; |
| 17 | + |
| 18 | +pub fn create() Error!void { |
| 19 | + if (heap != null) return Error.HeapNotNull; |
| 20 | + heap = c.mi_heap_new(); |
| 21 | + if (heap == null) return Error.HeapNull; |
| 22 | +} |
| 23 | + |
| 24 | +pub fn destroy() void { |
| 25 | + if (heap == null) return; |
| 26 | + c.mi_heap_destroy(heap.?); |
| 27 | + heap = null; |
| 28 | +} |
| 29 | + |
| 30 | +pub export fn m_alloc(size: usize) callconv(.C) ?*anyopaque { |
| 31 | + if (heap == null) return null; |
| 32 | + return c.mi_heap_malloc(heap.?, size); |
| 33 | +} |
| 34 | + |
| 35 | +pub export fn re_alloc(ptr: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque { |
| 36 | + if (heap == null) return null; |
| 37 | + return c.mi_heap_realloc(heap.?, ptr, size); |
| 38 | +} |
| 39 | + |
| 40 | +pub export fn c_alloc(nmemb: usize, size: usize) callconv(.C) ?*anyopaque { |
| 41 | + if (heap == null) return null; |
| 42 | + return c.mi_heap_calloc(heap.?, nmemb, size); |
| 43 | +} |
| 44 | + |
| 45 | +pub export fn str_dup(s: [*c]const u8) callconv(.C) [*c]u8 { |
| 46 | + if (heap == null) return null; |
| 47 | + return c.mi_heap_strdup(heap.?, s); |
| 48 | +} |
| 49 | + |
| 50 | +pub export fn strn_dup(s: [*c]const u8, size: usize) callconv(.C) [*c]u8 { |
| 51 | + if (heap == null) return null; |
| 52 | + return c.mi_heap_strndup(heap.?, s, size); |
| 53 | +} |
| 54 | + |
| 55 | +// NOOP, use destroy to clear all the memory allocated at once. |
| 56 | +pub export fn f_ree(_: ?*anyopaque) callconv(.C) void { |
| 57 | + return; |
| 58 | +} |
0 commit comments