#define Q 33554393L /* prime number */ #define LOG2D 8 /* 2^8 = 256 */ unsigned long rkHash(unsigned long *dm, char *pattern, int patlen) { int i; unsigned long h1; for (i = 1, *dm = 1; i < patlen; i++) *dm = (*dm << LOG2D) % Q; for (i = 0, h1 = 0; i < patlen; i++) h1 = ((h1 << LOG2D) + pattern[i]) % Q; return h1; } char *rkMatch(char *text, int len, int patlen, unsigned long patHash, unsigned long dm) { int i; char *textEnd; unsigned long h2; if (patlen == 0) return text; if (len < patlen) return NULL; for (i = 0, h2 = 0; i < patlen; i++) h2 = ((h2 << LOG2D) + text[i]) % Q; textEnd = text + (len - patlen) + 1; while (text != textEnd) { if (h2 == patHash) return text; h2 = (h2 + (Q << LOG2D) - *text * dm) % Q; h2 = ((h2 << LOG2D) + *(text + patlen)) % Q; text++; } return NULL; }