* Fwd: Alignment check in strlen
[not found] <CAMRJFfKkghLFLpxg4C12XQmNiWZpZbZGVYWwup5dXmZ7Ty=W-g@mail.gmail.com>
@ 2013-02-20 18:05 ` Jonas Wagner
2013-02-20 18:22 ` Szabolcs Nagy
0 siblings, 1 reply; 2+ messages in thread
From: Jonas Wagner @ 2013-02-20 18:05 UTC (permalink / raw)
To: musl
[-- Attachment #1.1: Type: text/plain, Size: 517 bytes --]
Dear all,
attached is a patch that makes the alignment check in strlen more
consistent with the one in memcpy, and hopefully faster.
In src/string/memcpy.c, I find the following:
#define ALIGN (sizeof(size_t)-1)
if (((uintptr_t)d & ALIGN) != ((uintptr_t)s & ALIGN))
goto misaligned;
In src/string/strlen.c, a different check was used instead:
#define ALIGN (sizeof(size_t))
for (; (uintptr_t)s % ALIGN; s++) if (!*s) return s-a;
I do not think there is any particular reason for this difference.
Best,
Jonas
[-- Attachment #1.2: Type: text/html, Size: 1166 bytes --]
[-- Attachment #2: 0001-strlen-use-bitwise-AND-for-alignment-test-instead-of.patch --]
[-- Type: application/octet-stream, Size: 1018 bytes --]
From d2b8aff9b799a2402e7f7769bdfa511cc246768b Mon Sep 17 00:00:00 2001
From: Jonas Wagner <jonas.wagner@epfl.ch>
Date: Wed, 20 Feb 2013 18:50:01 +0100
Subject: [PATCH] strlen: use bitwise AND for alignment test, instead of %.
---
src/string/strlen.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/string/strlen.c b/src/string/strlen.c
index d6f8631..92784ea 100644
--- a/src/string/strlen.c
+++ b/src/string/strlen.c
@@ -3,7 +3,7 @@
#include <stdint.h>
#include <limits.h>
-#define ALIGN (sizeof(size_t))
+#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)
@@ -12,7 +12,7 @@ size_t strlen(const char *s)
{
const char *a = s;
const size_t *w;
- for (; (uintptr_t)s % ALIGN; s++) if (!*s) return s-a;
+ for (; (uintptr_t)s & ALIGN; s++) if (!*s) return s-a;
for (w = (const void *)s; !HASZERO(*w); w++);
for (s = (const void *)w; *s; s++);
return s-a;
--
1.7.10.4
^ permalink raw reply [flat|nested] 2+ messages in thread