#include #include #define aliases __attribute__((__may_alias__)) #define byte_repeat(x) ((size_t)~0 / 0xff * (x)) #define word_has_zero(x) (((x) - byte_repeat(0x01)) & ~(x) & byte_repeat(0x80)) void *memchr(const void *_s, int i, size_t n) { i = (unsigned char)i; const unsigned char *s = _s; const size_t aliases *ws, wi = byte_repeat(i); if (n < sizeof(size_t) * 3) goto bytewise; for (; (uintptr_t)s & sizeof(size_t) - 1 && *s != i; s++, n--); if ((uintptr_t)s & sizeof(size_t) - 1) return (void *)s; ws = (const void *)s; for (; n >= sizeof(size_t) && !word_has_zero(*ws ^ wi) ; ws++, n -= sizeof(size_t)); s = (const void *)ws; bytewise: for (; n && *s != i; s++, n--); return n ? (void *)s : 0; }