From dadbeb6c7039bf5185ffa18e383f94f5beae0e76 Mon Sep 17 00:00:00 2001 From: TSUYUSATO Kitsune Date: Sun, 31 Dec 2017 15:21:55 +0900 Subject: [PATCH] Fix String#sub with negative index Fixed #5490 --- spec/std/string_spec.cr | 14 ++++++++++++++ src/string.cr | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/spec/std/string_spec.cr b/spec/std/string_spec.cr index 8d9551914444..3b4a9136d909 100644 --- a/spec/std/string_spec.cr +++ b/spec/std/string_spec.cr @@ -1173,6 +1173,13 @@ 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") @@ -1180,6 +1187,13 @@ describe "String" do 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("あいけくこえお") diff --git a/src/string.cr b/src/string.cr index 14f9ecf4f68d..db7939a87607 100644 --- a/src/string.cr +++ b/src/string.cr @@ -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