Skip to content

Commit

Permalink
Fix String#sub with negative index
Browse files Browse the repository at this point in the history
Fixed #5490
  • Loading branch information
makenowjust authored and asterite committed Jan 1, 2018
1 parent 15a357c commit dadbeb6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
14 changes: 14 additions & 0 deletions spec/std/string_spec.cr
Expand Up @@ -1173,13 +1173,27 @@ describe "String" do
string.bytesize.should eq("あいのえお".bytesize)
end

it "subs at negative index with char" do
string = "abc".sub(-1, 'd')
string.should eq("abd")
string = string.sub(-2, 'n')
string.should eq("and")
end

it "subs at index with string" do
string = "hello".sub(1, "eee")
string.should eq("heeello")
string.bytesize.should eq(7)
string.size.should eq(7)
end

it "subs at negative index with string" do
string = "hello".sub(-1, "ooo")
string.should eq("hellooo")
string.bytesize.should eq(7)
string.size.should eq(7)
end

it "subs at index with string, non-ascii" do
string = "あいうえお".sub(2, "けくこ")
string.should eq("あいけくこえお")
Expand Down
2 changes: 1 addition & 1 deletion src/string.cr
Expand Up @@ -1857,7 +1857,7 @@ class String
end

private def sub_index(index, replacement)
index += size + 1 if index < 0
index += size if index < 0

byte_index = char_index_to_byte_index(index)
raise IndexError.new unless byte_index
Expand Down

0 comments on commit dadbeb6

Please sign in to comment.