Skip to content

Commit

Permalink
[ji] review 's'.to_java(:char) conversion to act more like 's'.ord
Browse files Browse the repository at this point in the history
... we could still throw when the code-point as a high surrogate
  • Loading branch information
kares committed May 9, 2018
1 parent 89183d0 commit e3ad1b2
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 11 deletions.
10 changes: 3 additions & 7 deletions core/src/main/java/org/jruby/RubyString.java
Expand Up @@ -5816,9 +5816,7 @@ public RubySymbol intern19() {
@JRubyMethod
public IRubyObject ord(ThreadContext context) {
final Ruby runtime = context.runtime;
final ByteList value = this.value;
return RubyFixnum.newFixnum(runtime, codePoint(runtime, EncodingUtils.getEncoding(value),
value.getUnsafeBytes(), value.getBegin(), value.getBegin() + value.getRealSize()));
return RubyFixnum.newFixnum(runtime, codePoint(runtime, this.value));
}

@JRubyMethod
Expand Down Expand Up @@ -6113,10 +6111,8 @@ public <T> T toJava(Class<T> target) {
return target.cast(value);
}
if (target == Character.class || target == Character.TYPE) {
if ( strLength() != 1 ) {
throw getRuntime().newArgumentError("could not coerce string of length " + strLength() + " (!= 1) into a char");
}
return (T) (Character) decodeString().charAt(0);
// like ord we will only take the start off the string (not failing if str-length > 1)
return (T) Character.valueOf((char) codePoint(getRuntime(), value));
}
return super.toJava(target);
}
Expand Down
5 changes: 5 additions & 0 deletions core/src/main/java/org/jruby/util/StringSupport.java
Expand Up @@ -485,6 +485,11 @@ public static int codePoint(Ruby runtime, Encoding enc, byte[] bytes, int p, int
}
}

public static int codePoint(final Ruby runtime, final ByteList value) {
return codePoint(runtime, EncodingUtils.getEncoding(value),
value.getUnsafeBytes(), value.getBegin(), value.getBegin() + value.getRealSize());
}

public static int codeLength(Encoding enc, int c) {
int i = enc.codeToMbcLength(c);
return checkCodepointError(i);
Expand Down
7 changes: 3 additions & 4 deletions test/jruby/test_primitive_to_java.rb
Expand Up @@ -25,11 +25,10 @@ def test_char_conversion
char = str.to_java(java.lang.Character)
assert_equal 48.to_java(:char), char

assert_equal 228, 'ä'.to_java(:char).charValue unless RUBY_VERSION.index('1.8') == 0
assert_equal 228, 'ä'.to_java(:char).charValue

assert_raises(ArgumentError) { ''.to_java(:char) }
assert_raises(ArgumentError) { 'už'.to_java('java.lang.Character') }
'už'[1].to_java('java.lang.Character') unless RUBY_VERSION.index('1.8') == 0
assert_equal 'už'.ord, 'už'.to_java('java.lang.Character').charValue
assert_raises(ArgumentError) { ''.to_java(:char) } # like ''.ord
end

end

0 comments on commit e3ad1b2

Please sign in to comment.