#include "BumpAlloc.h"
#include "Types.h"
#include <stdio.h>
#include <stdlib.h>

struct BumpArena {
    void* memory;
    usize size;
    usize top;
};

BumpArena
B_create(usize size) {
    struct BumpArena *b = malloc(sizeof(struct BumpArena));
    b->memory = malloc(size);
    b->size = size;
    b->top = 0;

    return b;
}

Result
B_destroy(BumpArena bp) {
    if (NULL == bp)
        return R_Uninitialized;

    struct BumpArena b = *(struct BumpArena*)bp;

    if (NULL == b.memory) {
        free(bp);
        return R_Uninitialized;
    }

    free(b.memory);
    free(bp);

    return R_Ok;
}

static inline usize*
top_size(struct BumpArena* b) {
    return (usize*)(b->memory + b->top);
}

void*
B_alloc(BumpArena bp, usize size) {
    if (bp == NULL || size == 0)
        return NULL;

    struct BumpArena *b = (struct BumpArena*)bp;

    if (size + b->top + sizeof(usize) > b->size)
        return NULL;

    if (b->top > 0)
        b->top += sizeof(usize);
    usize start = b->top;

    b->top += size;
    // Keep allocated memory size at the end of every allocation
    *top_size(b) = size;

    return b->memory + start;
}

int
B_resizeable(BumpArena bp, void* ptr) {
    if (NULL == bp)
        return 0;

    struct BumpArena *b = (struct BumpArena*)bp;

    return b->memory + b->top - *top_size(b) <= ptr &&
           ptr < b->memory + b->top;
}

Result
B_resize(BumpArena bp, usize size) {
    if (NULL == bp)
        return R_Uninitialized;

    struct BumpArena *b = (struct BumpArena*)bp;

    if (size == 0) {
        B_free(bp);
        return R_Ok;
    }

    usize last_size = *top_size(b);
    usize start = b->top - last_size;

    if (start + size + sizeof(usize) > b->size)
        return R_OutOfBounds;

    *top_size(b) = 0;
    b->top = start + size;
    *top_size(b) = size;

    return R_Ok;
}

Result
B_free(BumpArena bp) {
    if (NULL == bp)
        return R_Uninitialized;

    struct BumpArena *b = (struct BumpArena*)bp;

    if (b->top > 0) {
        b->top -= *top_size(b);
        if (b->top > 0)
            b->top -= sizeof(usize);
    }

    return R_Ok;
}
