Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix String#index to clear MatchData when a regexp is passed #10751

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions spec/ruby/core/string/byteindex_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# -*- encoding: utf-8 -*-
require_relative '../../spec_helper'
require_relative 'fixtures/classes'

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

string = "blablabla"
string.byteindex(/bla/, string.bytesize + 1)
$~.should == nil
end
end
end
11 changes: 11 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,17 @@
$~.should == nil
end

ruby_bug "#20421", ""..."3.2" do
it "always clear $~" do
"a".index(/a/)
$~.should_not == nil

string = "blablabla"
string.index(/bla/, string.length + 1)
$~.should == nil
end
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
Loading