/*-
* Copyright 2003 John-Mark Gurney.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: util.c,v 1.4 2003/09/15 23:37:19 jmg Exp $
*
*/
#include <string.h>
#if 0
char *
memmemory(const char *big, int blen, const char *lit, int llen)
{
const char *pos;
for (pos = big; pos - big <= blen - llen; pos++) {
if (*pos == *lit && memcmp(pos, lit, llen) == 0)
return (char *)pos;
}
return NULL;
}
#else
static int cols = 0;
static unsigned int
powmod(int x, int y, int q)
{
unsigned int ret = 1;
while (y) {
if (y & 1)
ret = ((unsigned long long)ret * x) % q;
x = (unsigned long long) x * x % q;
y = y / 2;
}
return ret;
}
const char *
memmemory(const char *T, size_t n, const char *P, size_t m)
{
static unsigned int q = 4294967291u;
static unsigned int d = 256;
unsigned int h;
unsigned int p;
unsigned int t;
int i;
int s;
h = powmod(d, m - 1, q);
p = 0;
t = 0;
for (i = 0; i < m; i++) {
p = (d * p + P[i]) % q;
t = (d * t + T[i]) % q;
}
for (s = 0; s <= n - m; s++) {
if (p == t) {
if (memcmp(P, T + s, m) == 0)
return T + s;
cols++;
}
if (s < n - m)
t = (d * (t - T[s] * h) + T[s + m]) % q;
}
return NULL;
}
#endif
syntax highlighted by Code2HTML, v. 0.9.1