bpo-36791: Safer detection of integer overflow in sum(). (GH-13080) · python/cpython@2950073

Original file line numberDiff line numberDiff line change

@@ -2375,9 +2375,11 @@ builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)

23752375

}

23762376

if (PyLong_CheckExact(item)) {

23772377

long b = PyLong_AsLongAndOverflow(item, &overflow);

2378-

long x = i_result + b;

2379-

if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {

2380-

i_result = x;

2378+

if (overflow == 0 &&

2379+

(i_result >= 0 ? (b <= LONG_MAX - i_result)

2380+

: (b >= LONG_MIN - i_result)))

2381+

{

2382+

i_result += b;

23812383

Py_DECREF(item);

23822384

continue;

23832385

}