Skip to content

[3.10] bpo-42161: mathmodule.c: move _PyLong_GetOne() loop invariant (GH-26391) #26393

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 26, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions Modules/mathmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -845,13 +845,15 @@ math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
Py_SETREF(res, PyNumber_Absolute(res));
return res;
}

PyObject *one = _PyLong_GetOne(); // borrowed ref
for (i = 1; i < nargs; i++) {
x = _PyNumber_Index(args[i]);
if (x == NULL) {
Py_DECREF(res);
return NULL;
}
if (res == _PyLong_GetOne()) {
if (res == one) {
/* Fast path: just check arguments.
It is okay to use identity comparison here. */
Py_DECREF(x);
Expand Down Expand Up @@ -918,13 +920,15 @@ math_lcm(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
Py_SETREF(res, PyNumber_Absolute(res));
return res;
}

PyObject *zero = _PyLong_GetZero(); // borrowed ref
for (i = 1; i < nargs; i++) {
x = PyNumber_Index(args[i]);
if (x == NULL) {
Py_DECREF(res);
return NULL;
}
if (res == _PyLong_GetZero()) {
if (res == zero) {
/* Fast path: just check arguments.
It is okay to use identity comparison here. */
Py_DECREF(x);
Expand Down Expand Up @@ -3293,10 +3297,10 @@ math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
goto done;
}

factor = n;
Py_INCREF(factor);
factor = Py_NewRef(n);
PyObject *one = _PyLong_GetOne(); // borrowed ref
for (i = 1; i < factors; ++i) {
Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_GetOne()));
Py_SETREF(factor, PyNumber_Subtract(factor, one));
if (factor == NULL) {
goto error;
}
Expand Down Expand Up @@ -3415,10 +3419,10 @@ math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
goto done;
}

factor = n;
Py_INCREF(factor);
factor = Py_NewRef(n);
PyObject *one = _PyLong_GetOne(); // borrowed ref
for (i = 1; i < factors; ++i) {
Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_GetOne()));
Py_SETREF(factor, PyNumber_Subtract(factor, one));
if (factor == NULL) {
goto error;
}
Expand Down