5 static char *twobyte_strstr(const unsigned char *h, const unsigned char *n)
7 uint16_t nw = n[0]<<8 | n[1], hw = h[0]<<8 | h[1];
8 for (h++; *h && hw != nw; hw = hw<<8 | *++h);
9 return *h ? (char *)h-1 : 0;
12 static char *threebyte_strstr(const unsigned char *h, const unsigned char *n)
14 uint32_t nw = n[0]<<24 | n[1]<<16 | n[2]<<8;
15 uint32_t hw = h[0]<<24 | h[1]<<16 | h[2]<<8;
16 for (h+=2; *h && hw != nw; hw = (hw|*++h)<<8);
17 return *h ? (char *)h-2 : 0;
20 static char *fourbyte_strstr(const unsigned char *h, const unsigned char *n)
22 uint32_t nw = n[0]<<24 | n[1]<<16 | n[2]<<8 | n[3];
23 uint32_t hw = h[0]<<24 | h[1]<<16 | h[2]<<8 | h[3];
24 for (h+=3; *h && hw != nw; hw = hw<<8 | *++h);
25 return *h ? (char *)h-3 : 0;
28 #define MAX(a,b) ((a)>(b)?(a):(b))
29 #define MIN(a,b) ((a)<(b)?(a):(b))
31 #define BITOP(a,b,op) \
32 ((a)[(size_t)(b)/(8*sizeof *(a))] op (size_t)1<<((size_t)(b)%(8*sizeof *(a))))
34 static char *twoway_strstr(const unsigned char *h, const unsigned char *n)
36 const unsigned char *z;
37 size_t l, ip, jp, k, p, ms, p0, mem, mem0;
38 size_t byteset[32 / sizeof(size_t)] = { 0 };
41 /* Computing length of needle and fill shift table */
42 for (l=0; n[l] && h[l]; l++)
43 BITOP(byteset, n[l], |=), shift[n[l]] = l+1;
44 if (n[l]) return 0; /* hit the end of h */
46 /* Compute maximal suffix */
47 ip = -1; jp = 0; k = p = 1;
49 if (n[ip+k] == n[jp+k]) {
54 } else if (n[ip+k] > n[jp+k]) {
66 /* And with the opposite comparison */
67 ip = -1; jp = 0; k = p = 1;
69 if (n[ip+k] == n[jp+k]) {
74 } else if (n[ip+k] < n[jp+k]) {
83 if (ip+1 > ms+1) ms = ip;
86 /* Periodic needle? */
87 if (memcmp(n, n+p, ms+1)) {
89 p = MAX(ms, l-ms-1) + 1;
93 /* Initialize incremental end-of-haystack pointer */
98 /* Update incremental end-of-haystack pointer */
100 /* Fast estimate for MIN(l,63) */
101 size_t grow = l | 63;
102 const unsigned char *z2 = memchr(z, 0, grow);
105 if (z-h < l) return 0;
109 /* Check last byte first; advance by shift on mismatch */
110 if (BITOP(byteset, h[l-1], &)) {
112 //printf("adv by %zu (on %c) at [%s] (%zu;l=%zu)\n", k, h[l-1], h, shift[h[l-1]], l);
114 if (mem0 && mem && k < p) k = l-p;
125 /* Compare right half */
126 for (k=MAX(ms+1,mem); n[k] && n[k] == h[k]; k++);
132 /* Compare left half */
133 for (k=ms+1; k>mem && n[k-1] == h[k-1]; k--);
134 if (k == mem) return (char *)h;
140 char *strstr(const char *h, const char *n)
142 /* Return immediately on empty needle */
143 if (!n[0]) return (char *)h;
145 /* Use faster algorithms for short needles */
147 if (!h || !n[1]) return (char *)h;
149 if (!n[2]) return twobyte_strstr((void *)h, (void *)n);
151 if (!n[3]) return threebyte_strstr((void *)h, (void *)n);
153 if (!n[4]) return fourbyte_strstr((void *)h, (void *)n);
155 return twoway_strstr((void *)h, (void *)n);