Skip to content

Instantly share code, notes, and snippets.

@ErnyTech
Last active July 19, 2023 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ErnyTech/68c357215e5207df214005b9ea8d3319 to your computer and use it in GitHub Desktop.
Save ErnyTech/68c357215e5207df214005b9ea8d3319 to your computer and use it in GitHub Desktop.
Allocate memory on heap, which works like he stack
align(16) struct StackHeader {
StackHeader* next = void;
void* ptrDeep = void; // stack deep ptr
}
static StackHeader* lastAllocatedHeader = null;
void[] allocaHeap(size_t size) {
import core.stdc.stdlib : malloc, free;
int dummy = void;
auto ptrDeep = cast(void*) &dummy;
// Heap garbage collection
// Run when stack is deeper
auto header = lastAllocatedHeader;
while (header != null) {
if (header.ptrDeep < ptrDeep) {
auto nextHeader = header.next;
free(header);
header = nextHeader;
} else {
break;
}
}
lastAllocatedHeader = header;
// End garbage collection
if (size == 0) {
return null;
}
// Allocate memory on heap, DONT INVOKE FREE ON THIS! MEMORY IS AUTO-MANAGED!
auto allocatedMem = malloc(StackHeader.sizeof + size);
if (allocatedMem == null) {
return null;
}
// Set stack header with new value
auto newHeader = cast(StackHeader*) allocatedMem;
newHeader.next = lastAllocatedHeader;
newHeader.ptrDeep = ptrDeep;
// Set last allocated stack header
lastAllocatedHeader = newHeader;
// Memory is after the header
return (allocatedMem + StackHeader.sizeof)[0..size];
}
T[] allocaHeapArray(T)(size_t size) {
return cast(T[]) allocaHeap(size*T.sizeof);
}
void collectHeap() {
allocaHeap(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment