Skip to content

Commit 036fe85

Browse files
hongweipengmethane
authored andcommitted
bpo-27145: small_ints[x] could be returned in long_add and long_sub (GH-15716)
1 parent 386d00c commit 036fe85

File tree

3 files changed

+18
-7
lines changed

3 files changed

+18
-7
lines changed

Lib/test/test_long.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -956,6 +956,14 @@ def test_huge_rshift_of_huge(self, size):
956956
self.assertEqual(huge >> (sys.maxsize + 1), (1 << 499) + 5)
957957
self.assertEqual(huge >> (sys.maxsize + 1000), 0)
958958

959+
@support.cpython_only
960+
def test_small_ints_in_huge_calculation(self):
961+
a = 2 ** 100
962+
b = -a + 1
963+
c = a + 1
964+
self.assertIs(a + b, 1)
965+
self.assertIs(c - a, 1)
966+
959967
def test_small_ints(self):
960968
for i in range(-5, 257):
961969
self.assertIs(i, i + 0)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
int + int and int - int operators can now return small integer singletons. Patch by hongweipeng.

Objects/longobject.c

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3206,7 +3206,7 @@ x_sub(PyLongObject *a, PyLongObject *b)
32063206
if (sign < 0) {
32073207
Py_SIZE(z) = -Py_SIZE(z);
32083208
}
3209-
return long_normalize(z);
3209+
return maybe_small_long(long_normalize(z));
32103210
}
32113211

32123212
static PyObject *
@@ -3254,13 +3254,15 @@ long_sub(PyLongObject *a, PyLongObject *b)
32543254
return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
32553255
}
32563256
if (Py_SIZE(a) < 0) {
3257-
if (Py_SIZE(b) < 0)
3258-
z = x_sub(a, b);
3259-
else
3257+
if (Py_SIZE(b) < 0) {
3258+
z = x_sub(b, a);
3259+
}
3260+
else {
32603261
z = x_add(a, b);
3261-
if (z != NULL) {
3262-
assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
3263-
Py_SIZE(z) = -(Py_SIZE(z));
3262+
if (z != NULL) {
3263+
assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
3264+
Py_SIZE(z) = -(Py_SIZE(z));
3265+
}
32643266
}
32653267
}
32663268
else {

0 commit comments

Comments
 (0)