Skip to content

Commit

Permalink
Fix for the coerce cases in divide and DoDivmod
Browse files Browse the repository at this point in the history
  • Loading branch information
mrkn committed Jan 15, 2021
1 parent 716062b commit 1cb9248
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 10 deletions.
26 changes: 16 additions & 10 deletions ext/bigdecimal/bigdecimal.c
Original file line number Diff line number Diff line change
Expand Up @@ -1356,16 +1356,19 @@ BigDecimal_divide(VALUE self, VALUE r, Real **c, Real **res, Real **div)
TypedData_Get_Struct(self, Real, &BigDecimal_data_type, a);
SAVE(a);

VALUE rr = Qnil;
if (RB_TYPE_P(r, T_FLOAT)) {
VALUE rr = r;
if (is_kind_of_BigDecimal(rr)) {
/* do nothing */
}
else if (RB_INTEGER_TYPE_P(r)) {
rr = rb_inum_convert_to_BigDecimal(r, 0, true);
}
else if (RB_TYPE_P(r, T_FLOAT)) {
rr = rb_float_convert_to_BigDecimal(r, 0, true);
}
else if (RB_TYPE_P(r, T_RATIONAL)) {
rr = rb_rational_convert_to_BigDecimal(r, a->Prec*BASE_FIG, true);
}
else {
rr = rb_convert_to_BigDecimal(r, 0, false);
}

if (!is_kind_of_BigDecimal(rr)) {
return DoSomeOne(self, r, '/');
Expand Down Expand Up @@ -1428,16 +1431,19 @@ BigDecimal_DoDivmod(VALUE self, VALUE r, Real **div, Real **mod)
TypedData_Get_Struct(self, Real, &BigDecimal_data_type, a);
SAVE(a);

VALUE rr = Qnil;
if (RB_TYPE_P(r, T_FLOAT)) {
VALUE rr = r;
if (is_kind_of_BigDecimal(rr)) {
/* do nothing */
}
else if (RB_INTEGER_TYPE_P(r)) {
rr = rb_inum_convert_to_BigDecimal(r, 0, true);
}
else if (RB_TYPE_P(r, T_FLOAT)) {
rr = rb_float_convert_to_BigDecimal(r, 0, true);
}
else if (RB_TYPE_P(r, T_RATIONAL)) {
rr = rb_rational_convert_to_BigDecimal(r, a->Prec*BASE_FIG, true);
}
else {
rr = rb_convert_to_BigDecimal(r, 0, false);
}

if (!is_kind_of_BigDecimal(rr)) {
return Qfalse;
Expand Down
13 changes: 13 additions & 0 deletions test/bigdecimal/test_bigdecimal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -974,6 +974,15 @@ def test_div_with_rational
assert_kind_of(BigDecimal, BigDecimal("3") / 1.quo(3))
end

def test_div_with_complex
q = BigDecimal("3") / 1i
assert_kind_of(Complex, q)
end

def test_div_error
assert_raise(TypeError) { BigDecimal(20) / '2' }
end

def test_mod
x = BigDecimal((2**100).to_s)
assert_equal(1, x % 3)
Expand Down Expand Up @@ -1028,6 +1037,10 @@ def test_divmod_precision
assert_equal((a/b), q)
end

def test_divmod_error
assert_raise(TypeError) { BigDecimal(20).divmod('2') }
end

def test_add_bigdecimal
x = BigDecimal((2**100).to_s)
assert_equal(3000000000000000000000000000000, x.add(x, 1))
Expand Down

0 comments on commit 1cb9248

Please sign in to comment.