blob: d3563f18c932d139b7b78f5e37a473518671a5a0 [file] [log] [blame]
Rich Felker0b44a032011-02-12 00:22:29 -05001#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
11char *strchr(const char *s, int c)
12{
Rich Felkerc68b2632011-04-03 18:16:11 -040013 size_t *w, k;
14
15 c = (unsigned char)c;
Rich Felker0b44a032011-02-12 00:22:29 -050016 if (!c) return (char *)s + strlen(s);
Rich Felkerc68b2632011-04-03 18:16:11 -040017
Rich Felker16675df2011-04-05 09:27:41 -040018 for (; ((uintptr_t)s & ALIGN); s++)
Rich Felkerc68b2632011-04-03 18:16:11 -040019 if (*(unsigned char *)s == c) return (char *)s;
Rich Felker16675df2011-04-05 09:27:41 -040020 else if (!*s) return 0;
Rich Felkerc68b2632011-04-03 18:16:11 -040021 k = ONES * c;
22 for (w = (void *)s; !HASZERO(*w) && !HASZERO(*w^k); w++);
23 for (s = (void *)w; *s; s++)
24 if (*(unsigned char *)s == c) return (char *)s;
25 return 0;
Rich Felker0b44a032011-02-12 00:22:29 -050026}