Issue #27870: A left shift of zero by a large integer no longer attempts to allocate large amounts of memory.

This commit is contained in:
Mark Dickinson 2016-08-29 19:38:12 +01:00
parent e63af905a4
commit 02c0c0b6e7
3 changed files with 23 additions and 0 deletions

View File

@ -202,6 +202,21 @@ class LongTest(test_int.IntLongCommonTests, unittest.TestCase):
self.assertEqual(x, y, self.assertEqual(x, y,
Frm("bad result for a*b: a=%r, b=%r, x=%r, y=%r", a, b, x, y)) Frm("bad result for a*b: a=%r, b=%r, x=%r, y=%r", a, b, x, y))
def test_lshift_of_zero(self):
self.assertEqual(0L << 0, 0)
self.assertEqual(0L << 10, 0)
with self.assertRaises(ValueError):
0L << -1
@test_support.cpython_only
def test_huge_lshift_of_zero(self):
# Shouldn't try to allocate memory for a huge shift. See issue #27870.
# Other implementations may have a different boundary for overflow,
# or not raise at all.
self.assertEqual(0L << sys.maxsize, 0)
with self.assertRaises(OverflowError):
0L << (sys.maxsize + 1)
def check_bitop_identities_1(self, x): def check_bitop_identities_1(self, x):
eq = self.assertEqual eq = self.assertEqual
eq(x & 0, 0, Frm("x & 0 != 0 for x=%r", x)) eq(x & 0, 0, Frm("x & 0 != 0 for x=%r", x))

View File

@ -10,6 +10,9 @@ What's New in Python 2.7.13?
Core and Builtins Core and Builtins
----------------- -----------------
- Issue #27870: A left shift of zero by a large integer no longer attempts
to allocate large amounts of memory.
- Issue #25604: Fix a minor bug in integer true division; this bug could - Issue #25604: Fix a minor bug in integer true division; this bug could
potentially have caused off-by-one-ulp results on platforms with potentially have caused off-by-one-ulp results on platforms with
unreliable ldexp implementations. unreliable ldexp implementations.

View File

@ -3715,6 +3715,11 @@ long_lshift(PyObject *v, PyObject *w)
PyErr_SetString(PyExc_ValueError, "negative shift count"); PyErr_SetString(PyExc_ValueError, "negative shift count");
goto lshift_error; goto lshift_error;
} }
if (Py_SIZE(a) == 0) {
return PyLong_FromLong(0);
}
/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */ /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
wordshift = shiftby / PyLong_SHIFT; wordshift = shiftby / PyLong_SHIFT;
remshift = shiftby - wordshift * PyLong_SHIFT; remshift = shiftby - wordshift * PyLong_SHIFT;