2ccb31bb012b3b29cd536845ed1423c5a431054a
[musl] / src / string / memccpy.c
1 #include <string.h>
2 #include <stdlib.h>
3 #include <stdint.h>
4 #include <limits.h>
5
6 #define ALIGN (sizeof(size_t)-1)
7 #define ONES ((size_t)-1/UCHAR_MAX)
8 #define HIGHS (ONES * (UCHAR_MAX/2+1))
9 #define HASZERO(x) ((x)-ONES & ~(x) & HIGHS)
10
11 void *memccpy(void *dest, const void *src, int c, size_t n)
12 {
13         unsigned char *d = dest;
14         const unsigned char *s = src;
15         size_t *wd, k;
16         const size_t *ws;
17
18         c = (unsigned char)c;
19         if (((uintptr_t)s & ALIGN) == ((uintptr_t)d & ALIGN)) {
20                 for (; ((uintptr_t)s & ALIGN) && n && (*d=*s)!=c; n--, s++, d++);
21                 if ((uintptr_t)s & ALIGN) goto tail;
22                 k = ONES * c;
23                 wd=(void *)d; ws=(const void *)s;
24                 for (; n>=sizeof(size_t) && !HASZERO(*ws^k);
25                        n-=sizeof(size_t), ws++, wd++) *wd = *ws;
26                 d=(void *)wd; s=(const void *)ws;
27         }
28         for (; n && (*d=*s)!=c; n--, s++, d++);
29 tail:
30         if (*s==c) return d+1;
31         return 0;
32 }