From 4a884ce149b7064a8de949fe3d7bdf5212d309b8 Mon Sep 17 00:00:00 2001 From: Pekka Paalanen <pekka.paalanen@collabora.com> Date: Fri, 28 May 2021 14:40:00 +0300 Subject: [PATCH] shared: add str_printf() asprintf() has the problem that it leaves *strp undefined when it fails. Here is a simple wrapper that ensures NULL if asprintf() fails, which is much more convenient to use. This will be useful in future patches, where one needs to return error messages from maybe failing functions, and more. Signed-off-by: Pekka Paalanen <pekka.paalanen@collabora.com> --- shared/string-helpers.h | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/shared/string-helpers.h b/shared/string-helpers.h index c8ce4498cd..e7174b21aa 100644 --- a/shared/string-helpers.h +++ b/shared/string-helpers.h @@ -31,6 +31,8 @@ #include <stdint.h> #include <errno.h> #include <assert.h> +#include <stdarg.h> +#include <stdio.h> /* Convert string to integer * @@ -68,4 +70,29 @@ safe_strtoint(const char *str, int32_t *value) return true; } +/** + * Exactly like asprintf(), but sets *str_out to NULL if it fails. + * + * If str_out is NULL, does nothing. + */ +static inline void __attribute__ ((format (printf, 2, 3))) +str_printf(char **str_out, const char *fmt, ...) +{ + char *msg; + va_list ap; + int ret; + + if (!str_out) + return; + + va_start(ap, fmt); + ret = vasprintf(&msg, fmt, ap); + va_end(ap); + + if (ret >= 0) + *str_out = msg; + else + *str_out = NULL; +} + #endif /* WESTON_STRING_HELPERS_H */ -- GitLab