Skip to content

Commit a780c41

Browse files
authored
Merge pull request jruby#9345 from kares/enc-compatible-10
[fix] Encoding.compatible?: check when swapping args
2 parents 6454847 + 1ba0cb3 commit a780c41

2 files changed

Lines changed: 17 additions & 5 deletions

File tree

core/src/main/java/org/jruby/RubyEncoding.java

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -151,13 +151,11 @@ public static Encoding areCompatible(IRubyObject obj1, IRubyObject obj2) {
151151
if (!(obj1 instanceof RubyString) && enc1 instanceof USASCIIEncoding) return enc2;
152152

153153
if (!(obj1 instanceof RubyString)) {
154-
IRubyObject objTmp = obj1; // swap1 obj1 & obj2
154+
IRubyObject objTmp = obj1; // swap obj1 & obj2
155155
obj1 = obj2;
156156
obj2 = objTmp;
157-
158-
Encoding encTmp = enc1; // swap their encodings
159-
enc1 = enc2;
160-
enc2 = encTmp;
157+
// Note: enc1/enc2 are NOT swapped — they retain the
158+
// original argument order, matching CRuby's rb_enc_compatible.
161159
}
162160

163161
if (obj1 instanceof RubyString) {

spec/ruby/core/encoding/compatible_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,11 @@
557557
[Encoding, "\x82\xa0".dup.force_encoding("shift_jis"), Encoding::Shift_JIS],
558558
].should be_computed_by(:compatible?, /abc/)
559559
end
560+
561+
it "returns the Regexp's Encoding if the String is ASCII only and the Regexp is not" do
562+
r = Regexp.new("\xa4\xa2".dup.force_encoding("euc-jp"))
563+
Encoding.compatible?("hello".dup.force_encoding("utf-8"), r).should == Encoding::EUC_JP
564+
end
560565
end
561566

562567
describe "Encoding.compatible? String, Symbol" do
@@ -619,6 +624,15 @@
619624
Encoding.compatible?(/abc/, str).should == Encoding::US_ASCII
620625
end
621626

627+
it "returns the String's Encoding when the String is ASCII only with a different encoding" do
628+
r = Regexp.new("\xa4\xa2".dup.force_encoding("euc-jp"))
629+
Encoding.compatible?(r, "hello".dup.force_encoding("utf-8")).should == Encoding::UTF_8
630+
end
631+
632+
it "returns the Regexp's Encoding if the String has the same non-ASCII encoding" do
633+
r = Regexp.new("\xa4\xa2".dup.force_encoding("euc-jp"))
634+
Encoding.compatible?(r, "hello".dup.force_encoding("euc-jp")).should == Encoding::EUC_JP
635+
end
622636
end
623637

624638
describe "Encoding.compatible? Regexp, Regexp" do

0 commit comments

Comments
 (0)