// vim:fileencoding=utf-8:foldmethod=marker

#include "mem_arena_allocator.h"
#include "mem_arena.h"
#include "../../mem/mem_os.h"
#include "../../../common/aliases/aliases.h"

wapp_intern inline void *mem_arena_alloc(u64 size, void *alloc_obj);
wapp_intern inline void *mem_arena_alloc_aligned(u64 size, u64 alignment, void *alloc_obj);
wapp_intern inline void *mem_arena_realloc(void *ptr, u64 old_size, u64 new_size, void *alloc_obj);
wapp_intern inline void *mem_arena_realloc_aligned(void *ptr, u64 old_size, u64 new_size, u64 alignment,
                                                void *alloc_obj);


Allocator wapp_mem_arena_allocator_init_custom(u64 base_capacity, MemAllocFlags flags, b8 zero_buffer) {
  Allocator allocator = {0};
  b8 initialised = wapp_mem_arena_init_custom((Arena **)(&allocator.obj), base_capacity, flags, zero_buffer);
  if (!initialised) {
    return allocator;
  }

  allocator.alloc           = mem_arena_alloc;
  allocator.alloc_aligned   = mem_arena_alloc_aligned;
  allocator.realloc         = mem_arena_realloc;
  allocator.realloc_aligned = mem_arena_realloc_aligned;

  return allocator;
}

void wapp_mem_arena_allocator_clear(Allocator *allocator) {
  wapp_mem_arena_clear((Arena *)(allocator->obj));
}

void wapp_mem_arena_allocator_destroy(Allocator *allocator) {
  wapp_mem_arena_destroy((Arena **)(&(allocator->obj)));
  *allocator = (Allocator){0};
}


wapp_intern inline void *mem_arena_alloc(u64 size, void *alloc_obj) {
  Arena *arena = (Arena *)alloc_obj;
  return wapp_mem_arena_alloc(arena, size);
}

wapp_intern inline void *mem_arena_alloc_aligned(u64 size, u64 alignment, void *alloc_obj) {
  Arena *arena = (Arena *)alloc_obj;
  return wapp_mem_arena_alloc_aligned(arena, size, alignment);
}

wapp_intern inline void *mem_arena_realloc(void *ptr, u64 old_size, u64 new_size, void *alloc_obj) {
  Arena *arena = (Arena *)alloc_obj;
  return wapp_mem_arena_realloc(arena, ptr, old_size, new_size);
}

wapp_intern inline void *mem_arena_realloc_aligned(void *ptr, u64 old_size, u64 new_size, u64 alignment,
                                                void *alloc_obj) {
  Arena *arena = (Arena *)alloc_obj;
  return wapp_mem_arena_realloc_aligned(arena, ptr, old_size, new_size, alignment);
}
