6 static char *twobyte_memmem(const unsigned char *h, size_t k, const unsigned char *n)
8 uint16_t nw = n[0]<<8 | n[1], hw = h[0]<<8 | h[1];
9 for (h++, k--; k; k--, hw = hw<<8 | *++h)
10 if (hw == nw) return (char *)h-1;
14 static char *threebyte_memmem(const unsigned char *h, size_t k, const unsigned char *n)
16 uint32_t nw = n[0]<<24 | n[1]<<16 | n[2]<<8;
17 uint32_t hw = h[0]<<24 | h[1]<<16 | h[2]<<8;
18 for (h+=2, k-=2; k; k--, hw = (hw|*++h)<<8)
19 if (hw == nw) return (char *)h-2;
23 static char *fourbyte_memmem(const unsigned char *h, size_t k, const unsigned char *n)
25 uint32_t nw = n[0]<<24 | n[1]<<16 | n[2]<<8 | n[3];
26 uint32_t hw = h[0]<<24 | h[1]<<16 | h[2]<<8 | h[3];
27 for (h+=3, k-=3; k; k--, hw = hw<<8 | *++h)
28 if (hw == nw) return (char *)h-3;
32 #define MAX(a,b) ((a)>(b)?(a):(b))
33 #define MIN(a,b) ((a)<(b)?(a):(b))
35 #define BITOP(a,b,op) \
36 ((a)[(size_t)(b)/(8*sizeof *(a))] op (size_t)1<<((size_t)(b)%(8*sizeof *(a))))
38 static char *twoway_memmem(const unsigned char *h, const unsigned char *z, const unsigned char *n, size_t l)
40 size_t i, ip, jp, k, p, ms, p0, mem, mem0;
41 size_t byteset[32 / sizeof(size_t)] = { 0 };
44 /* Computing length of needle and fill shift table */
46 BITOP(byteset, n[i], |=), shift[n[i]] = i+1;
48 /* Compute maximal suffix */
49 ip = -1; jp = 0; k = p = 1;
51 if (n[ip+k] == n[jp+k]) {
56 } else if (n[ip+k] > n[jp+k]) {
68 /* And with the opposite comparison */
69 ip = -1; jp = 0; k = p = 1;
71 if (n[ip+k] == n[jp+k]) {
76 } else if (n[ip+k] < n[jp+k]) {
85 if (ip+1 > ms+1) ms = ip;
88 /* Periodic needle? */
89 if (memcmp(n, n+p, ms+1)) {
91 p = MAX(ms, l-ms-1) + 1;
97 /* If remainder of haystack is shorter than needle, done */
98 if (z-h < l) return 0;
100 /* Check last byte first; advance by shift on mismatch */
101 if (BITOP(byteset, h[l-1], &)) {
104 if (mem0 && mem && k < p) k = l-p;
115 /* Compare right half */
116 for (k=MAX(ms+1,mem); n[k] && n[k] == h[k]; k++);
122 /* Compare left half */
123 for (k=ms+1; k>mem && n[k-1] == h[k-1]; k--);
124 if (k == mem) return (char *)h;
130 void *memmem(const void *h0, size_t k, const void *n0, size_t l)
132 const unsigned char *h = h0, *n = n0;
134 /* Return immediately on empty needle */
135 if (!l) return (void *)h;
137 /* Return immediately when needle is longer than haystack */
140 /* Use faster algorithms for short needles */
141 h = memchr(h0, *n, k);
142 if (!h || l==1) return (void *)h;
143 if (l==2) return twobyte_memmem(h, k, n);
144 if (l==3) return threebyte_memmem(h, k, n);
145 if (l==4) return fourbyte_memmem(h, k, n);
147 return twoway_memmem(h, h+k, n, l);