[lxc-devel] [lxc/master] include: simplify strlcpy()

brauner on Github lxc-bot at linuxcontainers.org
Thu Oct 18 11:06:23 UTC 2018


A non-text attachment was scrubbed...
Name: not available
Type: text/x-mailbox
Size: 364 bytes
Desc: not available
URL: <http://lists.linuxcontainers.org/pipermail/lxc-devel/attachments/20181018/7ef55fc0/attachment.bin>
-------------- next part --------------
From 27bd77920d39bc660e314ba0211d9f35e96076cf Mon Sep 17 00:00:00 2001
From: Christian Brauner <christian.brauner at ubuntu.com>
Date: Thu, 18 Oct 2018 12:50:13 +0200
Subject: [PATCH] include: simplify strlcpy()

Signed-off-by: Christian Brauner <christian.brauner at ubuntu.com>
---
 src/include/strlcpy.c | 40 +++++++---------------------------------
 1 file changed, 7 insertions(+), 33 deletions(-)

diff --git a/src/include/strlcpy.c b/src/include/strlcpy.c
index 7be64c817..37782d394 100644
--- a/src/include/strlcpy.c
+++ b/src/include/strlcpy.c
@@ -19,43 +19,17 @@
  * This function has been copied from musl.
  */
 
-#include <limits.h>
-#include <stdint.h>
 #include <string.h>
 
-#define ALIGN (sizeof(size_t) - 1)
-#define ONES ((size_t)-1 / UCHAR_MAX)
-#define HIGHS (ONES * (UCHAR_MAX / 2 + 1))
-#define HASZERO(x) (((x)-ONES) & ~(x)&HIGHS)
-
-size_t strlcpy(char *d, const char *s, size_t n)
+size_t strlcpy(char *dest, const char *src, size_t size)
 {
-	char *d0 = d;
-	size_t *wd;
-	const size_t *ws;
-
-	if (!n--)
-		goto finish;
+	size_t ret = strlen(src);
 
-	if (((uintptr_t)s & ALIGN) == ((uintptr_t)d & ALIGN)) {
-		for (; ((uintptr_t)s & ALIGN) && n && (*d = *s); n--, s++, d++)
-			;
-		if (n && *s) {
-			wd = (void *)d;
-			ws = (const void *)s;
-			for (; n >= sizeof(size_t) && !HASZERO(*ws);
-			     n -= sizeof(size_t), ws++, wd++)
-				*wd = *ws;
-			d = (void *)wd;
-			s = (const void *)ws;
-		}
+	if (size) {
+		size_t len = (ret >= size) ? size - 1 : ret;
+		memcpy(dest, src, len);
+		dest[len] = '\0';
 	}
 
-	for (; n && (*d = *s); n--, s++, d++)
-		;
-
-	*d = 0;
-
-finish:
-	return d - d0 + strlen(s);
+	return ret;
 }


More information about the lxc-devel mailing list