From: WATANABE Hirofumi Date: 1999-06-27T18:40:17+09:00 Subject: [ruby-dev:7233] Re: String#rindex with arbitrary starting point わたなべです. ruby-dev に振ります. YANAGAWA Kazuhisa writes: :# FIXNUM が渡った場合のは謎の `pos-1' のせいだとわかりましたが,他は良 :# くわからないの. pos が位置なのか長さなのかというあたりがはっきりしてないのが バグの原因のようですね. pos は位置にしてみました. ついでに "" や // にも対応したつもり. ただし Regexp のときは不完全. "012345".rindex /5/, 5 が nil. "012355".rindex /5/, 5 だとなぜか ok. これは re.c, regex.c のほうがなんかおかしい気がする. "012345".rindex /0/, 0 もだめ. これは range が 0 になって reverse にならないためかな. ところで index, rindex はマルチバイト対応しなくていいんだっけ? --- string.c.orig Fri Jun 25 18:02:48 1999 +++ string.c Sun Jun 27 16:21:32 1999 @@ -633,4 +633,6 @@ case T_REGEXP: - pos = rb_reg_search(sub, str, pos, 1); - if (pos >= 0) return INT2NUM(pos); + if (RREGEXP(sub)->len) { + pos = rb_reg_search(sub, str, pos, 1); + } + if (pos >= 0) return INT2NUM(pos); break; @@ -639,12 +641,17 @@ /* substring longer than string */ - if (pos < RSTRING(sub)->len) return Qnil; + if (pos + 1 < RSTRING(sub)->len) return Qnil; sbeg = RSTRING(str)->ptr; - s = RSTRING(str)->ptr + pos - RSTRING(sub)->len; + s = RSTRING(str)->ptr + pos + 1 - RSTRING(sub)->len; t = RSTRING(sub)->ptr; len = RSTRING(sub)->len; - while (sbeg <= s) { - if (*s == *t && memcmp(s, t, len) == 0) { - return INT2NUM(s - RSTRING(str)->ptr); + if (len) { + while (sbeg <= s) { + if (*s == *t && memcmp(s, t, len) == 0) { + return INT2NUM(s - RSTRING(str)->ptr); + } + s--; } - s--; + } + else { + return INT2NUM(pos); } @@ -655,3 +662,3 @@ int c = FIX2INT(sub); - char *p = RSTRING(str)->ptr + pos - 1; + char *p = RSTRING(str)->ptr + pos; char *pbeg = RSTRING(str)->ptr;