]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
lib/sprintf.[ch]: Add x[v]asprintf()
authorAlejandro Colomar <alx@kernel.org>
Fri, 25 Aug 2023 23:27:12 +0000 (01:27 +0200)
committerAlejandro Colomar <alx@kernel.org>
Fri, 20 Oct 2023 19:05:33 +0000 (21:05 +0200)
As other x...() wrappers around functions that allocate, these wrappers
are like [v]asprintf(3), but exit on failure.

Reviewed-by: Iker Pedrosa <ipedrosa@redhat.com>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/Makefile.am
lib/sprintf.c [new file with mode: 0644]
lib/sprintf.h [new file with mode: 0644]

index 897f0602fef1ed58cee6fd47184940c21c0b5ae5..d6b639c60f12231d4b6f88b202206114aef66869 100644 (file)
@@ -133,6 +133,8 @@ libshadow_la_SOURCES = \
        shell.c \
        sizeof.h \
        spawn.c \
+       sprintf.c \
+       sprintf.h \
        sssd.c \
        sssd.h \
        stpecpy.c \
diff --git a/lib/sprintf.c b/lib/sprintf.c
new file mode 100644 (file)
index 0000000..fee58ca
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+#include <config.h>
+
+#ident "$Id$"
+
+#include "sprintf.h"
+
+#include <stdarg.h>
+#include <stddef.h>
+#include <stdio.h>
+
+
+extern inline int xasprintf(char **restrict s, const char *restrict fmt, ...);
+extern inline int xvasprintf(char **restrict s, const char *restrict fmt,
+    va_list ap);
diff --git a/lib/sprintf.h b/lib/sprintf.h
new file mode 100644 (file)
index 0000000..a1219f3
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+
+#ifndef SHADOW_INCLUDE_LIB_SPRINTF_H_
+#define SHADOW_INCLUDE_LIB_SPRINTF_H_
+
+
+#include <config.h>
+
+#include <stdarg.h>
+#include <stddef.h>
+#include <stdio.h>
+
+#include "defines.h"
+
+
+format_attr(printf, 2, 3)
+inline int xasprintf(char **restrict s, const char *restrict fmt, ...);
+format_attr(printf, 2, 0)
+inline int xvasprintf(char **restrict s, const char *restrict fmt, va_list ap);
+
+
+inline int
+xasprintf(char **restrict s, const char *restrict fmt, ...)
+{
+       int      len;
+       va_list  ap;
+
+       va_start(ap, fmt);
+       len = xvasprintf(s, fmt, ap);
+       va_end(ap);
+
+       return len;
+}
+
+
+inline int
+xvasprintf(char **restrict s, const char *restrict fmt, va_list ap)
+{
+       int  len;
+
+       len = vasprintf(s, fmt, ap);
+       if (len == -1) {
+               perror("asprintf");
+               exit(EXIT_FAILURE);
+       }
+
+       return len;
+}
+
+
+#endif  // include guard