]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
basic: Make snprintf_ok() a static inline function
authorDaan De Meyer <daan.j.demeyer@gmail.com>
Fri, 12 Aug 2022 11:17:24 +0000 (13:17 +0200)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Sun, 8 Jan 2023 15:31:15 +0000 (16:31 +0100)
This allows passing pre-allocated buffers via compound initializers
to snprint_ok(). If snprintf_ok() is a macro, the compound initializer
block will be scoped to the macro block, if snprint_ok() is a function,
the compound initializer block will be scoped to the block from which
snprintf_ok() is called.

src/basic/stdio-util.h

index f647f125ac8e7d25a2a89dbc20a36a61be3b9c0b..a29170e20362d5a716e6ffada92ab1c984b5359a 100644 (file)
@@ -9,13 +9,19 @@
 #include "macro.h"
 #include "memory-util.h"
 
-#define snprintf_ok(buf, len, fmt, ...)                                 \
-        ({                                                              \
-                char *_buf = (buf);                                     \
-                size_t _len = (len);                                    \
-                int _snpf = snprintf(_buf, _len, (fmt), ##__VA_ARGS__); \
-                _snpf >= 0 && (size_t) _snpf < _len ? _buf : NULL;      \
-        })
+_printf_(3, 4)
+static inline char *snprintf_ok(char *buf, size_t len, const char *format, ...) {
+        va_list ap;
+        int r;
+
+        va_start(ap, format);
+        DISABLE_WARNING_FORMAT_NONLITERAL;
+        r = vsnprintf(buf, len, format, ap);
+        REENABLE_WARNING;
+        va_end(ap);
+
+        return r >= 0 && (size_t) r < len ? buf : NULL;
+}
 
 #define xsprintf(buf, fmt, ...) \
         assert_message_se(snprintf_ok(buf, ELEMENTSOF(buf), fmt, ##__VA_ARGS__), "xsprintf: " #buf "[] must be big enough")