blob: 4ae17c972c2154133502085daa99b62322dc5d34 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Victor Stinner4a3fe082020-04-14 14:26:24 +02006#include "pycore_interp.h" // _PY_NSMALLPOSINTS
7#include "pycore_pystate.h" // _Py_IsMainInterpreter()
Guido van Rossumedcc38a1991-05-05 20:09:44 +00008#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00009
Mark Dickinsonc6300392009-04-20 21:38:00 +000010#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000011#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000012#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000013
Serhiy Storchaka495e8802017-02-01 23:12:20 +020014#include "clinic/longobject.c.h"
15/*[clinic input]
16class int "PyObject *" "&PyLong_Type"
17[clinic start generated code]*/
18/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
19
Victor Stinner630c8df2019-12-17 13:02:18 +010020#define NSMALLPOSINTS _PY_NSMALLPOSINTS
21#define NSMALLNEGINTS _PY_NSMALLNEGINTS
Facundo Batista6e6f59b2008-07-24 18:57:11 +000022
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020023_Py_IDENTIFIER(little);
24_Py_IDENTIFIER(big);
25
Mark Dickinsone4416742009-02-15 15:14:57 +000026/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020027#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
28 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 (Py_SIZE(x) == 0 ? (sdigit)0 : \
30 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000031
Serhiy Storchakaba85d692017-03-30 09:09:41 +030032PyObject *_PyLong_Zero = NULL;
33PyObject *_PyLong_One = NULL;
34
Guido van Rossumddefaf32007-01-14 03:31:43 +000035#if NSMALLNEGINTS + NSMALLPOSINTS > 0
animalize6b519982019-09-06 14:00:56 +080036#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050037#define IS_SMALL_UINT(ival) ((ival) < NSMALLPOSINTS)
Greg Price5e63ab02019-08-24 10:19:37 -070038
Guido van Rossum7eaf8222007-06-18 17:58:50 +000039static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000040get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000041{
animalize6b519982019-09-06 14:00:56 +080042 assert(IS_SMALL_INT(ival));
Victor Stinner630c8df2019-12-17 13:02:18 +010043 PyThreadState *tstate = _PyThreadState_GET();
44 PyObject *v = (PyObject*)tstate->interp->small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000047}
Guido van Rossumddefaf32007-01-14 03:31:43 +000048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000050maybe_small_long(PyLongObject *v)
51{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020052 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080054 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 Py_DECREF(v);
56 return (PyLongObject *)get_small_int(ival);
57 }
58 }
59 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000060}
Guido van Rossumddefaf32007-01-14 03:31:43 +000061#else
animalize6b519982019-09-06 14:00:56 +080062#define IS_SMALL_INT(ival) 0
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050063#define IS_SMALL_UINT(ival) 0
animalize6b519982019-09-06 14:00:56 +080064#define get_small_int(ival) (Py_UNREACHABLE(), NULL)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000065#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#endif
67
Serhiy Storchaka95949422013-08-27 19:40:23 +030068/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000069 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020070Py_LOCAL_INLINE(void)
71_PyLong_Negate(PyLongObject **x_p)
72{
73 PyLongObject *x;
74
75 x = (PyLongObject *)*x_p;
76 if (Py_REFCNT(x) == 1) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +010077 Py_SET_SIZE(x, -Py_SIZE(x));
Victor Stinner8aed6f12013-07-17 22:31:17 +020078 return;
79 }
80
81 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
82 Py_DECREF(x);
83}
84
Serhiy Storchaka95949422013-08-27 19:40:23 +030085/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000086 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030087 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000088 */
Tim Peters0973b992004-08-29 22:16:50 +000089#define KARATSUBA_CUTOFF 70
90#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000091
Tim Peters47e52ee2004-08-30 02:44:38 +000092/* For exponentiation, use the binary left-to-right algorithm
93 * unless the exponent contains more than FIVEARY_CUTOFF digits.
94 * In that case, do 5 bits at a time. The potential drawback is that
95 * a table of 2**5 intermediate results is computed.
96 */
97#define FIVEARY_CUTOFF 8
98
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000099#define SIGCHECK(PyTryBlock) \
100 do { \
101 if (PyErr_CheckSignals()) PyTryBlock \
102 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000103
Serhiy Storchaka95949422013-08-27 19:40:23 +0300104/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000105 Doesn't attempt to free the storage--in most cases, due to the nature
106 of the algorithms used, this could save at most be one word anyway. */
107
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000108static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200109long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000110{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200111 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 while (i > 0 && v->ob_digit[i-1] == 0)
115 --i;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100116 if (i != j) {
117 Py_SET_SIZE(v, (Py_SIZE(v) < 0) ? -(i) : i);
118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000120}
121
Serhiy Storchaka95949422013-08-27 19:40:23 +0300122/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000123 Return NULL and set exception if we run out of memory. */
124
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000125#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000127
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000128PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000129_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 PyLongObject *result;
132 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
133 sizeof(digit)*size. Previous incarnations of this code used
134 sizeof(PyVarObject) instead of the offsetof, but this risks being
135 incorrect in the presence of padding between the PyVarObject header
136 and the digits. */
137 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
138 PyErr_SetString(PyExc_OverflowError,
139 "too many digits in integer");
140 return NULL;
141 }
142 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
143 size*sizeof(digit));
144 if (!result) {
145 PyErr_NoMemory();
146 return NULL;
147 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100148 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000149}
150
Tim Peters64b5ce32001-09-10 20:52:51 +0000151PyObject *
152_PyLong_Copy(PyLongObject *src)
153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 PyLongObject *result;
155 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 assert(src != NULL);
158 i = Py_SIZE(src);
159 if (i < 0)
160 i = -(i);
161 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100162 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800163 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700164 return get_small_int(ival);
165 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 }
167 result = _PyLong_New(i);
168 if (result != NULL) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100169 Py_SET_SIZE(result, Py_SIZE(src));
170 while (--i >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 result->ob_digit[i] = src->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100172 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 }
174 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000175}
176
Serhiy Storchaka95949422013-08-27 19:40:23 +0300177/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000178
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000179PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000180PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 PyLongObject *v;
183 unsigned long abs_ival;
184 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
185 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100186 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000187
animalize6b519982019-09-06 14:00:56 +0800188 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700189 return get_small_int((sdigit)ival);
190 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 if (ival < 0) {
193 /* negate: can't write this as abs_ival = -ival since that
194 invokes undefined behaviour when ival is LONG_MIN */
195 abs_ival = 0U-(unsigned long)ival;
196 sign = -1;
197 }
198 else {
199 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100200 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 /* Fast path for single-digit ints */
204 if (!(abs_ival >> PyLong_SHIFT)) {
205 v = _PyLong_New(1);
206 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100207 Py_SET_SIZE(v, sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 v->ob_digit[0] = Py_SAFE_DOWNCAST(
209 abs_ival, unsigned long, digit);
210 }
211 return (PyObject*)v;
212 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000213
Mark Dickinson249b8982009-04-27 19:41:00 +0000214#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 /* 2 digits */
216 if (!(abs_ival >> 2*PyLong_SHIFT)) {
217 v = _PyLong_New(2);
218 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100219 Py_SET_SIZE(v, 2 * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 v->ob_digit[0] = Py_SAFE_DOWNCAST(
221 abs_ival & PyLong_MASK, unsigned long, digit);
222 v->ob_digit[1] = Py_SAFE_DOWNCAST(
223 abs_ival >> PyLong_SHIFT, unsigned long, digit);
224 }
225 return (PyObject*)v;
226 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000227#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 /* Larger numbers: loop to determine number of digits */
230 t = abs_ival;
231 while (t) {
232 ++ndigits;
233 t >>= PyLong_SHIFT;
234 }
235 v = _PyLong_New(ndigits);
236 if (v != NULL) {
237 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100238 Py_SET_SIZE(v, ndigits * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 t = abs_ival;
240 while (t) {
241 *p++ = Py_SAFE_DOWNCAST(
242 t & PyLong_MASK, unsigned long, digit);
243 t >>= PyLong_SHIFT;
244 }
245 }
246 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000247}
248
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500249#define PYLONG_FROM_UINT(INT_TYPE, ival) \
250 do { \
251 if (IS_SMALL_UINT(ival)) { \
Victor Stinner6314abc2019-10-01 13:29:53 +0200252 return get_small_int((sdigit)(ival)); \
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500253 } \
254 /* Count the number of Python digits. */ \
255 Py_ssize_t ndigits = 0; \
256 INT_TYPE t = (ival); \
257 while (t) { \
258 ++ndigits; \
259 t >>= PyLong_SHIFT; \
260 } \
261 PyLongObject *v = _PyLong_New(ndigits); \
262 if (v == NULL) { \
263 return NULL; \
264 } \
265 digit *p = v->ob_digit; \
266 while ((ival)) { \
267 *p++ = (digit)((ival) & PyLong_MASK); \
268 (ival) >>= PyLong_SHIFT; \
269 } \
270 return (PyObject *)v; \
271 } while(0)
272
Serhiy Storchaka95949422013-08-27 19:40:23 +0300273/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000274
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000275PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000276PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000277{
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500278 PYLONG_FROM_UINT(unsigned long, ival);
279}
Tim Petersce9de2f2001-06-14 04:56:19 +0000280
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500281/* Create a new int object from a C unsigned long long int. */
282
283PyObject *
284PyLong_FromUnsignedLongLong(unsigned long long ival)
285{
286 PYLONG_FROM_UINT(unsigned long long, ival);
287}
288
289/* Create a new int object from a C size_t. */
290
291PyObject *
292PyLong_FromSize_t(size_t ival)
293{
294 PYLONG_FROM_UINT(size_t, ival);
Guido van Rossum53756b11997-01-03 17:14:46 +0000295}
296
Serhiy Storchaka95949422013-08-27 19:40:23 +0300297/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000298
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000300PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000301{
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500302 /* Try to get out cheap if this fits in a long. When a finite value of real
303 * floating type is converted to an integer type, the value is truncated
304 * toward zero. If the value of the integral part cannot be represented by
305 * the integer type, the behavior is undefined. Thus, we must check that
306 * value is in range (LONG_MIN - 1, LONG_MAX + 1). If a long has more bits
307 * of precision than a double, casting LONG_MIN - 1 to double may yield an
308 * approximation, but LONG_MAX + 1 is a power of two and can be represented
309 * as double exactly (assuming FLT_RADIX is 2 or 16), so for simplicity
310 * check against [-(LONG_MAX + 1), LONG_MAX + 1).
311 */
312 const double int_max = (unsigned long)LONG_MAX + 1;
313 if (-int_max < dval && dval < int_max) {
314 return PyLong_FromLong((long)dval);
315 }
316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 PyLongObject *v;
318 double frac;
319 int i, ndig, expo, neg;
320 neg = 0;
321 if (Py_IS_INFINITY(dval)) {
322 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000323 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 return NULL;
325 }
326 if (Py_IS_NAN(dval)) {
327 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000328 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 return NULL;
330 }
331 if (dval < 0.0) {
332 neg = 1;
333 dval = -dval;
334 }
335 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500336 assert(expo > 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
338 v = _PyLong_New(ndig);
339 if (v == NULL)
340 return NULL;
341 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
342 for (i = ndig; --i >= 0; ) {
343 digit bits = (digit)frac;
344 v->ob_digit[i] = bits;
345 frac = frac - (double)bits;
346 frac = ldexp(frac, PyLong_SHIFT);
347 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100348 if (neg) {
349 Py_SET_SIZE(v, -(Py_SIZE(v)));
350 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000352}
353
Thomas Wouters89f507f2006-12-13 04:49:30 +0000354/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
355 * anything about what happens when a signed integer operation overflows,
356 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700357 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000358 * (unsigned long)LONG_MAX, and for the smallest negative signed long
359 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
360 * However, some other compilers warn about applying unary minus to an
361 * unsigned operand. Hence the weird "0-".
362 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
364#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000365
Mark Dickinson20941de2020-05-27 13:43:17 +0100366/* Get a C long int from an int object or any object that has an __index__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100367 method.
368
369 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
370 the result. Otherwise *overflow is 0.
371
372 For other errors (e.g., TypeError), return -1 and set an error condition.
373 In this case *overflow will be 0.
374*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000375
376long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000377PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200380 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 unsigned long x, prev;
382 long res;
383 Py_ssize_t i;
384 int sign;
Mark Dickinson20941de2020-05-27 13:43:17 +0100385 int do_decref = 0; /* if PyNumber_Index was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 *overflow = 0;
388 if (vv == NULL) {
389 PyErr_BadInternalCall();
390 return -1;
391 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000392
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200393 if (PyLong_Check(vv)) {
394 v = (PyLongObject *)vv;
395 }
396 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300397 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200398 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 return -1;
400 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 switch (i) {
407 case -1:
408 res = -(sdigit)v->ob_digit[0];
409 break;
410 case 0:
411 res = 0;
412 break;
413 case 1:
414 res = v->ob_digit[0];
415 break;
416 default:
417 sign = 1;
418 x = 0;
419 if (i < 0) {
420 sign = -1;
421 i = -(i);
422 }
423 while (--i >= 0) {
424 prev = x;
425 x = (x << PyLong_SHIFT) | v->ob_digit[i];
426 if ((x >> PyLong_SHIFT) != prev) {
427 *overflow = sign;
428 goto exit;
429 }
430 }
431 /* Haven't lost any bits, but casting to long requires extra
432 * care (see comment above).
433 */
434 if (x <= (unsigned long)LONG_MAX) {
435 res = (long)x * sign;
436 }
437 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
438 res = LONG_MIN;
439 }
440 else {
441 *overflow = sign;
442 /* res is already set to -1 */
443 }
444 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000445 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200447 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 }
449 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000450}
451
Mark Dickinson20941de2020-05-27 13:43:17 +0100452/* Get a C long int from an int object or any object that has an __index__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100453 method. Return -1 and set an error if overflow occurs. */
454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000456PyLong_AsLong(PyObject *obj)
457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 int overflow;
459 long result = PyLong_AsLongAndOverflow(obj, &overflow);
460 if (overflow) {
461 /* XXX: could be cute and give a different
462 message for overflow == -1 */
463 PyErr_SetString(PyExc_OverflowError,
464 "Python int too large to convert to C long");
465 }
466 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000467}
468
Mark Dickinson20941de2020-05-27 13:43:17 +0100469/* Get a C int from an int object or any object that has an __index__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200470 method. Return -1 and set an error if overflow occurs. */
471
472int
473_PyLong_AsInt(PyObject *obj)
474{
475 int overflow;
476 long result = PyLong_AsLongAndOverflow(obj, &overflow);
477 if (overflow || result > INT_MAX || result < INT_MIN) {
478 /* XXX: could be cute and give a different
479 message for overflow == -1 */
480 PyErr_SetString(PyExc_OverflowError,
481 "Python int too large to convert to C int");
482 return -1;
483 }
484 return (int)result;
485}
486
Serhiy Storchaka95949422013-08-27 19:40:23 +0300487/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000488 Returns -1 and sets an error condition if overflow occurs. */
489
490Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000491PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200492 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 size_t x, prev;
494 Py_ssize_t i;
495 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (vv == NULL) {
498 PyErr_BadInternalCall();
499 return -1;
500 }
501 if (!PyLong_Check(vv)) {
502 PyErr_SetString(PyExc_TypeError, "an integer is required");
503 return -1;
504 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 v = (PyLongObject *)vv;
507 i = Py_SIZE(v);
508 switch (i) {
509 case -1: return -(sdigit)v->ob_digit[0];
510 case 0: return 0;
511 case 1: return v->ob_digit[0];
512 }
513 sign = 1;
514 x = 0;
515 if (i < 0) {
516 sign = -1;
517 i = -(i);
518 }
519 while (--i >= 0) {
520 prev = x;
521 x = (x << PyLong_SHIFT) | v->ob_digit[i];
522 if ((x >> PyLong_SHIFT) != prev)
523 goto overflow;
524 }
525 /* Haven't lost any bits, but casting to a signed type requires
526 * extra care (see comment above).
527 */
528 if (x <= (size_t)PY_SSIZE_T_MAX) {
529 return (Py_ssize_t)x * sign;
530 }
531 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
532 return PY_SSIZE_T_MIN;
533 }
534 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000535
Mark Dickinson22b20182010-05-10 21:27:53 +0000536 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 PyErr_SetString(PyExc_OverflowError,
538 "Python int too large to convert to C ssize_t");
539 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000540}
541
Serhiy Storchaka95949422013-08-27 19:40:23 +0300542/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000543 Returns -1 and sets an error condition if overflow occurs. */
544
545unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000546PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000547{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200548 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 unsigned long x, prev;
550 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 if (vv == NULL) {
553 PyErr_BadInternalCall();
554 return (unsigned long)-1;
555 }
556 if (!PyLong_Check(vv)) {
557 PyErr_SetString(PyExc_TypeError, "an integer is required");
558 return (unsigned long)-1;
559 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 v = (PyLongObject *)vv;
562 i = Py_SIZE(v);
563 x = 0;
564 if (i < 0) {
565 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000566 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 return (unsigned long) -1;
568 }
569 switch (i) {
570 case 0: return 0;
571 case 1: return v->ob_digit[0];
572 }
573 while (--i >= 0) {
574 prev = x;
575 x = (x << PyLong_SHIFT) | v->ob_digit[i];
576 if ((x >> PyLong_SHIFT) != prev) {
577 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100578 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000579 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return (unsigned long) -1;
581 }
582 }
583 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000584}
585
Serhiy Storchaka95949422013-08-27 19:40:23 +0300586/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200587 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000588
589size_t
590PyLong_AsSize_t(PyObject *vv)
591{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200592 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 size_t x, prev;
594 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (vv == NULL) {
597 PyErr_BadInternalCall();
598 return (size_t) -1;
599 }
600 if (!PyLong_Check(vv)) {
601 PyErr_SetString(PyExc_TypeError, "an integer is required");
602 return (size_t)-1;
603 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 v = (PyLongObject *)vv;
606 i = Py_SIZE(v);
607 x = 0;
608 if (i < 0) {
609 PyErr_SetString(PyExc_OverflowError,
610 "can't convert negative value to size_t");
611 return (size_t) -1;
612 }
613 switch (i) {
614 case 0: return 0;
615 case 1: return v->ob_digit[0];
616 }
617 while (--i >= 0) {
618 prev = x;
619 x = (x << PyLong_SHIFT) | v->ob_digit[i];
620 if ((x >> PyLong_SHIFT) != prev) {
621 PyErr_SetString(PyExc_OverflowError,
622 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200623 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 }
625 }
626 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000627}
628
Serhiy Storchaka95949422013-08-27 19:40:23 +0300629/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000630 Returns -1 and sets an error condition if an error occurs. */
631
Guido van Rossumddefaf32007-01-14 03:31:43 +0000632static unsigned long
633_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000634{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200635 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 unsigned long x;
637 Py_ssize_t i;
638 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (vv == NULL || !PyLong_Check(vv)) {
641 PyErr_BadInternalCall();
642 return (unsigned long) -1;
643 }
644 v = (PyLongObject *)vv;
645 i = Py_SIZE(v);
646 switch (i) {
647 case 0: return 0;
648 case 1: return v->ob_digit[0];
649 }
650 sign = 1;
651 x = 0;
652 if (i < 0) {
653 sign = -1;
654 i = -i;
655 }
656 while (--i >= 0) {
657 x = (x << PyLong_SHIFT) | v->ob_digit[i];
658 }
659 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000660}
661
Guido van Rossumddefaf32007-01-14 03:31:43 +0000662unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200663PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 PyLongObject *lo;
666 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000667
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200668 if (op == NULL) {
669 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 return (unsigned long)-1;
671 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000672
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200673 if (PyLong_Check(op)) {
674 return _PyLong_AsUnsignedLongMask(op);
675 }
676
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300677 lo = (PyLongObject *)_PyNumber_Index(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if (lo == NULL)
679 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200680
681 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
682 Py_DECREF(lo);
683 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000684}
685
Tim Peters5b8132f2003-01-31 15:52:05 +0000686int
687_PyLong_Sign(PyObject *vv)
688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 assert(v != NULL);
692 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000695}
696
Tim Petersbaefd9e2003-01-28 20:37:45 +0000697size_t
698_PyLong_NumBits(PyObject *vv)
699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 PyLongObject *v = (PyLongObject *)vv;
701 size_t result = 0;
702 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200703 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 assert(v != NULL);
706 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200707 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
709 if (ndigits > 0) {
710 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700711 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100713 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Niklas Fiekasc5b79002020-01-16 15:09:19 +0100714 msd_bits = _Py_bit_length(msd);
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200715 if (SIZE_MAX - msd_bits < result)
716 goto Overflow;
717 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 }
719 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000720
Mark Dickinson22b20182010-05-10 21:27:53 +0000721 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
723 "to express in a platform size_t");
724 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000725}
726
Tim Peters2a9b3672001-06-11 21:23:58 +0000727PyObject *
728_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000730{
Mark Dickinson22b20182010-05-10 21:27:53 +0000731 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 int incr; /* direction to move pstartbyte */
733 const unsigned char* pendbyte; /* MSB of bytes */
734 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300735 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyLongObject* v; /* result */
737 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (n == 0)
740 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 if (little_endian) {
743 pstartbyte = bytes;
744 pendbyte = bytes + n - 1;
745 incr = 1;
746 }
747 else {
748 pstartbyte = bytes + n - 1;
749 pendbyte = bytes;
750 incr = -1;
751 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (is_signed)
754 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200757 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 is positive, and leading 0xff bytes if negative. */
759 {
760 size_t i;
761 const unsigned char* p = pendbyte;
762 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000763 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000766 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 break;
768 }
769 numsignificantbytes = n - i;
770 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
771 actually has 2 significant bytes. OTOH, 0xff0001 ==
772 -0x00ffff, so we wouldn't *need* to bump it there; but we
773 do for 0xffff = -0x0001. To be safe without bothering to
774 check every case, bump it regardless. */
775 if (is_signed && numsignificantbytes < n)
776 ++numsignificantbytes;
777 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000778
Serhiy Storchaka95949422013-08-27 19:40:23 +0300779 /* How many Python int digits do we need? We have
780 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
782 /* catch overflow before it happens */
783 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
784 PyErr_SetString(PyExc_OverflowError,
785 "byte array too long to convert to int");
786 return NULL;
787 }
788 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
789 v = _PyLong_New(ndigits);
790 if (v == NULL)
791 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 /* Copy the bits over. The tricky parts are computing 2's-comp on
794 the fly for signed numbers, and dealing with the mismatch between
795 8-bit bytes and (probably) 15-bit Python digits.*/
796 {
797 size_t i;
798 twodigits carry = 1; /* for 2's-comp calculation */
799 twodigits accum = 0; /* sliding register */
800 unsigned int accumbits = 0; /* number of bits in accum */
801 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
804 twodigits thisbyte = *p;
805 /* Compute correction for 2's comp, if needed. */
806 if (is_signed) {
807 thisbyte = (0xff ^ thisbyte) + carry;
808 carry = thisbyte >> 8;
809 thisbyte &= 0xff;
810 }
811 /* Because we're going LSB to MSB, thisbyte is
812 more significant than what's already in accum,
813 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200814 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 accumbits += 8;
816 if (accumbits >= PyLong_SHIFT) {
817 /* There's enough to fill a Python digit. */
818 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000819 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 ++idigit;
821 accum >>= PyLong_SHIFT;
822 accumbits -= PyLong_SHIFT;
823 assert(accumbits < PyLong_SHIFT);
824 }
825 }
826 assert(accumbits < PyLong_SHIFT);
827 if (accumbits) {
828 assert(idigit < ndigits);
829 v->ob_digit[idigit] = (digit)accum;
830 ++idigit;
831 }
832 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000833
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100834 Py_SET_SIZE(v, is_signed ? -idigit : idigit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000836}
837
838int
839_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 unsigned char* bytes, size_t n,
841 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000844 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000846 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
848 digit carry; /* for computing 2's-comp */
849 size_t j; /* # bytes filled */
850 unsigned char* p; /* pointer to next byte in bytes */
851 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (Py_SIZE(v) < 0) {
856 ndigits = -(Py_SIZE(v));
857 if (!is_signed) {
858 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000859 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 return -1;
861 }
862 do_twos_comp = 1;
863 }
864 else {
865 ndigits = Py_SIZE(v);
866 do_twos_comp = 0;
867 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 if (little_endian) {
870 p = bytes;
871 pincr = 1;
872 }
873 else {
874 p = bytes + n - 1;
875 pincr = -1;
876 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 /* Copy over all the Python digits.
879 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300880 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 normalized. */
882 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
883 j = 0;
884 accum = 0;
885 accumbits = 0;
886 carry = do_twos_comp ? 1 : 0;
887 for (i = 0; i < ndigits; ++i) {
888 digit thisdigit = v->ob_digit[i];
889 if (do_twos_comp) {
890 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
891 carry = thisdigit >> PyLong_SHIFT;
892 thisdigit &= PyLong_MASK;
893 }
894 /* Because we're going LSB to MSB, thisdigit is more
895 significant than what's already in accum, so needs to be
896 prepended to accum. */
897 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 /* The most-significant digit may be (probably is) at least
900 partly empty. */
901 if (i == ndigits - 1) {
902 /* Count # of sign bits -- they needn't be stored,
903 * although for signed conversion we need later to
904 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000905 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 while (s != 0) {
907 s >>= 1;
908 accumbits++;
909 }
910 }
911 else
912 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* Store as many bytes as possible. */
915 while (accumbits >= 8) {
916 if (j >= n)
917 goto Overflow;
918 ++j;
919 *p = (unsigned char)(accum & 0xff);
920 p += pincr;
921 accumbits -= 8;
922 accum >>= 8;
923 }
924 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* Store the straggler (if any). */
927 assert(accumbits < 8);
928 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
929 if (accumbits > 0) {
930 if (j >= n)
931 goto Overflow;
932 ++j;
933 if (do_twos_comp) {
934 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300935 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 infinite supply of sign bits). */
937 accum |= (~(twodigits)0) << accumbits;
938 }
939 *p = (unsigned char)(accum & 0xff);
940 p += pincr;
941 }
942 else if (j == n && n > 0 && is_signed) {
943 /* The main loop filled the byte array exactly, so the code
944 just above didn't get to ensure there's a sign bit, and the
945 loop below wouldn't add one either. Make sure a sign bit
946 exists. */
947 unsigned char msb = *(p - pincr);
948 int sign_bit_set = msb >= 0x80;
949 assert(accumbits == 0);
950 if (sign_bit_set == do_twos_comp)
951 return 0;
952 else
953 goto Overflow;
954 }
Tim Peters05607ad2001-06-13 21:01:27 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 /* Fill remaining bytes with copies of the sign bit. */
957 {
958 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
959 for ( ; j < n; ++j, p += pincr)
960 *p = signbyte;
961 }
Tim Peters05607ad2001-06-13 21:01:27 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000964
Mark Dickinson22b20182010-05-10 21:27:53 +0000965 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
967 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000968
Tim Peters2a9b3672001-06-11 21:23:58 +0000969}
970
Serhiy Storchaka95949422013-08-27 19:40:23 +0300971/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000972
973PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000974PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000975{
Mark Dickinson91044792012-10-18 19:21:43 +0100976#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -0700977 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100978#else
979
Tim Peters70128a12001-06-16 08:48:40 +0000980#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700981# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000982#endif
Benjamin Petersonca470632016-09-06 13:47:26 -0700983 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100984#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000985
Guido van Rossum78694d91998-09-18 14:14:13 +0000986}
987
Serhiy Storchaka95949422013-08-27 19:40:23 +0300988/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000989
990void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000991PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000992{
Tim Peters70128a12001-06-16 08:48:40 +0000993#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
997 x = PyLong_AsLong(vv);
998 else
999 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001000#else
Tim Peters70128a12001-06-16 08:48:40 +00001001
Tim Peters70128a12001-06-16 08:48:40 +00001002#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001003# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001004#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001005 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1008 x = PyLong_AsLongLong(vv);
1009 else
1010 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001011
1012#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (x == -1 && PyErr_Occurred())
1015 return NULL;
1016 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001017}
1018
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001019/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001020 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001021 */
1022
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001023#define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001024
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001025/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001026
1027PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001028PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001031 unsigned long long abs_ival;
1032 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 int ndigits = 0;
1034 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001035
animalize6b519982019-09-06 14:00:56 +08001036 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001037 return get_small_int((sdigit)ival);
1038 }
1039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 if (ival < 0) {
1041 /* avoid signed overflow on negation; see comments
1042 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001043 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 negative = 1;
1045 }
1046 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001047 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 /* Count the number of Python digits.
1051 We used to pick 5 ("big enough for anything"), but that's a
1052 waste of time and space given that 5*15 = 75 bits are rarely
1053 needed. */
1054 t = abs_ival;
1055 while (t) {
1056 ++ndigits;
1057 t >>= PyLong_SHIFT;
1058 }
1059 v = _PyLong_New(ndigits);
1060 if (v != NULL) {
1061 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001062 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 t = abs_ival;
1064 while (t) {
1065 *p++ = (digit)(t & PyLong_MASK);
1066 t >>= PyLong_SHIFT;
1067 }
1068 }
1069 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001070}
1071
Serhiy Storchaka95949422013-08-27 19:40:23 +03001072/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001073
1074PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001075PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 PyLongObject *v;
1078 size_t abs_ival;
1079 size_t t; /* unsigned so >> doesn't propagate sign bit */
1080 int ndigits = 0;
1081 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001082
animalize6b519982019-09-06 14:00:56 +08001083 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001084 return get_small_int((sdigit)ival);
1085 }
1086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 if (ival < 0) {
1088 /* avoid signed overflow when ival = SIZE_T_MIN */
1089 abs_ival = (size_t)(-1-ival)+1;
1090 negative = 1;
1091 }
1092 else {
1093 abs_ival = (size_t)ival;
1094 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 /* Count the number of Python digits. */
1097 t = abs_ival;
1098 while (t) {
1099 ++ndigits;
1100 t >>= PyLong_SHIFT;
1101 }
1102 v = _PyLong_New(ndigits);
1103 if (v != NULL) {
1104 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001105 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 t = abs_ival;
1107 while (t) {
1108 *p++ = (digit)(t & PyLong_MASK);
1109 t >>= PyLong_SHIFT;
1110 }
1111 }
1112 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001113}
1114
Serhiy Storchaka95949422013-08-27 19:40:23 +03001115/* Get a C long long int from an int object or any object that has an
Mark Dickinson20941de2020-05-27 13:43:17 +01001116 __index__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001117
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001118long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001119PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001122 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 int res;
Mark Dickinson20941de2020-05-27 13:43:17 +01001124 int do_decref = 0; /* if PyNumber_Index was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (vv == NULL) {
1127 PyErr_BadInternalCall();
1128 return -1;
1129 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001130
1131 if (PyLong_Check(vv)) {
1132 v = (PyLongObject *)vv;
1133 }
1134 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001135 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001136 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001138 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001140
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001141 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001143 case -1:
1144 bytes = -(sdigit)v->ob_digit[0];
1145 break;
1146 case 0:
1147 bytes = 0;
1148 break;
1149 case 1:
1150 bytes = v->ob_digit[0];
1151 break;
1152 default:
1153 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001154 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001156 if (do_decref) {
1157 Py_DECREF(v);
1158 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001159
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001160 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001162 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 else
1164 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001165}
1166
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001167/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001168 Return -1 and set an error if overflow occurs. */
1169
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001170unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001171PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001174 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001176
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001177 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001179 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001181 if (!PyLong_Check(vv)) {
1182 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001183 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001184 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 v = (PyLongObject*)vv;
1187 switch(Py_SIZE(v)) {
1188 case 0: return 0;
1189 case 1: return v->ob_digit[0];
1190 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001191
Mark Dickinson22b20182010-05-10 21:27:53 +00001192 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001193 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001194
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001195 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001197 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 else
1199 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001200}
Tim Petersd1a7da62001-06-13 00:35:57 +00001201
Serhiy Storchaka95949422013-08-27 19:40:23 +03001202/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001203 Returns -1 and sets an error condition if an error occurs. */
1204
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001205static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001206_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001207{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001208 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001209 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 Py_ssize_t i;
1211 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (vv == NULL || !PyLong_Check(vv)) {
1214 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001215 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 }
1217 v = (PyLongObject *)vv;
1218 switch(Py_SIZE(v)) {
1219 case 0: return 0;
1220 case 1: return v->ob_digit[0];
1221 }
1222 i = Py_SIZE(v);
1223 sign = 1;
1224 x = 0;
1225 if (i < 0) {
1226 sign = -1;
1227 i = -i;
1228 }
1229 while (--i >= 0) {
1230 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1231 }
1232 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001233}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001234
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001235unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001236PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001239 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001240
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001241 if (op == NULL) {
1242 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001243 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001245
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001246 if (PyLong_Check(op)) {
1247 return _PyLong_AsUnsignedLongLongMask(op);
1248 }
1249
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001250 lo = (PyLongObject *)_PyNumber_Index(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001252 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001253
1254 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1255 Py_DECREF(lo);
1256 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001257}
Tim Petersd1a7da62001-06-13 00:35:57 +00001258
Serhiy Storchaka95949422013-08-27 19:40:23 +03001259/* Get a C long long int from an int object or any object that has an
Mark Dickinson20941de2020-05-27 13:43:17 +01001260 __index__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001261
Mark Dickinson8d48b432011-10-23 20:47:14 +01001262 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1263 the result. Otherwise *overflow is 0.
1264
1265 For other errors (e.g., TypeError), return -1 and set an error condition.
1266 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001267*/
1268
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001269long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001270PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001273 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001274 unsigned long long x, prev;
1275 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 Py_ssize_t i;
1277 int sign;
Mark Dickinson20941de2020-05-27 13:43:17 +01001278 int do_decref = 0; /* if PyNumber_Index was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 *overflow = 0;
1281 if (vv == NULL) {
1282 PyErr_BadInternalCall();
1283 return -1;
1284 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001285
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001286 if (PyLong_Check(vv)) {
1287 v = (PyLongObject *)vv;
1288 }
1289 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001290 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001291 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 return -1;
1293 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 switch (i) {
1300 case -1:
1301 res = -(sdigit)v->ob_digit[0];
1302 break;
1303 case 0:
1304 res = 0;
1305 break;
1306 case 1:
1307 res = v->ob_digit[0];
1308 break;
1309 default:
1310 sign = 1;
1311 x = 0;
1312 if (i < 0) {
1313 sign = -1;
1314 i = -(i);
1315 }
1316 while (--i >= 0) {
1317 prev = x;
1318 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1319 if ((x >> PyLong_SHIFT) != prev) {
1320 *overflow = sign;
1321 goto exit;
1322 }
1323 }
1324 /* Haven't lost any bits, but casting to long requires extra
1325 * care (see comment above).
1326 */
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001327 if (x <= (unsigned long long)LLONG_MAX) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001328 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 }
1330 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001331 res = LLONG_MIN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 }
1333 else {
1334 *overflow = sign;
1335 /* res is already set to -1 */
1336 }
1337 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001338 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001340 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 }
1342 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001343}
1344
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001345int
1346_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1347{
1348 unsigned long uval;
1349
1350 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1351 PyErr_SetString(PyExc_ValueError, "value must be positive");
1352 return 0;
1353 }
1354 uval = PyLong_AsUnsignedLong(obj);
1355 if (uval == (unsigned long)-1 && PyErr_Occurred())
1356 return 0;
1357 if (uval > USHRT_MAX) {
1358 PyErr_SetString(PyExc_OverflowError,
1359 "Python int too large for C unsigned short");
1360 return 0;
1361 }
1362
1363 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1364 return 1;
1365}
1366
1367int
1368_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1369{
1370 unsigned long uval;
1371
1372 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1373 PyErr_SetString(PyExc_ValueError, "value must be positive");
1374 return 0;
1375 }
1376 uval = PyLong_AsUnsignedLong(obj);
1377 if (uval == (unsigned long)-1 && PyErr_Occurred())
1378 return 0;
1379 if (uval > UINT_MAX) {
1380 PyErr_SetString(PyExc_OverflowError,
1381 "Python int too large for C unsigned int");
1382 return 0;
1383 }
1384
1385 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1386 return 1;
1387}
1388
1389int
1390_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1391{
1392 unsigned long uval;
1393
1394 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1395 PyErr_SetString(PyExc_ValueError, "value must be positive");
1396 return 0;
1397 }
1398 uval = PyLong_AsUnsignedLong(obj);
1399 if (uval == (unsigned long)-1 && PyErr_Occurred())
1400 return 0;
1401
1402 *(unsigned long *)ptr = uval;
1403 return 1;
1404}
1405
1406int
1407_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1408{
1409 unsigned long long uval;
1410
1411 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1412 PyErr_SetString(PyExc_ValueError, "value must be positive");
1413 return 0;
1414 }
1415 uval = PyLong_AsUnsignedLongLong(obj);
1416 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1417 return 0;
1418
1419 *(unsigned long long *)ptr = uval;
1420 return 1;
1421}
1422
1423int
1424_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1425{
1426 size_t uval;
1427
1428 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1429 PyErr_SetString(PyExc_ValueError, "value must be positive");
1430 return 0;
1431 }
1432 uval = PyLong_AsSize_t(obj);
1433 if (uval == (size_t)-1 && PyErr_Occurred())
1434 return 0;
1435
1436 *(size_t *)ptr = uval;
1437 return 1;
1438}
1439
1440
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001441#define CHECK_BINOP(v,w) \
1442 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001443 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1444 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001445 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001446
Tim Peters877a2122002-08-12 05:09:36 +00001447/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1448 * is modified in place, by adding y to it. Carries are propagated as far as
1449 * x[m-1], and the remaining carry (0 or 1) is returned.
1450 */
1451static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001452v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 Py_ssize_t i;
1455 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 assert(m >= n);
1458 for (i = 0; i < n; ++i) {
1459 carry += x[i] + y[i];
1460 x[i] = carry & PyLong_MASK;
1461 carry >>= PyLong_SHIFT;
1462 assert((carry & 1) == carry);
1463 }
1464 for (; carry && i < m; ++i) {
1465 carry += x[i];
1466 x[i] = carry & PyLong_MASK;
1467 carry >>= PyLong_SHIFT;
1468 assert((carry & 1) == carry);
1469 }
1470 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001471}
1472
1473/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1474 * is modified in place, by subtracting y from it. Borrows are propagated as
1475 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1476 */
1477static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001478v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 Py_ssize_t i;
1481 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 assert(m >= n);
1484 for (i = 0; i < n; ++i) {
1485 borrow = x[i] - y[i] - borrow;
1486 x[i] = borrow & PyLong_MASK;
1487 borrow >>= PyLong_SHIFT;
1488 borrow &= 1; /* keep only 1 sign bit */
1489 }
1490 for (; borrow && i < m; ++i) {
1491 borrow = x[i] - borrow;
1492 x[i] = borrow & PyLong_MASK;
1493 borrow >>= PyLong_SHIFT;
1494 borrow &= 1;
1495 }
1496 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001497}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001498
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001499/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1500 * result in z[0:m], and return the d bits shifted out of the top.
1501 */
1502static digit
1503v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 Py_ssize_t i;
1506 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 assert(0 <= d && d < PyLong_SHIFT);
1509 for (i=0; i < m; i++) {
1510 twodigits acc = (twodigits)a[i] << d | carry;
1511 z[i] = (digit)acc & PyLong_MASK;
1512 carry = (digit)(acc >> PyLong_SHIFT);
1513 }
1514 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001515}
1516
1517/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1518 * result in z[0:m], and return the d bits shifted out of the bottom.
1519 */
1520static digit
1521v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 Py_ssize_t i;
1524 digit carry = 0;
1525 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 assert(0 <= d && d < PyLong_SHIFT);
1528 for (i=m; i-- > 0;) {
1529 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1530 carry = (digit)acc & mask;
1531 z[i] = (digit)(acc >> d);
1532 }
1533 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001534}
1535
Tim Peters212e6142001-07-14 12:23:19 +00001536/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1537 in pout, and returning the remainder. pin and pout point at the LSD.
1538 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001539 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001540 immutable. */
1541
1542static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001543inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 assert(n > 0 && n <= PyLong_MASK);
1548 pin += size;
1549 pout += size;
1550 while (--size >= 0) {
1551 digit hi;
1552 rem = (rem << PyLong_SHIFT) | *--pin;
1553 *--pout = hi = (digit)(rem / n);
1554 rem -= (twodigits)hi * n;
1555 }
1556 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001557}
1558
Serhiy Storchaka95949422013-08-27 19:40:23 +03001559/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001560 (as function result) and the remainder (through *prem).
1561 The sign of a is ignored; n should not be zero. */
1562
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001563static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001564divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001565{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001566 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 assert(n > 0 && n <= PyLong_MASK);
1570 z = _PyLong_New(size);
1571 if (z == NULL)
1572 return NULL;
1573 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1574 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001575}
1576
Serhiy Storchaka95949422013-08-27 19:40:23 +03001577/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001578 string. (Return value is non-shared so that callers can modify the
1579 returned value if necessary.) */
1580
Victor Stinnerd3f08822012-05-29 12:57:52 +02001581static int
1582long_to_decimal_string_internal(PyObject *aa,
1583 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001584 _PyUnicodeWriter *writer,
1585 _PyBytesWriter *bytes_writer,
1586 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001589 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 Py_ssize_t size, strlen, size_a, i, j;
1591 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001593 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001594 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 a = (PyLongObject *)aa;
1597 if (a == NULL || !PyLong_Check(a)) {
1598 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001599 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001601 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 /* quick and dirty upper bound for the number of digits
1605 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 But log2(a) < size_a * PyLong_SHIFT, and
1610 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001611 > 3.3 * _PyLong_DECIMAL_SHIFT
1612
1613 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1614 size_a + size_a / d < size_a + size_a / floor(d),
1615 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1616 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001618 d = (33 * _PyLong_DECIMAL_SHIFT) /
1619 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1620 assert(size_a < PY_SSIZE_T_MAX/2);
1621 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 scratch = _PyLong_New(size);
1623 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001624 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 /* convert array of base _PyLong_BASE digits in pin to an array of
1627 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1628 Volume 2 (3rd edn), section 4.4, Method 1b). */
1629 pin = a->ob_digit;
1630 pout = scratch->ob_digit;
1631 size = 0;
1632 for (i = size_a; --i >= 0; ) {
1633 digit hi = pin[i];
1634 for (j = 0; j < size; j++) {
1635 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1636 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1637 pout[j] = (digit)(z - (twodigits)hi *
1638 _PyLong_DECIMAL_BASE);
1639 }
1640 while (hi) {
1641 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1642 hi /= _PyLong_DECIMAL_BASE;
1643 }
1644 /* check for keyboard interrupt */
1645 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001646 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001647 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001648 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 }
1650 /* pout should have at least one digit, so that the case when a = 0
1651 works correctly */
1652 if (size == 0)
1653 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 /* calculate exact length of output string, and allocate */
1656 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1657 tenpow = 10;
1658 rem = pout[size-1];
1659 while (rem >= tenpow) {
1660 tenpow *= 10;
1661 strlen++;
1662 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001663 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001664 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1665 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001666 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001667 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001668 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001670 else if (bytes_writer) {
1671 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1672 if (*bytes_str == NULL) {
1673 Py_DECREF(scratch);
1674 return -1;
1675 }
1676 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001677 else {
1678 str = PyUnicode_New(strlen, '9');
1679 if (str == NULL) {
1680 Py_DECREF(scratch);
1681 return -1;
1682 }
1683 kind = PyUnicode_KIND(str);
1684 }
1685
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001686#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001687 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001688 /* pout[0] through pout[size-2] contribute exactly \
1689 _PyLong_DECIMAL_SHIFT digits each */ \
1690 for (i=0; i < size - 1; i++) { \
1691 rem = pout[i]; \
1692 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1693 *--p = '0' + rem % 10; \
1694 rem /= 10; \
1695 } \
1696 } \
1697 /* pout[size-1]: always produce at least one decimal digit */ \
1698 rem = pout[i]; \
1699 do { \
1700 *--p = '0' + rem % 10; \
1701 rem /= 10; \
1702 } while (rem != 0); \
1703 \
1704 /* and sign */ \
1705 if (negative) \
1706 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001707 } while (0)
1708
1709#define WRITE_UNICODE_DIGITS(TYPE) \
1710 do { \
1711 if (writer) \
1712 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1713 else \
1714 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1715 \
1716 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001717 \
1718 /* check we've counted correctly */ \
1719 if (writer) \
1720 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1721 else \
1722 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1723 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001726 if (bytes_writer) {
1727 char *p = *bytes_str + strlen;
1728 WRITE_DIGITS(p);
1729 assert(p == *bytes_str);
1730 }
1731 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001732 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001733 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001735 else if (kind == PyUnicode_2BYTE_KIND) {
1736 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001737 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001738 }
1739 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001740 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001741 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001742 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001743 }
1744#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001745#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001748 if (writer) {
1749 writer->pos += strlen;
1750 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001751 else if (bytes_writer) {
1752 (*bytes_str) += strlen;
1753 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001754 else {
1755 assert(_PyUnicode_CheckConsistency(str, 1));
1756 *p_output = (PyObject *)str;
1757 }
1758 return 0;
1759}
1760
1761static PyObject *
1762long_to_decimal_string(PyObject *aa)
1763{
1764 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001765 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001766 return NULL;
1767 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001768}
1769
Serhiy Storchaka95949422013-08-27 19:40:23 +03001770/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001771 which should be one of 2, 8 or 16. Return a string object.
1772 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1773 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001774
Victor Stinnerd3f08822012-05-29 12:57:52 +02001775static int
1776long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001777 PyObject **p_output, _PyUnicodeWriter *writer,
1778 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001779{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001780 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001781 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001782 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001784 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001785 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001787
Victor Stinnerd3f08822012-05-29 12:57:52 +02001788 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (a == NULL || !PyLong_Check(a)) {
1790 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001791 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001793 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001794 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 /* Compute a rough upper bound for the length of the string */
1797 switch (base) {
1798 case 16:
1799 bits = 4;
1800 break;
1801 case 8:
1802 bits = 3;
1803 break;
1804 case 2:
1805 bits = 1;
1806 break;
1807 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001808 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001810
Mark Dickinsone2846542012-04-20 21:21:24 +01001811 /* Compute exact length 'sz' of output string. */
1812 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001813 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001814 }
1815 else {
1816 Py_ssize_t size_a_in_bits;
1817 /* Ensure overflow doesn't occur during computation of sz. */
1818 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1819 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001820 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001821 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001822 }
1823 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001824 _Py_bit_length(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001825 /* Allow 1 character for a '-' sign. */
1826 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1827 }
1828 if (alternate) {
1829 /* 2 characters for prefix */
1830 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001831 }
1832
Victor Stinnerd3f08822012-05-29 12:57:52 +02001833 if (writer) {
1834 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1835 return -1;
1836 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001838 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001839 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1840 if (*bytes_str == NULL)
1841 return -1;
1842 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001844 v = PyUnicode_New(sz, 'x');
1845 if (v == NULL)
1846 return -1;
1847 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001849
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001850#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001851 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001852 if (size_a == 0) { \
1853 *--p = '0'; \
1854 } \
1855 else { \
1856 /* JRH: special case for power-of-2 bases */ \
1857 twodigits accum = 0; \
1858 int accumbits = 0; /* # of bits in accum */ \
1859 Py_ssize_t i; \
1860 for (i = 0; i < size_a; ++i) { \
1861 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1862 accumbits += PyLong_SHIFT; \
1863 assert(accumbits >= bits); \
1864 do { \
1865 char cdigit; \
1866 cdigit = (char)(accum & (base - 1)); \
1867 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1868 *--p = cdigit; \
1869 accumbits -= bits; \
1870 accum >>= bits; \
1871 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1872 } \
1873 } \
1874 \
1875 if (alternate) { \
1876 if (base == 16) \
1877 *--p = 'x'; \
1878 else if (base == 8) \
1879 *--p = 'o'; \
1880 else /* (base == 2) */ \
1881 *--p = 'b'; \
1882 *--p = '0'; \
1883 } \
1884 if (negative) \
1885 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001886 } while (0)
1887
1888#define WRITE_UNICODE_DIGITS(TYPE) \
1889 do { \
1890 if (writer) \
1891 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1892 else \
1893 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1894 \
1895 WRITE_DIGITS(p); \
1896 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001897 if (writer) \
1898 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1899 else \
1900 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1901 } while (0)
1902
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001903 if (bytes_writer) {
1904 char *p = *bytes_str + sz;
1905 WRITE_DIGITS(p);
1906 assert(p == *bytes_str);
1907 }
1908 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001909 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001910 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001911 }
1912 else if (kind == PyUnicode_2BYTE_KIND) {
1913 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001914 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001915 }
1916 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001917 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001918 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001919 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001920 }
1921#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001922#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02001923
1924 if (writer) {
1925 writer->pos += sz;
1926 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001927 else if (bytes_writer) {
1928 (*bytes_str) += sz;
1929 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001930 else {
1931 assert(_PyUnicode_CheckConsistency(v, 1));
1932 *p_output = v;
1933 }
1934 return 0;
1935}
1936
1937PyObject *
1938_PyLong_Format(PyObject *obj, int base)
1939{
1940 PyObject *str;
1941 int err;
1942 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001943 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001944 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001945 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001946 if (err == -1)
1947 return NULL;
1948 return str;
1949}
1950
1951int
1952_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1953 PyObject *obj,
1954 int base, int alternate)
1955{
1956 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001957 return long_to_decimal_string_internal(obj, NULL, writer,
1958 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001959 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001960 return long_format_binary(obj, base, alternate, NULL, writer,
1961 NULL, NULL);
1962}
1963
1964char*
1965_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
1966 PyObject *obj,
1967 int base, int alternate)
1968{
1969 char *str2;
1970 int res;
1971 str2 = str;
1972 if (base == 10)
1973 res = long_to_decimal_string_internal(obj, NULL, NULL,
1974 writer, &str2);
1975 else
1976 res = long_format_binary(obj, base, alternate, NULL, NULL,
1977 writer, &str2);
1978 if (res < 0)
1979 return NULL;
1980 assert(str2 != NULL);
1981 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001982}
1983
Thomas Wouters477c8d52006-05-27 19:21:47 +00001984/* Table of digit values for 8-bit string -> integer conversion.
1985 * '0' maps to 0, ..., '9' maps to 9.
1986 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1987 * All other indices map to 37.
1988 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001989 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001990 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001991unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1993 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1994 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1995 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1996 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1997 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1998 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1999 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2000 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2001 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2002 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2003 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2004 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2005 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2006 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2007 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002008};
2009
2010/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002011 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
Serhiy Storchaka95949422013-08-27 19:40:23 +03002012 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002013 * The point to this routine is that it takes time linear in the number of
2014 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002015 *
2016 * Return values:
2017 * -1 on syntax error (exception needs to be set, *res is untouched)
2018 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002019 */
Brett Cannona721aba2016-09-09 14:57:09 -07002020static int
2021long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002022{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002023 const char *p = *str;
2024 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002025 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002026 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 int bits_per_char;
2028 Py_ssize_t n;
2029 PyLongObject *z;
2030 twodigits accum;
2031 int bits_in_accum;
2032 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2035 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002036 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002038 }
2039 /* count digits and set p to end-of-string */
2040 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2041 if (*p == '_') {
2042 if (prev == '_') {
2043 *str = p - 1;
2044 return -1;
2045 }
2046 } else {
2047 ++digits;
2048 }
2049 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002051 }
2052 if (prev == '_') {
2053 /* Trailing underscore not allowed. */
2054 *str = p - 1;
2055 return -1;
2056 }
2057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002059 /* n <- the number of Python digits needed,
2060 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2061 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 PyErr_SetString(PyExc_ValueError,
2063 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002064 *res = NULL;
2065 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002067 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002069 if (z == NULL) {
2070 *res = NULL;
2071 return 0;
2072 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002073 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 * from least to most significant in both.
2075 */
2076 accum = 0;
2077 bits_in_accum = 0;
2078 pdigit = z->ob_digit;
2079 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002080 int k;
2081 if (*p == '_') {
2082 continue;
2083 }
2084 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 assert(k >= 0 && k < base);
2086 accum |= (twodigits)k << bits_in_accum;
2087 bits_in_accum += bits_per_char;
2088 if (bits_in_accum >= PyLong_SHIFT) {
2089 *pdigit++ = (digit)(accum & PyLong_MASK);
2090 assert(pdigit - z->ob_digit <= n);
2091 accum >>= PyLong_SHIFT;
2092 bits_in_accum -= PyLong_SHIFT;
2093 assert(bits_in_accum < PyLong_SHIFT);
2094 }
2095 }
2096 if (bits_in_accum) {
2097 assert(bits_in_accum <= PyLong_SHIFT);
2098 *pdigit++ = (digit)accum;
2099 assert(pdigit - z->ob_digit <= n);
2100 }
2101 while (pdigit - z->ob_digit < n)
2102 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002103 *res = long_normalize(z);
2104 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002105}
2106
Serhiy Storchaka95949422013-08-27 19:40:23 +03002107/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002108 * ignored.
2109 *
2110 * If successful, a PyLong object will be returned and 'pend' will be pointing
2111 * to the first unused byte unless it's NULL.
2112 *
2113 * If unsuccessful, NULL will be returned.
2114 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002115PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002116PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002119 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 PyLongObject *z = NULL;
2121 PyObject *strobj;
2122 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 if ((base != 0 && base < 2) || base > 36) {
2125 PyErr_SetString(PyExc_ValueError,
2126 "int() arg 2 must be >= 2 and <= 36");
2127 return NULL;
2128 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002129 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002131 }
2132 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002134 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 else if (*str == '-') {
2136 ++str;
2137 sign = -1;
2138 }
2139 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002140 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002142 }
2143 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002145 }
2146 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002148 }
2149 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002151 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 else {
2153 /* "old" (C-style) octal literal, now invalid.
2154 it might still be zero though */
2155 error_if_nonzero = 1;
2156 base = 10;
2157 }
2158 }
2159 if (str[0] == '0' &&
2160 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2161 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002162 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002164 /* One underscore allowed here. */
2165 if (*str == '_') {
2166 ++str;
2167 }
2168 }
2169 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002170 /* May not start with underscores. */
2171 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002172 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002175 if ((base & (base - 1)) == 0) {
2176 int res = long_from_binary_base(&str, base, &z);
2177 if (res < 0) {
2178 /* Syntax error. */
2179 goto onError;
2180 }
2181 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002183/***
2184Binary bases can be converted in time linear in the number of digits, because
2185Python's representation base is binary. Other bases (including decimal!) use
2186the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002187
Thomas Wouters477c8d52006-05-27 19:21:47 +00002188First some math: the largest integer that can be expressed in N base-B digits
2189is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2190case number of Python digits needed to hold it is the smallest integer n s.t.
2191
2192 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2193 BASE**n >= B**N [taking logs to base BASE]
2194 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2195
2196The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002197this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002198and the result is computed into it.
2199
2200The input string is actually treated as being in base base**i (i.e., i digits
2201are processed at a time), where two more static arrays hold:
2202
2203 convwidth_base[base] = the largest integer i such that base**i <= BASE
2204 convmultmax_base[base] = base ** convwidth_base[base]
2205
2206The first of these is the largest i such that i consecutive input digits
2207must fit in a single Python digit. The second is effectively the input
2208base we're really using.
2209
2210Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2211convmultmax_base[base], the result is "simply"
2212
2213 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2214
2215where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002216
2217Error analysis: as above, the number of Python digits `n` needed is worst-
2218case
2219
2220 n >= N * log(B)/log(BASE)
2221
2222where `N` is the number of input digits in base `B`. This is computed via
2223
2224 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2225
2226below. Two numeric concerns are how much space this can waste, and whether
2227the computed result can be too small. To be concrete, assume BASE = 2**15,
2228which is the default (and it's unlikely anyone changes that).
2229
2230Waste isn't a problem: provided the first input digit isn't 0, the difference
2231between the worst-case input with N digits and the smallest input with N
2232digits is about a factor of B, but B is small compared to BASE so at most
2233one allocated Python digit can remain unused on that count. If
2234N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2235and adding 1 returns a result 1 larger than necessary. However, that can't
2236happen: whenever B is a power of 2, long_from_binary_base() is called
2237instead, and it's impossible for B**i to be an integer power of 2**15 when
2238B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2239an exact integer when B is not a power of 2, since B**i has a prime factor
2240other than 2 in that case, but (2**15)**j's only prime factor is 2).
2241
2242The computed result can be too small if the true value of N*log(B)/log(BASE)
2243is a little bit larger than an exact integer, but due to roundoff errors (in
2244computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2245yields a numeric result a little less than that integer. Unfortunately, "how
2246close can a transcendental function get to an integer over some range?"
2247questions are generally theoretically intractable. Computer analysis via
2248continued fractions is practical: expand log(B)/log(BASE) via continued
2249fractions, giving a sequence i/j of "the best" rational approximations. Then
2250j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2251we can get very close to being in trouble, but very rarely. For example,
225276573 is a denominator in one of the continued-fraction approximations to
2253log(10)/log(2**15), and indeed:
2254
2255 >>> log(10)/log(2**15)*76573
2256 16958.000000654003
2257
2258is very close to an integer. If we were working with IEEE single-precision,
2259rounding errors could kill us. Finding worst cases in IEEE double-precision
2260requires better-than-double-precision log() functions, and Tim didn't bother.
2261Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002262new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002263This should happen extremely rarely, and in fact I don't have a test case
2264that triggers it(!). Instead the code was tested by artificially allocating
2265just 1 digit at the start, so that the copying code was exercised for every
2266digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002267***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002268 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002270 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 int i;
2272 int convwidth;
2273 twodigits convmultmax, convmult;
2274 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002275 const char *scan, *lastdigit;
2276 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 static double log_base_BASE[37] = {0.0e0,};
2279 static int convwidth_base[37] = {0,};
2280 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 if (log_base_BASE[base] == 0.0) {
2283 twodigits convmax = base;
2284 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002285
Mark Dickinson22b20182010-05-10 21:27:53 +00002286 log_base_BASE[base] = (log((double)base) /
2287 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 for (;;) {
2289 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002290 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002292 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 convmax = next;
2294 ++i;
2295 }
2296 convmultmax_base[base] = convmax;
2297 assert(i > 0);
2298 convwidth_base[base] = i;
2299 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* Find length of the string of numeric characters. */
2302 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002303 lastdigit = str;
2304
2305 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2306 if (*scan == '_') {
2307 if (prev == '_') {
2308 /* Only one underscore allowed. */
2309 str = lastdigit + 1;
2310 goto onError;
2311 }
2312 }
2313 else {
2314 ++digits;
2315 lastdigit = scan;
2316 }
2317 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002319 }
2320 if (prev == '_') {
2321 /* Trailing underscore not allowed. */
2322 /* Set error pointer to first underscore. */
2323 str = lastdigit + 1;
2324 goto onError;
2325 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002326
Serhiy Storchaka95949422013-08-27 19:40:23 +03002327 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 * integer with this base and length. Note that there's no
2329 * need to initialize z->ob_digit -- no slot is read up before
2330 * being stored into.
2331 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002332 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2333 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002334 /* The same exception as in _PyLong_New(). */
2335 PyErr_SetString(PyExc_OverflowError,
2336 "too many digits in integer");
2337 return NULL;
2338 }
2339 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 /* Uncomment next line to test exceedingly rare copy code */
2341 /* size_z = 1; */
2342 assert(size_z > 0);
2343 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002344 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002346 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002347 Py_SET_SIZE(z, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* `convwidth` consecutive input digits are treated as a single
2350 * digit in base `convmultmax`.
2351 */
2352 convwidth = convwidth_base[base];
2353 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 /* Work ;-) */
2356 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002357 if (*str == '_') {
2358 str++;
2359 continue;
2360 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 /* grab up to convwidth digits from the input string */
2362 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002363 for (i = 1; i < convwidth && str != scan; ++str) {
2364 if (*str == '_') {
2365 continue;
2366 }
2367 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002369 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 assert(c < PyLong_BASE);
2371 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 convmult = convmultmax;
2374 /* Calculate the shift only if we couldn't get
2375 * convwidth digits.
2376 */
2377 if (i != convwidth) {
2378 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002379 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002381 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 /* Multiply z by convmult, and add c. */
2385 pz = z->ob_digit;
2386 pzstop = pz + Py_SIZE(z);
2387 for (; pz < pzstop; ++pz) {
2388 c += (twodigits)*pz * convmult;
2389 *pz = (digit)(c & PyLong_MASK);
2390 c >>= PyLong_SHIFT;
2391 }
2392 /* carry off the current end? */
2393 if (c) {
2394 assert(c < PyLong_BASE);
2395 if (Py_SIZE(z) < size_z) {
2396 *pz = (digit)c;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002397 Py_SET_SIZE(z, Py_SIZE(z) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 }
2399 else {
2400 PyLongObject *tmp;
2401 /* Extremely rare. Get more space. */
2402 assert(Py_SIZE(z) == size_z);
2403 tmp = _PyLong_New(size_z + 1);
2404 if (tmp == NULL) {
2405 Py_DECREF(z);
2406 return NULL;
2407 }
2408 memcpy(tmp->ob_digit,
2409 z->ob_digit,
2410 sizeof(digit) * size_z);
2411 Py_DECREF(z);
2412 z = tmp;
2413 z->ob_digit[size_z] = (digit)c;
2414 ++size_z;
2415 }
2416 }
2417 }
2418 }
Brett Cannona721aba2016-09-09 14:57:09 -07002419 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002421 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 if (error_if_nonzero) {
2423 /* reset the base to 0, else the exception message
2424 doesn't make too much sense */
2425 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002426 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 /* there might still be other problems, therefore base
2430 remains zero here for the same reason */
2431 }
Brett Cannona721aba2016-09-09 14:57:09 -07002432 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002434 }
2435 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002436 Py_SET_SIZE(z, -(Py_SIZE(z)));
Brett Cannona721aba2016-09-09 14:57:09 -07002437 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002438 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002440 }
2441 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002443 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002445 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002446 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002447 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002448 }
2449 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002450 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002451 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002452 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002453
Mark Dickinson22b20182010-05-10 21:27:53 +00002454 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002455 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002456 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 Py_XDECREF(z);
2459 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2460 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002461 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002463 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002465 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 base, strobj);
2467 Py_DECREF(strobj);
2468 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002469}
2470
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002471/* Since PyLong_FromString doesn't have a length parameter,
2472 * check here for possible NULs in the string.
2473 *
2474 * Reports an invalid literal as a bytes object.
2475 */
2476PyObject *
2477_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2478{
2479 PyObject *result, *strobj;
2480 char *end = NULL;
2481
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002482 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002483 if (end == NULL || (result != NULL && end == s + len))
2484 return result;
2485 Py_XDECREF(result);
2486 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2487 if (strobj != NULL) {
2488 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002489 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002490 base, strobj);
2491 Py_DECREF(strobj);
2492 }
2493 return NULL;
2494}
2495
Guido van Rossum9e896b32000-04-05 20:11:21 +00002496PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002497PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002498{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002499 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500 if (unicode == NULL)
2501 return NULL;
2502 v = PyLong_FromUnicodeObject(unicode, base);
2503 Py_DECREF(unicode);
2504 return v;
2505}
2506
2507PyObject *
2508PyLong_FromUnicodeObject(PyObject *u, int base)
2509{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002510 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002511 const char *buffer;
2512 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002513 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002514
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002516 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002518 assert(PyUnicode_IS_ASCII(asciidig));
2519 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002520 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002521 assert(buffer != NULL);
2522
2523 result = PyLong_FromString(buffer, &end, base);
2524 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002525 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002526 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002528 Py_DECREF(asciidig);
2529 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002530 PyErr_Format(PyExc_ValueError,
2531 "invalid literal for int() with base %d: %.200R",
2532 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002533 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002534}
2535
Tim Peters9f688bf2000-07-07 15:53:28 +00002536/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002537static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002539static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002540
Serhiy Storchaka95949422013-08-27 19:40:23 +03002541/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002542
Guido van Rossume32e0141992-01-19 16:31:05 +00002543static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002544long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002546{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002547 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 if (size_b == 0) {
2551 PyErr_SetString(PyExc_ZeroDivisionError,
2552 "integer division or modulo by zero");
2553 return -1;
2554 }
2555 if (size_a < size_b ||
2556 (size_a == size_b &&
2557 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2558 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002559 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002560 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002561 return -1;
2562 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002563 Py_INCREF(_PyLong_Zero);
2564 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 return 0;
2566 }
2567 if (size_b == 1) {
2568 digit rem = 0;
2569 z = divrem1(a, b->ob_digit[0], &rem);
2570 if (z == NULL)
2571 return -1;
2572 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2573 if (*prem == NULL) {
2574 Py_DECREF(z);
2575 return -1;
2576 }
2577 }
2578 else {
2579 z = x_divrem(a, b, prem);
2580 if (z == NULL)
2581 return -1;
2582 }
2583 /* Set the signs.
2584 The quotient z has the sign of a*b;
2585 the remainder r has the sign of a,
2586 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002587 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2588 _PyLong_Negate(&z);
2589 if (z == NULL) {
2590 Py_CLEAR(*prem);
2591 return -1;
2592 }
2593 }
2594 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2595 _PyLong_Negate(prem);
2596 if (*prem == NULL) {
2597 Py_DECREF(z);
2598 Py_CLEAR(*prem);
2599 return -1;
2600 }
2601 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 *pdiv = maybe_small_long(z);
2603 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002604}
2605
Serhiy Storchaka95949422013-08-27 19:40:23 +03002606/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002607 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002608
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002609static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002610x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 PyLongObject *v, *w, *a;
2613 Py_ssize_t i, k, size_v, size_w;
2614 int d;
2615 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2616 twodigits vv;
2617 sdigit zhi;
2618 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2621 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2622 handle the special case when the initial estimate q for a quotient
2623 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2624 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002627 size_v = Py_ABS(Py_SIZE(v1));
2628 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2630 v = _PyLong_New(size_v+1);
2631 if (v == NULL) {
2632 *prem = NULL;
2633 return NULL;
2634 }
2635 w = _PyLong_New(size_w);
2636 if (w == NULL) {
2637 Py_DECREF(v);
2638 *prem = NULL;
2639 return NULL;
2640 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2643 shift v1 left by the same amount. Results go into w and v. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002644 d = PyLong_SHIFT - _Py_bit_length(w1->ob_digit[size_w-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2646 assert(carry == 0);
2647 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2648 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2649 v->ob_digit[size_v] = carry;
2650 size_v++;
2651 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2654 at most (and usually exactly) k = size_v - size_w digits. */
2655 k = size_v - size_w;
2656 assert(k >= 0);
2657 a = _PyLong_New(k);
2658 if (a == NULL) {
2659 Py_DECREF(w);
2660 Py_DECREF(v);
2661 *prem = NULL;
2662 return NULL;
2663 }
2664 v0 = v->ob_digit;
2665 w0 = w->ob_digit;
2666 wm1 = w0[size_w-1];
2667 wm2 = w0[size_w-2];
2668 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2669 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2670 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002673 Py_DECREF(a);
2674 Py_DECREF(w);
2675 Py_DECREF(v);
2676 *prem = NULL;
2677 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002678 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 /* estimate quotient digit q; may overestimate by 1 (rare) */
2681 vtop = vk[size_w];
2682 assert(vtop <= wm1);
2683 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2684 q = (digit)(vv / wm1);
2685 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2686 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2687 | vk[size_w-2])) {
2688 --q;
2689 r += wm1;
2690 if (r >= PyLong_BASE)
2691 break;
2692 }
2693 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2696 zhi = 0;
2697 for (i = 0; i < size_w; ++i) {
2698 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2699 -PyLong_BASE * q <= z < PyLong_BASE */
2700 z = (sdigit)vk[i] + zhi -
2701 (stwodigits)q * (stwodigits)w0[i];
2702 vk[i] = (digit)z & PyLong_MASK;
2703 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002704 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 /* add w back if q was too large (this branch taken rarely) */
2708 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2709 if ((sdigit)vtop + zhi < 0) {
2710 carry = 0;
2711 for (i = 0; i < size_w; ++i) {
2712 carry += vk[i] + w0[i];
2713 vk[i] = carry & PyLong_MASK;
2714 carry >>= PyLong_SHIFT;
2715 }
2716 --q;
2717 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 /* store quotient digit */
2720 assert(q < PyLong_BASE);
2721 *--ak = q;
2722 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 /* unshift remainder; we reuse w to store the result */
2725 carry = v_rshift(w0, v0, size_w, d);
2726 assert(carry==0);
2727 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 *prem = long_normalize(w);
2730 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002731}
2732
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002733/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2734 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2735 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2736 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2737 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2738 -1.0. */
2739
2740/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2741#if DBL_MANT_DIG == 53
2742#define EXP2_DBL_MANT_DIG 9007199254740992.0
2743#else
2744#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2745#endif
2746
2747double
2748_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2751 /* See below for why x_digits is always large enough. */
Dong-hee Nab88cd582020-05-04 22:32:42 +09002752 digit rem;
2753 digit x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT] = {0,};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 double dx;
2755 /* Correction term for round-half-to-even rounding. For a digit x,
2756 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2757 multiple of 4, rounding ties to a multiple of 8. */
2758 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002759
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002760 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 if (a_size == 0) {
2762 /* Special case for 0: significand 0.0, exponent 0. */
2763 *e = 0;
2764 return 0.0;
2765 }
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002766 a_bits = _Py_bit_length(a->ob_digit[a_size-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 /* The following is an overflow-free version of the check
2768 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2769 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2770 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2771 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002772 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2776 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 Number of digits needed for result: write // for floor division.
2779 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2788 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2791 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2792 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 in both cases.
2799 */
2800 if (a_bits <= DBL_MANT_DIG + 2) {
2801 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2802 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
Dong-hee Nab88cd582020-05-04 22:32:42 +09002803 x_size = shift_digits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2805 (int)shift_bits);
2806 x_size += a_size;
2807 x_digits[x_size++] = rem;
2808 }
2809 else {
2810 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2811 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2812 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2813 a_size - shift_digits, (int)shift_bits);
2814 x_size = a_size - shift_digits;
2815 /* For correct rounding below, we need the least significant
2816 bit of x to be 'sticky' for this shift: if any of the bits
2817 shifted out was nonzero, we set the least significant bit
2818 of x. */
2819 if (rem)
2820 x_digits[0] |= 1;
2821 else
2822 while (shift_digits > 0)
2823 if (a->ob_digit[--shift_digits]) {
2824 x_digits[0] |= 1;
2825 break;
2826 }
2827 }
Victor Stinner63941882011-09-29 00:42:28 +02002828 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 /* Round, and convert to double. */
2831 x_digits[0] += half_even_correction[x_digits[0] & 7];
2832 dx = x_digits[--x_size];
2833 while (x_size > 0)
2834 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 /* Rescale; make correction if result is 1.0. */
2837 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2838 if (dx == 1.0) {
2839 if (a_bits == PY_SSIZE_T_MAX)
2840 goto overflow;
2841 dx = 0.5;
2842 a_bits += 1;
2843 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 *e = a_bits;
2846 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002847
2848 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 /* exponent > PY_SSIZE_T_MAX */
2850 PyErr_SetString(PyExc_OverflowError,
2851 "huge integer: number of bits overflows a Py_ssize_t");
2852 *e = 0;
2853 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002854}
2855
Serhiy Storchaka95949422013-08-27 19:40:23 +03002856/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002857 using the round-half-to-even rule in the case of a tie. */
2858
2859double
2860PyLong_AsDouble(PyObject *v)
2861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 Py_ssize_t exponent;
2863 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002864
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002865 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 PyErr_BadInternalCall();
2867 return -1.0;
2868 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002869 if (!PyLong_Check(v)) {
2870 PyErr_SetString(PyExc_TypeError, "an integer is required");
2871 return -1.0;
2872 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002873 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002874 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002875 to double. This improves performance of FP/long operations
2876 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002877 */
2878 return (double)MEDIUM_VALUE((PyLongObject *)v);
2879 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2881 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2882 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002883 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 return -1.0;
2885 }
2886 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002887}
2888
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002889/* Methods */
2890
HongWeipeng42acb7b2019-09-18 23:10:15 +08002891/* if a < b, return a negative number
2892 if a == b, return 0
2893 if a > b, return a positive number */
2894
2895static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002896long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002897{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002898 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
2899 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002900 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08002901 sdigit diff = 0;
2902 while (--i >= 0) {
2903 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
2904 if (diff) {
2905 break;
2906 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08002908 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08002910 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002911}
2912
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002913static PyObject *
2914long_richcompare(PyObject *self, PyObject *other, int op)
2915{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002916 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 CHECK_BINOP(self, other);
2918 if (self == other)
2919 result = 0;
2920 else
2921 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01002922 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002923}
2924
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002925static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002926long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002927{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002928 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 Py_ssize_t i;
2930 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 i = Py_SIZE(v);
2933 switch(i) {
2934 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2935 case 0: return 0;
2936 case 1: return v->ob_digit[0];
2937 }
2938 sign = 1;
2939 x = 0;
2940 if (i < 0) {
2941 sign = -1;
2942 i = -(i);
2943 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002945 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2946 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2947 _PyHASH_MODULUS.
2948
2949 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2950 amounts to a rotation of the bits of x. To see this, write
2951
2952 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2953
2954 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2955 PyLong_SHIFT bits of x (those that are shifted out of the
2956 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2957 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2958 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2959 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2960 congruent to y modulo _PyHASH_MODULUS. So
2961
2962 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2963
2964 The right-hand side is just the result of rotating the
2965 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2966 not all _PyHASH_BITS bits of x are 1s, the same is true
2967 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2968 the reduction of x*2**PyLong_SHIFT modulo
2969 _PyHASH_MODULUS. */
2970 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2971 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002973 if (x >= _PyHASH_MODULUS)
2974 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 }
2976 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002977 if (x == (Py_uhash_t)-1)
2978 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002979 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002980}
2981
2982
Serhiy Storchaka95949422013-08-27 19:40:23 +03002983/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002984
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002985static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002986x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002987{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002988 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 PyLongObject *z;
2990 Py_ssize_t i;
2991 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 /* Ensure a is the larger of the two: */
2994 if (size_a < size_b) {
2995 { PyLongObject *temp = a; a = b; b = temp; }
2996 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002997 size_a = size_b;
2998 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 }
3000 z = _PyLong_New(size_a+1);
3001 if (z == NULL)
3002 return NULL;
3003 for (i = 0; i < size_b; ++i) {
3004 carry += a->ob_digit[i] + b->ob_digit[i];
3005 z->ob_digit[i] = carry & PyLong_MASK;
3006 carry >>= PyLong_SHIFT;
3007 }
3008 for (; i < size_a; ++i) {
3009 carry += a->ob_digit[i];
3010 z->ob_digit[i] = carry & PyLong_MASK;
3011 carry >>= PyLong_SHIFT;
3012 }
3013 z->ob_digit[i] = carry;
3014 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003015}
3016
3017/* Subtract the absolute values of two integers. */
3018
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003019static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003020x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003021{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003022 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 PyLongObject *z;
3024 Py_ssize_t i;
3025 int sign = 1;
3026 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 /* Ensure a is the larger of the two: */
3029 if (size_a < size_b) {
3030 sign = -1;
3031 { PyLongObject *temp = a; a = b; b = temp; }
3032 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003033 size_a = size_b;
3034 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 }
3036 else if (size_a == size_b) {
3037 /* Find highest digit where a and b differ: */
3038 i = size_a;
3039 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3040 ;
3041 if (i < 0)
3042 return (PyLongObject *)PyLong_FromLong(0);
3043 if (a->ob_digit[i] < b->ob_digit[i]) {
3044 sign = -1;
3045 { PyLongObject *temp = a; a = b; b = temp; }
3046 }
3047 size_a = size_b = i+1;
3048 }
3049 z = _PyLong_New(size_a);
3050 if (z == NULL)
3051 return NULL;
3052 for (i = 0; i < size_b; ++i) {
3053 /* The following assumes unsigned arithmetic
3054 works module 2**N for some N>PyLong_SHIFT. */
3055 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3056 z->ob_digit[i] = borrow & PyLong_MASK;
3057 borrow >>= PyLong_SHIFT;
3058 borrow &= 1; /* Keep only one sign bit */
3059 }
3060 for (; i < size_a; ++i) {
3061 borrow = a->ob_digit[i] - borrow;
3062 z->ob_digit[i] = borrow & PyLong_MASK;
3063 borrow >>= PyLong_SHIFT;
3064 borrow &= 1; /* Keep only one sign bit */
3065 }
3066 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003067 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003068 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02003069 }
HongWeipeng036fe852019-11-26 15:54:49 +08003070 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003071}
3072
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003073static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003074long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003079
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003080 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003081 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 }
3083 if (Py_SIZE(a) < 0) {
3084 if (Py_SIZE(b) < 0) {
3085 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003086 if (z != NULL) {
3087 /* x_add received at least one multiple-digit int,
3088 and thus z must be a multiple-digit int.
3089 That also means z is not an element of
3090 small_ints, so negating it in-place is safe. */
3091 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003092 Py_SET_SIZE(z, -(Py_SIZE(z)));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003093 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 }
3095 else
3096 z = x_sub(b, a);
3097 }
3098 else {
3099 if (Py_SIZE(b) < 0)
3100 z = x_sub(a, b);
3101 else
3102 z = x_add(a, b);
3103 }
3104 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003105}
3106
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003107static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003108long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003113
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003114 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003115 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 }
3117 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003118 if (Py_SIZE(b) < 0) {
3119 z = x_sub(b, a);
3120 }
3121 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003123 if (z != NULL) {
3124 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003125 Py_SET_SIZE(z, -(Py_SIZE(z)));
HongWeipeng036fe852019-11-26 15:54:49 +08003126 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003127 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 }
3129 else {
3130 if (Py_SIZE(b) < 0)
3131 z = x_add(a, b);
3132 else
3133 z = x_sub(a, b);
3134 }
3135 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003136}
3137
Tim Peters5af4e6c2002-08-12 02:31:19 +00003138/* Grade school multiplication, ignoring the signs.
3139 * Returns the absolute value of the product, or NULL if error.
3140 */
3141static PyLongObject *
3142x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003145 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3146 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 z = _PyLong_New(size_a + size_b);
3150 if (z == NULL)
3151 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3154 if (a == b) {
3155 /* Efficient squaring per HAC, Algorithm 14.16:
3156 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3157 * Gives slightly less than a 2x speedup when a == b,
3158 * via exploiting that each entry in the multiplication
3159 * pyramid appears twice (except for the size_a squares).
3160 */
3161 for (i = 0; i < size_a; ++i) {
3162 twodigits carry;
3163 twodigits f = a->ob_digit[i];
3164 digit *pz = z->ob_digit + (i << 1);
3165 digit *pa = a->ob_digit + i + 1;
3166 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003169 Py_DECREF(z);
3170 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003171 });
Tim Peters0973b992004-08-29 22:16:50 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 carry = *pz + f * f;
3174 *pz++ = (digit)(carry & PyLong_MASK);
3175 carry >>= PyLong_SHIFT;
3176 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 /* Now f is added in twice in each column of the
3179 * pyramid it appears. Same as adding f<<1 once.
3180 */
3181 f <<= 1;
3182 while (pa < paend) {
3183 carry += *pz + *pa++ * f;
3184 *pz++ = (digit)(carry & PyLong_MASK);
3185 carry >>= PyLong_SHIFT;
3186 assert(carry <= (PyLong_MASK << 1));
3187 }
3188 if (carry) {
3189 carry += *pz;
3190 *pz++ = (digit)(carry & PyLong_MASK);
3191 carry >>= PyLong_SHIFT;
3192 }
3193 if (carry)
3194 *pz += (digit)(carry & PyLong_MASK);
3195 assert((carry >> PyLong_SHIFT) == 0);
3196 }
3197 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003198 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 for (i = 0; i < size_a; ++i) {
3200 twodigits carry = 0;
3201 twodigits f = a->ob_digit[i];
3202 digit *pz = z->ob_digit + i;
3203 digit *pb = b->ob_digit;
3204 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003207 Py_DECREF(z);
3208 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003209 });
Tim Peters0973b992004-08-29 22:16:50 +00003210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 while (pb < pbend) {
3212 carry += *pz + *pb++ * f;
3213 *pz++ = (digit)(carry & PyLong_MASK);
3214 carry >>= PyLong_SHIFT;
3215 assert(carry <= PyLong_MASK);
3216 }
3217 if (carry)
3218 *pz += (digit)(carry & PyLong_MASK);
3219 assert((carry >> PyLong_SHIFT) == 0);
3220 }
3221 }
3222 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003223}
3224
3225/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003226 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003227 split, and sets low and high such that abs(n) == (high << size) + low,
3228 viewing the shift as being by digits. The sign bit is ignored, and
3229 the return values are >= 0.
3230 Returns 0 on success, -1 on failure.
3231*/
3232static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003233kmul_split(PyLongObject *n,
3234 Py_ssize_t size,
3235 PyLongObject **high,
3236 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 PyLongObject *hi, *lo;
3239 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003240 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003241
Victor Stinner640c35c2013-06-04 23:14:37 +02003242 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 if ((hi = _PyLong_New(size_hi)) == NULL)
3246 return -1;
3247 if ((lo = _PyLong_New(size_lo)) == NULL) {
3248 Py_DECREF(hi);
3249 return -1;
3250 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3253 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 *high = long_normalize(hi);
3256 *low = long_normalize(lo);
3257 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003258}
3259
Tim Peters60004642002-08-12 22:01:34 +00003260static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3261
Tim Peters5af4e6c2002-08-12 02:31:19 +00003262/* Karatsuba multiplication. Ignores the input signs, and returns the
3263 * absolute value of the product (or NULL if error).
3264 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3265 */
3266static PyLongObject *
3267k_mul(PyLongObject *a, PyLongObject *b)
3268{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003269 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3270 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 PyLongObject *ah = NULL;
3272 PyLongObject *al = NULL;
3273 PyLongObject *bh = NULL;
3274 PyLongObject *bl = NULL;
3275 PyLongObject *ret = NULL;
3276 PyLongObject *t1, *t2, *t3;
3277 Py_ssize_t shift; /* the number of digits we split off */
3278 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3281 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3282 * Then the original product is
3283 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3284 * By picking X to be a power of 2, "*X" is just shifting, and it's
3285 * been reduced to 3 multiplies on numbers half the size.
3286 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 /* We want to split based on the larger number; fiddle so that b
3289 * is largest.
3290 */
3291 if (asize > bsize) {
3292 t1 = a;
3293 a = b;
3294 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 i = asize;
3297 asize = bsize;
3298 bsize = i;
3299 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 /* Use gradeschool math when either number is too small. */
3302 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3303 if (asize <= i) {
3304 if (asize == 0)
3305 return (PyLongObject *)PyLong_FromLong(0);
3306 else
3307 return x_mul(a, b);
3308 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 /* If a is small compared to b, splitting on b gives a degenerate
3311 * case with ah==0, and Karatsuba may be (even much) less efficient
3312 * than "grade school" then. However, we can still win, by viewing
3313 * b as a string of "big digits", each of width a->ob_size. That
3314 * leads to a sequence of balanced calls to k_mul.
3315 */
3316 if (2 * asize <= bsize)
3317 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 /* Split a & b into hi & lo pieces. */
3320 shift = bsize >> 1;
3321 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3322 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 if (a == b) {
3325 bh = ah;
3326 bl = al;
3327 Py_INCREF(bh);
3328 Py_INCREF(bl);
3329 }
3330 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 /* The plan:
3333 * 1. Allocate result space (asize + bsize digits: that's always
3334 * enough).
3335 * 2. Compute ah*bh, and copy into result at 2*shift.
3336 * 3. Compute al*bl, and copy into result at 0. Note that this
3337 * can't overlap with #2.
3338 * 4. Subtract al*bl from the result, starting at shift. This may
3339 * underflow (borrow out of the high digit), but we don't care:
3340 * we're effectively doing unsigned arithmetic mod
3341 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3342 * borrows and carries out of the high digit can be ignored.
3343 * 5. Subtract ah*bh from the result, starting at shift.
3344 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3345 * at shift.
3346 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 /* 1. Allocate result space. */
3349 ret = _PyLong_New(asize + bsize);
3350 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003351#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 /* Fill with trash, to catch reference to uninitialized digits. */
3353 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003354#endif
Tim Peters44121a62002-08-12 06:17:58 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3357 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3358 assert(Py_SIZE(t1) >= 0);
3359 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3360 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3361 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 /* Zero-out the digits higher than the ah*bh copy. */
3364 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3365 if (i)
3366 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3367 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 /* 3. t2 <- al*bl, and copy into the low digits. */
3370 if ((t2 = k_mul(al, bl)) == NULL) {
3371 Py_DECREF(t1);
3372 goto fail;
3373 }
3374 assert(Py_SIZE(t2) >= 0);
3375 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3376 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 /* Zero out remaining digits. */
3379 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3380 if (i)
3381 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3384 * because it's fresher in cache.
3385 */
3386 i = Py_SIZE(ret) - shift; /* # digits after shift */
3387 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3388 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3391 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3394 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3395 Py_DECREF(ah);
3396 Py_DECREF(al);
3397 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 if (a == b) {
3400 t2 = t1;
3401 Py_INCREF(t2);
3402 }
3403 else if ((t2 = x_add(bh, bl)) == NULL) {
3404 Py_DECREF(t1);
3405 goto fail;
3406 }
3407 Py_DECREF(bh);
3408 Py_DECREF(bl);
3409 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 t3 = k_mul(t1, t2);
3412 Py_DECREF(t1);
3413 Py_DECREF(t2);
3414 if (t3 == NULL) goto fail;
3415 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 /* Add t3. It's not obvious why we can't run out of room here.
3418 * See the (*) comment after this function.
3419 */
3420 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3421 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003424
Mark Dickinson22b20182010-05-10 21:27:53 +00003425 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 Py_XDECREF(ret);
3427 Py_XDECREF(ah);
3428 Py_XDECREF(al);
3429 Py_XDECREF(bh);
3430 Py_XDECREF(bl);
3431 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003432}
3433
Tim Petersd6974a52002-08-13 20:37:51 +00003434/* (*) Why adding t3 can't "run out of room" above.
3435
Tim Petersab86c2b2002-08-15 20:06:00 +00003436Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3437to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003438
Tim Petersab86c2b2002-08-15 20:06:00 +000034391. For any integer i, i = c(i/2) + f(i/2). In particular,
3440 bsize = c(bsize/2) + f(bsize/2).
34412. shift = f(bsize/2)
34423. asize <= bsize
34434. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3444 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003445
Tim Petersab86c2b2002-08-15 20:06:00 +00003446We allocated asize + bsize result digits, and add t3 into them at an offset
3447of shift. This leaves asize+bsize-shift allocated digit positions for t3
3448to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3449asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003450
Tim Petersab86c2b2002-08-15 20:06:00 +00003451bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3452at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003453
Tim Petersab86c2b2002-08-15 20:06:00 +00003454If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3455digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3456most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003457
Tim Petersab86c2b2002-08-15 20:06:00 +00003458The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003459
Tim Petersab86c2b2002-08-15 20:06:00 +00003460 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003461
Tim Petersab86c2b2002-08-15 20:06:00 +00003462and we have asize + c(bsize/2) available digit positions. We need to show
3463this is always enough. An instance of c(bsize/2) cancels out in both, so
3464the question reduces to whether asize digits is enough to hold
3465(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3466then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3467asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003468digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003469asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003470c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3471is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3472bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003473
Tim Peters48d52c02002-08-14 17:07:32 +00003474Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3475clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3476ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003477*/
3478
Tim Peters60004642002-08-12 22:01:34 +00003479/* b has at least twice the digits of a, and a is big enough that Karatsuba
3480 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3481 * of slices, each with a->ob_size digits, and multiply the slices by a,
3482 * one at a time. This gives k_mul balanced inputs to work with, and is
3483 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003484 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003485 * single-width slice overlap between successive partial sums).
3486 */
3487static PyLongObject *
3488k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3489{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003490 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3491 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 Py_ssize_t nbdone; /* # of b digits already multiplied */
3493 PyLongObject *ret;
3494 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 assert(asize > KARATSUBA_CUTOFF);
3497 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 /* Allocate result space, and zero it out. */
3500 ret = _PyLong_New(asize + bsize);
3501 if (ret == NULL)
3502 return NULL;
3503 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 /* Successive slices of b are copied into bslice. */
3506 bslice = _PyLong_New(asize);
3507 if (bslice == NULL)
3508 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 nbdone = 0;
3511 while (bsize > 0) {
3512 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003513 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 /* Multiply the next slice of b by a. */
3516 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3517 nbtouse * sizeof(digit));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003518 Py_SET_SIZE(bslice, nbtouse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 product = k_mul(a, bslice);
3520 if (product == NULL)
3521 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 /* Add into result. */
3524 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3525 product->ob_digit, Py_SIZE(product));
3526 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 bsize -= nbtouse;
3529 nbdone += nbtouse;
3530 }
Tim Peters60004642002-08-12 22:01:34 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 Py_DECREF(bslice);
3533 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003534
Mark Dickinson22b20182010-05-10 21:27:53 +00003535 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 Py_DECREF(ret);
3537 Py_XDECREF(bslice);
3538 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003539}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003540
3541static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003542long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003549 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003551 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 z = k_mul(a, b);
3555 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003556 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3557 _PyLong_Negate(&z);
3558 if (z == NULL)
3559 return NULL;
3560 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003562}
3563
Yury Selivanove0b23092016-02-11 10:26:27 -05003564/* Fast modulo division for single-digit longs. */
3565static PyObject *
3566fast_mod(PyLongObject *a, PyLongObject *b)
3567{
3568 sdigit left = a->ob_digit[0];
3569 sdigit right = b->ob_digit[0];
3570 sdigit mod;
3571
3572 assert(Py_ABS(Py_SIZE(a)) == 1);
3573 assert(Py_ABS(Py_SIZE(b)) == 1);
3574
3575 if (Py_SIZE(a) == Py_SIZE(b)) {
3576 /* 'a' and 'b' have the same sign. */
3577 mod = left % right;
3578 }
3579 else {
3580 /* Either 'a' or 'b' is negative. */
3581 mod = right - 1 - (left - 1) % right;
3582 }
3583
Victor Stinnerf963c132016-03-23 18:36:54 +01003584 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003585}
3586
3587/* Fast floor division for single-digit longs. */
3588static PyObject *
3589fast_floor_div(PyLongObject *a, PyLongObject *b)
3590{
3591 sdigit left = a->ob_digit[0];
3592 sdigit right = b->ob_digit[0];
3593 sdigit div;
3594
3595 assert(Py_ABS(Py_SIZE(a)) == 1);
3596 assert(Py_ABS(Py_SIZE(b)) == 1);
3597
3598 if (Py_SIZE(a) == Py_SIZE(b)) {
3599 /* 'a' and 'b' have the same sign. */
3600 div = left / right;
3601 }
3602 else {
3603 /* Either 'a' or 'b' is negative. */
3604 div = -1 - (left - 1) / right;
3605 }
3606
3607 return PyLong_FromLong(div);
3608}
3609
Guido van Rossume32e0141992-01-19 16:31:05 +00003610/* The / and % operators are now defined in terms of divmod().
3611 The expression a mod b has the value a - b*floor(a/b).
3612 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003613 |a| by |b|, with the sign of a. This is also expressed
3614 as a - b*trunc(a/b), if trunc truncates towards zero.
3615 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 a b a rem b a mod b
3617 13 10 3 3
3618 -13 10 -3 7
3619 13 -10 3 -7
3620 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003621 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003622 have different signs. We then subtract one from the 'div'
3623 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003624
Tim Peters47e52ee2004-08-30 02:44:38 +00003625/* Compute
3626 * *pdiv, *pmod = divmod(v, w)
3627 * NULL can be passed for pdiv or pmod, in which case that part of
3628 * the result is simply thrown away. The caller owns a reference to
3629 * each of these it requests (does not pass NULL for).
3630 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003631static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003632l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003636
Yury Selivanove0b23092016-02-11 10:26:27 -05003637 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3638 /* Fast path for single-digit longs */
3639 div = NULL;
3640 if (pdiv != NULL) {
3641 div = (PyLongObject *)fast_floor_div(v, w);
3642 if (div == NULL) {
3643 return -1;
3644 }
3645 }
3646 if (pmod != NULL) {
3647 mod = (PyLongObject *)fast_mod(v, w);
3648 if (mod == NULL) {
3649 Py_XDECREF(div);
3650 return -1;
3651 }
3652 *pmod = mod;
3653 }
3654 if (pdiv != NULL) {
3655 /* We only want to set `*pdiv` when `*pmod` is
3656 set successfully. */
3657 *pdiv = div;
3658 }
3659 return 0;
3660 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 if (long_divrem(v, w, &div, &mod) < 0)
3662 return -1;
3663 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3664 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3665 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 temp = (PyLongObject *) long_add(mod, w);
3667 Py_DECREF(mod);
3668 mod = temp;
3669 if (mod == NULL) {
3670 Py_DECREF(div);
3671 return -1;
3672 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003673 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3674 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 Py_DECREF(mod);
3676 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 return -1;
3678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 Py_DECREF(div);
3680 div = temp;
3681 }
3682 if (pdiv != NULL)
3683 *pdiv = div;
3684 else
3685 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 if (pmod != NULL)
3688 *pmod = mod;
3689 else
3690 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003693}
3694
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003695static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003696long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003701
3702 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3703 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3704 }
3705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3707 div = NULL;
3708 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003709}
3710
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003711/* PyLong/PyLong -> float, with correctly rounded result. */
3712
3713#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3714#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3715
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003716static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003717long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 PyLongObject *a, *b, *x;
3720 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3721 digit mask, low;
3722 int inexact, negate, a_is_small, b_is_small;
3723 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 CHECK_BINOP(v, w);
3726 a = (PyLongObject *)v;
3727 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 /*
3730 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3733 1. choose a suitable integer 'shift'
3734 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3735 3. adjust x for correct rounding
3736 4. convert x to a double dx with the same value
3737 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3742 returns either 0.0 or -0.0, depending on the sign of b. For a and
3743 b both nonzero, ignore signs of a and b, and add the sign back in
3744 at the end. Now write a_bits and b_bits for the bit lengths of a
3745 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3746 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3751 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3752 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3753 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 1. The integer 'shift' is chosen so that x has the right number of
3758 bits for a double, plus two or three extra bits that will be used
3759 in the rounding decisions. Writing a_bits and b_bits for the
3760 number of significant bits in a and b respectively, a
3761 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 This is fine in the usual case, but if a/b is smaller than the
3766 smallest normal float then it can lead to double rounding on an
3767 IEEE 754 platform, giving incorrectly rounded results. So we
3768 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 2. The quantity x is computed by first shifting a (left -shift bits
3773 if shift <= 0, right shift bits if shift > 0) and then dividing by
3774 b. For both the shift and the division, we keep track of whether
3775 the result is inexact, in a flag 'inexact'; this information is
3776 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 With the choice of shift above, together with our assumption that
3779 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3780 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3783 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 For float representability, we need x/2**extra_bits <
3788 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3789 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 To round, we just modify the bottom digit of x in-place; this can
3794 end up giving a digit with value > PyLONG_MASK, but that's not a
3795 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 With the original choices for shift above, extra_bits will always
3798 be 2 or 3. Then rounding under the round-half-to-even rule, we
3799 round up iff the most significant of the extra bits is 1, and
3800 either: (a) the computation of x in step 2 had an inexact result,
3801 or (b) at least one other of the extra bits is 1, or (c) the least
3802 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 4. Conversion to a double is straightforward; all floating-point
3805 operations involved in the conversion are exact, so there's no
3806 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3809 The result will always be exactly representable as a double, except
3810 in the case that it overflows. To avoid dependence on the exact
3811 behaviour of ldexp on overflow, we check for overflow before
3812 applying ldexp. The result of ldexp is adjusted for sign before
3813 returning.
3814 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003817 a_size = Py_ABS(Py_SIZE(a));
3818 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3820 if (b_size == 0) {
3821 PyErr_SetString(PyExc_ZeroDivisionError,
3822 "division by zero");
3823 goto error;
3824 }
3825 if (a_size == 0)
3826 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 /* Fast path for a and b small (exactly representable in a double).
3829 Relies on floating-point division being correctly rounded; results
3830 may be subject to double rounding on x86 machines that operate with
3831 the x87 FPU set to 64-bit precision. */
3832 a_is_small = a_size <= MANT_DIG_DIGITS ||
3833 (a_size == MANT_DIG_DIGITS+1 &&
3834 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3835 b_is_small = b_size <= MANT_DIG_DIGITS ||
3836 (b_size == MANT_DIG_DIGITS+1 &&
3837 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3838 if (a_is_small && b_is_small) {
3839 double da, db;
3840 da = a->ob_digit[--a_size];
3841 while (a_size > 0)
3842 da = da * PyLong_BASE + a->ob_digit[--a_size];
3843 db = b->ob_digit[--b_size];
3844 while (b_size > 0)
3845 db = db * PyLong_BASE + b->ob_digit[--b_size];
3846 result = da / db;
3847 goto success;
3848 }
Tim Peterse2a60002001-09-04 06:17:36 +00003849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 /* Catch obvious cases of underflow and overflow */
3851 diff = a_size - b_size;
3852 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3853 /* Extreme overflow */
3854 goto overflow;
3855 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3856 /* Extreme underflow */
3857 goto underflow_or_zero;
3858 /* Next line is now safe from overflowing a Py_ssize_t */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01003859 diff = diff * PyLong_SHIFT + _Py_bit_length(a->ob_digit[a_size - 1]) -
3860 _Py_bit_length(b->ob_digit[b_size - 1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 /* Now diff = a_bits - b_bits. */
3862 if (diff > DBL_MAX_EXP)
3863 goto overflow;
3864 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3865 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003868 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 /* x = abs(a * 2**-shift) */
3873 if (shift <= 0) {
3874 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3875 digit rem;
3876 /* x = a << -shift */
3877 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3878 /* In practice, it's probably impossible to end up
3879 here. Both a and b would have to be enormous,
3880 using close to SIZE_T_MAX bytes of memory each. */
3881 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003882 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 goto error;
3884 }
3885 x = _PyLong_New(a_size + shift_digits + 1);
3886 if (x == NULL)
3887 goto error;
3888 for (i = 0; i < shift_digits; i++)
3889 x->ob_digit[i] = 0;
3890 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3891 a_size, -shift % PyLong_SHIFT);
3892 x->ob_digit[a_size + shift_digits] = rem;
3893 }
3894 else {
3895 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3896 digit rem;
3897 /* x = a >> shift */
3898 assert(a_size >= shift_digits);
3899 x = _PyLong_New(a_size - shift_digits);
3900 if (x == NULL)
3901 goto error;
3902 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3903 a_size - shift_digits, shift % PyLong_SHIFT);
3904 /* set inexact if any of the bits shifted out is nonzero */
3905 if (rem)
3906 inexact = 1;
3907 while (!inexact && shift_digits > 0)
3908 if (a->ob_digit[--shift_digits])
3909 inexact = 1;
3910 }
3911 long_normalize(x);
3912 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3915 reference to x, so it's safe to modify it in-place. */
3916 if (b_size == 1) {
3917 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3918 b->ob_digit[0]);
3919 long_normalize(x);
3920 if (rem)
3921 inexact = 1;
3922 }
3923 else {
3924 PyLongObject *div, *rem;
3925 div = x_divrem(x, b, &rem);
3926 Py_DECREF(x);
3927 x = div;
3928 if (x == NULL)
3929 goto error;
3930 if (Py_SIZE(rem))
3931 inexact = 1;
3932 Py_DECREF(rem);
3933 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003934 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 assert(x_size > 0); /* result of division is never zero */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01003936 x_bits = (x_size-1)*PyLong_SHIFT+_Py_bit_length(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003939 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 /* Round by directly modifying the low digit of x. */
3943 mask = (digit)1 << (extra_bits - 1);
3944 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003945 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003947 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 /* Convert x to a double dx; the conversion is exact. */
3950 dx = x->ob_digit[--x_size];
3951 while (x_size > 0)
3952 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3953 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 /* Check whether ldexp result will overflow a double. */
3956 if (shift + x_bits >= DBL_MAX_EXP &&
3957 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3958 goto overflow;
3959 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003960
3961 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003963
3964 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003966
3967 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 PyErr_SetString(PyExc_OverflowError,
3969 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003970 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003972}
3973
3974static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003975long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 CHECK_BINOP(a, b);
3980
Yury Selivanove0b23092016-02-11 10:26:27 -05003981 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3982 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
3983 }
3984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3986 mod = NULL;
3987 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003988}
3989
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003990static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003991long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 PyLongObject *div, *mod;
3994 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3999 return NULL;
4000 }
4001 z = PyTuple_New(2);
4002 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004003 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4004 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 }
4006 else {
4007 Py_DECREF(div);
4008 Py_DECREF(mod);
4009 }
4010 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004011}
4012
Mark Dickinsonc5299672019-06-02 10:24:06 +01004013
4014/* Compute an inverse to a modulo n, or raise ValueError if a is not
4015 invertible modulo n. Assumes n is positive. The inverse returned
4016 is whatever falls out of the extended Euclidean algorithm: it may
4017 be either positive or negative, but will be smaller than n in
4018 absolute value.
4019
4020 Pure Python equivalent for long_invmod:
4021
4022 def invmod(a, n):
4023 b, c = 1, 0
4024 while n:
4025 q, r = divmod(a, n)
4026 a, b, c, n = n, c, b - q*c, r
4027
4028 # at this point a is the gcd of the original inputs
4029 if a == 1:
4030 return b
4031 raise ValueError("Not invertible")
4032*/
4033
4034static PyLongObject *
4035long_invmod(PyLongObject *a, PyLongObject *n)
4036{
4037 PyLongObject *b, *c;
4038
4039 /* Should only ever be called for positive n */
4040 assert(Py_SIZE(n) > 0);
4041
4042 b = (PyLongObject *)PyLong_FromLong(1L);
4043 if (b == NULL) {
4044 return NULL;
4045 }
4046 c = (PyLongObject *)PyLong_FromLong(0L);
4047 if (c == NULL) {
4048 Py_DECREF(b);
4049 return NULL;
4050 }
4051 Py_INCREF(a);
4052 Py_INCREF(n);
4053
4054 /* references now owned: a, b, c, n */
4055 while (Py_SIZE(n) != 0) {
4056 PyLongObject *q, *r, *s, *t;
4057
4058 if (l_divmod(a, n, &q, &r) == -1) {
4059 goto Error;
4060 }
4061 Py_DECREF(a);
4062 a = n;
4063 n = r;
4064 t = (PyLongObject *)long_mul(q, c);
4065 Py_DECREF(q);
4066 if (t == NULL) {
4067 goto Error;
4068 }
4069 s = (PyLongObject *)long_sub(b, t);
4070 Py_DECREF(t);
4071 if (s == NULL) {
4072 goto Error;
4073 }
4074 Py_DECREF(b);
4075 b = c;
4076 c = s;
4077 }
4078 /* references now owned: a, b, c, n */
4079
4080 Py_DECREF(c);
4081 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004082 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004083 /* a != 1; we don't have an inverse. */
4084 Py_DECREF(a);
4085 Py_DECREF(b);
4086 PyErr_SetString(PyExc_ValueError,
4087 "base is not invertible for the given modulus");
4088 return NULL;
4089 }
4090 else {
4091 /* a == 1; b gives an inverse modulo n */
4092 Py_DECREF(a);
4093 return b;
4094 }
4095
4096 Error:
4097 Py_DECREF(a);
4098 Py_DECREF(b);
4099 Py_DECREF(c);
4100 Py_DECREF(n);
4101 return NULL;
4102}
4103
4104
Tim Peters47e52ee2004-08-30 02:44:38 +00004105/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004106static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004107long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4110 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 PyLongObject *z = NULL; /* accumulated result */
4113 Py_ssize_t i, j, k; /* counters */
4114 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 /* 5-ary values. If the exponent is large enough, table is
4117 * precomputed so that table[i] == a**i % c for i in range(32).
4118 */
4119 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4120 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 /* a, b, c = v, w, x */
4123 CHECK_BINOP(v, w);
4124 a = (PyLongObject*)v; Py_INCREF(a);
4125 b = (PyLongObject*)w; Py_INCREF(b);
4126 if (PyLong_Check(x)) {
4127 c = (PyLongObject *)x;
4128 Py_INCREF(x);
4129 }
4130 else if (x == Py_None)
4131 c = NULL;
4132 else {
4133 Py_DECREF(a);
4134 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004135 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 }
Tim Peters4c483c42001-09-05 06:24:58 +00004137
Mark Dickinsonc5299672019-06-02 10:24:06 +01004138 if (Py_SIZE(b) < 0 && c == NULL) {
4139 /* if exponent is negative and there's no modulus:
4140 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 that this calls float_pow() which converts its
4142 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004143 Py_DECREF(a);
4144 Py_DECREF(b);
4145 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 if (c) {
4149 /* if modulus == 0:
4150 raise ValueError() */
4151 if (Py_SIZE(c) == 0) {
4152 PyErr_SetString(PyExc_ValueError,
4153 "pow() 3rd argument cannot be 0");
4154 goto Error;
4155 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 /* if modulus < 0:
4158 negativeOutput = True
4159 modulus = -modulus */
4160 if (Py_SIZE(c) < 0) {
4161 negativeOutput = 1;
4162 temp = (PyLongObject *)_PyLong_Copy(c);
4163 if (temp == NULL)
4164 goto Error;
4165 Py_DECREF(c);
4166 c = temp;
4167 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004168 _PyLong_Negate(&c);
4169 if (c == NULL)
4170 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004171 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 /* if modulus == 1:
4174 return 0 */
4175 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4176 z = (PyLongObject *)PyLong_FromLong(0L);
4177 goto Done;
4178 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004179
Mark Dickinsonc5299672019-06-02 10:24:06 +01004180 /* if exponent is negative, negate the exponent and
4181 replace the base with a modular inverse */
4182 if (Py_SIZE(b) < 0) {
4183 temp = (PyLongObject *)_PyLong_Copy(b);
4184 if (temp == NULL)
4185 goto Error;
4186 Py_DECREF(b);
4187 b = temp;
4188 temp = NULL;
4189 _PyLong_Negate(&b);
4190 if (b == NULL)
4191 goto Error;
4192
4193 temp = long_invmod(a, c);
4194 if (temp == NULL)
4195 goto Error;
4196 Py_DECREF(a);
4197 a = temp;
4198 }
4199
Tim Peters81a93152013-10-05 16:53:52 -05004200 /* Reduce base by modulus in some cases:
4201 1. If base < 0. Forcing the base non-negative makes things easier.
4202 2. If base is obviously larger than the modulus. The "small
4203 exponent" case later can multiply directly by base repeatedly,
4204 while the "large exponent" case multiplies directly by base 31
4205 times. It can be unboundedly faster to multiply by
4206 base % modulus instead.
4207 We could _always_ do this reduction, but l_divmod() isn't cheap,
4208 so we only do it when it buys something. */
4209 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 if (l_divmod(a, c, NULL, &temp) < 0)
4211 goto Error;
4212 Py_DECREF(a);
4213 a = temp;
4214 temp = NULL;
4215 }
4216 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 /* At this point a, b, and c are guaranteed non-negative UNLESS
4219 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 z = (PyLongObject *)PyLong_FromLong(1L);
4222 if (z == NULL)
4223 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 /* Perform a modular reduction, X = X % c, but leave X alone if c
4226 * is NULL.
4227 */
4228#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004229 do { \
4230 if (c != NULL) { \
4231 if (l_divmod(X, c, NULL, &temp) < 0) \
4232 goto Error; \
4233 Py_XDECREF(X); \
4234 X = temp; \
4235 temp = NULL; \
4236 } \
4237 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 /* Multiply two values, then reduce the result:
4240 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004241#define MULT(X, Y, result) \
4242 do { \
4243 temp = (PyLongObject *)long_mul(X, Y); \
4244 if (temp == NULL) \
4245 goto Error; \
4246 Py_XDECREF(result); \
4247 result = temp; \
4248 temp = NULL; \
4249 REDUCE(result); \
4250 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4253 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4254 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4255 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4256 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004259 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004261 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 }
4263 }
4264 }
4265 else {
4266 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4267 Py_INCREF(z); /* still holds 1L */
4268 table[0] = z;
4269 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004270 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4273 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4276 const int index = (bi >> j) & 0x1f;
4277 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004278 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004279 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004280 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 }
4282 }
4283 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 if (negativeOutput && (Py_SIZE(z) != 0)) {
4286 temp = (PyLongObject *)long_sub(z, c);
4287 if (temp == NULL)
4288 goto Error;
4289 Py_DECREF(z);
4290 z = temp;
4291 temp = NULL;
4292 }
4293 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004294
Mark Dickinson22b20182010-05-10 21:27:53 +00004295 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004296 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004298 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4300 for (i = 0; i < 32; ++i)
4301 Py_XDECREF(table[i]);
4302 }
4303 Py_DECREF(a);
4304 Py_DECREF(b);
4305 Py_XDECREF(c);
4306 Py_XDECREF(temp);
4307 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004308}
4309
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004310static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004311long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 /* Implement ~x as -(x+1) */
4314 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004315 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004317 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318 if (x == NULL)
4319 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004320 _PyLong_Negate(&x);
4321 /* No need for maybe_small_long here, since any small
4322 longs will have been caught in the Py_SIZE <= 1 fast path. */
4323 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004324}
4325
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004326static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004327long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004330 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 return PyLong_FromLong(-MEDIUM_VALUE(v));
4332 z = (PyLongObject *)_PyLong_Copy(v);
4333 if (z != NULL)
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004334 Py_SET_SIZE(z, -(Py_SIZE(v)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004336}
4337
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004338static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004339long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 if (Py_SIZE(v) < 0)
4342 return long_neg(v);
4343 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004344 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004345}
4346
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004347static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004348long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004351}
4352
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004353/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4354static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004355divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004356{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004357 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004358 assert(Py_SIZE(shiftby) >= 0);
4359 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4360 if (lshiftby >= 0) {
4361 *wordshift = lshiftby / PyLong_SHIFT;
4362 *remshift = lshiftby % PyLong_SHIFT;
4363 return 0;
4364 }
4365 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4366 be that PyLong_AsSsize_t raised an OverflowError. */
4367 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4368 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004369 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004370 if (wordshift_obj == NULL) {
4371 return -1;
4372 }
4373 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4374 Py_DECREF(wordshift_obj);
4375 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4376 return 0;
4377 }
4378 PyErr_Clear();
4379 /* Clip the value. With such large wordshift the right shift
4380 returns 0 and the left shift raises an error in _PyLong_New(). */
4381 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4382 *remshift = 0;
4383 return 0;
4384}
4385
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004386static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004387long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004390 Py_ssize_t newsize, hishift, i, j;
4391 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393 if (Py_SIZE(a) < 0) {
4394 /* Right shifting negative numbers is harder */
4395 PyLongObject *a1, *a2;
4396 a1 = (PyLongObject *) long_invert(a);
4397 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004398 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004399 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 Py_DECREF(a1);
4401 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004402 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 z = (PyLongObject *) long_invert(a2);
4404 Py_DECREF(a2);
4405 }
4406 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004407 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 if (newsize <= 0)
4409 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004410 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 lomask = ((digit)1 << hishift) - 1;
4412 himask = PyLong_MASK ^ lomask;
4413 z = _PyLong_New(newsize);
4414 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004415 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004417 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004419 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004421 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004423 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004424}
4425
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004426static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004427long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004428{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004429 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004430 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004433
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004434 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004436 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004438 if (Py_SIZE(a) == 0) {
4439 return PyLong_FromLong(0);
4440 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004441 if (divmod_shift(b, &wordshift, &remshift) < 0)
4442 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004443 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4444}
4445
4446/* Return a >> shiftby. */
4447PyObject *
4448_PyLong_Rshift(PyObject *a, size_t shiftby)
4449{
4450 Py_ssize_t wordshift;
4451 digit remshift;
4452
4453 assert(PyLong_Check(a));
4454 if (Py_SIZE(a) == 0) {
4455 return PyLong_FromLong(0);
4456 }
4457 wordshift = shiftby / PyLong_SHIFT;
4458 remshift = shiftby % PyLong_SHIFT;
4459 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4460}
4461
4462static PyObject *
4463long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4464{
4465 /* This version due to Tim Peters */
4466 PyLongObject *z = NULL;
4467 Py_ssize_t oldsize, newsize, i, j;
4468 twodigits accum;
4469
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004470 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 newsize = oldsize + wordshift;
4472 if (remshift)
4473 ++newsize;
4474 z = _PyLong_New(newsize);
4475 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004476 return NULL;
4477 if (Py_SIZE(a) < 0) {
4478 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004479 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02004480 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 for (i = 0; i < wordshift; i++)
4482 z->ob_digit[i] = 0;
4483 accum = 0;
4484 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4485 accum |= (twodigits)a->ob_digit[j] << remshift;
4486 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4487 accum >>= PyLong_SHIFT;
4488 }
4489 if (remshift)
4490 z->ob_digit[newsize-1] = (digit)accum;
4491 else
4492 assert(!accum);
4493 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004495}
4496
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004497static PyObject *
4498long_lshift(PyObject *a, PyObject *b)
4499{
4500 Py_ssize_t wordshift;
4501 digit remshift;
4502
4503 CHECK_BINOP(a, b);
4504
4505 if (Py_SIZE(b) < 0) {
4506 PyErr_SetString(PyExc_ValueError, "negative shift count");
4507 return NULL;
4508 }
4509 if (Py_SIZE(a) == 0) {
4510 return PyLong_FromLong(0);
4511 }
4512 if (divmod_shift(b, &wordshift, &remshift) < 0)
4513 return NULL;
4514 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4515}
4516
4517/* Return a << shiftby. */
4518PyObject *
4519_PyLong_Lshift(PyObject *a, size_t shiftby)
4520{
4521 Py_ssize_t wordshift;
4522 digit remshift;
4523
4524 assert(PyLong_Check(a));
4525 if (Py_SIZE(a) == 0) {
4526 return PyLong_FromLong(0);
4527 }
4528 wordshift = shiftby / PyLong_SHIFT;
4529 remshift = shiftby % PyLong_SHIFT;
4530 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4531}
4532
Mark Dickinson27a87a22009-10-25 20:43:34 +00004533/* Compute two's complement of digit vector a[0:m], writing result to
4534 z[0:m]. The digit vector a need not be normalized, but should not
4535 be entirely zero. a and z may point to the same digit vector. */
4536
4537static void
4538v_complement(digit *z, digit *a, Py_ssize_t m)
4539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 Py_ssize_t i;
4541 digit carry = 1;
4542 for (i = 0; i < m; ++i) {
4543 carry += a[i] ^ PyLong_MASK;
4544 z[i] = carry & PyLong_MASK;
4545 carry >>= PyLong_SHIFT;
4546 }
4547 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004548}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004549
4550/* Bitwise and/xor/or operations */
4551
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004552static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004553long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004554 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004555 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 int nega, negb, negz;
4558 Py_ssize_t size_a, size_b, size_z, i;
4559 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 /* Bitwise operations for negative numbers operate as though
4562 on a two's complement representation. So convert arguments
4563 from sign-magnitude to two's complement, and convert the
4564 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004567 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004568 nega = Py_SIZE(a) < 0;
4569 if (nega) {
4570 z = _PyLong_New(size_a);
4571 if (z == NULL)
4572 return NULL;
4573 v_complement(z->ob_digit, a->ob_digit, size_a);
4574 a = z;
4575 }
4576 else
4577 /* Keep reference count consistent. */
4578 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004580 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004581 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 negb = Py_SIZE(b) < 0;
4583 if (negb) {
4584 z = _PyLong_New(size_b);
4585 if (z == NULL) {
4586 Py_DECREF(a);
4587 return NULL;
4588 }
4589 v_complement(z->ob_digit, b->ob_digit, size_b);
4590 b = z;
4591 }
4592 else
4593 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004595 /* Swap a and b if necessary to ensure size_a >= size_b. */
4596 if (size_a < size_b) {
4597 z = a; a = b; b = z;
4598 size_z = size_a; size_a = size_b; size_b = size_z;
4599 negz = nega; nega = negb; negb = negz;
4600 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004602 /* JRH: The original logic here was to allocate the result value (z)
4603 as the longer of the two operands. However, there are some cases
4604 where the result is guaranteed to be shorter than that: AND of two
4605 positives, OR of two negatives: use the shorter number. AND with
4606 mixed signs: use the positive number. OR with mixed signs: use the
4607 negative number.
4608 */
4609 switch (op) {
4610 case '^':
4611 negz = nega ^ negb;
4612 size_z = size_a;
4613 break;
4614 case '&':
4615 negz = nega & negb;
4616 size_z = negb ? size_a : size_b;
4617 break;
4618 case '|':
4619 negz = nega | negb;
4620 size_z = negb ? size_b : size_a;
4621 break;
4622 default:
stratakisa10d4262019-03-18 18:59:20 +01004623 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 /* We allow an extra digit if z is negative, to make sure that
4627 the final two's complement of z doesn't overflow. */
4628 z = _PyLong_New(size_z + negz);
4629 if (z == NULL) {
4630 Py_DECREF(a);
4631 Py_DECREF(b);
4632 return NULL;
4633 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 /* Compute digits for overlap of a and b. */
4636 switch(op) {
4637 case '&':
4638 for (i = 0; i < size_b; ++i)
4639 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4640 break;
4641 case '|':
4642 for (i = 0; i < size_b; ++i)
4643 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4644 break;
4645 case '^':
4646 for (i = 0; i < size_b; ++i)
4647 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4648 break;
4649 default:
stratakisa10d4262019-03-18 18:59:20 +01004650 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 /* Copy any remaining digits of a, inverting if necessary. */
4654 if (op == '^' && negb)
4655 for (; i < size_z; ++i)
4656 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4657 else if (i < size_z)
4658 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4659 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 /* Complement result if negative. */
4662 if (negz) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004663 Py_SET_SIZE(z, -(Py_SIZE(z)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 z->ob_digit[size_z] = PyLong_MASK;
4665 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4666 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 Py_DECREF(a);
4669 Py_DECREF(b);
4670 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004671}
4672
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004673static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004674long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 PyObject *c;
4677 CHECK_BINOP(a, b);
4678 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4679 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004680}
4681
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004682static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004683long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 PyObject *c;
4686 CHECK_BINOP(a, b);
4687 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4688 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004689}
4690
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004691static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004692long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 PyObject *c;
4695 CHECK_BINOP(a, b);
4696 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4697 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004698}
4699
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004700static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004701long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 if (PyLong_CheckExact(v))
4704 Py_INCREF(v);
4705 else
4706 v = _PyLong_Copy((PyLongObject *)v);
4707 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004708}
4709
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004710PyObject *
4711_PyLong_GCD(PyObject *aarg, PyObject *barg)
4712{
4713 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4714 stwodigits x, y, q, s, t, c_carry, d_carry;
4715 stwodigits A, B, C, D, T;
4716 int nbits, k;
4717 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4718 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4719
4720 a = (PyLongObject *)aarg;
4721 b = (PyLongObject *)barg;
4722 size_a = Py_SIZE(a);
4723 size_b = Py_SIZE(b);
4724 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4725 Py_INCREF(a);
4726 Py_INCREF(b);
4727 goto simple;
4728 }
4729
4730 /* Initial reduction: make sure that 0 <= b <= a. */
4731 a = (PyLongObject *)long_abs(a);
4732 if (a == NULL)
4733 return NULL;
4734 b = (PyLongObject *)long_abs(b);
4735 if (b == NULL) {
4736 Py_DECREF(a);
4737 return NULL;
4738 }
4739 if (long_compare(a, b) < 0) {
4740 r = a;
4741 a = b;
4742 b = r;
4743 }
4744 /* We now own references to a and b */
4745
4746 alloc_a = Py_SIZE(a);
4747 alloc_b = Py_SIZE(b);
4748 /* reduce until a fits into 2 digits */
4749 while ((size_a = Py_SIZE(a)) > 2) {
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004750 nbits = _Py_bit_length(a->ob_digit[size_a-1]);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004751 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4752 corresponding bits of b into y */
4753 size_b = Py_SIZE(b);
4754 assert(size_b <= size_a);
4755 if (size_b == 0) {
4756 if (size_a < alloc_a) {
4757 r = (PyLongObject *)_PyLong_Copy(a);
4758 Py_DECREF(a);
4759 }
4760 else
4761 r = a;
4762 Py_DECREF(b);
4763 Py_XDECREF(c);
4764 Py_XDECREF(d);
4765 return (PyObject *)r;
4766 }
4767 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4768 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4769 (a->ob_digit[size_a-3] >> nbits));
4770
4771 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4772 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4773 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4774
4775 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4776 larger than PyLong_MASK during the algorithm. */
4777 A = 1; B = 0; C = 0; D = 1;
4778 for (k=0;; k++) {
4779 if (y-C == 0)
4780 break;
4781 q = (x+(A-1))/(y-C);
4782 s = B+q*D;
4783 t = x-q*y;
4784 if (s > t)
4785 break;
4786 x = y; y = t;
4787 t = A+q*C; A = D; B = C; C = s; D = t;
4788 }
4789
4790 if (k == 0) {
4791 /* no progress; do a Euclidean step */
4792 if (l_divmod(a, b, NULL, &r) < 0)
4793 goto error;
4794 Py_DECREF(a);
4795 a = b;
4796 b = r;
4797 alloc_a = alloc_b;
4798 alloc_b = Py_SIZE(b);
4799 continue;
4800 }
4801
4802 /*
4803 a, b = A*b-B*a, D*a-C*b if k is odd
4804 a, b = A*a-B*b, D*b-C*a if k is even
4805 */
4806 if (k&1) {
4807 T = -A; A = -B; B = T;
4808 T = -C; C = -D; D = T;
4809 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004810 if (c != NULL) {
4811 Py_SET_SIZE(c, size_a);
4812 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004813 else if (Py_REFCNT(a) == 1) {
4814 Py_INCREF(a);
4815 c = a;
4816 }
4817 else {
4818 alloc_a = size_a;
4819 c = _PyLong_New(size_a);
4820 if (c == NULL)
4821 goto error;
4822 }
4823
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004824 if (d != NULL) {
4825 Py_SET_SIZE(d, size_a);
4826 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004827 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4828 Py_INCREF(b);
4829 d = b;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004830 Py_SET_SIZE(d, size_a);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004831 }
4832 else {
4833 alloc_b = size_a;
4834 d = _PyLong_New(size_a);
4835 if (d == NULL)
4836 goto error;
4837 }
4838 a_end = a->ob_digit + size_a;
4839 b_end = b->ob_digit + size_b;
4840
4841 /* compute new a and new b in parallel */
4842 a_digit = a->ob_digit;
4843 b_digit = b->ob_digit;
4844 c_digit = c->ob_digit;
4845 d_digit = d->ob_digit;
4846 c_carry = 0;
4847 d_carry = 0;
4848 while (b_digit < b_end) {
4849 c_carry += (A * *a_digit) - (B * *b_digit);
4850 d_carry += (D * *b_digit++) - (C * *a_digit++);
4851 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4852 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4853 c_carry >>= PyLong_SHIFT;
4854 d_carry >>= PyLong_SHIFT;
4855 }
4856 while (a_digit < a_end) {
4857 c_carry += A * *a_digit;
4858 d_carry -= C * *a_digit++;
4859 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4860 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4861 c_carry >>= PyLong_SHIFT;
4862 d_carry >>= PyLong_SHIFT;
4863 }
4864 assert(c_carry == 0);
4865 assert(d_carry == 0);
4866
4867 Py_INCREF(c);
4868 Py_INCREF(d);
4869 Py_DECREF(a);
4870 Py_DECREF(b);
4871 a = long_normalize(c);
4872 b = long_normalize(d);
4873 }
4874 Py_XDECREF(c);
4875 Py_XDECREF(d);
4876
4877simple:
4878 assert(Py_REFCNT(a) > 0);
4879 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004880/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4881 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4882#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004883 /* a fits into a long, so b must too */
4884 x = PyLong_AsLong((PyObject *)a);
4885 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004886#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004887 x = PyLong_AsLongLong((PyObject *)a);
4888 y = PyLong_AsLongLong((PyObject *)b);
4889#else
4890# error "_PyLong_GCD"
4891#endif
4892 x = Py_ABS(x);
4893 y = Py_ABS(y);
4894 Py_DECREF(a);
4895 Py_DECREF(b);
4896
4897 /* usual Euclidean algorithm for longs */
4898 while (y != 0) {
4899 t = y;
4900 y = x % y;
4901 x = t;
4902 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004903#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004904 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004905#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004906 return PyLong_FromLongLong(x);
4907#else
4908# error "_PyLong_GCD"
4909#endif
4910
4911error:
4912 Py_DECREF(a);
4913 Py_DECREF(b);
4914 Py_XDECREF(c);
4915 Py_XDECREF(d);
4916 return NULL;
4917}
4918
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004919static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004920long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004922 double result;
4923 result = PyLong_AsDouble(v);
4924 if (result == -1.0 && PyErr_Occurred())
4925 return NULL;
4926 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004927}
4928
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004929static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004930long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
4931
4932/*[clinic input]
4933@classmethod
4934int.__new__ as long_new
4935 x: object(c_default="NULL") = 0
4936 /
4937 base as obase: object(c_default="NULL") = 10
4938[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004939
Tim Peters6d6c1a32001-08-02 04:15:00 +00004940static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004941long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
4942/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00004943{
Gregory P. Smitha689e522012-12-25 22:38:32 -08004944 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004947 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004948 if (x == NULL) {
4949 if (obase != NULL) {
4950 PyErr_SetString(PyExc_TypeError,
4951 "int() missing string argument");
4952 return NULL;
4953 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004955 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004956 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004957 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004958
Gregory P. Smitha689e522012-12-25 22:38:32 -08004959 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004960 if (base == -1 && PyErr_Occurred())
4961 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004962 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004963 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05304964 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004965 return NULL;
4966 }
4967
4968 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004969 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004970 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004971 const char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004972 if (PyByteArray_Check(x))
4973 string = PyByteArray_AS_STRING(x);
4974 else
4975 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004976 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004977 }
4978 else {
4979 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004980 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 return NULL;
4982 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004983}
4984
Serhiy Storchaka95949422013-08-27 19:40:23 +03004985/* Wimpy, slow approach to tp_new calls for subtypes of int:
4986 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004987 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004988 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004989*/
4990static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004991long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00004992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 PyLongObject *tmp, *newobj;
4994 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004997 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 if (tmp == NULL)
4999 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005000 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 n = Py_SIZE(tmp);
5002 if (n < 0)
5003 n = -n;
5004 newobj = (PyLongObject *)type->tp_alloc(type, n);
5005 if (newobj == NULL) {
5006 Py_DECREF(tmp);
5007 return NULL;
5008 }
5009 assert(PyLong_Check(newobj));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005010 Py_SET_SIZE(newobj, Py_SIZE(tmp));
5011 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 newobj->ob_digit[i] = tmp->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005013 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 Py_DECREF(tmp);
5015 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005016}
5017
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005018/*[clinic input]
5019int.__getnewargs__
5020[clinic start generated code]*/
5021
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005022static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005023int___getnewargs___impl(PyObject *self)
5024/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005025{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005026 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005027}
5028
Guido van Rossumb43daf72007-08-01 18:08:08 +00005029static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005030long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005033}
5034
5035static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005036long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005039}
5040
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005041/*[clinic input]
5042int.__format__
5043
5044 format_spec: unicode
5045 /
5046[clinic start generated code]*/
5047
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005048static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005049int___format___impl(PyObject *self, PyObject *format_spec)
5050/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005051{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005052 _PyUnicodeWriter writer;
5053 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005054
Victor Stinner8f674cc2013-04-17 23:02:17 +02005055 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005056 ret = _PyLong_FormatAdvancedWriter(
5057 &writer,
5058 self,
5059 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5060 if (ret == -1) {
5061 _PyUnicodeWriter_Dealloc(&writer);
5062 return NULL;
5063 }
5064 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005065}
5066
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005067/* Return a pair (q, r) such that a = b * q + r, and
5068 abs(r) <= abs(b)/2, with equality possible only if q is even.
5069 In other words, q == a / b, rounded to the nearest integer using
5070 round-half-to-even. */
5071
5072PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005073_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005074{
5075 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005076 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005077 int quo_is_odd, quo_is_neg;
5078 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005079
5080 /* Equivalent Python code:
5081
5082 def divmod_near(a, b):
5083 q, r = divmod(a, b)
5084 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5085 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5086 # positive, 2 * r < b if b negative.
5087 greater_than_half = 2*r > b if b > 0 else 2*r < b
5088 exactly_half = 2*r == b
5089 if greater_than_half or exactly_half and q % 2 == 1:
5090 q += 1
5091 r -= b
5092 return q, r
5093
5094 */
5095 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5096 PyErr_SetString(PyExc_TypeError,
5097 "non-integer arguments in division");
5098 return NULL;
5099 }
5100
5101 /* Do a and b have different signs? If so, quotient is negative. */
5102 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5103
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005104 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5105 goto error;
5106
5107 /* compare twice the remainder with the divisor, to see
5108 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005109 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005110 if (twice_rem == NULL)
5111 goto error;
5112 if (quo_is_neg) {
5113 temp = long_neg((PyLongObject*)twice_rem);
5114 Py_DECREF(twice_rem);
5115 twice_rem = temp;
5116 if (twice_rem == NULL)
5117 goto error;
5118 }
5119 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5120 Py_DECREF(twice_rem);
5121
5122 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5123 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5124 /* fix up quotient */
5125 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005126 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005127 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005128 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005129 Py_DECREF(quo);
5130 quo = (PyLongObject *)temp;
5131 if (quo == NULL)
5132 goto error;
5133 /* and remainder */
5134 if (quo_is_neg)
5135 temp = long_add(rem, (PyLongObject *)b);
5136 else
5137 temp = long_sub(rem, (PyLongObject *)b);
5138 Py_DECREF(rem);
5139 rem = (PyLongObject *)temp;
5140 if (rem == NULL)
5141 goto error;
5142 }
5143
5144 result = PyTuple_New(2);
5145 if (result == NULL)
5146 goto error;
5147
5148 /* PyTuple_SET_ITEM steals references */
5149 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5150 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005151 return result;
5152
5153 error:
5154 Py_XDECREF(quo);
5155 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005156 return NULL;
5157}
5158
Eric Smith8c663262007-08-25 02:26:07 +00005159static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005160long_round(PyObject *self, PyObject *args)
5161{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005162 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005163
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005164 /* To round an integer m to the nearest 10**n (n positive), we make use of
5165 * the divmod_near operation, defined by:
5166 *
5167 * divmod_near(a, b) = (q, r)
5168 *
5169 * where q is the nearest integer to the quotient a / b (the
5170 * nearest even integer in the case of a tie) and r == a - q * b.
5171 * Hence q * b = a - r is the nearest multiple of b to a,
5172 * preferring even multiples in the case of a tie.
5173 *
5174 * So the nearest multiple of 10**n to m is:
5175 *
5176 * m - divmod_near(m, 10**n)[1].
5177 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5179 return NULL;
5180 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005181 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005182
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03005183 ndigits = _PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 if (ndigits == NULL)
5185 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005186
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005187 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005188 if (Py_SIZE(ndigits) >= 0) {
5189 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005190 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005191 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005192
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005193 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5194 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005196 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005197 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005198 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005199
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005200 result = PyLong_FromLong(10L);
5201 if (result == NULL) {
5202 Py_DECREF(ndigits);
5203 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005205
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005206 temp = long_pow(result, ndigits, Py_None);
5207 Py_DECREF(ndigits);
5208 Py_DECREF(result);
5209 result = temp;
5210 if (result == NULL)
5211 return NULL;
5212
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005213 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005214 Py_DECREF(result);
5215 result = temp;
5216 if (result == NULL)
5217 return NULL;
5218
5219 temp = long_sub((PyLongObject *)self,
5220 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5221 Py_DECREF(result);
5222 result = temp;
5223
5224 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005225}
5226
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005227/*[clinic input]
5228int.__sizeof__ -> Py_ssize_t
5229
5230Returns size in memory, in bytes.
5231[clinic start generated code]*/
5232
5233static Py_ssize_t
5234int___sizeof___impl(PyObject *self)
5235/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005237 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005238
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005239 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5240 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005241}
5242
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005243/*[clinic input]
5244int.bit_length
5245
5246Number of bits necessary to represent self in binary.
5247
5248>>> bin(37)
5249'0b100101'
5250>>> (37).bit_length()
52516
5252[clinic start generated code]*/
5253
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005254static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005255int_bit_length_impl(PyObject *self)
5256/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005259 Py_ssize_t ndigits;
5260 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005262
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005263 assert(self != NULL);
5264 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005265
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005266 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 if (ndigits == 0)
5268 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005269
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005270 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Niklas Fiekasc5b79002020-01-16 15:09:19 +01005271 msd_bits = _Py_bit_length(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5274 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 /* expression above may overflow; use Python integers instead */
5277 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5278 if (result == NULL)
5279 return NULL;
5280 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5281 if (x == NULL)
5282 goto error;
5283 y = (PyLongObject *)long_mul(result, x);
5284 Py_DECREF(x);
5285 if (y == NULL)
5286 goto error;
5287 Py_DECREF(result);
5288 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005290 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5291 if (x == NULL)
5292 goto error;
5293 y = (PyLongObject *)long_add(result, x);
5294 Py_DECREF(x);
5295 if (y == NULL)
5296 goto error;
5297 Py_DECREF(result);
5298 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005301
Mark Dickinson22b20182010-05-10 21:27:53 +00005302 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 Py_DECREF(result);
5304 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005305}
5306
Christian Heimes53876d92008-04-19 00:31:39 +00005307
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005308/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005309int.as_integer_ratio
5310
5311Return integer ratio.
5312
5313Return a pair of integers, whose ratio is exactly equal to the original int
5314and with a positive denominator.
5315
5316>>> (10).as_integer_ratio()
5317(10, 1)
5318>>> (-10).as_integer_ratio()
5319(-10, 1)
5320>>> (0).as_integer_ratio()
5321(0, 1)
5322[clinic start generated code]*/
5323
5324static PyObject *
5325int_as_integer_ratio_impl(PyObject *self)
5326/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5327{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005328 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005329 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005330 if (numerator == NULL) {
5331 return NULL;
5332 }
5333 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5334 Py_DECREF(numerator);
5335 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005336}
5337
5338/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005339int.to_bytes
5340
5341 length: Py_ssize_t
5342 Length of bytes object to use. An OverflowError is raised if the
5343 integer is not representable with the given number of bytes.
5344 byteorder: unicode
5345 The byte order used to represent the integer. If byteorder is 'big',
5346 the most significant byte is at the beginning of the byte array. If
5347 byteorder is 'little', the most significant byte is at the end of the
5348 byte array. To request the native byte order of the host system, use
5349 `sys.byteorder' as the byte order value.
5350 *
5351 signed as is_signed: bool = False
5352 Determines whether two's complement is used to represent the integer.
5353 If signed is False and a negative integer is given, an OverflowError
5354 is raised.
5355
5356Return an array of bytes representing an integer.
5357[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005358
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005359static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005360int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5361 int is_signed)
5362/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005366
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005367 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005368 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005369 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 little_endian = 0;
5371 else {
5372 PyErr_SetString(PyExc_ValueError,
5373 "byteorder must be either 'little' or 'big'");
5374 return NULL;
5375 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005377 if (length < 0) {
5378 PyErr_SetString(PyExc_ValueError,
5379 "length argument must be non-negative");
5380 return NULL;
5381 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 bytes = PyBytes_FromStringAndSize(NULL, length);
5384 if (bytes == NULL)
5385 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005386
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005387 if (_PyLong_AsByteArray((PyLongObject *)self,
5388 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 length, little_endian, is_signed) < 0) {
5390 Py_DECREF(bytes);
5391 return NULL;
5392 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005395}
5396
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005397/*[clinic input]
5398@classmethod
5399int.from_bytes
5400
5401 bytes as bytes_obj: object
5402 Holds the array of bytes to convert. The argument must either
5403 support the buffer protocol or be an iterable object producing bytes.
5404 Bytes and bytearray are examples of built-in objects that support the
5405 buffer protocol.
5406 byteorder: unicode
5407 The byte order used to represent the integer. If byteorder is 'big',
5408 the most significant byte is at the beginning of the byte array. If
5409 byteorder is 'little', the most significant byte is at the end of the
5410 byte array. To request the native byte order of the host system, use
5411 `sys.byteorder' as the byte order value.
5412 *
5413 signed as is_signed: bool = False
5414 Indicates whether two's complement is used to represent the integer.
5415
5416Return the integer represented by the given array of bytes.
5417[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005418
5419static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005420int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5421 PyObject *byteorder, int is_signed)
5422/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005424 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005425 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005426
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005427 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005429 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005430 little_endian = 0;
5431 else {
5432 PyErr_SetString(PyExc_ValueError,
5433 "byteorder must be either 'little' or 'big'");
5434 return NULL;
5435 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005436
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005437 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 if (bytes == NULL)
5439 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 long_obj = _PyLong_FromByteArray(
5442 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5443 little_endian, is_signed);
5444 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005445
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005446 if (long_obj != NULL && type != &PyLong_Type) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005447 Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005451}
5452
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005453static PyObject *
5454long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5455{
5456 return long_long(self);
5457}
5458
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005459static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005460 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005462 INT_BIT_LENGTH_METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005463 INT_TO_BYTES_METHODDEF
5464 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005465 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005466 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005468 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005470 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 "Ceiling of an Integral returns itself."},
5472 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5473 "Rounding an Integral returns itself.\n"
5474 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005475 INT___GETNEWARGS___METHODDEF
5476 INT___FORMAT___METHODDEF
5477 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005478 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005479};
5480
Guido van Rossumb43daf72007-08-01 18:08:08 +00005481static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005482 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005483 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005484 "the real part of a complex number",
5485 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005486 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005487 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005488 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005489 NULL},
5490 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005491 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005492 "the numerator of a rational number in lowest terms",
5493 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005494 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005495 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005496 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005497 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005498 {NULL} /* Sentinel */
5499};
5500
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005501PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005502"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005503int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005504\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005505Convert a number or string to an integer, or return 0 if no arguments\n\
5506are given. If x is a number, return x.__int__(). For floating point\n\
5507numbers, this truncates towards zero.\n\
5508\n\
5509If x is not a number or if base is given, then x must be a string,\n\
5510bytes, or bytearray instance representing an integer literal in the\n\
5511given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5512by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5513Base 0 means to interpret the base from the string as an integer literal.\n\
5514>>> int('0b100', base=0)\n\
55154");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005516
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005517static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005518 (binaryfunc)long_add, /*nb_add*/
5519 (binaryfunc)long_sub, /*nb_subtract*/
5520 (binaryfunc)long_mul, /*nb_multiply*/
5521 long_mod, /*nb_remainder*/
5522 long_divmod, /*nb_divmod*/
5523 long_pow, /*nb_power*/
5524 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005525 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005526 (unaryfunc)long_abs, /*tp_absolute*/
5527 (inquiry)long_bool, /*tp_bool*/
5528 (unaryfunc)long_invert, /*nb_invert*/
5529 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005530 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005531 long_and, /*nb_and*/
5532 long_xor, /*nb_xor*/
5533 long_or, /*nb_or*/
5534 long_long, /*nb_int*/
5535 0, /*nb_reserved*/
5536 long_float, /*nb_float*/
5537 0, /* nb_inplace_add */
5538 0, /* nb_inplace_subtract */
5539 0, /* nb_inplace_multiply */
5540 0, /* nb_inplace_remainder */
5541 0, /* nb_inplace_power */
5542 0, /* nb_inplace_lshift */
5543 0, /* nb_inplace_rshift */
5544 0, /* nb_inplace_and */
5545 0, /* nb_inplace_xor */
5546 0, /* nb_inplace_or */
5547 long_div, /* nb_floor_divide */
5548 long_true_divide, /* nb_true_divide */
5549 0, /* nb_inplace_floor_divide */
5550 0, /* nb_inplace_true_divide */
5551 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005552};
5553
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005554PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005555 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5556 "int", /* tp_name */
5557 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5558 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005559 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005560 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005561 0, /* tp_getattr */
5562 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005563 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 long_to_decimal_string, /* tp_repr */
5565 &long_as_number, /* tp_as_number */
5566 0, /* tp_as_sequence */
5567 0, /* tp_as_mapping */
5568 (hashfunc)long_hash, /* tp_hash */
5569 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005570 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005571 PyObject_GenericGetAttr, /* tp_getattro */
5572 0, /* tp_setattro */
5573 0, /* tp_as_buffer */
5574 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5575 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5576 long_doc, /* tp_doc */
5577 0, /* tp_traverse */
5578 0, /* tp_clear */
5579 long_richcompare, /* tp_richcompare */
5580 0, /* tp_weaklistoffset */
5581 0, /* tp_iter */
5582 0, /* tp_iternext */
5583 long_methods, /* tp_methods */
5584 0, /* tp_members */
5585 long_getset, /* tp_getset */
5586 0, /* tp_base */
5587 0, /* tp_dict */
5588 0, /* tp_descr_get */
5589 0, /* tp_descr_set */
5590 0, /* tp_dictoffset */
5591 0, /* tp_init */
5592 0, /* tp_alloc */
5593 long_new, /* tp_new */
5594 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005595};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005596
Mark Dickinsonbd792642009-03-18 20:06:12 +00005597static PyTypeObject Int_InfoType;
5598
5599PyDoc_STRVAR(int_info__doc__,
5600"sys.int_info\n\
5601\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005602A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005603internal representation of integers. The attributes are read only.");
5604
5605static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005607 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005608 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005609};
5610
5611static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005612 "sys.int_info", /* name */
5613 int_info__doc__, /* doc */
5614 int_info_fields, /* fields */
5615 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005616};
5617
5618PyObject *
5619PyLong_GetInfo(void)
5620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005621 PyObject* int_info;
5622 int field = 0;
5623 int_info = PyStructSequence_New(&Int_InfoType);
5624 if (int_info == NULL)
5625 return NULL;
5626 PyStructSequence_SET_ITEM(int_info, field++,
5627 PyLong_FromLong(PyLong_SHIFT));
5628 PyStructSequence_SET_ITEM(int_info, field++,
5629 PyLong_FromLong(sizeof(digit)));
5630 if (PyErr_Occurred()) {
5631 Py_CLEAR(int_info);
5632 return NULL;
5633 }
5634 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005635}
5636
Guido van Rossumddefaf32007-01-14 03:31:43 +00005637int
Victor Stinner630c8df2019-12-17 13:02:18 +01005638_PyLong_Init(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005639{
5640#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005641 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5642 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5643 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005644
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005645 PyLongObject *v = _PyLong_New(1);
5646 if (!v) {
5647 return -1;
5648 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005649
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005650 Py_SET_SIZE(v, size);
Victor Stinner12174a52014-08-15 23:17:38 +02005651 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005652
Victor Stinner630c8df2019-12-17 13:02:18 +01005653 tstate->interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005655#endif
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005656
Victor Stinner630c8df2019-12-17 13:02:18 +01005657 if (_Py_IsMainInterpreter(tstate)) {
5658 _PyLong_Zero = PyLong_FromLong(0);
5659 if (_PyLong_Zero == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005660 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005661 }
Victor Stinner630c8df2019-12-17 13:02:18 +01005662
5663 _PyLong_One = PyLong_FromLong(1);
5664 if (_PyLong_One == NULL) {
5665 return 0;
5666 }
5667
5668 /* initialize int_info */
5669 if (Int_InfoType.tp_name == NULL) {
5670 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5671 return 0;
5672 }
5673 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005674 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005676 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005677}
5678
5679void
Victor Stinner630c8df2019-12-17 13:02:18 +01005680_PyLong_Fini(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005681{
Victor Stinner630c8df2019-12-17 13:02:18 +01005682 if (_Py_IsMainInterpreter(tstate)) {
5683 Py_CLEAR(_PyLong_One);
5684 Py_CLEAR(_PyLong_Zero);
5685 }
5686
Guido van Rossumddefaf32007-01-14 03:31:43 +00005687#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005688 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinner630c8df2019-12-17 13:02:18 +01005689 Py_CLEAR(tstate->interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005691#endif
5692}