From d5f6697f3a592245e8bd12a0ea8dbd24d3129296 Mon Sep 17 00:00:00 2001 From: Romain Vimont Date: Wed, 24 Nov 2021 19:55:00 +0100 Subject: [PATCH] Add (v)asprintf compatibility functions In case they are not available on the platform. --- app/meson.build | 2 ++ app/src/compat.c | 36 ++++++++++++++++++++++++++++++++++++ app/src/compat.h | 8 ++++++++ 3 files changed, 46 insertions(+) diff --git a/app/meson.build b/app/meson.build index 32adf18b..1561fdcd 100644 --- a/app/meson.build +++ b/app/meson.build @@ -138,6 +138,8 @@ endif check_functions = [ 'strdup', + 'asprintf', + 'vasprintf', ] foreach f : check_functions diff --git a/app/src/compat.c b/app/src/compat.c index 4d084517..11ddd3cb 100644 --- a/app/src/compat.c +++ b/app/src/compat.c @@ -2,7 +2,10 @@ #include "config.h" +#include #include +#include +#include #include #ifndef HAVE_STRDUP @@ -15,3 +18,36 @@ char *strdup(const char *s) { return dup; } #endif + +#ifndef HAVE_ASPRINTF +int asprintf(char **strp, const char *fmt, ...) { + va_list va; + va_start(va, fmt); + int ret = vasprintf(strp, fmt, va); + va_end(va); + return ret; +} +#endif + +#ifndef HAVE_VASPRINTF +int vasprintf(char **strp, const char *fmt, va_list ap) { + va_list va; + va_copy(va, ap); + int len = vsnprintf(NULL, 0, fmt, va); + va_end(va); + + char *str = malloc(len + 1); + if (!str) { + return -1; + } + + va_copy(va, ap); + int len2 = vsnprintf(str, len + 1, fmt, va); + (void) len2; + assert(len == len2); + va_end(va); + + *strp = str; + return len; +} +#endif diff --git a/app/src/compat.h b/app/src/compat.h index c06c23fa..3ab56049 100644 --- a/app/src/compat.h +++ b/app/src/compat.h @@ -58,4 +58,12 @@ char *strdup(const char *s); #endif +#ifndef HAVE_ASPRINTF +int asprintf(char **strp, const char *fmt, ...); +#endif + +#ifndef HAVE_VASPRINTF +int vasprintf(char **strp, const char *fmt, va_list ap); +#endif + #endif