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.
This commit is contained in:
Daan De Meyer
2023-01-08 16:31:15 +01:00
parent 4f79f545b3
commit 3952290619
+13 -7
View 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")