#include "MemoryManager.h"
#include "Types.h"
#include <stdlib.h>
#include <string.h>

Result
std_alloc(MemoryManager mm, void **ptr, usize size) {
    if (NULL == ptr)
        return R_NullArgument;

    *ptr = malloc(size);
    return (*ptr == NULL) ? R_Err : R_Ok;
}

Result
std_realloc(MemoryManager mm, void **ptr, usize size) {
    if (NULL == ptr)
        return R_NullArgument;

    *ptr = realloc(*ptr, size);
    return (*ptr == NULL) ? R_Err : R_Ok;
}

Result
std_free(MemoryManager mm, void **ptr) {
    if (NULL == ptr)
        return R_NullArgument;

    free(*ptr);
    *ptr = NULL;
    return R_Ok;
}

Result
std_destroy(MemoryManager *mm) {
    return R_Unavailable;
}

MemoryManager
M_std() {
    return (MemoryManager){
        .alloc = &std_alloc,
        .realloc = &std_realloc,
        .free = &std_free,
        .destroy = &std_destroy,
    };
}

char*
M_strdup(MemoryManager mm, const char* str) {
    if (NULL == str)
        return NULL;

    char* newstr = NULL;
    if (R_Ok != mm.alloc(mm, (void**)&newstr, strlen(str) + 1) ||
        NULL == newstr)
    {
        return NULL;
    }

    strcpy(newstr, str);
    return newstr;
}
