add AllocCopy functions

This commit is contained in:
Matthew 2025-09-27 19:38:40 +10:00
parent 235b077266
commit fe1a04d3b4

63
alloc.d
View File

@ -75,13 +75,27 @@ Alloc(T)()
} }
T[] T[]
AllocArray(T)(u64 count) Alloc(T)(u64 count)
{ {
void* mem = pureMalloc(T.sizeof * count); void* mem = pureMalloc(T.sizeof * count);
memset(mem, 0, T.sizeof * count); memset(mem, 0, T.sizeof * count);
return (cast(T*)mem)[0 .. count]; return (cast(T*)mem)[0 .. count];
} }
T[]
AllocCopy(T)(T[] target)
{
T[] arr = Alloc!(T)(target.length);
arr[] = target[];
return arr;
}
T[]
AllocArray(T)(u64 count)
{
return Alloc!(T)(count);
}
T[] T[]
ReallocArray(T)(T[] arr, u64 count) ReallocArray(T)(T[] arr, u64 count)
{ {
@ -143,10 +157,22 @@ End(TempArena* t)
} }
} }
T[]
AllocCopy(T)(TempArena* t, T[] target)
{
return AllocCopy!(T)(t.arena, target);
}
T[]
Alloc(T)(TempArena* t, u64 count)
{
return Alloc!(T)(t.arena, count);
}
T[] T[]
AllocArray(T)(TempArena* t, u64 count) AllocArray(T)(TempArena* t, u64 count)
{ {
return AllocArray!(T)(t.arena, count); return Alloc!(T)(t.arena, count);
} }
T* T*
@ -171,13 +197,27 @@ AddArenaPool(Arena* arena)
} }
T[] T[]
AllocArray(T)(Arena* arena, u64 count) Alloc(T)(Arena* arena, u64 count)
{ {
void* mem = AllocAlign(arena, T.sizeof * count, DEFAULT_ALIGNMENT); void* mem = AllocAlign(arena, T.sizeof * count, DEFAULT_ALIGNMENT);
memset(mem, 0, T.sizeof * count); memset(mem, 0, T.sizeof * count);
return (cast(T*)mem)[0 .. count]; return (cast(T*)mem)[0 .. count];
} }
T[]
AllocArray(T)(Arena* arena, u64 count)
{
return Alloc!(T)(arena, count);
}
T[]
AllocCopy(T)(Arena* arena, T[] target)
{
T[] arr = Alloc!(T)(arena, target.length);
arr[] = target[];
return arr;
}
T* T*
Alloc(T)(Arena* arena) Alloc(T)(Arena* arena)
{ {
@ -278,3 +318,20 @@ ScratchAlloc(T)(u64 count)
{ {
return AllocArray!(T)(&g_scratch.arena, count); return AllocArray!(T)(&g_scratch.arena, count);
} }
T[]
ScratchAllocCopy(T)(T[] target)
{
T[] arr = ScratchAlloc!(T)(target.length);
arr[] = target[];
return arr;
}
unittest
{
u64[5] arr = [1, 2, 3, 4, 5];
u64[] copy = AllocCopy!(u64)(arr);
assert(arr == copy);
}