From f31cdfbedfa7cc49f795196493f484db10a7bf9d Mon Sep 17 00:00:00 2001 From: Matthew Date: Fri, 12 Sep 2025 06:39:33 +1000 Subject: [PATCH] add thread local scratch allocator --- alloc.d | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/alloc.d b/alloc.d index ca50f2c..0085b84 100644 --- a/alloc.d +++ b/alloc.d @@ -9,8 +9,16 @@ import std.stdio; import core.stdc.string : memset; import core.memory; +static Scratch g_scratch; + const DEFAULT_ALIGNMENT = (void *).sizeof * 2; +struct Scratch +{ + Arena arena; + bool init; +} + struct ArenaPool { u8* mem; @@ -173,7 +181,32 @@ FreeArray(T)(T[] arr) pureFree(arr.ptr); } -void Free(T)(T* ptr) +void +Free(T)(T* ptr) { pureFree(ptr); } + +void +ResetScratch(u64 size) +{ + if (!g_scratch.init) + { + g_scratch.arena = CreateArena(size); + g_scratch.init = true; + } + + Reset(&g_scratch.arena); +} + +T* +ScratchAlloc(T)() +{ + return Alloc!(T)(&g_scratch.arena); +} + +T[] +ScratchAlloc(T)(u64 count) +{ + return AllocArray!(T)(&g_scratch.arena, count); +}