Skip to content

Commit 85a4dbe

Browse files
committed
gmp_invert improvement
1 parent 77aefe1 commit 85a4dbe

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

ext/gmp/gmp.c

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1562,17 +1562,23 @@ ZEND_FUNCTION(gmp_invert)
15621562
if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &a_arg, &b_arg) == FAILURE){
15631563
RETURN_THROWS();
15641564
}
1565-
// TODO Check b_arg is not 0 as behaviour is undefined for op2 = 0 for mpz_invert
15661565

15671566
FETCH_GMP_ZVAL(gmpnum_a, a_arg, temp_a, 1);
15681567
FETCH_GMP_ZVAL_DEP(gmpnum_b, b_arg, temp_b, temp_a, 2);
15691568

1569+
// TODO Early check if b_arg IS_LONG?
1570+
if (0 == mpz_cmp_ui(gmpnum_b, 0)) {
1571+
zend_throw_exception_ex(zend_ce_division_by_zero_error, 0, "Division by zero");
1572+
FREE_GMP_TEMP(temp_a);
1573+
FREE_GMP_TEMP(temp_b);
1574+
RETURN_THROWS();
1575+
}
1576+
15701577
INIT_GMP_RETVAL(gmpnum_result);
15711578
res = mpz_invert(gmpnum_result, gmpnum_a, gmpnum_b);
15721579
FREE_GMP_TEMP(temp_a);
15731580
FREE_GMP_TEMP(temp_b);
15741581
if (!res) {
1575-
// Should return 0 instead of false? A legit 0 value is impossible.
15761582
zval_ptr_dtor(return_value);
15771583
RETURN_FALSE;
15781584
}

ext/gmp/tests/gmp_invert.phpt

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,13 @@ gmp_invert() basic tests
88
var_dump(gmp_strval(gmp_invert(123123,5467624)));
99
var_dump(gmp_strval(gmp_invert(123123,"3333334345467624")));
1010
var_dump(gmp_strval(gmp_invert("12312323213123123",7624)));
11-
var_dump(gmp_strval(gmp_invert(444,0)));
11+
12+
try {
13+
var_dump(gmp_strval(gmp_invert(444,0)));
14+
} catch (\DivisionByZeroError $e) {
15+
echo $e->getMessage() . \PHP_EOL;
16+
}
17+
1218
var_dump(gmp_strval(gmp_invert(0,28347)));
1319
var_dump(gmp_strval(gmp_invert(-12,456456)));
1420
var_dump(gmp_strval(gmp_invert(234234,-435345)));
@@ -41,7 +47,7 @@ echo "Done\n";
4147
string(7) "2293131"
4248
string(1) "0"
4349
string(4) "5827"
44-
string(1) "0"
50+
Division by zero
4551
string(1) "0"
4652
string(1) "0"
4753
string(1) "0"

0 commit comments

Comments
 (0)