Skip to content

Commit

Permalink
Convert PyLong_FromLongLong() as well to leverage macro PYLONG_FROM_S…
Browse files Browse the repository at this point in the history
…IGNED. And also added a blurb about the changes
  • Loading branch information
srinivasreddy committed Jan 22, 2025
1 parent 34315cb commit 0ef383c
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 36 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Add Missing fast path in PyLong_FromLong(), PyLong_FromLongLong() functions
for compact integers
39 changes: 3 additions & 36 deletions Objects/longobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -117,15 +117,15 @@ maybe_small_long(PyLongObject *v)

#define PYLONG_FROM_SIGNED(INT_TYPE, ival) \
do { \
unsigned long abs_ival, t; \
unsigned INT_TYPE abs_ival, t; \
if (IS_SMALL_INT(ival)) { \
return get_small_int((sdigit)(ival)); \
} \
if (-(INT_TYPE)PyLong_MASK <= (ival) && (ival) <= (INT_TYPE)PyLong_MASK) { \
return _PyLong_FromMedium((sdigit)(ival)); \
} \
/* Count digits (at least two - smaller cases were handled above). */ \
abs_ival = (ival) < 0 ? 0U-(unsigned long)(ival) : (unsigned long)(ival); \
abs_ival = (ival) < 0 ? 0U-(unsigned INT_TYPE)(ival) : (unsigned INT_TYPE)(ival); \
/* Do shift in two steps to avoid possible undefined behavior. */ \
t = abs_ival >> PyLong_SHIFT >> PyLong_SHIFT; \
Py_ssize_t ndigits = 2; \
Expand Down Expand Up @@ -1456,40 +1456,7 @@ PyLong_AsVoidPtr(PyObject *vv)
PyObject *
PyLong_FromLongLong(long long ival)
{
PyLongObject *v;
unsigned long long abs_ival, t;
int ndigits;

/* Handle small and medium cases. */
if (IS_SMALL_INT(ival)) {
return get_small_int((sdigit)ival);
}
if (-(long long)PyLong_MASK <= ival && ival <= (long long)PyLong_MASK) {
return _PyLong_FromMedium((sdigit)ival);
}

/* Count digits (at least two - smaller cases were handled above). */
abs_ival = ival < 0 ? 0U-(unsigned long long)ival : (unsigned long long)ival;
/* Do shift in two steps to avoid possible undefined behavior. */
t = abs_ival >> PyLong_SHIFT >> PyLong_SHIFT;
ndigits = 2;
while (t) {
++ndigits;
t >>= PyLong_SHIFT;
}

/* Construct output value. */
v = _PyLong_New(ndigits);
if (v != NULL) {
digit *p = v->long_value.ob_digit;
_PyLong_SetSignAndDigitCount(v, ival < 0 ? -1 : 1, ndigits);
t = abs_ival;
while (t) {
*p++ = (digit)(t & PyLong_MASK);
t >>= PyLong_SHIFT;
}
}
return (PyObject *)v;
PYLONG_FROM_SIGNED(long long, ival);
}

/* Create a new int object from a C Py_ssize_t. */
Expand Down

0 comments on commit 0ef383c

Please sign in to comment.