// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial

#ifndef QUL_PLATFORM_SKIP_PLATFORM_CONFIG
#include "platform_config.h"
#endif
#include <platform/private/alloc_overloads.h>

#include <platform/mem.h>

#include <cstdio>
#include <cstdlib>

namespace Qul {
namespace Platform {

namespace Private {
bool (*triggerMallocFailureHook)(std::size_t size) = nullptr;
}

void printHeapStats()
{
    fprintf(stderr, "Current heap allocations: %d (max: %d)\n", Private::allocatedSize, Private::maxAllocatedSize);
}

void printStackStats()
{
    fprintf(stderr, "printStackStats has not been implemented for this platform.\n");
}

void *qul_malloc(std::size_t size)
{
    if (Private::triggerMallocFailureHook && Private::triggerMallocFailureHook(size))
        return nullptr;

#ifdef QUL_ENABLE_PERFORMANCE_LOGGING
    return Private::qul_mallocPerf(size);
#else
    return std::malloc(size);
#endif
}

void qul_free(void *ptr)
{
#ifdef QUL_ENABLE_PERFORMANCE_LOGGING
    return Private::qul_freePerf(ptr);
#else
    std::free(ptr);
#endif
}

void *qul_realloc(void *ptr, size_t s)
{
#ifdef QUL_ENABLE_PERFORMANCE_LOGGING
    return Private::qul_reallocPerf(ptr, s);
#else
    return std::realloc(ptr, s);
#endif
}

} // namespace Platform
} // namespace Qul
