From: Daan De Meyer Date: Fri, 12 Aug 2022 11:17:24 +0000 (+0200) Subject: basic: Make snprintf_ok() a static inline function X-Git-Tag: v253-rc1~56^2~6 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=3952290619614cc0f6d9fdabb4f1048a481fb6aa;p=thirdparty%2Fsystemd.git basic: Make snprintf_ok() a static inline function 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. --- diff --git a/src/basic/stdio-util.h b/src/basic/stdio-util.h index f647f125ac8..a29170e2036 100644 --- a/src/basic/stdio-util.h +++ b/src/basic/stdio-util.h @@ -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")