Skip to content

Commit

Permalink
Raise ArgumentError if BigFloat initialized with invalid string (crys…
Browse files Browse the repository at this point in the history
…tal-lang#5638)

* Raise ArgumentError if BigFloat initialized with invalid string

Raise ArgumentError if BigFloat.new() initialized with string
that doesn't denote a valid float

* fixup! Raise ArgumentError if BigFloat initialized with invalid string
  • Loading branch information
mjago authored and RX14 committed Jan 25, 2018
1 parent 302ff6c commit 0f9af00
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 6 additions & 0 deletions spec/std/big/big_float_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ describe "BigFloat" do
BigFloat.new("-#{string_of_integer_value}").to_s.should eq("-#{string_of_integer_value}")
end

it "raises an ArgumentError unless string denotes valid float" do
expect_raises(ArgumentError) { BigFloat.new("abc") }
expect_raises(ArgumentError) { BigFloat.new("+") }
expect_raises(ArgumentError) { BigFloat.new("") }
end

it "new(BigInt)" do
bigfloat_on_bigint_value = BigFloat.new(BigInt.new(string_of_integer_value))
bigfloat_on_bigint_value.should eq(bigfloat_of_integer_value)
Expand Down
4 changes: 3 additions & 1 deletion src/big/big_float.cr
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ struct BigFloat < Float
def initialize(str : String)
# Strip leading '+' char to smooth out cases with strings like "+123"
str = str.lchop('+')
LibGMP.mpf_init_set_str(out @mpf, str, 10)
if LibGMP.mpf_init_set_str(out @mpf, str, 10) == -1
raise ArgumentError.new("Invalid BigFloat: #{str.inspect}")
end
end

def initialize(num : BigInt)
Expand Down

0 comments on commit 0f9af00

Please sign in to comment.