/*
 * Copyright (c) 2020, Michael Grunder <michael dot grunder at gmail dot com>
 *
 * SPDX-FileCopyrightText: 2024 Hiredict Contributors
 * SPDX-FileCopyrightText: 2024 Michael Grunder <michael dot grunder at gmail dot com>
 *
 * SPDX-License-Identifier: BSD-3-Clause
 * SPDX-License-Identifier: LGPL-3.0-or-later
 *
 */

#include "fmacros.h"
#include "alloc.h"
#include <string.h>
#include <stdlib.h>

hiredictAllocFuncs hiredictAllocFns = {
    .mallocFn = malloc,
    .callocFn = calloc,
    .reallocFn = realloc,
    .strdupFn = strdup,
    .freeFn = free,
};

/* Override hiredict' allocators with ones supplied by the user */
hiredictAllocFuncs hiredictSetAllocators(hiredictAllocFuncs *override) {
    hiredictAllocFuncs orig = hiredictAllocFns;

    hiredictAllocFns = *override;

    return orig;
}

/* Reset allocators to use libc defaults */
void hiredictResetAllocators(void) {
    hiredictAllocFns = (hiredictAllocFuncs) {
        .mallocFn = malloc,
        .callocFn = calloc,
        .reallocFn = realloc,
        .strdupFn = strdup,
        .freeFn = free,
    };
}

#ifdef _WIN32

void *hi_malloc(size_t size) {
    return hiredictAllocFns.mallocFn(size);
}

void *hi_calloc(size_t nmemb, size_t size) {
    /* Overflow check as the user can specify any arbitrary allocator */
    if (SIZE_MAX / size < nmemb)
        return NULL;

    return hiredictAllocFns.callocFn(nmemb, size);
}

void *hi_realloc(void *ptr, size_t size) {
    return hiredictAllocFns.reallocFn(ptr, size);
}

char *hi_strdup(const char *str) {
    return hiredictAllocFns.strdupFn(str);
}

void hi_free(void *ptr) {
    hiredictAllocFns.freeFn(ptr);
}

#endif
