Skip to content

Commit

Permalink
Fix String#index to clear MatchData when a regexp is passed
Browse files Browse the repository at this point in the history
[Bug #20421]

The bug was fixed in Ruby 3.3 via 9dcdffb
  • Loading branch information
byroot committed May 9, 2024
1 parent a10a0d0 commit 3cd85cf
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 1 deletion.
14 changes: 14 additions & 0 deletions spec/ruby/core/string/byteindex_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# -*- encoding: utf-8 -*-
require_relative '../../spec_helper'
require_relative 'fixtures/classes'

describe "String#byteindex with Regexp" do
it "always clear $~" do
"a".byteindex(/a/)
$~.should_not == nil

string = "blablabla"
string.byteindex(/bla/, string.bytesize + 1)
$~.should == nil
end
end
9 changes: 9 additions & 0 deletions spec/ruby/core/string/index_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,15 @@
$~.should == nil
end

it "always clear $~" do
"a".index(/a/)
$~.should_not == nil

string = "blablabla"
string.index(/bla/, string.length + 1)
$~.should == nil
end

it "starts the search at the given offset" do
"blablabla".index(/.{0}/, 5).should == 5
"blablabla".index(/.{1}/, 5).should == 5
Expand Down
9 changes: 9 additions & 0 deletions spec/ruby/core/string/rindex_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,15 @@ def obj.method_missing(*args) 5 end
$~.should == nil
end

it "always clear $~" do
"a".rindex(/a/)
$~.should_not == nil

string = "blablabla"
string.rindex(/bla/, -(string.length + 1))
$~.should == nil
end

it "starts the search at the given offset" do
"blablabla".rindex(/.{0}/, 5).should == 5
"blablabla".rindex(/.{1}/, 5).should == 5
Expand Down
4 changes: 3 additions & 1 deletion string.c
Original file line number Diff line number Diff line change
Expand Up @@ -3993,8 +3993,10 @@ rb_str_index_m(int argc, VALUE *argv, VALUE str)
}

if (RB_TYPE_P(sub, T_REGEXP)) {
if (pos > str_strlen(str, NULL))
if (pos > str_strlen(str, NULL)) {
rb_backref_set(Qnil);
return Qnil;
}
pos = str_offset(RSTRING_PTR(str), RSTRING_END(str), pos,
rb_enc_check(str, sub), single_byte_optimizable(str));

Expand Down

0 comments on commit 3cd85cf

Please sign in to comment.