1 #include <string.h> 2 #include <stdint.h> 3 #include <limits.h> 4 5 #define SS (sizeof(size_t)) 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 memchr(const void * src,int c,size_t n)11void *memchr(const void *src, int c, size_t n) 12 { 13 const unsigned char *s = src; 14 c = (unsigned char)c; 15 #ifdef __GNUC__ 16 for (; ((uintptr_t)s & ALIGN) && n && *s != c; s++, n--); 17 if (n && *s != c) { 18 typedef size_t __attribute__((__may_alias__)) word; 19 const word *w; 20 size_t k = ONES * c; 21 for (w = (const void *)s; n>=SS && !HASZERO(*w^k); w++, n-=SS); 22 s = (const void *)w; 23 } 24 #endif 25 for (; n && *s != c; s++, n--); 26 return n ? (void *)s : 0; 27 } 28