Skip to content

Commit

Permalink
Merge pull request #484 from skirpichev/int-mpz-conversion
Browse files Browse the repository at this point in the history
Update int <-> mpz conversion
  • Loading branch information
casevh authored May 22, 2024
2 parents 8e78aef + 2f0b03f commit e78b5b3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 14 deletions.
23 changes: 9 additions & 14 deletions src/gmpy2_convert_gmp.c
Original file line number Diff line number Diff line change
Expand Up @@ -128,14 +128,15 @@ GMPy_MPZ_From_PyFloat(PyObject *obj, CTXT_Object *context)
static PyObject *
GMPy_PyLong_From_MPZ(MPZ_Object *obj, CTXT_Object *context)
{
int negative;
size_t count, size;
PyLongObject *result;
if (mpz_fits_slong_p(obj->z)) {
return PyLong_FromLong(mpz_get_si(obj->z));
}

/* Assume gmp uses limbs as least as large as the builtin longs do */

negative = mpz_sgn(obj->z) < 0;
size = (mpz_sizeinbase(obj->z, 2) + PyLong_SHIFT - 1) / PyLong_SHIFT;
size_t count, size = (mpz_sizeinbase(obj->z, 2) +
PyLong_SHIFT - 1) / PyLong_SHIFT;
PyLongObject *result;

if (!(result = _PyLong_New(size))) {
/* LCOV_EXCL_START */
Expand All @@ -146,17 +147,11 @@ GMPy_PyLong_From_MPZ(MPZ_Object *obj, CTXT_Object *context)
mpz_export(GET_OB_DIGIT(result), &count, -1, sizeof(digit), 0,
sizeof(digit)*8 - PyLong_SHIFT, obj->z);

if (count == 0) {
GET_OB_DIGIT(result)[0] = 0;
}

/* long_normalize() is file-static so we must reimplement it */
/* longobjp = long_normalize(longobjp); */
while ((size>0) && (GET_OB_DIGIT(result)[size-1] == 0)) {
size--;
for (size_t i = count; i < size; i++) {
GET_OB_DIGIT(result)[i] = 0;
}
_PyLong_SetSignAndDigitCount(result, mpz_sgn(obj->z) < 0, count);

_PyLong_SetSignAndDigitCount(result, negative, size);
return (PyObject*)result;
}

Expand Down
2 changes: 2 additions & 0 deletions test/test_mpz.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,8 @@ def test_mpz_conversion():

assert int(mpz(-3)) == -3

assert int(mpz(11)) is int(mpz(11))


def test_mpz_create():
assert mpz() == mpz(0)
Expand Down

0 comments on commit e78b5b3

Please sign in to comment.