Skip to content

Commit

Permalink
[GR-20121] BigDecimal coerce initial argument using to_str (#1826).
Browse files Browse the repository at this point in the history
PullRequest: truffleruby/1193
  • Loading branch information
bjfish committed Dec 16, 2019
2 parents b78f6bb + 990b6e6 commit 53b07fd
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Bug fixes:
* Fixed File.fnmatch causes ArrayIndexOutOfBoundsException (#1845).
* Make `String#concat` work with no or multiple arguments (#1519).
* Make `Array#concat` work with no or multiple arguments (#1519).
* Fixed BigDecimal coerce initial argument using `to_str` (#1826).

Compatibility:

Expand Down
46 changes: 44 additions & 2 deletions lib/truffle/bigdecimal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -326,8 +326,50 @@ def self.new(*args)
end

module Kernel
def BigDecimal(value, precision = Truffle::UNDEFINED)
TrufflePrimitive.bigdecimal_new value, precision, true
def BigDecimal(value, precision = Truffle::UNDEFINED, exception: true)
if !TrufflePrimitive.undefined?(precision)
precision = Truffle::Type.rb_num2int(precision)
if precision < 0
if exception
raise ArgumentError, 'negative precision'
else
return nil
end
end
end

case value
when nil
if exception
raise TypeError, "can't convert nil into BigDecimal"
else
return nil
end
when true
if exception
raise TypeError, "can't convert true into BigDecimal"
else
return nil
end
when false
if exception
raise TypeError, "can't convert false into BigDecimal"
else
return nil
end
when BigDecimal, Integer, Float, Rational, String
# conversion handled in primitive
else
if exception
value = StringValue(value)
else
value = Truffle::Type.rb_check_convert_type(count, String, :to_str)
if value.nil?
return nil
end
end
end
TrufflePrimitive.bigdecimal_new value, precision, exception
end
end

Expand Down
6 changes: 6 additions & 0 deletions spec/ruby/library/bigdecimal/BigDecimal_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@
BigDecimal(" \t\n \r-Infinity \n").infinite?.should == -1
end

it "coerces the value argument with #to_str" do
initial = mock("value")
initial.should_receive(:to_str).and_return("123")
BigDecimal(initial).should == BigDecimal("123")
end

ruby_version_is ""..."2.6" do
it "ignores trailing garbage" do
BigDecimal("123E45ruby").should == BigDecimal("123E45")
Expand Down

0 comments on commit 53b07fd

Please sign in to comment.