]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
lib/string/sprintf.h: Add SNPRINTF() macro
authorAlejandro Colomar <alx@kernel.org>
Sat, 26 Aug 2023 10:11:59 +0000 (12:11 +0200)
committerIker Pedrosa <ikerpedrosam@gmail.com>
Fri, 15 Dec 2023 15:41:47 +0000 (16:41 +0100)
It wraps snprintf(3) so that it performs some steps that one might
forget, or might be prone to accidents:

-  It calculates the size of the destination buffer, and makes sure it's
   an array (otherwise, using sizeof(s) would be very bad).

-  It calculates if there's truncation or an error, returning -1 if so.

BTW, this macro doesn't have any issues of double evaluation, because
sizeof() doesn't evaluate its argument (unless it's a VLA, but then the
static_assert(3) within NITEMS() makes sure VLAs are not allowed).

This macro is very similar to STRTCPY(), defined in
<lib/string/strtcpy.h>.

Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/string/sprintf.h

index c9d7e6c78e7f831a106cd8a2ccf5da2f2f614eac..33e0bc2d3d0199a8543b61a3d2d40a7a5700325c 100644 (file)
 
 #include "attr.h"
 #include "defines.h"
+#include "sizeof.h"
+
+
+#define SNPRINTF(s, fmt, ...)                                                 \
+({                                                                            \
+       size_t  sz_, len_;                                                    \
+                                                                              \
+       sz_ = NITEMS(s);                                                      \
+       len_ = snprintf(s, sz_, fmt __VA_OPT__(,) __VA_ARGS__);               \
+                                                                              \
+       (len_ >= sz_) ? -1 : len_;                                            \
+})
 
 
 format_attr(printf, 2, 3)