Skip to content

Commit 6326341

Browse files
bjfisheregon
authored andcommitted
Fixed String#{chomp, chomp!} issue with invalid encoded strings
(cherry picked from commit 026e983)
1 parent 6de02d8 commit 6326341

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ Bug fixes:
2020
* Fixed constant/identifier detection in lexer for non-ASCII encodings (#2079, #2102, @ivoanjo).
2121
* Fixed parsing of `--jvm` as an application argument (#2108).
2222
* Fix `rb_rescue2` to ignore the end marker `(VALUE)0` (#2127, #2130).
23+
* Fix `String#{chomp, chomp!}` issue with invalid encoded strings (#2133).
2324

2425
Compatibility:
2526

spec/ruby/core/string/chomp_spec.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,10 @@
5555
$/ = "cdef"
5656
"abcdef".chomp.should == "ab"
5757
end
58+
59+
it "removes one trailing newline for string with invalid encoding" do
60+
"\xa0\xa1\n".chomp.should == "\xa0\xa1"
61+
end
5862
end
5963

6064
describe "when passed nil" do
@@ -108,6 +112,10 @@
108112
it "returns an empty String when self is empty" do
109113
"".chomp("").should == ""
110114
end
115+
116+
it "removes one trailing newline for string with invalid encoding" do
117+
"\xa0\xa1\n".chomp("").should == "\xa0\xa1"
118+
end
111119
end
112120

113121
describe "when passed '\\n'" do

src/main/ruby/truffleruby/core/string.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -844,7 +844,7 @@ def chomp!(sep=undefined)
844844
if j = Primitive.string_previous_byte_index(self, bytes)
845845
chr = Primitive.string_chr_at(self, j)
846846

847-
if chr.ord == 13
847+
if !Primitive.nil?(chr) && chr.ord == 13
848848
bytes = j
849849
end
850850
end
@@ -857,13 +857,13 @@ def chomp!(sep=undefined)
857857

858858
while i = Primitive.string_previous_byte_index(self, bytes)
859859
chr = Primitive.string_chr_at(self, i)
860-
break unless chr.ord == 10
860+
break unless !Primitive.nil?(chr) && chr.ord == 10
861861

862862
bytes = i
863863

864864
if j = Primitive.string_previous_byte_index(self, i)
865865
chr = Primitive.string_chr_at(self, j)
866-
if chr.ord == 13
866+
if !Primitive.nil?(chr) && chr.ord == 13
867867
bytes = j
868868
end
869869
end

0 commit comments

Comments
 (0)