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;
29 static char *naive_strstr(const char *h, const char *n)
32 for (i=0; n[i] && h[i]; i++)
33 for ( ; n[i] != h[i]; h++, i=0);
34 return n[i] ? 0 : (char *)h;
38 #define MAX(a,b) ((a)>(b)?(a):(b))
39 #define MIN(a,b) ((a)<(b)?(a):(b))
41 #define BITOP(a,b,op) \
42 ((a)[(size_t)(b)/(8*sizeof *(a))] op (size_t)1<<((size_t)(b)%(8*sizeof *(a))))
44 static char *twoway_strstr(const unsigned char *h, const unsigned char *n)
46 const unsigned char *z;
47 size_t l, ip, jp, k, p, ms, p0, mem, mem0;
48 size_t byteset[32 / sizeof(size_t)] = { 0 };
51 /* Computing length of needle and fill shift table */
52 for (l=0; n[l] && h[l]; l++)
53 BITOP(byteset, n[l], |=), shift[n[l]] = l+1;
54 if (n[l]) return 0; /* hit the end of h */
56 /* Compute maximal suffix */
57 ip = -1; jp = 0; k = p = 1;
59 if (n[ip+k] == n[jp+k]) {
64 } else if (n[ip+k] > n[jp+k]) {
76 /* And with the opposite comparison */
77 ip = -1; jp = 0; k = p = 1;
79 if (n[ip+k] == n[jp+k]) {
84 } else if (n[ip+k] < n[jp+k]) {
93 if (ip+1 > ms+1) ms = ip;
96 /* Periodic needle? */
97 if (memcmp(n, n+p, ms+1)) {
99 p = MAX(ms, l-ms-1) + 1;
103 /* Initialize incremental end-of-haystack pointer */
108 /* Update incremental end-of-haystack pointer */
110 /* Fast estimate for MIN(l,63) */
111 size_t grow = l | 63;
112 const char *z2 = memchr(z, 0, grow);
115 if (z-h < l) return 0;
119 /* Check last byte first; advance by shift on mismatch */
120 if (BITOP(byteset, h[l-1], &)) {
122 //printf("adv by %zu (on %c) at [%s] (%zu;l=%zu)\n", k, h[l-1], h, shift[h[l-1]], l);
124 if (mem0 && mem && k < p) k = l-p;
135 /* Compare right half */
136 for (k=MAX(ms+1,mem); n[k] && n[k] == h[k]; k++);
142 /* Compare left half */
143 for (k=ms+1; k>mem && n[k-1] == h[k-1]; k--);
144 if (k == mem) return (char *)h;
150 char *strstr(const char *h, const char *n)
152 /* Return immediately on empty needle */
153 if (!n[0]) return (char *)h;
155 /* Use faster algorithms for short needles */
157 if (!h || !n[1]) return (char *)h;
159 if (!n[2]) return twobyte_strstr(h, n);
161 if (!n[3]) return threebyte_strstr(h, n);
163 if (!n[4]) return fourbyte_strstr(h, n);
165 return twoway_strstr(h, n);