Skip to content

Commit ac66dc8

Browse files
committed
Let Rope#toString() show an escaped String if the encoding is binary
1 parent d52e42e commit ac66dc8

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

src/main/java/org/truffleruby/core/rope/RopeOperations.java

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -205,24 +205,24 @@ public static String decodeOrEscapeBinaryRope(Rope rope, byte[] bytes) {
205205
if (rope.isAsciiOnly() || rope.getEncoding() != ASCIIEncoding.INSTANCE) {
206206
return decodeRopeSegment(rope, bytes, 0, bytes.length);
207207
} else {
208-
// A Rope with BINARY encoding cannot be converted faithfully to a Java String.
209-
// (ISO_8859_1 would just show random characters for bytes above 128)
210-
// Therefore we convert non-US-ASCII characters to "\xNN".
211-
// MRI Symbol#inspect for binary symbols is similar: "\xff".b.to_sym => :"\xFF"
212-
213-
final StringBuilder builder = new StringBuilder(rope.byteLength());
208+
return escapeBinaryRope(bytes);
209+
}
210+
}
214211

215-
for (int i = 0; i < bytes.length; i++) {
216-
final byte c = bytes[i];
217-
if (c >= 0) { // US-ASCII character
218-
builder.append((char) (c & 0xFF));
219-
} else {
220-
builder.append("\\x").append(String.format("%02X", c & 0xFF));
221-
}
212+
private static String escapeBinaryRope(byte[] bytes) {
213+
// A Rope with BINARY encoding cannot be converted faithfully to a Java String.
214+
// (ISO_8859_1 would just show random characters for bytes above 128)
215+
// Therefore we convert non-US-ASCII characters to "\xNN".
216+
// MRI Symbol#inspect for binary symbols is similar: "\xff".b.to_sym => :"\xFF"
217+
final StringBuilder builder = new StringBuilder(bytes.length);
218+
for (final byte c : bytes) {
219+
if (c >= 0) { // US-ASCII character
220+
builder.append((char) (c & 0xFF));
221+
} else {
222+
builder.append("\\x").append(String.format("%02X", c & 0xFF));
222223
}
223-
224-
return builder.toString();
225224
}
225+
return builder.toString();
226226
}
227227

228228
public static String decodeRope(Rope value) {
@@ -242,9 +242,15 @@ private static String decodeRopeSegment(Rope value, byte[] bytes, int byteOffset
242242
}
243243
}
244244

245+
/** This method has no side effects, because it does not even have access to the Rope - for debugging only. */
245246
@TruffleBoundary
246247
public static String decode(Encoding encoding, byte[] bytes) {
247-
return decode(EncodingManager.charsetForEncoding(encoding), bytes, 0, bytes.length);
248+
if (encoding == ASCIIEncoding.INSTANCE) {
249+
return escapeBinaryRope(bytes);
250+
} else {
251+
final Charset charset = EncodingManager.charsetForEncoding(encoding);
252+
return decode(charset, bytes, 0, bytes.length);
253+
}
248254
}
249255

250256
private static String decode(Charset charset, byte[] bytes, int byteOffset, int byteLength) {

0 commit comments

Comments
 (0)