Skip to content

Commit 0f611ac

Browse files
committed
Rework PyLong import/export functions
* Only call _PyLong_GetDigits() once in PyLongWriter_Finish(). * _PyLong_DigitCount() now uses Py_ABS(Py_SIZE(obj)). * Enhance PyLong_Export() tests: test negative value and test PyObject_Str().
1 parent cb26b93 commit 0f611ac

2 files changed

Lines changed: 15 additions & 4 deletions

File tree

‎pythoncapi_compat.h‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2064,7 +2064,8 @@ _PyLong_DigitCount(const PyLongObject *op)
20642064
#if PY_VERSION_HEX >= _Py_PACK_VERSION(3, 12)
20652065
return (Py_ssize_t)(op->long_value.lv_tag >> 3);
20662066
#else
2067-
return _PyLong_Sign((PyObject*)op) < 0 ? -Py_SIZE(op) : Py_SIZE(op);
2067+
Py_ssize_t size = Py_SIZE(op);
2068+
return Py_ABS(size);
20682069
#endif
20692070
}
20702071

@@ -2201,7 +2202,8 @@ PyLongWriter_Finish(PyLongWriter *writer)
22012202
assert(Py_REFCNT(obj) == 1);
22022203

22032204
// Normalize and get singleton if possible
2204-
while (i > 0 && _PyLong_GetDigits(self)[i-1] == 0) {
2205+
digit *digits = _PyLong_GetDigits(self);
2206+
while (i > 0 && digits[i-1] == 0) {
22052207
--i;
22062208
}
22072209
if (i != j) {
@@ -2211,7 +2213,7 @@ PyLongWriter_Finish(PyLongWriter *writer)
22112213
_PyLong_SetSignAndDigitCount(self, sign, i);
22122214
}
22132215
if (i <= 1) {
2214-
long val = sign * (long)(_PyLong_GetDigits(self)[0]);
2216+
long val = sign * (long)digits[0];
22152217
Py_DECREF(obj);
22162218
return PyLong_FromLong(val);
22172219
}

‎tests/test_pythoncapi_compat_cext.c‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1457,11 +1457,13 @@ test_long_import_export()
14571457
return -1;
14581458
}
14591459
assert(long_export.value == -123);
1460+
assert(long_export.negative == 0);
1461+
assert(long_export.ndigits == 0);
14601462
assert(long_export.digits == NULL);
14611463
PyLong_FreeExport(&long_export);
14621464
Py_DECREF(obj);
14631465

1464-
writer = PyLongWriter_Create(0, 5, (void **)&digits);
1466+
writer = PyLongWriter_Create(1, 5, (void **)&digits);
14651467
if (writer == NULL) {
14661468
return -1;
14671469
}
@@ -1475,10 +1477,17 @@ test_long_import_export()
14751477
return -1;
14761478
}
14771479

1480+
PyObject *str = PyObject_Str(obj);
1481+
assert(str != NULL);
1482+
assert(PyUnicode_EqualToUTF8(str, "-1329227995784915872903807060280344577") == 1);
1483+
Py_DECREF(str);
1484+
14781485
if (PyLong_Export(obj, &long_export) < 0) {
14791486
return -1;
14801487
}
14811488
assert(long_export.value == 0);
1489+
assert(long_export.negative == 1);
1490+
assert(long_export.ndigits == 5);
14821491
digits = (uint32_t*)long_export.digits;
14831492
assert(digits[0] == 1);
14841493
assert(digits[1] == 0);

0 commit comments

Comments
 (0)