|
Message-Id: <1359936735-31915-5-git-send-email-nwmcsween@gmail.com> Date: Mon, 4 Feb 2013 00:12:15 +0000 From: Nathan McSween <nwmcsween@...il.com> To: musl@...ts.openwall.com Cc: Nathan McSween <nwmcsween@...il.com> Subject: [PATCH 4/4] String: refactor to utilize word.h and always terminate string --- src/string/strlcpy.c | 56 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 32 insertions(+), 24 deletions(-) diff --git a/src/string/strlcpy.c b/src/string/strlcpy.c index 4d3ff92..bc26441 100644 --- a/src/string/strlcpy.c +++ b/src/string/strlcpy.c @@ -1,32 +1,40 @@ -#include <string.h> -#include <stdlib.h> +#include <stddef.h> #include <stdint.h> -#include <limits.h> -#include "libc.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) +#include <string.h> +#include "word.h" +/** + * strlcpy - Word sized bsd strlcpy. + * @d: Destination + * @s: Source + * @n: Max @s + */ size_t strlcpy(char *d, const char *s, size_t n) { - char *d0 = d; + char *z = d; size_t *wd; const size_t *ws; - if (!n--) goto finish; - 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; - } - } - for (; n && (*d=*s); n--, s++, d++); - *d = 0; -finish: - return d-d0 + strlen(s); + /* A byte for nul */ + if (!n--) goto terminate; + + if ((uintptr_t)d % sizeof(size_t) != (uintptr_t)s % sizeof(size_t)) + goto misaligned; + + for (; (uintptr_t)s % sizeof(size_t); *d++ = *s++, n--) + if (!*s || !n) goto terminate; + + for (wd = (size_t *)d, ws= (const size_t *)s + ; !word_has_zero(*ws) && n >= sizeof(size_t) + ; *wd = *ws, wd++, ws++, n -= sizeof(size_t)) + + d = (char *)wd; + s = (const char *)ws; + +misaligned: + for (; (*d = *s) && n; d++, s++, n--); +terminate: + *d = '\0'; + + return d - z + strlen(s); } -- 1.7.11.4
Powered by blists - more mailing lists
Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.