Skip to content

Commit 4115996

Browse files
bpo-42161: mathmodule.c: move _PyLong_GetOne() loop invariant (GH-26391) (GH-26393)
Move _PyLong_GetZero() and _PyLong_GetOne() loop invariants outside loops in functions: * math.comb() * math.gcd() * math.lcm() * math.perm() (cherry picked from commit 3e7ee02) Co-authored-by: Victor Stinner <[email protected]>
1 parent 150a8e8 commit 4115996

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

Modules/mathmodule.c

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -845,13 +845,15 @@ math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
845845
Py_SETREF(res, PyNumber_Absolute(res));
846846
return res;
847847
}
848+
849+
PyObject *one = _PyLong_GetOne(); // borrowed ref
848850
for (i = 1; i < nargs; i++) {
849851
x = _PyNumber_Index(args[i]);
850852
if (x == NULL) {
851853
Py_DECREF(res);
852854
return NULL;
853855
}
854-
if (res == _PyLong_GetOne()) {
856+
if (res == one) {
855857
/* Fast path: just check arguments.
856858
It is okay to use identity comparison here. */
857859
Py_DECREF(x);
@@ -918,13 +920,15 @@ math_lcm(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
918920
Py_SETREF(res, PyNumber_Absolute(res));
919921
return res;
920922
}
923+
924+
PyObject *zero = _PyLong_GetZero(); // borrowed ref
921925
for (i = 1; i < nargs; i++) {
922926
x = PyNumber_Index(args[i]);
923927
if (x == NULL) {
924928
Py_DECREF(res);
925929
return NULL;
926930
}
927-
if (res == _PyLong_GetZero()) {
931+
if (res == zero) {
928932
/* Fast path: just check arguments.
929933
It is okay to use identity comparison here. */
930934
Py_DECREF(x);
@@ -3293,10 +3297,10 @@ math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
32933297
goto done;
32943298
}
32953299

3296-
factor = n;
3297-
Py_INCREF(factor);
3300+
factor = Py_NewRef(n);
3301+
PyObject *one = _PyLong_GetOne(); // borrowed ref
32983302
for (i = 1; i < factors; ++i) {
3299-
Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_GetOne()));
3303+
Py_SETREF(factor, PyNumber_Subtract(factor, one));
33003304
if (factor == NULL) {
33013305
goto error;
33023306
}
@@ -3415,10 +3419,10 @@ math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
34153419
goto done;
34163420
}
34173421

3418-
factor = n;
3419-
Py_INCREF(factor);
3422+
factor = Py_NewRef(n);
3423+
PyObject *one = _PyLong_GetOne(); // borrowed ref
34203424
for (i = 1; i < factors; ++i) {
3421-
Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_GetOne()));
3425+
Py_SETREF(factor, PyNumber_Subtract(factor, one));
34223426
if (factor == NULL) {
34233427
goto error;
34243428
}

0 commit comments

Comments
 (0)