Skip to content

Commit f27bfd1

Browse files
committed
Replace Ruby-based implementation of get_actual_encoding with a primitive.
There's no value in having this logic implemented in both Java and Ruby. `String#inspect` was also altered a bit to make its logic match MRI more closely.
1 parent 87b85ef commit f27bfd1

File tree

2 files changed

+20
-17
lines changed

2 files changed

+20
-17
lines changed

src/main/java/org/truffleruby/core/encoding/EncodingNodes.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,21 @@ public boolean isUnicode(DynamicObject encoding) {
474474

475475
}
476476

477+
@Primitive(name = "get_actual_encoding", needsSelf = false)
478+
public abstract static class GetActualEncodingPrimitiveNode extends PrimitiveArrayArgumentsNode {
479+
480+
@Specialization
481+
public DynamicObject getActualEncoding(DynamicObject string,
482+
@Cached("create()") GetActualEncodingNode getActualEncodingNode,
483+
@Cached("create()") GetRubyEncodingNode getRubyEncodingNode) {
484+
final Rope rope = StringOperations.rope(string);
485+
final Encoding actualEncoding = getActualEncodingNode.execute(rope);
486+
487+
return getRubyEncodingNode.executeGetRubyEncoding(actualEncoding);
488+
}
489+
490+
}
491+
477492
// Port of MRI's `get_actual_encoding`.
478493
public abstract static class GetActualEncodingNode extends RubyBaseNode {
479494

src/main/ruby/core/string.rb

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -550,23 +550,11 @@ def inspect
550550
ascii = enc.ascii_compatible?
551551
unicode = Truffle.invoke_primitive :encoding_is_unicode, enc
552552

553-
if unicode
554-
if enc.equal? Encoding::UTF_16
555-
a = getbyte 0
556-
b = getbyte 1
557-
558-
unless (a == 0xfe and b == 0xff) or (a == 0xff and b == 0xfe)
559-
unicode = false
560-
end
561-
elsif enc.equal? Encoding::UTF_32
562-
a = getbyte 0
563-
b = getbyte 1
564-
c = getbyte 2
565-
d = getbyte 3
566-
567-
unless (a == 0 and b == 0 and c == 0xfe and d == 0xfe) or (a == 0xff and b == 0xfe and c == 0 and d == 0)
568-
unicode = false
569-
end
553+
actual_encoding = enc.dummy? ? Truffle.invoke_primitive(:get_actual_encoding, self) : enc
554+
if actual_encoding != enc
555+
enc = actual_encoding
556+
if unicode
557+
unicode = Truffle.invoke_primitive :encoding_is_unicode, enc
570558
end
571559
end
572560

0 commit comments

Comments
 (0)