strchr.c 631 B

1234567891011121314151617181920212223242526
  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <limits.h>
  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. char *strchr(const char *s, int c)
  10. {
  11. size_t *w, k;
  12. c = (unsigned char)c;
  13. if (!c) return (char *)s + strlen(s);
  14. for (; ((uintptr_t)s & ALIGN); s++)
  15. if (*(unsigned char *)s == c) return (char *)s;
  16. else if (!*s) return 0;
  17. k = ONES * c;
  18. for (w = (void *)s; !HASZERO(*w) && !HASZERO(*w^k); w++);
  19. for (s = (void *)w; *s; s++)
  20. if (*(unsigned char *)s == c) return (char *)s;
  21. return 0;
  22. }