Chameleon

Chameleon Svn Source Tree

Root/branches/ErmaC/Trunk/i386/modules/klibc/memmem.c

1/*
2 * memmem.c
3 *
4 * Find a byte string inside a longer byte string
5 *
6 * This uses the "Not So Naive" algorithm, a very simple but
7 * usually effective algorithm, see:
8 *
9 * http://www-igm.univ-mlv.fr/~lecroq/string/
10 */
11
12#include <string.h>
13
14void *memmem(const void *haystack, size_t n, const void *needle, size_t m)
15{
16const unsigned char *y = (const unsigned char *)haystack;
17const unsigned char *x = (const unsigned char *)needle;
18
19size_t j, k, l;
20
21if (m > n || !m || !n)
22return NULL;
23
24if (1 != m) {
25if (x[0] == x[1]) {
26k = 2;
27l = 1;
28} else {
29k = 1;
30l = 2;
31}
32
33j = 0;
34while (j <= n - m) {
35if (x[1] != y[j + 1]) {
36j += k;
37} else {
38if (!memcmp(x + 2, y + j + 2, m - 2)
39 && x[0] == y[j])
40return (void *)&y[j];
41j += l;
42}
43}
44} else
45do {
46if (*y == *x)
47return (void *)y;
48y++;
49} while (--n);
50
51return NULL;
52}
53

Archive Download this file

Revision: 1622