slightly cleaner strlen, also seems to compile to better code
[musl] / src / string / stpncpy.c
1 #include <string.h>
2 #include <stdlib.h>
3 #include <stdint.h>
4 #include <limits.h>
5 #include "libc.h"
6
7 #define ALIGN (sizeof(size_t)-1)
8 #define ONES ((size_t)-1/UCHAR_MAX)
9 #define HIGHS (ONES * (UCHAR_MAX/2+1))
10 #define HASZERO(x) ((x)-ONES & ~(x) & HIGHS)
11
12 char *__stpncpy(char *restrict d, const char *restrict s, size_t n)
13 {
14         size_t *wd;
15         const size_t *ws;
16
17         if (((uintptr_t)s & ALIGN) == ((uintptr_t)d & ALIGN)) {
18                 for (; ((uintptr_t)s & ALIGN) && n && (*d=*s); n--, s++, d++);
19                 if (!n || !*s) goto tail;
20                 wd=(void *)d; ws=(const void *)s;
21                 for (; n>=sizeof(size_t) && !HASZERO(*ws);
22                        n-=sizeof(size_t), ws++, wd++) *wd = *ws;
23                 d=(void *)wd; s=(const void *)ws;
24         }
25         for (; n && (*d=*s); n--, s++, d++);
26 tail:
27         memset(d, 0, n);
28         return d;
29 }
30
31 weak_alias(__stpncpy, stpncpy);
32