]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
strlcpy.[ch]: Add strlcpy_()
authorAlejandro Colomar <alx@kernel.org>
Sat, 26 Aug 2023 13:28:24 +0000 (15:28 +0200)
committerIker Pedrosa <ikerpedrosam@gmail.com>
Fri, 1 Sep 2023 07:39:23 +0000 (09:39 +0200)
This function is like strlcpy(3), but returns -1 on truncation, which
makes it much easier to test.  strlcpy(3) is useful in two cases:

-  We don't care if the output is truncated.  strlcpy(3) is fine for
   those, and the return value can be ignored.

-  Truncation is bad.  In that case, we just want to signal truncation,
   and the length of the original string is quite useless.  Return the
   length iff no truncation so that we can use it if necessary.

This simplifies the definition of the STRLCPY() macro.

Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/strlcpy.c [new file with mode: 0644]
lib/strlcpy.h

diff --git a/lib/strlcpy.c b/lib/strlcpy.c
new file mode 100644 (file)
index 0000000..fab04fe
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * SPDX-FileCopyrightText: 2022-2023, Alejandro Colomar <alx@kernel.org>
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+
+#include <config.h>
+
+#ident "$Id$"
+
+#include "strlcpy.h"
+
+
+extern inline size_t strlcpy_(char *restrict dst, const char *restrict src,
+    size_t size);
index 5ef9b8a76384955ea8b5478519740996e0e61a61..e725078b491d05779e7d4427834e3d398bc002ca 100644 (file)
  */
 
 
-#define STRLCPY(dst, src)                                                     \
-({                                                                            \
-       size_t  sz_, len_;                                                    \
-                                                                              \
-       sz_ = SIZEOF_ARRAY(dst);                                              \
-       len_ = strlcpy(dst, src, sz_);                                        \
-                                                                              \
-       (len_ >= sz_) ? -1 : len_;                                            \
-})
+#define STRLCPY(dst, src)  strlcpy_(dst, src, SIZEOF_ARRAY(dst))
+
+
+inline size_t strlcpy_(char *restrict dst, const char *restrict src,
+    size_t size);
+
+
+inline size_t
+strlcpy_(char *restrict dst, const char *restrict src, size_t size)
+{
+       size_t  len;
+
+       len = strlcpy(dst, src, size);
+
+       return (len >= size) ? -1 : len;
+}
 
 
 #endif  // include guard