#include "runtime.h"

#include <stdarg.h>

#ifdef __SANITIZE_ADDRESS__
/* stb_sprintf has issues with ASAN under msvc */
#define ENABLE_STB_SPRINTF 0
#else
#define ENABLE_STB_SPRINTF 1
#endif

#if ENABLE_STB_SPRINTF
#pragma warning(push, 0)
#define STB_SPRINTF_IMPLEMENTATION
#define STB_SPRINTF_STATIC
#include <stb_sprintf.h>
#pragma warning(pop)
#else
#include <stdio.h>
#endif

RT_DLLEXPORT int rtSPrint(char *dest, size_t n, const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
#if ENABLE_STB_SPRINTF
    int r = stbsp_vsnprintf(dest, (int)n, fmt, ap);
#else
    int r = vsnprintf(dest, n, fmt, ap);
    if (r >= (int)n)
        dest[n - 1] = '\0';
#endif
    va_end(ap);
    return r;
}

RT_DLLEXPORT int rtVSPrint(char *dest, size_t n, const char *fmt, va_list ap) 
{
#if ENABLE_STB_SPRINTF
    return stbsp_vsnprintf(dest, (int)n, fmt, ap);
#else
    int r = vsnprintf(dest, n, fmt, ap);
    if (r >= (int)n)
        dest[n - 1] = '\0';
    return r;
#endif
}