#include "stack_alloc.h"

#include "memory.h"

BzStackAlloc bzStackAllocCreate(size_t size) {
    BzStackAlloc alloc = {
            .memory=bzAlloc(size),
            .size=size,
            .allocated=0
    };
    BZ_ASSERT(alloc.memory);

    return alloc;
}

void bzStackAllocDestroy(BzStackAlloc *alloc) {
    bzFree(alloc->memory);
    alloc->memory    = NULL;
    alloc->size      = 0;
    alloc->allocated = 0;
}

void bzStackAllocReset(BzStackAlloc *alloc) {
    alloc->allocated = 0;
}

void *bzStackAlloc(BzStackAlloc *alloc, size_t numBytes) {
    BZ_ASSERT(alloc->allocated + numBytes < alloc->size);
    void *allocated = (u8 *) alloc->memory + alloc->allocated;
    alloc->allocated += numBytes;
    return allocated;
}

void bzStackAllocFree(BzStackAlloc *alloc, void *ptr) {
    size_t byteOffset = (u8 *) ptr - (u8 *) alloc->memory;
    BZ_ASSERT(byteOffset >= 0 && byteOffset < alloc->size);
    alloc->allocated = byteOffset;
}
