gh-100637: Fix int and bool __sizeof__ calculation to include the 1 element ob_digit array for 0 and False (#100663)

Fixes behaviour where int (and subtypes like bool) __sizeof__ under-reports true size as it did not take into account the size 1 `ob_digit` array for the zero int.

Co-authored-by: Mark Dickinson <dickinsm@gmail.com>
This commit is contained in:
Ionite 2023-01-03 05:11:49 +08:00 committed by GitHub
parent 9dee973166
commit d7e7f79ca7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 7 additions and 2 deletions

View File

@ -1322,6 +1322,7 @@ class SizeofTest(unittest.TestCase):
check = self.check_sizeof check = self.check_sizeof
# bool # bool
check(True, vsize('') + self.longdigit) check(True, vsize('') + self.longdigit)
check(False, vsize('') + self.longdigit)
# buffer # buffer
# XXX # XXX
# builtin_function_or_method # builtin_function_or_method
@ -1459,7 +1460,7 @@ class SizeofTest(unittest.TestCase):
# listreverseiterator (list) # listreverseiterator (list)
check(reversed([]), size('nP')) check(reversed([]), size('nP'))
# int # int
check(0, vsize('')) check(0, vsize('') + self.longdigit)
check(1, vsize('') + self.longdigit) check(1, vsize('') + self.longdigit)
check(-1, vsize('') + self.longdigit) check(-1, vsize('') + self.longdigit)
PyLong_BASE = 2**sys.int_info.bits_per_digit PyLong_BASE = 2**sys.int_info.bits_per_digit

View File

@ -0,0 +1 @@
Fix :func:`int.__sizeof__` calculation to include the 1 element ob_digit array for 0 and False.

View File

@ -5879,7 +5879,10 @@ int___sizeof___impl(PyObject *self)
{ {
Py_ssize_t res; Py_ssize_t res;
res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit); res = offsetof(PyLongObject, ob_digit)
/* using Py_MAX(..., 1) because we always allocate space for at least
one digit, even though the integer zero has a Py_SIZE of 0 */
+ Py_MAX(Py_ABS(Py_SIZE(self)), 1)*sizeof(digit);
return res; return res;
} }