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