Skip to content

Commit

Permalink
Reuse mpz_set_PyLong in GMPy_MPZ/XMPZ_From_PyLong()
Browse files Browse the repository at this point in the history
  • Loading branch information
skirpichev committed Mar 13, 2024
1 parent e26d7f1 commit 4074299
Showing 1 changed file with 17 additions and 54 deletions.
71 changes: 17 additions & 54 deletions src/gmpy2_convert_gmp.c
Original file line number Diff line number Diff line change
Expand Up @@ -38,42 +38,6 @@
* Conversion between native Python objects and MPZ. *
* ======================================================================== */

static MPZ_Object *
GMPy_MPZ_From_PyLong(PyObject *obj, CTXT_Object *context)
{
MPZ_Object *result;
int negative;
Py_ssize_t len;
PyLongObject *templong = (PyLongObject*)obj;

if(!(result = GMPy_MPZ_New(context))) {
/* LCOV_EXCL_START */
return NULL;
/* LCOV_EXCL_STOP */
}

len = _PyLong_DigitCount(templong);
negative = _PyLong_Sign(obj) < 0;

switch (len) {
case 1:
mpz_set_si(result->z, (sdigit)GET_OB_DIGIT(templong)[0]);
break;
case 0:
mpz_set_si(result->z, 0);
break;
default:
mpz_import(result->z, len, -1, sizeof(GET_OB_DIGIT(templong)[0]), 0,
sizeof(GET_OB_DIGIT(templong)[0])*8 - PyLong_SHIFT,
GET_OB_DIGIT(templong));
}

if (negative) {
mpz_neg(result->z, result->z);
}
return result;
}

/* To support creation of temporary mpz objects. */
static void
mpz_set_PyLong(mpz_t z, PyObject *obj)
Expand Down Expand Up @@ -104,6 +68,22 @@ mpz_set_PyLong(mpz_t z, PyObject *obj)
return;
}

static MPZ_Object *
GMPy_MPZ_From_PyLong(PyObject *obj, CTXT_Object *context)
{
MPZ_Object *result;

if(!(result = GMPy_MPZ_New(context))) {
/* LCOV_EXCL_START */
return NULL;
/* LCOV_EXCL_STOP */
}

mpz_set_PyLong(MPZ(result), obj);

return result;
}

static MPZ_Object *
GMPy_MPZ_From_PyStr(PyObject *s, int base, CTXT_Object *context)
{
Expand Down Expand Up @@ -393,25 +373,8 @@ GMPy_XMPZ_From_PyLong(PyObject *obj, CTXT_Object *context)
/* LCOV_EXCL_STOP */
}

len = _PyLong_DigitCount(templong);
negative = _PyLong_Sign(obj) < 0;
mpz_set_PyLong(result->z, obj);

switch (len) {
case 1:
mpz_set_si(result->z, (sdigit)GET_OB_DIGIT(templong)[0]);
break;
case 0:
mpz_set_si(result->z, 0);
break;
default:
mpz_import(result->z, len, -1, sizeof(GET_OB_DIGIT(templong)[0]), 0,
sizeof(GET_OB_DIGIT(templong)[0])*8 - PyLong_SHIFT,
GET_OB_DIGIT(templong));
}

if (negative) {
mpz_neg(result->z, result->z);
}
return result;
}

Expand Down

0 comments on commit 4074299

Please sign in to comment.