summaryrefslogtreecommitdiffstats
path: root/shared/string-helpers.h
diff options
context:
space:
mode:
authorMarius Vlad <marius.vlad@collabora.com>2022-09-19 22:56:43 +0300
committerMarius Vlad <marius.vlad@collabora.com>2022-09-22 14:28:47 +0300
commit86146a4e7455769d2057ff886c1f9ea7a67d84c2 (patch)
tree099b2da5aeb59454ea2c53a9a9a4f52ffe78ea99 /shared/string-helpers.h
parent1b93121761e16117d1926e8d57bad17cc5b2701a (diff)
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. Bug-AGL: SPEC-4510 Signed-off-by: Pekka Paalanen <pekka.paalanen@collabora.com> Signed-off-by: Marius Vlad <marius.vlad@collabora.com> Change-Id: I2e689551797da525d110a51b02fd608c9e07c567
Diffstat (limited to 'shared/string-helpers.h')
-rw-r--r--shared/string-helpers.h26
1 files changed, 26 insertions, 0 deletions
diff --git a/shared/string-helpers.h b/shared/string-helpers.h
index c8ce449..3c2f07f 100644
--- a/shared/string-helpers.h
+++ b/shared/string-helpers.h
@@ -27,6 +27,7 @@
#define WESTON_STRING_HELPERS_H
#include <stdbool.h>
+#include <stdarg.h>
#include <stdlib.h>
#include <stdint.h>
#include <errno.h>
@@ -68,4 +69,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 */