* re.c (rb_memsearch): a little improvement.

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@3434 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
nobu 2003-02-03 07:34:06 +00:00
parent ddce7d5ebf
commit 056585d6dc
2 changed files with 17 additions and 12 deletions

View File

@ -1,3 +1,7 @@
Mon Feb 3 16:32:52 2003 Nobuyoshi Nakada <nobu.nokada@softhome.net>
* re.c (rb_memsearch): a little improvement.
Mon Feb 3 13:18:05 2003 Yukihiro Matsumoto <matz@ruby-lang.org> Mon Feb 3 13:18:05 2003 Yukihiro Matsumoto <matz@ruby-lang.org>
* re.c (rb_memsearch): algorithm body of String#index. * re.c (rb_memsearch): algorithm body of String#index.

25
re.c
View File

@ -103,46 +103,47 @@ rb_memsearch(x0, m, y0, n)
{ {
unsigned char *x = x0, *y = y0; unsigned char *x = x0, *y = y0;
unsigned char *s, *e; unsigned char *s, *e;
long d, i; long i;
int d;
unsigned long hx, hy; unsigned long hx, hy;
#define KR_REHASH(a, b, h) ((((h) - (a)*d) << 1) + (b)) #define KR_REHASH(a, b, h) (((h) << 1) - ((a)<<d) + (b))
s = y; e = s + n - m + 1; s = y; e = s + n - m + 1;
/* Preprocessing */ /* Preprocessing */
/* computes d = 2^(m-1) with /* computes d = 2^(m-1) with
the left-shift operator */ the left-shift operator */
for (d = i = 1; i < m; ++i) d = sizeof(hx) * CHAR_BIT - 1;
d = (d<<1); if (d > m) d = m;
if (ruby_ignorecase) { if (ruby_ignorecase) {
/* Prepare hash value */ /* Prepare hash value */
for (hy = hx = i = 0; i < m; ++i) { for (hy = hx = i = 0; i < d; ++i) {
hx = ((hx<<1) + casetable[x[i]]); hx = KR_REHASH(0, casetable[x[i]], hx);
hy = ((hy<<1) + casetable[s[i]]); hy = KR_REHASH(0, casetable[s[i]], hy);
} }
/* Searching */ /* Searching */
while (s < e) { while (s < e) {
if (hx == hy && rb_memcicmp(x, s, m) == 0) { if (hx == hy && rb_memcicmp(x, s, m) == 0) {
return s-y; return s-y;
} }
hy = KR_REHASH(casetable[*s], casetable[*(s+m)], hy); hy = KR_REHASH(casetable[*s], casetable[*(s+d)], hy);
s++; s++;
} }
} }
else { else {
/* Prepare hash value */ /* Prepare hash value */
for (hy = hx = i = 0; i < m; ++i) { for (hy = hx = i = 0; i < d; ++i) {
hx = ((hx<<1) + x[i]); hx = KR_REHASH(0, x[i], hx);
hy = ((hy<<1) + s[i]); hy = KR_REHASH(0, s[i], hy);
} }
/* Searching */ /* Searching */
while (s < e) { while (s < e) {
if (hx == hy && memcmp(x, s, m) == 0) { if (hx == hy && memcmp(x, s, m) == 0) {
return s-y; return s-y;
} }
hy = KR_REHASH(*s, *(s+m), hy); hy = KR_REHASH(*s, *(s+d), hy);
s++; s++;
} }
} }