Skip to content

Commit 3a193f2

Browse files
authored
Merge pull request jruby#9045 from enebo/topic/fix_9044
Fixes basic float hex value strings for Kernel#Float
2 parents 6329fe0 + c55f833 commit 3a193f2

2 files changed

Lines changed: 19 additions & 3 deletions

File tree

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

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -420,8 +420,6 @@ public static RubyFloat new_float(IRubyObject recv, IRubyObject object) {
420420
return (RubyFloat) new_float(recv.getRuntime().getCurrentContext(), object, true);
421421
}
422422

423-
private static final ByteList ZEROx = new ByteList(new byte[] { '0','x' }, false);
424-
425423
public static RubyFloat new_float(final Ruby runtime, IRubyObject object) {
426424
return (RubyFloat) new_float(runtime.getCurrentContext(), object, true);
427425
}
@@ -540,7 +538,7 @@ public static IRubyObject new_float(ThreadContext context, IRubyObject object, b
540538
throw runtime.newArgumentError("invalid value for Float(): " + object.inspect());
541539
}
542540

543-
if (bytes.startsWith(ZEROx)) { // startsWith("0x")
541+
if (isHexValue(bytes)) {
544542
if (bytes.indexOf('p') != -1 || bytes.indexOf('P') != -1) {
545543
return runtime.newFloat(parseHexidecimalExponentString2(runtime, bytes));
546544
}
@@ -567,6 +565,12 @@ public static IRubyObject new_float(ThreadContext context, IRubyObject object, b
567565
return TypeConverter.handleUncoercibleObject(runtime, object, runtime.getFloat(), true);
568566
}
569567

568+
static boolean isHexValue(ByteList bytes) {
569+
int length = bytes.getRealSize();
570+
int index = length >= 1 && bytes.get(0) == '-' ? 1 : 0;
571+
return length >= index + 2 && bytes.get(index) == '0' && (bytes.get(index + 1) == 'x' || bytes.get(index + 1) == 'X');
572+
}
573+
570574
static RubyFloat new_float(final Ruby runtime, RubyInteger num) {
571575
if (num instanceof RubyBignum) {
572576
return RubyFloat.newFloat(runtime, RubyBignum.big2dbl((RubyBignum) num));

spec/ruby/core/kernel/Float_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,18 @@ def to_f() 1.2 end
222222
end
223223
end
224224

225+
describe "for hexidecimal literals" do
226+
it "interprets positive hex value" do
227+
@object.send(:Float, "0x10").should == 16.0
228+
@object.send(:Float, "0X10").should == 16.0
229+
end
230+
231+
it "interprets negative hex value" do
232+
@object.send(:Float, "-0x10").should == -16.0
233+
@object.send(:Float, "-0X10").should == -16.0
234+
end
235+
end
236+
225237
describe "for hexadecimal literals with binary exponent" do
226238
%w(p P).each do |p|
227239
it "interprets the fractional part (on the left side of '#{p}') in hexadecimal" do

0 commit comments

Comments
 (0)