diff --git a/src/gmpy2_convert_gmp.c b/src/gmpy2_convert_gmp.c index 87c91f2c..f90520b0 100644 --- a/src/gmpy2_convert_gmp.c +++ b/src/gmpy2_convert_gmp.c @@ -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 */ @@ -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; } diff --git a/test/test_mpz.py b/test/test_mpz.py index dfaea66a..0b499e69 100644 --- a/test/test_mpz.py +++ b/test/test_mpz.py @@ -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)