blob: 571f53a3c00eb57ea65844ce1727f0b90f34b64e [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 Stinnerc6b292c2020-06-08 16:30:33 +02006#include "pycore_bitutils.h" // _Py_popcount32()
7#include "pycore_interp.h" // _PY_NSMALLPOSINTS
Victor Stinner04fc4f22020-06-16 01:28:07 +02008#include "pycore_object.h" // _PyObject_InitVar()
Victor Stinnerc6b292c2020-06-08 16:30:33 +02009#include "pycore_pystate.h" // _Py_IsMainInterpreter()
Guido van Rossumedcc38a1991-05-05 20:09:44 +000010#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +000011
Mark Dickinsonc6300392009-04-20 21:38:00 +000012#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000013#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000014#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000015
Serhiy Storchaka495e8802017-02-01 23:12:20 +020016#include "clinic/longobject.c.h"
17/*[clinic input]
18class int "PyObject *" "&PyLong_Type"
19[clinic start generated code]*/
20/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
21
Victor Stinner630c8df2019-12-17 13:02:18 +010022#define NSMALLPOSINTS _PY_NSMALLPOSINTS
23#define NSMALLNEGINTS _PY_NSMALLNEGINTS
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020025_Py_IDENTIFIER(little);
26_Py_IDENTIFIER(big);
27
Mark Dickinsone4416742009-02-15 15:14:57 +000028/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020029#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
30 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 (Py_SIZE(x) == 0 ? (sdigit)0 : \
32 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000033
Serhiy Storchakaba85d692017-03-30 09:09:41 +030034PyObject *_PyLong_Zero = NULL;
35PyObject *_PyLong_One = NULL;
36
Guido van Rossumddefaf32007-01-14 03:31:43 +000037#if NSMALLNEGINTS + NSMALLPOSINTS > 0
animalize6b519982019-09-06 14:00:56 +080038#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050039#define IS_SMALL_UINT(ival) ((ival) < NSMALLPOSINTS)
Greg Price5e63ab02019-08-24 10:19:37 -070040
Guido van Rossum7eaf8222007-06-18 17:58:50 +000041static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000042get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000043{
animalize6b519982019-09-06 14:00:56 +080044 assert(IS_SMALL_INT(ival));
Victor Stinner1bcc32f2020-06-10 20:08:26 +020045 PyInterpreterState *interp = _PyInterpreterState_GET();
46 PyObject *v = (PyObject*)interp->small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000049}
Guido van Rossumddefaf32007-01-14 03:31:43 +000050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000052maybe_small_long(PyLongObject *v)
53{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020054 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080056 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 Py_DECREF(v);
58 return (PyLongObject *)get_small_int(ival);
59 }
60 }
61 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000062}
Guido van Rossumddefaf32007-01-14 03:31:43 +000063#else
animalize6b519982019-09-06 14:00:56 +080064#define IS_SMALL_INT(ival) 0
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050065#define IS_SMALL_UINT(ival) 0
animalize6b519982019-09-06 14:00:56 +080066#define get_small_int(ival) (Py_UNREACHABLE(), NULL)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000067#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000068#endif
69
Serhiy Storchaka95949422013-08-27 19:40:23 +030070/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000071 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020072Py_LOCAL_INLINE(void)
73_PyLong_Negate(PyLongObject **x_p)
74{
75 PyLongObject *x;
76
77 x = (PyLongObject *)*x_p;
78 if (Py_REFCNT(x) == 1) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +010079 Py_SET_SIZE(x, -Py_SIZE(x));
Victor Stinner8aed6f12013-07-17 22:31:17 +020080 return;
81 }
82
83 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
84 Py_DECREF(x);
85}
86
Serhiy Storchaka95949422013-08-27 19:40:23 +030087/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000088 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030089 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000090 */
Tim Peters0973b992004-08-29 22:16:50 +000091#define KARATSUBA_CUTOFF 70
92#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000093
Tim Peters47e52ee2004-08-30 02:44:38 +000094/* For exponentiation, use the binary left-to-right algorithm
95 * unless the exponent contains more than FIVEARY_CUTOFF digits.
96 * In that case, do 5 bits at a time. The potential drawback is that
97 * a table of 2**5 intermediate results is computed.
98 */
99#define FIVEARY_CUTOFF 8
100
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000101#define SIGCHECK(PyTryBlock) \
102 do { \
103 if (PyErr_CheckSignals()) PyTryBlock \
104 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000105
Serhiy Storchaka95949422013-08-27 19:40:23 +0300106/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000107 Doesn't attempt to free the storage--in most cases, due to the nature
108 of the algorithms used, this could save at most be one word anyway. */
109
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000110static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200111long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000112{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200113 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 while (i > 0 && v->ob_digit[i-1] == 0)
117 --i;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100118 if (i != j) {
119 Py_SET_SIZE(v, (Py_SIZE(v) < 0) ? -(i) : i);
120 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000122}
123
Serhiy Storchaka95949422013-08-27 19:40:23 +0300124/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000125 Return NULL and set exception if we run out of memory. */
126
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000127#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000129
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000131_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 PyLongObject *result;
134 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
135 sizeof(digit)*size. Previous incarnations of this code used
136 sizeof(PyVarObject) instead of the offsetof, but this risks being
137 incorrect in the presence of padding between the PyVarObject header
138 and the digits. */
139 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
140 PyErr_SetString(PyExc_OverflowError,
141 "too many digits in integer");
142 return NULL;
143 }
144 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
145 size*sizeof(digit));
146 if (!result) {
147 PyErr_NoMemory();
148 return NULL;
149 }
Victor Stinner04fc4f22020-06-16 01:28:07 +0200150 _PyObject_InitVar((PyVarObject*)result, &PyLong_Type, size);
151 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000152}
153
Tim Peters64b5ce32001-09-10 20:52:51 +0000154PyObject *
155_PyLong_Copy(PyLongObject *src)
156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 PyLongObject *result;
158 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 assert(src != NULL);
161 i = Py_SIZE(src);
162 if (i < 0)
163 i = -(i);
164 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100165 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800166 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700167 return get_small_int(ival);
168 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 }
170 result = _PyLong_New(i);
171 if (result != NULL) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100172 Py_SET_SIZE(result, Py_SIZE(src));
173 while (--i >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 result->ob_digit[i] = src->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 }
177 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000178}
179
Serhiy Storchaka95949422013-08-27 19:40:23 +0300180/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000181
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000182PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000183PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyLongObject *v;
186 unsigned long abs_ival;
187 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
188 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100189 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000190
animalize6b519982019-09-06 14:00:56 +0800191 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700192 return get_small_int((sdigit)ival);
193 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (ival < 0) {
196 /* negate: can't write this as abs_ival = -ival since that
197 invokes undefined behaviour when ival is LONG_MIN */
198 abs_ival = 0U-(unsigned long)ival;
199 sign = -1;
200 }
201 else {
202 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100203 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 /* Fast path for single-digit ints */
207 if (!(abs_ival >> PyLong_SHIFT)) {
208 v = _PyLong_New(1);
209 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100210 Py_SET_SIZE(v, sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 v->ob_digit[0] = Py_SAFE_DOWNCAST(
212 abs_ival, unsigned long, digit);
213 }
214 return (PyObject*)v;
215 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000216
Mark Dickinson249b8982009-04-27 19:41:00 +0000217#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 /* 2 digits */
219 if (!(abs_ival >> 2*PyLong_SHIFT)) {
220 v = _PyLong_New(2);
221 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100222 Py_SET_SIZE(v, 2 * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 v->ob_digit[0] = Py_SAFE_DOWNCAST(
224 abs_ival & PyLong_MASK, unsigned long, digit);
225 v->ob_digit[1] = Py_SAFE_DOWNCAST(
226 abs_ival >> PyLong_SHIFT, unsigned long, digit);
227 }
228 return (PyObject*)v;
229 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000230#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 /* Larger numbers: loop to determine number of digits */
233 t = abs_ival;
234 while (t) {
235 ++ndigits;
236 t >>= PyLong_SHIFT;
237 }
238 v = _PyLong_New(ndigits);
239 if (v != NULL) {
240 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100241 Py_SET_SIZE(v, ndigits * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 t = abs_ival;
243 while (t) {
244 *p++ = Py_SAFE_DOWNCAST(
245 t & PyLong_MASK, unsigned long, digit);
246 t >>= PyLong_SHIFT;
247 }
248 }
249 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000250}
251
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500252#define PYLONG_FROM_UINT(INT_TYPE, ival) \
253 do { \
254 if (IS_SMALL_UINT(ival)) { \
Victor Stinner6314abc2019-10-01 13:29:53 +0200255 return get_small_int((sdigit)(ival)); \
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500256 } \
257 /* Count the number of Python digits. */ \
258 Py_ssize_t ndigits = 0; \
259 INT_TYPE t = (ival); \
260 while (t) { \
261 ++ndigits; \
262 t >>= PyLong_SHIFT; \
263 } \
264 PyLongObject *v = _PyLong_New(ndigits); \
265 if (v == NULL) { \
266 return NULL; \
267 } \
268 digit *p = v->ob_digit; \
269 while ((ival)) { \
270 *p++ = (digit)((ival) & PyLong_MASK); \
271 (ival) >>= PyLong_SHIFT; \
272 } \
273 return (PyObject *)v; \
274 } while(0)
275
Serhiy Storchaka95949422013-08-27 19:40:23 +0300276/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000277
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000278PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000279PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000280{
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500281 PYLONG_FROM_UINT(unsigned long, ival);
282}
Tim Petersce9de2f2001-06-14 04:56:19 +0000283
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500284/* Create a new int object from a C unsigned long long int. */
285
286PyObject *
287PyLong_FromUnsignedLongLong(unsigned long long ival)
288{
289 PYLONG_FROM_UINT(unsigned long long, ival);
290}
291
292/* Create a new int object from a C size_t. */
293
294PyObject *
295PyLong_FromSize_t(size_t ival)
296{
297 PYLONG_FROM_UINT(size_t, ival);
Guido van Rossum53756b11997-01-03 17:14:46 +0000298}
299
Serhiy Storchaka95949422013-08-27 19:40:23 +0300300/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000301
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000303PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000304{
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500305 /* Try to get out cheap if this fits in a long. When a finite value of real
306 * floating type is converted to an integer type, the value is truncated
307 * toward zero. If the value of the integral part cannot be represented by
308 * the integer type, the behavior is undefined. Thus, we must check that
309 * value is in range (LONG_MIN - 1, LONG_MAX + 1). If a long has more bits
310 * of precision than a double, casting LONG_MIN - 1 to double may yield an
311 * approximation, but LONG_MAX + 1 is a power of two and can be represented
312 * as double exactly (assuming FLT_RADIX is 2 or 16), so for simplicity
313 * check against [-(LONG_MAX + 1), LONG_MAX + 1).
314 */
315 const double int_max = (unsigned long)LONG_MAX + 1;
316 if (-int_max < dval && dval < int_max) {
317 return PyLong_FromLong((long)dval);
318 }
319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 PyLongObject *v;
321 double frac;
322 int i, ndig, expo, neg;
323 neg = 0;
324 if (Py_IS_INFINITY(dval)) {
325 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000326 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 return NULL;
328 }
329 if (Py_IS_NAN(dval)) {
330 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000331 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 return NULL;
333 }
334 if (dval < 0.0) {
335 neg = 1;
336 dval = -dval;
337 }
338 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500339 assert(expo > 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
341 v = _PyLong_New(ndig);
342 if (v == NULL)
343 return NULL;
344 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
345 for (i = ndig; --i >= 0; ) {
346 digit bits = (digit)frac;
347 v->ob_digit[i] = bits;
348 frac = frac - (double)bits;
349 frac = ldexp(frac, PyLong_SHIFT);
350 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100351 if (neg) {
352 Py_SET_SIZE(v, -(Py_SIZE(v)));
353 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000355}
356
Thomas Wouters89f507f2006-12-13 04:49:30 +0000357/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
358 * anything about what happens when a signed integer operation overflows,
359 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700360 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000361 * (unsigned long)LONG_MAX, and for the smallest negative signed long
362 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
363 * However, some other compilers warn about applying unary minus to an
364 * unsigned operand. Hence the weird "0-".
365 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
367#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000368
Mark Dickinson20941de2020-05-27 13:43:17 +0100369/* Get a C long int from an int object or any object that has an __index__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100370 method.
371
372 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
373 the result. Otherwise *overflow is 0.
374
375 For other errors (e.g., TypeError), return -1 and set an error condition.
376 In this case *overflow will be 0.
377*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000378
379long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000380PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200383 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 unsigned long x, prev;
385 long res;
386 Py_ssize_t i;
387 int sign;
Mark Dickinson20941de2020-05-27 13:43:17 +0100388 int do_decref = 0; /* if PyNumber_Index was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 *overflow = 0;
391 if (vv == NULL) {
392 PyErr_BadInternalCall();
393 return -1;
394 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000395
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200396 if (PyLong_Check(vv)) {
397 v = (PyLongObject *)vv;
398 }
399 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300400 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200401 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 return -1;
403 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 switch (i) {
410 case -1:
411 res = -(sdigit)v->ob_digit[0];
412 break;
413 case 0:
414 res = 0;
415 break;
416 case 1:
417 res = v->ob_digit[0];
418 break;
419 default:
420 sign = 1;
421 x = 0;
422 if (i < 0) {
423 sign = -1;
424 i = -(i);
425 }
426 while (--i >= 0) {
427 prev = x;
428 x = (x << PyLong_SHIFT) | v->ob_digit[i];
429 if ((x >> PyLong_SHIFT) != prev) {
430 *overflow = sign;
431 goto exit;
432 }
433 }
434 /* Haven't lost any bits, but casting to long requires extra
435 * care (see comment above).
436 */
437 if (x <= (unsigned long)LONG_MAX) {
438 res = (long)x * sign;
439 }
440 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
441 res = LONG_MIN;
442 }
443 else {
444 *overflow = sign;
445 /* res is already set to -1 */
446 }
447 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000448 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200450 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 }
452 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000453}
454
Mark Dickinson20941de2020-05-27 13:43:17 +0100455/* Get a C long int from an int object or any object that has an __index__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100456 method. Return -1 and set an error if overflow occurs. */
457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000459PyLong_AsLong(PyObject *obj)
460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 int overflow;
462 long result = PyLong_AsLongAndOverflow(obj, &overflow);
463 if (overflow) {
464 /* XXX: could be cute and give a different
465 message for overflow == -1 */
466 PyErr_SetString(PyExc_OverflowError,
467 "Python int too large to convert to C long");
468 }
469 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000470}
471
Mark Dickinson20941de2020-05-27 13:43:17 +0100472/* Get a C int from an int object or any object that has an __index__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200473 method. Return -1 and set an error if overflow occurs. */
474
475int
476_PyLong_AsInt(PyObject *obj)
477{
478 int overflow;
479 long result = PyLong_AsLongAndOverflow(obj, &overflow);
480 if (overflow || result > INT_MAX || result < INT_MIN) {
481 /* XXX: could be cute and give a different
482 message for overflow == -1 */
483 PyErr_SetString(PyExc_OverflowError,
484 "Python int too large to convert to C int");
485 return -1;
486 }
487 return (int)result;
488}
489
Serhiy Storchaka95949422013-08-27 19:40:23 +0300490/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000491 Returns -1 and sets an error condition if overflow occurs. */
492
493Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000494PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200495 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 size_t x, prev;
497 Py_ssize_t i;
498 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (vv == NULL) {
501 PyErr_BadInternalCall();
502 return -1;
503 }
504 if (!PyLong_Check(vv)) {
505 PyErr_SetString(PyExc_TypeError, "an integer is required");
506 return -1;
507 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 v = (PyLongObject *)vv;
510 i = Py_SIZE(v);
511 switch (i) {
512 case -1: return -(sdigit)v->ob_digit[0];
513 case 0: return 0;
514 case 1: return v->ob_digit[0];
515 }
516 sign = 1;
517 x = 0;
518 if (i < 0) {
519 sign = -1;
520 i = -(i);
521 }
522 while (--i >= 0) {
523 prev = x;
524 x = (x << PyLong_SHIFT) | v->ob_digit[i];
525 if ((x >> PyLong_SHIFT) != prev)
526 goto overflow;
527 }
528 /* Haven't lost any bits, but casting to a signed type requires
529 * extra care (see comment above).
530 */
531 if (x <= (size_t)PY_SSIZE_T_MAX) {
532 return (Py_ssize_t)x * sign;
533 }
534 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
535 return PY_SSIZE_T_MIN;
536 }
537 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000538
Mark Dickinson22b20182010-05-10 21:27:53 +0000539 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 PyErr_SetString(PyExc_OverflowError,
541 "Python int too large to convert to C ssize_t");
542 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000543}
544
Serhiy Storchaka95949422013-08-27 19:40:23 +0300545/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000546 Returns -1 and sets an error condition if overflow occurs. */
547
548unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000549PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000550{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200551 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 unsigned long x, prev;
553 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (vv == NULL) {
556 PyErr_BadInternalCall();
557 return (unsigned long)-1;
558 }
559 if (!PyLong_Check(vv)) {
560 PyErr_SetString(PyExc_TypeError, "an integer is required");
561 return (unsigned long)-1;
562 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 v = (PyLongObject *)vv;
565 i = Py_SIZE(v);
566 x = 0;
567 if (i < 0) {
568 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000569 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 return (unsigned long) -1;
571 }
572 switch (i) {
573 case 0: return 0;
574 case 1: return v->ob_digit[0];
575 }
576 while (--i >= 0) {
577 prev = x;
578 x = (x << PyLong_SHIFT) | v->ob_digit[i];
579 if ((x >> PyLong_SHIFT) != prev) {
580 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100581 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000582 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 return (unsigned long) -1;
584 }
585 }
586 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000587}
588
Serhiy Storchaka95949422013-08-27 19:40:23 +0300589/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200590 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000591
592size_t
593PyLong_AsSize_t(PyObject *vv)
594{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200595 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 size_t x, prev;
597 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (vv == NULL) {
600 PyErr_BadInternalCall();
601 return (size_t) -1;
602 }
603 if (!PyLong_Check(vv)) {
604 PyErr_SetString(PyExc_TypeError, "an integer is required");
605 return (size_t)-1;
606 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 v = (PyLongObject *)vv;
609 i = Py_SIZE(v);
610 x = 0;
611 if (i < 0) {
612 PyErr_SetString(PyExc_OverflowError,
613 "can't convert negative value to size_t");
614 return (size_t) -1;
615 }
616 switch (i) {
617 case 0: return 0;
618 case 1: return v->ob_digit[0];
619 }
620 while (--i >= 0) {
621 prev = x;
622 x = (x << PyLong_SHIFT) | v->ob_digit[i];
623 if ((x >> PyLong_SHIFT) != prev) {
624 PyErr_SetString(PyExc_OverflowError,
625 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200626 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 }
628 }
629 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000630}
631
Serhiy Storchaka95949422013-08-27 19:40:23 +0300632/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000633 Returns -1 and sets an error condition if an error occurs. */
634
Guido van Rossumddefaf32007-01-14 03:31:43 +0000635static unsigned long
636_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000637{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200638 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 unsigned long x;
640 Py_ssize_t i;
641 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 if (vv == NULL || !PyLong_Check(vv)) {
644 PyErr_BadInternalCall();
645 return (unsigned long) -1;
646 }
647 v = (PyLongObject *)vv;
648 i = Py_SIZE(v);
649 switch (i) {
650 case 0: return 0;
651 case 1: return v->ob_digit[0];
652 }
653 sign = 1;
654 x = 0;
655 if (i < 0) {
656 sign = -1;
657 i = -i;
658 }
659 while (--i >= 0) {
660 x = (x << PyLong_SHIFT) | v->ob_digit[i];
661 }
662 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000663}
664
Guido van Rossumddefaf32007-01-14 03:31:43 +0000665unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200666PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyLongObject *lo;
669 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000670
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200671 if (op == NULL) {
672 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 return (unsigned long)-1;
674 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000675
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200676 if (PyLong_Check(op)) {
677 return _PyLong_AsUnsignedLongMask(op);
678 }
679
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300680 lo = (PyLongObject *)_PyNumber_Index(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 if (lo == NULL)
682 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200683
684 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
685 Py_DECREF(lo);
686 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000687}
688
Tim Peters5b8132f2003-01-31 15:52:05 +0000689int
690_PyLong_Sign(PyObject *vv)
691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 assert(v != NULL);
695 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000698}
699
Niklas Fiekas794e7d12020-06-15 14:33:48 +0200700static int
701bit_length_digit(digit x)
702{
703 Py_BUILD_ASSERT(PyLong_SHIFT <= sizeof(unsigned long) * 8);
704 return _Py_bit_length((unsigned long)x);
705}
706
Tim Petersbaefd9e2003-01-28 20:37:45 +0000707size_t
708_PyLong_NumBits(PyObject *vv)
709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 PyLongObject *v = (PyLongObject *)vv;
711 size_t result = 0;
712 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200713 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 assert(v != NULL);
716 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200717 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
719 if (ndigits > 0) {
720 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700721 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100723 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Niklas Fiekas794e7d12020-06-15 14:33:48 +0200724 msd_bits = bit_length_digit(msd);
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200725 if (SIZE_MAX - msd_bits < result)
726 goto Overflow;
727 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 }
729 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000730
Mark Dickinson22b20182010-05-10 21:27:53 +0000731 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
733 "to express in a platform size_t");
734 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000735}
736
Tim Peters2a9b3672001-06-11 21:23:58 +0000737PyObject *
738_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000740{
Mark Dickinson22b20182010-05-10 21:27:53 +0000741 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 int incr; /* direction to move pstartbyte */
743 const unsigned char* pendbyte; /* MSB of bytes */
744 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300745 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 PyLongObject* v; /* result */
747 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (n == 0)
750 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 if (little_endian) {
753 pstartbyte = bytes;
754 pendbyte = bytes + n - 1;
755 incr = 1;
756 }
757 else {
758 pstartbyte = bytes + n - 1;
759 pendbyte = bytes;
760 incr = -1;
761 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 if (is_signed)
764 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200767 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 is positive, and leading 0xff bytes if negative. */
769 {
770 size_t i;
771 const unsigned char* p = pendbyte;
772 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000773 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000776 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 break;
778 }
779 numsignificantbytes = n - i;
780 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
781 actually has 2 significant bytes. OTOH, 0xff0001 ==
782 -0x00ffff, so we wouldn't *need* to bump it there; but we
783 do for 0xffff = -0x0001. To be safe without bothering to
784 check every case, bump it regardless. */
785 if (is_signed && numsignificantbytes < n)
786 ++numsignificantbytes;
787 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000788
Serhiy Storchaka95949422013-08-27 19:40:23 +0300789 /* How many Python int digits do we need? We have
790 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
792 /* catch overflow before it happens */
793 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
794 PyErr_SetString(PyExc_OverflowError,
795 "byte array too long to convert to int");
796 return NULL;
797 }
798 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
799 v = _PyLong_New(ndigits);
800 if (v == NULL)
801 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 /* Copy the bits over. The tricky parts are computing 2's-comp on
804 the fly for signed numbers, and dealing with the mismatch between
805 8-bit bytes and (probably) 15-bit Python digits.*/
806 {
807 size_t i;
808 twodigits carry = 1; /* for 2's-comp calculation */
809 twodigits accum = 0; /* sliding register */
810 unsigned int accumbits = 0; /* number of bits in accum */
811 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
814 twodigits thisbyte = *p;
815 /* Compute correction for 2's comp, if needed. */
816 if (is_signed) {
817 thisbyte = (0xff ^ thisbyte) + carry;
818 carry = thisbyte >> 8;
819 thisbyte &= 0xff;
820 }
821 /* Because we're going LSB to MSB, thisbyte is
822 more significant than what's already in accum,
823 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200824 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 accumbits += 8;
826 if (accumbits >= PyLong_SHIFT) {
827 /* There's enough to fill a Python digit. */
828 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000829 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 ++idigit;
831 accum >>= PyLong_SHIFT;
832 accumbits -= PyLong_SHIFT;
833 assert(accumbits < PyLong_SHIFT);
834 }
835 }
836 assert(accumbits < PyLong_SHIFT);
837 if (accumbits) {
838 assert(idigit < ndigits);
839 v->ob_digit[idigit] = (digit)accum;
840 ++idigit;
841 }
842 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000843
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100844 Py_SET_SIZE(v, is_signed ? -idigit : idigit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000846}
847
848int
849_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 unsigned char* bytes, size_t n,
851 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000854 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000856 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
858 digit carry; /* for computing 2's-comp */
859 size_t j; /* # bytes filled */
860 unsigned char* p; /* pointer to next byte in bytes */
861 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 if (Py_SIZE(v) < 0) {
866 ndigits = -(Py_SIZE(v));
867 if (!is_signed) {
868 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000869 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 return -1;
871 }
872 do_twos_comp = 1;
873 }
874 else {
875 ndigits = Py_SIZE(v);
876 do_twos_comp = 0;
877 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 if (little_endian) {
880 p = bytes;
881 pincr = 1;
882 }
883 else {
884 p = bytes + n - 1;
885 pincr = -1;
886 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 /* Copy over all the Python digits.
889 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300890 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 normalized. */
892 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
893 j = 0;
894 accum = 0;
895 accumbits = 0;
896 carry = do_twos_comp ? 1 : 0;
897 for (i = 0; i < ndigits; ++i) {
898 digit thisdigit = v->ob_digit[i];
899 if (do_twos_comp) {
900 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
901 carry = thisdigit >> PyLong_SHIFT;
902 thisdigit &= PyLong_MASK;
903 }
904 /* Because we're going LSB to MSB, thisdigit is more
905 significant than what's already in accum, so needs to be
906 prepended to accum. */
907 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 /* The most-significant digit may be (probably is) at least
910 partly empty. */
911 if (i == ndigits - 1) {
912 /* Count # of sign bits -- they needn't be stored,
913 * although for signed conversion we need later to
914 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000915 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 while (s != 0) {
917 s >>= 1;
918 accumbits++;
919 }
920 }
921 else
922 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* Store as many bytes as possible. */
925 while (accumbits >= 8) {
926 if (j >= n)
927 goto Overflow;
928 ++j;
929 *p = (unsigned char)(accum & 0xff);
930 p += pincr;
931 accumbits -= 8;
932 accum >>= 8;
933 }
934 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* Store the straggler (if any). */
937 assert(accumbits < 8);
938 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
939 if (accumbits > 0) {
940 if (j >= n)
941 goto Overflow;
942 ++j;
943 if (do_twos_comp) {
944 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300945 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 infinite supply of sign bits). */
947 accum |= (~(twodigits)0) << accumbits;
948 }
949 *p = (unsigned char)(accum & 0xff);
950 p += pincr;
951 }
952 else if (j == n && n > 0 && is_signed) {
953 /* The main loop filled the byte array exactly, so the code
954 just above didn't get to ensure there's a sign bit, and the
955 loop below wouldn't add one either. Make sure a sign bit
956 exists. */
957 unsigned char msb = *(p - pincr);
958 int sign_bit_set = msb >= 0x80;
959 assert(accumbits == 0);
960 if (sign_bit_set == do_twos_comp)
961 return 0;
962 else
963 goto Overflow;
964 }
Tim Peters05607ad2001-06-13 21:01:27 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 /* Fill remaining bytes with copies of the sign bit. */
967 {
968 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
969 for ( ; j < n; ++j, p += pincr)
970 *p = signbyte;
971 }
Tim Peters05607ad2001-06-13 21:01:27 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000974
Mark Dickinson22b20182010-05-10 21:27:53 +0000975 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
977 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000978
Tim Peters2a9b3672001-06-11 21:23:58 +0000979}
980
Serhiy Storchaka95949422013-08-27 19:40:23 +0300981/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000982
983PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000984PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000985{
Mark Dickinson91044792012-10-18 19:21:43 +0100986#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -0700987 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100988#else
989
Tim Peters70128a12001-06-16 08:48:40 +0000990#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700991# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000992#endif
Benjamin Petersonca470632016-09-06 13:47:26 -0700993 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100994#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000995
Guido van Rossum78694d91998-09-18 14:14:13 +0000996}
997
Serhiy Storchaka95949422013-08-27 19:40:23 +0300998/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000999
1000void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001001PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001002{
Tim Peters70128a12001-06-16 08:48:40 +00001003#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1007 x = PyLong_AsLong(vv);
1008 else
1009 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001010#else
Tim Peters70128a12001-06-16 08:48:40 +00001011
Tim Peters70128a12001-06-16 08:48:40 +00001012#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001013# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001014#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001015 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1018 x = PyLong_AsLongLong(vv);
1019 else
1020 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001021
1022#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 if (x == -1 && PyErr_Occurred())
1025 return NULL;
1026 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001027}
1028
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001029/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001030 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001031 */
1032
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001033#define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001034
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001035/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001036
1037PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001038PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001041 unsigned long long abs_ival;
1042 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 int ndigits = 0;
1044 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001045
animalize6b519982019-09-06 14:00:56 +08001046 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001047 return get_small_int((sdigit)ival);
1048 }
1049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 if (ival < 0) {
1051 /* avoid signed overflow on negation; see comments
1052 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001053 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 negative = 1;
1055 }
1056 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001057 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 /* Count the number of Python digits.
1061 We used to pick 5 ("big enough for anything"), but that's a
1062 waste of time and space given that 5*15 = 75 bits are rarely
1063 needed. */
1064 t = abs_ival;
1065 while (t) {
1066 ++ndigits;
1067 t >>= PyLong_SHIFT;
1068 }
1069 v = _PyLong_New(ndigits);
1070 if (v != NULL) {
1071 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001072 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 t = abs_ival;
1074 while (t) {
1075 *p++ = (digit)(t & PyLong_MASK);
1076 t >>= PyLong_SHIFT;
1077 }
1078 }
1079 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001080}
1081
Serhiy Storchaka95949422013-08-27 19:40:23 +03001082/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001083
1084PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001085PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 PyLongObject *v;
1088 size_t abs_ival;
1089 size_t t; /* unsigned so >> doesn't propagate sign bit */
1090 int ndigits = 0;
1091 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001092
animalize6b519982019-09-06 14:00:56 +08001093 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001094 return get_small_int((sdigit)ival);
1095 }
1096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 if (ival < 0) {
1098 /* avoid signed overflow when ival = SIZE_T_MIN */
1099 abs_ival = (size_t)(-1-ival)+1;
1100 negative = 1;
1101 }
1102 else {
1103 abs_ival = (size_t)ival;
1104 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 /* Count the number of Python digits. */
1107 t = abs_ival;
1108 while (t) {
1109 ++ndigits;
1110 t >>= PyLong_SHIFT;
1111 }
1112 v = _PyLong_New(ndigits);
1113 if (v != NULL) {
1114 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001115 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 t = abs_ival;
1117 while (t) {
1118 *p++ = (digit)(t & PyLong_MASK);
1119 t >>= PyLong_SHIFT;
1120 }
1121 }
1122 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001123}
1124
Serhiy Storchaka95949422013-08-27 19:40:23 +03001125/* Get a C long long int from an int object or any object that has an
Mark Dickinson20941de2020-05-27 13:43:17 +01001126 __index__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001127
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001128long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001129PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001132 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 int res;
Mark Dickinson20941de2020-05-27 13:43:17 +01001134 int do_decref = 0; /* if PyNumber_Index was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (vv == NULL) {
1137 PyErr_BadInternalCall();
1138 return -1;
1139 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001140
1141 if (PyLong_Check(vv)) {
1142 v = (PyLongObject *)vv;
1143 }
1144 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001145 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001146 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001148 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001150
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001151 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001153 case -1:
1154 bytes = -(sdigit)v->ob_digit[0];
1155 break;
1156 case 0:
1157 bytes = 0;
1158 break;
1159 case 1:
1160 bytes = v->ob_digit[0];
1161 break;
1162 default:
1163 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001164 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001166 if (do_decref) {
1167 Py_DECREF(v);
1168 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001169
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001170 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001172 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 else
1174 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001175}
1176
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001177/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001178 Return -1 and set an error if overflow occurs. */
1179
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001180unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001181PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001184 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001186
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001187 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001189 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001191 if (!PyLong_Check(vv)) {
1192 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001193 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001194 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 v = (PyLongObject*)vv;
1197 switch(Py_SIZE(v)) {
1198 case 0: return 0;
1199 case 1: return v->ob_digit[0];
1200 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001201
Mark Dickinson22b20182010-05-10 21:27:53 +00001202 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001203 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001204
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001205 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001207 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 else
1209 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001210}
Tim Petersd1a7da62001-06-13 00:35:57 +00001211
Serhiy Storchaka95949422013-08-27 19:40:23 +03001212/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001213 Returns -1 and sets an error condition if an error occurs. */
1214
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001215static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001216_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001217{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001218 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001219 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 Py_ssize_t i;
1221 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (vv == NULL || !PyLong_Check(vv)) {
1224 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001225 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 }
1227 v = (PyLongObject *)vv;
1228 switch(Py_SIZE(v)) {
1229 case 0: return 0;
1230 case 1: return v->ob_digit[0];
1231 }
1232 i = Py_SIZE(v);
1233 sign = 1;
1234 x = 0;
1235 if (i < 0) {
1236 sign = -1;
1237 i = -i;
1238 }
1239 while (--i >= 0) {
1240 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1241 }
1242 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001243}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001244
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001245unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001246PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001249 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001250
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001251 if (op == NULL) {
1252 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001253 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001255
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001256 if (PyLong_Check(op)) {
1257 return _PyLong_AsUnsignedLongLongMask(op);
1258 }
1259
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001260 lo = (PyLongObject *)_PyNumber_Index(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001262 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001263
1264 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1265 Py_DECREF(lo);
1266 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001267}
Tim Petersd1a7da62001-06-13 00:35:57 +00001268
Serhiy Storchaka95949422013-08-27 19:40:23 +03001269/* Get a C long long int from an int object or any object that has an
Mark Dickinson20941de2020-05-27 13:43:17 +01001270 __index__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001271
Mark Dickinson8d48b432011-10-23 20:47:14 +01001272 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1273 the result. Otherwise *overflow is 0.
1274
1275 For other errors (e.g., TypeError), return -1 and set an error condition.
1276 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001277*/
1278
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001279long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001280PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001283 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001284 unsigned long long x, prev;
1285 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 Py_ssize_t i;
1287 int sign;
Mark Dickinson20941de2020-05-27 13:43:17 +01001288 int do_decref = 0; /* if PyNumber_Index was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 *overflow = 0;
1291 if (vv == NULL) {
1292 PyErr_BadInternalCall();
1293 return -1;
1294 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001295
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001296 if (PyLong_Check(vv)) {
1297 v = (PyLongObject *)vv;
1298 }
1299 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001300 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001301 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 return -1;
1303 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 switch (i) {
1310 case -1:
1311 res = -(sdigit)v->ob_digit[0];
1312 break;
1313 case 0:
1314 res = 0;
1315 break;
1316 case 1:
1317 res = v->ob_digit[0];
1318 break;
1319 default:
1320 sign = 1;
1321 x = 0;
1322 if (i < 0) {
1323 sign = -1;
1324 i = -(i);
1325 }
1326 while (--i >= 0) {
1327 prev = x;
1328 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1329 if ((x >> PyLong_SHIFT) != prev) {
1330 *overflow = sign;
1331 goto exit;
1332 }
1333 }
1334 /* Haven't lost any bits, but casting to long requires extra
1335 * care (see comment above).
1336 */
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001337 if (x <= (unsigned long long)LLONG_MAX) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001338 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 }
1340 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001341 res = LLONG_MIN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 }
1343 else {
1344 *overflow = sign;
1345 /* res is already set to -1 */
1346 }
1347 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001348 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001350 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 }
1352 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001353}
1354
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001355int
1356_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1357{
1358 unsigned long uval;
1359
1360 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1361 PyErr_SetString(PyExc_ValueError, "value must be positive");
1362 return 0;
1363 }
1364 uval = PyLong_AsUnsignedLong(obj);
1365 if (uval == (unsigned long)-1 && PyErr_Occurred())
1366 return 0;
1367 if (uval > USHRT_MAX) {
1368 PyErr_SetString(PyExc_OverflowError,
1369 "Python int too large for C unsigned short");
1370 return 0;
1371 }
1372
1373 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1374 return 1;
1375}
1376
1377int
1378_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1379{
1380 unsigned long uval;
1381
1382 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1383 PyErr_SetString(PyExc_ValueError, "value must be positive");
1384 return 0;
1385 }
1386 uval = PyLong_AsUnsignedLong(obj);
1387 if (uval == (unsigned long)-1 && PyErr_Occurred())
1388 return 0;
1389 if (uval > UINT_MAX) {
1390 PyErr_SetString(PyExc_OverflowError,
1391 "Python int too large for C unsigned int");
1392 return 0;
1393 }
1394
1395 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1396 return 1;
1397}
1398
1399int
1400_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1401{
1402 unsigned long uval;
1403
1404 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1405 PyErr_SetString(PyExc_ValueError, "value must be positive");
1406 return 0;
1407 }
1408 uval = PyLong_AsUnsignedLong(obj);
1409 if (uval == (unsigned long)-1 && PyErr_Occurred())
1410 return 0;
1411
1412 *(unsigned long *)ptr = uval;
1413 return 1;
1414}
1415
1416int
1417_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1418{
1419 unsigned long long uval;
1420
1421 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1422 PyErr_SetString(PyExc_ValueError, "value must be positive");
1423 return 0;
1424 }
1425 uval = PyLong_AsUnsignedLongLong(obj);
1426 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1427 return 0;
1428
1429 *(unsigned long long *)ptr = uval;
1430 return 1;
1431}
1432
1433int
1434_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1435{
1436 size_t uval;
1437
1438 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1439 PyErr_SetString(PyExc_ValueError, "value must be positive");
1440 return 0;
1441 }
1442 uval = PyLong_AsSize_t(obj);
1443 if (uval == (size_t)-1 && PyErr_Occurred())
1444 return 0;
1445
1446 *(size_t *)ptr = uval;
1447 return 1;
1448}
1449
1450
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001451#define CHECK_BINOP(v,w) \
1452 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001453 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1454 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001455 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001456
Tim Peters877a2122002-08-12 05:09:36 +00001457/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1458 * is modified in place, by adding y to it. Carries are propagated as far as
1459 * x[m-1], and the remaining carry (0 or 1) is returned.
1460 */
1461static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001462v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 Py_ssize_t i;
1465 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 assert(m >= n);
1468 for (i = 0; i < n; ++i) {
1469 carry += x[i] + y[i];
1470 x[i] = carry & PyLong_MASK;
1471 carry >>= PyLong_SHIFT;
1472 assert((carry & 1) == carry);
1473 }
1474 for (; carry && i < m; ++i) {
1475 carry += x[i];
1476 x[i] = carry & PyLong_MASK;
1477 carry >>= PyLong_SHIFT;
1478 assert((carry & 1) == carry);
1479 }
1480 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001481}
1482
1483/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1484 * is modified in place, by subtracting y from it. Borrows are propagated as
1485 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1486 */
1487static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001488v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 Py_ssize_t i;
1491 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 assert(m >= n);
1494 for (i = 0; i < n; ++i) {
1495 borrow = x[i] - y[i] - borrow;
1496 x[i] = borrow & PyLong_MASK;
1497 borrow >>= PyLong_SHIFT;
1498 borrow &= 1; /* keep only 1 sign bit */
1499 }
1500 for (; borrow && i < m; ++i) {
1501 borrow = x[i] - borrow;
1502 x[i] = borrow & PyLong_MASK;
1503 borrow >>= PyLong_SHIFT;
1504 borrow &= 1;
1505 }
1506 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001507}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001508
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001509/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1510 * result in z[0:m], and return the d bits shifted out of the top.
1511 */
1512static digit
1513v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 Py_ssize_t i;
1516 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 assert(0 <= d && d < PyLong_SHIFT);
1519 for (i=0; i < m; i++) {
1520 twodigits acc = (twodigits)a[i] << d | carry;
1521 z[i] = (digit)acc & PyLong_MASK;
1522 carry = (digit)(acc >> PyLong_SHIFT);
1523 }
1524 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001525}
1526
1527/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1528 * result in z[0:m], and return the d bits shifted out of the bottom.
1529 */
1530static digit
1531v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 Py_ssize_t i;
1534 digit carry = 0;
1535 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 assert(0 <= d && d < PyLong_SHIFT);
1538 for (i=m; i-- > 0;) {
1539 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1540 carry = (digit)acc & mask;
1541 z[i] = (digit)(acc >> d);
1542 }
1543 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001544}
1545
Tim Peters212e6142001-07-14 12:23:19 +00001546/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1547 in pout, and returning the remainder. pin and pout point at the LSD.
1548 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001549 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001550 immutable. */
1551
1552static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001553inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 assert(n > 0 && n <= PyLong_MASK);
1558 pin += size;
1559 pout += size;
1560 while (--size >= 0) {
1561 digit hi;
1562 rem = (rem << PyLong_SHIFT) | *--pin;
1563 *--pout = hi = (digit)(rem / n);
1564 rem -= (twodigits)hi * n;
1565 }
1566 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001567}
1568
Serhiy Storchaka95949422013-08-27 19:40:23 +03001569/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001570 (as function result) and the remainder (through *prem).
1571 The sign of a is ignored; n should not be zero. */
1572
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001573static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001574divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001575{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001576 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 assert(n > 0 && n <= PyLong_MASK);
1580 z = _PyLong_New(size);
1581 if (z == NULL)
1582 return NULL;
1583 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1584 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001585}
1586
Serhiy Storchaka95949422013-08-27 19:40:23 +03001587/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001588 string. (Return value is non-shared so that callers can modify the
1589 returned value if necessary.) */
1590
Victor Stinnerd3f08822012-05-29 12:57:52 +02001591static int
1592long_to_decimal_string_internal(PyObject *aa,
1593 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001594 _PyUnicodeWriter *writer,
1595 _PyBytesWriter *bytes_writer,
1596 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001599 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 Py_ssize_t size, strlen, size_a, i, j;
1601 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001603 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001604 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 a = (PyLongObject *)aa;
1607 if (a == NULL || !PyLong_Check(a)) {
1608 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001609 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001611 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 /* quick and dirty upper bound for the number of digits
1615 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 But log2(a) < size_a * PyLong_SHIFT, and
1620 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001621 > 3.3 * _PyLong_DECIMAL_SHIFT
1622
1623 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1624 size_a + size_a / d < size_a + size_a / floor(d),
1625 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1626 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001628 d = (33 * _PyLong_DECIMAL_SHIFT) /
1629 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1630 assert(size_a < PY_SSIZE_T_MAX/2);
1631 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 scratch = _PyLong_New(size);
1633 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001634 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 /* convert array of base _PyLong_BASE digits in pin to an array of
1637 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1638 Volume 2 (3rd edn), section 4.4, Method 1b). */
1639 pin = a->ob_digit;
1640 pout = scratch->ob_digit;
1641 size = 0;
1642 for (i = size_a; --i >= 0; ) {
1643 digit hi = pin[i];
1644 for (j = 0; j < size; j++) {
1645 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1646 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1647 pout[j] = (digit)(z - (twodigits)hi *
1648 _PyLong_DECIMAL_BASE);
1649 }
1650 while (hi) {
1651 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1652 hi /= _PyLong_DECIMAL_BASE;
1653 }
1654 /* check for keyboard interrupt */
1655 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001656 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001657 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001658 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 }
1660 /* pout should have at least one digit, so that the case when a = 0
1661 works correctly */
1662 if (size == 0)
1663 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 /* calculate exact length of output string, and allocate */
1666 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1667 tenpow = 10;
1668 rem = pout[size-1];
1669 while (rem >= tenpow) {
1670 tenpow *= 10;
1671 strlen++;
1672 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001673 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001674 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1675 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001676 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001677 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001678 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001680 else if (bytes_writer) {
1681 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1682 if (*bytes_str == NULL) {
1683 Py_DECREF(scratch);
1684 return -1;
1685 }
1686 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001687 else {
1688 str = PyUnicode_New(strlen, '9');
1689 if (str == NULL) {
1690 Py_DECREF(scratch);
1691 return -1;
1692 }
1693 kind = PyUnicode_KIND(str);
1694 }
1695
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001696#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001697 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001698 /* pout[0] through pout[size-2] contribute exactly \
1699 _PyLong_DECIMAL_SHIFT digits each */ \
1700 for (i=0; i < size - 1; i++) { \
1701 rem = pout[i]; \
1702 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1703 *--p = '0' + rem % 10; \
1704 rem /= 10; \
1705 } \
1706 } \
1707 /* pout[size-1]: always produce at least one decimal digit */ \
1708 rem = pout[i]; \
1709 do { \
1710 *--p = '0' + rem % 10; \
1711 rem /= 10; \
1712 } while (rem != 0); \
1713 \
1714 /* and sign */ \
1715 if (negative) \
1716 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001717 } while (0)
1718
1719#define WRITE_UNICODE_DIGITS(TYPE) \
1720 do { \
1721 if (writer) \
1722 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1723 else \
1724 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1725 \
1726 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001727 \
1728 /* check we've counted correctly */ \
1729 if (writer) \
1730 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1731 else \
1732 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1733 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001736 if (bytes_writer) {
1737 char *p = *bytes_str + strlen;
1738 WRITE_DIGITS(p);
1739 assert(p == *bytes_str);
1740 }
1741 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001742 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001743 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001745 else if (kind == PyUnicode_2BYTE_KIND) {
1746 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001747 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001748 }
1749 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001750 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001751 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001752 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001753 }
1754#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001755#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001758 if (writer) {
1759 writer->pos += strlen;
1760 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001761 else if (bytes_writer) {
1762 (*bytes_str) += strlen;
1763 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001764 else {
1765 assert(_PyUnicode_CheckConsistency(str, 1));
1766 *p_output = (PyObject *)str;
1767 }
1768 return 0;
1769}
1770
1771static PyObject *
1772long_to_decimal_string(PyObject *aa)
1773{
1774 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001775 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001776 return NULL;
1777 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001778}
1779
Serhiy Storchaka95949422013-08-27 19:40:23 +03001780/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001781 which should be one of 2, 8 or 16. Return a string object.
1782 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1783 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001784
Victor Stinnerd3f08822012-05-29 12:57:52 +02001785static int
1786long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001787 PyObject **p_output, _PyUnicodeWriter *writer,
1788 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001789{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001790 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001791 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001792 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001794 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001795 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001797
Victor Stinnerd3f08822012-05-29 12:57:52 +02001798 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 if (a == NULL || !PyLong_Check(a)) {
1800 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001801 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001803 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001804 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 /* Compute a rough upper bound for the length of the string */
1807 switch (base) {
1808 case 16:
1809 bits = 4;
1810 break;
1811 case 8:
1812 bits = 3;
1813 break;
1814 case 2:
1815 bits = 1;
1816 break;
1817 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001818 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001820
Mark Dickinsone2846542012-04-20 21:21:24 +01001821 /* Compute exact length 'sz' of output string. */
1822 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001823 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001824 }
1825 else {
1826 Py_ssize_t size_a_in_bits;
1827 /* Ensure overflow doesn't occur during computation of sz. */
1828 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1829 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001830 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001831 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001832 }
1833 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
Niklas Fiekas794e7d12020-06-15 14:33:48 +02001834 bit_length_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001835 /* Allow 1 character for a '-' sign. */
1836 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1837 }
1838 if (alternate) {
1839 /* 2 characters for prefix */
1840 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001841 }
1842
Victor Stinnerd3f08822012-05-29 12:57:52 +02001843 if (writer) {
1844 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1845 return -1;
1846 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001848 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001849 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1850 if (*bytes_str == NULL)
1851 return -1;
1852 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001854 v = PyUnicode_New(sz, 'x');
1855 if (v == NULL)
1856 return -1;
1857 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001859
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001860#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001861 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001862 if (size_a == 0) { \
1863 *--p = '0'; \
1864 } \
1865 else { \
1866 /* JRH: special case for power-of-2 bases */ \
1867 twodigits accum = 0; \
1868 int accumbits = 0; /* # of bits in accum */ \
1869 Py_ssize_t i; \
1870 for (i = 0; i < size_a; ++i) { \
1871 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1872 accumbits += PyLong_SHIFT; \
1873 assert(accumbits >= bits); \
1874 do { \
1875 char cdigit; \
1876 cdigit = (char)(accum & (base - 1)); \
1877 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1878 *--p = cdigit; \
1879 accumbits -= bits; \
1880 accum >>= bits; \
1881 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1882 } \
1883 } \
1884 \
1885 if (alternate) { \
1886 if (base == 16) \
1887 *--p = 'x'; \
1888 else if (base == 8) \
1889 *--p = 'o'; \
1890 else /* (base == 2) */ \
1891 *--p = 'b'; \
1892 *--p = '0'; \
1893 } \
1894 if (negative) \
1895 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001896 } while (0)
1897
1898#define WRITE_UNICODE_DIGITS(TYPE) \
1899 do { \
1900 if (writer) \
1901 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1902 else \
1903 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1904 \
1905 WRITE_DIGITS(p); \
1906 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001907 if (writer) \
1908 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1909 else \
1910 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1911 } while (0)
1912
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001913 if (bytes_writer) {
1914 char *p = *bytes_str + sz;
1915 WRITE_DIGITS(p);
1916 assert(p == *bytes_str);
1917 }
1918 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001919 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001920 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001921 }
1922 else if (kind == PyUnicode_2BYTE_KIND) {
1923 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001924 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001925 }
1926 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001927 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001928 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001929 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001930 }
1931#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001932#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02001933
1934 if (writer) {
1935 writer->pos += sz;
1936 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001937 else if (bytes_writer) {
1938 (*bytes_str) += sz;
1939 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001940 else {
1941 assert(_PyUnicode_CheckConsistency(v, 1));
1942 *p_output = v;
1943 }
1944 return 0;
1945}
1946
1947PyObject *
1948_PyLong_Format(PyObject *obj, int base)
1949{
1950 PyObject *str;
1951 int err;
1952 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001953 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001954 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001955 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001956 if (err == -1)
1957 return NULL;
1958 return str;
1959}
1960
1961int
1962_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1963 PyObject *obj,
1964 int base, int alternate)
1965{
1966 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001967 return long_to_decimal_string_internal(obj, NULL, writer,
1968 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001969 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001970 return long_format_binary(obj, base, alternate, NULL, writer,
1971 NULL, NULL);
1972}
1973
1974char*
1975_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
1976 PyObject *obj,
1977 int base, int alternate)
1978{
1979 char *str2;
1980 int res;
1981 str2 = str;
1982 if (base == 10)
1983 res = long_to_decimal_string_internal(obj, NULL, NULL,
1984 writer, &str2);
1985 else
1986 res = long_format_binary(obj, base, alternate, NULL, NULL,
1987 writer, &str2);
1988 if (res < 0)
1989 return NULL;
1990 assert(str2 != NULL);
1991 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001992}
1993
Thomas Wouters477c8d52006-05-27 19:21:47 +00001994/* Table of digit values for 8-bit string -> integer conversion.
1995 * '0' maps to 0, ..., '9' maps to 9.
1996 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1997 * All other indices map to 37.
1998 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001999 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002000 */
Raymond Hettinger35631532009-01-09 03:58:09 +00002001unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 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 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2006 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2007 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2008 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2009 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2010 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2011 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2012 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2013 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2014 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2015 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2016 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2017 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002018};
2019
2020/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002021 * 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 +03002022 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002023 * The point to this routine is that it takes time linear in the number of
2024 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002025 *
2026 * Return values:
2027 * -1 on syntax error (exception needs to be set, *res is untouched)
2028 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002029 */
Brett Cannona721aba2016-09-09 14:57:09 -07002030static int
2031long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002032{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002033 const char *p = *str;
2034 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002035 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002036 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 int bits_per_char;
2038 Py_ssize_t n;
2039 PyLongObject *z;
2040 twodigits accum;
2041 int bits_in_accum;
2042 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2045 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002046 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002048 }
2049 /* count digits and set p to end-of-string */
2050 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2051 if (*p == '_') {
2052 if (prev == '_') {
2053 *str = p - 1;
2054 return -1;
2055 }
2056 } else {
2057 ++digits;
2058 }
2059 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002061 }
2062 if (prev == '_') {
2063 /* Trailing underscore not allowed. */
2064 *str = p - 1;
2065 return -1;
2066 }
2067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002069 /* n <- the number of Python digits needed,
2070 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2071 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 PyErr_SetString(PyExc_ValueError,
2073 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002074 *res = NULL;
2075 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002077 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002079 if (z == NULL) {
2080 *res = NULL;
2081 return 0;
2082 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002083 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 * from least to most significant in both.
2085 */
2086 accum = 0;
2087 bits_in_accum = 0;
2088 pdigit = z->ob_digit;
2089 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002090 int k;
2091 if (*p == '_') {
2092 continue;
2093 }
2094 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 assert(k >= 0 && k < base);
2096 accum |= (twodigits)k << bits_in_accum;
2097 bits_in_accum += bits_per_char;
2098 if (bits_in_accum >= PyLong_SHIFT) {
2099 *pdigit++ = (digit)(accum & PyLong_MASK);
2100 assert(pdigit - z->ob_digit <= n);
2101 accum >>= PyLong_SHIFT;
2102 bits_in_accum -= PyLong_SHIFT;
2103 assert(bits_in_accum < PyLong_SHIFT);
2104 }
2105 }
2106 if (bits_in_accum) {
2107 assert(bits_in_accum <= PyLong_SHIFT);
2108 *pdigit++ = (digit)accum;
2109 assert(pdigit - z->ob_digit <= n);
2110 }
2111 while (pdigit - z->ob_digit < n)
2112 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002113 *res = long_normalize(z);
2114 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002115}
2116
Serhiy Storchaka95949422013-08-27 19:40:23 +03002117/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002118 * ignored.
2119 *
2120 * If successful, a PyLong object will be returned and 'pend' will be pointing
2121 * to the first unused byte unless it's NULL.
2122 *
2123 * If unsuccessful, NULL will be returned.
2124 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002125PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002126PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002129 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 PyLongObject *z = NULL;
2131 PyObject *strobj;
2132 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 if ((base != 0 && base < 2) || base > 36) {
2135 PyErr_SetString(PyExc_ValueError,
2136 "int() arg 2 must be >= 2 and <= 36");
2137 return NULL;
2138 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002139 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002141 }
2142 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002144 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 else if (*str == '-') {
2146 ++str;
2147 sign = -1;
2148 }
2149 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002150 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002152 }
2153 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002155 }
2156 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002158 }
2159 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002161 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 else {
2163 /* "old" (C-style) octal literal, now invalid.
2164 it might still be zero though */
2165 error_if_nonzero = 1;
2166 base = 10;
2167 }
2168 }
2169 if (str[0] == '0' &&
2170 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2171 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002172 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002174 /* One underscore allowed here. */
2175 if (*str == '_') {
2176 ++str;
2177 }
2178 }
2179 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002180 /* May not start with underscores. */
2181 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002182 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002185 if ((base & (base - 1)) == 0) {
2186 int res = long_from_binary_base(&str, base, &z);
2187 if (res < 0) {
2188 /* Syntax error. */
2189 goto onError;
2190 }
2191 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002193/***
2194Binary bases can be converted in time linear in the number of digits, because
2195Python's representation base is binary. Other bases (including decimal!) use
2196the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002197
Thomas Wouters477c8d52006-05-27 19:21:47 +00002198First some math: the largest integer that can be expressed in N base-B digits
2199is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2200case number of Python digits needed to hold it is the smallest integer n s.t.
2201
2202 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2203 BASE**n >= B**N [taking logs to base BASE]
2204 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2205
2206The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002207this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002208and the result is computed into it.
2209
2210The input string is actually treated as being in base base**i (i.e., i digits
2211are processed at a time), where two more static arrays hold:
2212
2213 convwidth_base[base] = the largest integer i such that base**i <= BASE
2214 convmultmax_base[base] = base ** convwidth_base[base]
2215
2216The first of these is the largest i such that i consecutive input digits
2217must fit in a single Python digit. The second is effectively the input
2218base we're really using.
2219
2220Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2221convmultmax_base[base], the result is "simply"
2222
2223 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2224
2225where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002226
2227Error analysis: as above, the number of Python digits `n` needed is worst-
2228case
2229
2230 n >= N * log(B)/log(BASE)
2231
2232where `N` is the number of input digits in base `B`. This is computed via
2233
2234 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2235
2236below. Two numeric concerns are how much space this can waste, and whether
2237the computed result can be too small. To be concrete, assume BASE = 2**15,
2238which is the default (and it's unlikely anyone changes that).
2239
2240Waste isn't a problem: provided the first input digit isn't 0, the difference
2241between the worst-case input with N digits and the smallest input with N
2242digits is about a factor of B, but B is small compared to BASE so at most
2243one allocated Python digit can remain unused on that count. If
2244N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2245and adding 1 returns a result 1 larger than necessary. However, that can't
2246happen: whenever B is a power of 2, long_from_binary_base() is called
2247instead, and it's impossible for B**i to be an integer power of 2**15 when
2248B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2249an exact integer when B is not a power of 2, since B**i has a prime factor
2250other than 2 in that case, but (2**15)**j's only prime factor is 2).
2251
2252The computed result can be too small if the true value of N*log(B)/log(BASE)
2253is a little bit larger than an exact integer, but due to roundoff errors (in
2254computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2255yields a numeric result a little less than that integer. Unfortunately, "how
2256close can a transcendental function get to an integer over some range?"
2257questions are generally theoretically intractable. Computer analysis via
2258continued fractions is practical: expand log(B)/log(BASE) via continued
2259fractions, giving a sequence i/j of "the best" rational approximations. Then
2260j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2261we can get very close to being in trouble, but very rarely. For example,
226276573 is a denominator in one of the continued-fraction approximations to
2263log(10)/log(2**15), and indeed:
2264
2265 >>> log(10)/log(2**15)*76573
2266 16958.000000654003
2267
2268is very close to an integer. If we were working with IEEE single-precision,
2269rounding errors could kill us. Finding worst cases in IEEE double-precision
2270requires better-than-double-precision log() functions, and Tim didn't bother.
2271Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002272new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002273This should happen extremely rarely, and in fact I don't have a test case
2274that triggers it(!). Instead the code was tested by artificially allocating
2275just 1 digit at the start, so that the copying code was exercised for every
2276digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002277***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002278 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002280 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 int i;
2282 int convwidth;
2283 twodigits convmultmax, convmult;
2284 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002285 const char *scan, *lastdigit;
2286 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 static double log_base_BASE[37] = {0.0e0,};
2289 static int convwidth_base[37] = {0,};
2290 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 if (log_base_BASE[base] == 0.0) {
2293 twodigits convmax = base;
2294 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002295
Mark Dickinson22b20182010-05-10 21:27:53 +00002296 log_base_BASE[base] = (log((double)base) /
2297 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 for (;;) {
2299 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002300 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002302 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 convmax = next;
2304 ++i;
2305 }
2306 convmultmax_base[base] = convmax;
2307 assert(i > 0);
2308 convwidth_base[base] = i;
2309 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* Find length of the string of numeric characters. */
2312 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002313 lastdigit = str;
2314
2315 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2316 if (*scan == '_') {
2317 if (prev == '_') {
2318 /* Only one underscore allowed. */
2319 str = lastdigit + 1;
2320 goto onError;
2321 }
2322 }
2323 else {
2324 ++digits;
2325 lastdigit = scan;
2326 }
2327 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002329 }
2330 if (prev == '_') {
2331 /* Trailing underscore not allowed. */
2332 /* Set error pointer to first underscore. */
2333 str = lastdigit + 1;
2334 goto onError;
2335 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002336
Serhiy Storchaka95949422013-08-27 19:40:23 +03002337 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 * integer with this base and length. Note that there's no
2339 * need to initialize z->ob_digit -- no slot is read up before
2340 * being stored into.
2341 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002342 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2343 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002344 /* The same exception as in _PyLong_New(). */
2345 PyErr_SetString(PyExc_OverflowError,
2346 "too many digits in integer");
2347 return NULL;
2348 }
2349 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 /* Uncomment next line to test exceedingly rare copy code */
2351 /* size_z = 1; */
2352 assert(size_z > 0);
2353 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002354 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002356 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002357 Py_SET_SIZE(z, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 /* `convwidth` consecutive input digits are treated as a single
2360 * digit in base `convmultmax`.
2361 */
2362 convwidth = convwidth_base[base];
2363 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* Work ;-) */
2366 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002367 if (*str == '_') {
2368 str++;
2369 continue;
2370 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 /* grab up to convwidth digits from the input string */
2372 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002373 for (i = 1; i < convwidth && str != scan; ++str) {
2374 if (*str == '_') {
2375 continue;
2376 }
2377 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002379 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 assert(c < PyLong_BASE);
2381 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 convmult = convmultmax;
2384 /* Calculate the shift only if we couldn't get
2385 * convwidth digits.
2386 */
2387 if (i != convwidth) {
2388 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002389 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002391 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* Multiply z by convmult, and add c. */
2395 pz = z->ob_digit;
2396 pzstop = pz + Py_SIZE(z);
2397 for (; pz < pzstop; ++pz) {
2398 c += (twodigits)*pz * convmult;
2399 *pz = (digit)(c & PyLong_MASK);
2400 c >>= PyLong_SHIFT;
2401 }
2402 /* carry off the current end? */
2403 if (c) {
2404 assert(c < PyLong_BASE);
2405 if (Py_SIZE(z) < size_z) {
2406 *pz = (digit)c;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002407 Py_SET_SIZE(z, Py_SIZE(z) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 }
2409 else {
2410 PyLongObject *tmp;
2411 /* Extremely rare. Get more space. */
2412 assert(Py_SIZE(z) == size_z);
2413 tmp = _PyLong_New(size_z + 1);
2414 if (tmp == NULL) {
2415 Py_DECREF(z);
2416 return NULL;
2417 }
2418 memcpy(tmp->ob_digit,
2419 z->ob_digit,
2420 sizeof(digit) * size_z);
2421 Py_DECREF(z);
2422 z = tmp;
2423 z->ob_digit[size_z] = (digit)c;
2424 ++size_z;
2425 }
2426 }
2427 }
2428 }
Brett Cannona721aba2016-09-09 14:57:09 -07002429 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 if (error_if_nonzero) {
2433 /* reset the base to 0, else the exception message
2434 doesn't make too much sense */
2435 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002436 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002438 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 /* there might still be other problems, therefore base
2440 remains zero here for the same reason */
2441 }
Brett Cannona721aba2016-09-09 14:57:09 -07002442 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002444 }
2445 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002446 Py_SET_SIZE(z, -(Py_SIZE(z)));
Brett Cannona721aba2016-09-09 14:57:09 -07002447 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002448 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002450 }
2451 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002453 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002455 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002456 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002457 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002458 }
2459 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002460 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002461 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002462 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002463
Mark Dickinson22b20182010-05-10 21:27:53 +00002464 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002465 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002466 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 Py_XDECREF(z);
2469 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2470 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002471 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002473 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002475 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 base, strobj);
2477 Py_DECREF(strobj);
2478 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002479}
2480
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002481/* Since PyLong_FromString doesn't have a length parameter,
2482 * check here for possible NULs in the string.
2483 *
2484 * Reports an invalid literal as a bytes object.
2485 */
2486PyObject *
2487_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2488{
2489 PyObject *result, *strobj;
2490 char *end = NULL;
2491
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002492 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002493 if (end == NULL || (result != NULL && end == s + len))
2494 return result;
2495 Py_XDECREF(result);
2496 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2497 if (strobj != NULL) {
2498 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002499 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002500 base, strobj);
2501 Py_DECREF(strobj);
2502 }
2503 return NULL;
2504}
2505
Guido van Rossum9e896b32000-04-05 20:11:21 +00002506PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002507PyLong_FromUnicodeObject(PyObject *u, int base)
2508{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002509 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002510 const char *buffer;
2511 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002512 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002513
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002514 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002515 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002517 assert(PyUnicode_IS_ASCII(asciidig));
2518 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002519 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002520 assert(buffer != NULL);
2521
2522 result = PyLong_FromString(buffer, &end, base);
2523 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002524 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002525 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002527 Py_DECREF(asciidig);
2528 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002529 PyErr_Format(PyExc_ValueError,
2530 "invalid literal for int() with base %d: %.200R",
2531 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002532 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002533}
2534
Tim Peters9f688bf2000-07-07 15:53:28 +00002535/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002536static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002538static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002539
Serhiy Storchaka95949422013-08-27 19:40:23 +03002540/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002541
Guido van Rossume32e0141992-01-19 16:31:05 +00002542static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002543long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002545{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002546 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 if (size_b == 0) {
2550 PyErr_SetString(PyExc_ZeroDivisionError,
2551 "integer division or modulo by zero");
2552 return -1;
2553 }
2554 if (size_a < size_b ||
2555 (size_a == size_b &&
2556 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2557 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002558 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002559 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002560 return -1;
2561 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002562 Py_INCREF(_PyLong_Zero);
2563 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 return 0;
2565 }
2566 if (size_b == 1) {
2567 digit rem = 0;
2568 z = divrem1(a, b->ob_digit[0], &rem);
2569 if (z == NULL)
2570 return -1;
2571 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2572 if (*prem == NULL) {
2573 Py_DECREF(z);
2574 return -1;
2575 }
2576 }
2577 else {
2578 z = x_divrem(a, b, prem);
2579 if (z == NULL)
2580 return -1;
2581 }
2582 /* Set the signs.
2583 The quotient z has the sign of a*b;
2584 the remainder r has the sign of a,
2585 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002586 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2587 _PyLong_Negate(&z);
2588 if (z == NULL) {
2589 Py_CLEAR(*prem);
2590 return -1;
2591 }
2592 }
2593 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2594 _PyLong_Negate(prem);
2595 if (*prem == NULL) {
2596 Py_DECREF(z);
2597 Py_CLEAR(*prem);
2598 return -1;
2599 }
2600 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 *pdiv = maybe_small_long(z);
2602 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002603}
2604
Serhiy Storchaka95949422013-08-27 19:40:23 +03002605/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002606 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002607
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002608static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002609x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 PyLongObject *v, *w, *a;
2612 Py_ssize_t i, k, size_v, size_w;
2613 int d;
2614 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2615 twodigits vv;
2616 sdigit zhi;
2617 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2620 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2621 handle the special case when the initial estimate q for a quotient
2622 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2623 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002626 size_v = Py_ABS(Py_SIZE(v1));
2627 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2629 v = _PyLong_New(size_v+1);
2630 if (v == NULL) {
2631 *prem = NULL;
2632 return NULL;
2633 }
2634 w = _PyLong_New(size_w);
2635 if (w == NULL) {
2636 Py_DECREF(v);
2637 *prem = NULL;
2638 return NULL;
2639 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2642 shift v1 left by the same amount. Results go into w and v. */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02002643 d = PyLong_SHIFT - bit_length_digit(w1->ob_digit[size_w-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2645 assert(carry == 0);
2646 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2647 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2648 v->ob_digit[size_v] = carry;
2649 size_v++;
2650 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2653 at most (and usually exactly) k = size_v - size_w digits. */
2654 k = size_v - size_w;
2655 assert(k >= 0);
2656 a = _PyLong_New(k);
2657 if (a == NULL) {
2658 Py_DECREF(w);
2659 Py_DECREF(v);
2660 *prem = NULL;
2661 return NULL;
2662 }
2663 v0 = v->ob_digit;
2664 w0 = w->ob_digit;
2665 wm1 = w0[size_w-1];
2666 wm2 = w0[size_w-2];
2667 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2668 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2669 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002672 Py_DECREF(a);
2673 Py_DECREF(w);
2674 Py_DECREF(v);
2675 *prem = NULL;
2676 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002677 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 /* estimate quotient digit q; may overestimate by 1 (rare) */
2680 vtop = vk[size_w];
2681 assert(vtop <= wm1);
2682 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2683 q = (digit)(vv / wm1);
2684 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2685 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2686 | vk[size_w-2])) {
2687 --q;
2688 r += wm1;
2689 if (r >= PyLong_BASE)
2690 break;
2691 }
2692 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2695 zhi = 0;
2696 for (i = 0; i < size_w; ++i) {
2697 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2698 -PyLong_BASE * q <= z < PyLong_BASE */
2699 z = (sdigit)vk[i] + zhi -
2700 (stwodigits)q * (stwodigits)w0[i];
2701 vk[i] = (digit)z & PyLong_MASK;
2702 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002703 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 /* add w back if q was too large (this branch taken rarely) */
2707 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2708 if ((sdigit)vtop + zhi < 0) {
2709 carry = 0;
2710 for (i = 0; i < size_w; ++i) {
2711 carry += vk[i] + w0[i];
2712 vk[i] = carry & PyLong_MASK;
2713 carry >>= PyLong_SHIFT;
2714 }
2715 --q;
2716 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 /* store quotient digit */
2719 assert(q < PyLong_BASE);
2720 *--ak = q;
2721 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 /* unshift remainder; we reuse w to store the result */
2724 carry = v_rshift(w0, v0, size_w, d);
2725 assert(carry==0);
2726 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 *prem = long_normalize(w);
2729 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002730}
2731
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002732/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2733 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2734 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2735 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2736 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2737 -1.0. */
2738
2739/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2740#if DBL_MANT_DIG == 53
2741#define EXP2_DBL_MANT_DIG 9007199254740992.0
2742#else
2743#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2744#endif
2745
2746double
2747_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2750 /* See below for why x_digits is always large enough. */
Dong-hee Nab88cd582020-05-04 22:32:42 +09002751 digit rem;
2752 digit x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT] = {0,};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 double dx;
2754 /* Correction term for round-half-to-even rounding. For a digit x,
2755 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2756 multiple of 4, rounding ties to a multiple of 8. */
2757 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002758
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002759 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 if (a_size == 0) {
2761 /* Special case for 0: significand 0.0, exponent 0. */
2762 *e = 0;
2763 return 0.0;
2764 }
Niklas Fiekas794e7d12020-06-15 14:33:48 +02002765 a_bits = bit_length_digit(a->ob_digit[a_size-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 /* The following is an overflow-free version of the check
2767 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2768 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2769 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2770 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002771 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2775 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 Number of digits needed for result: write // for floor division.
2778 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2787 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2790 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2791 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 in both cases.
2798 */
2799 if (a_bits <= DBL_MANT_DIG + 2) {
2800 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2801 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
Dong-hee Nab88cd582020-05-04 22:32:42 +09002802 x_size = shift_digits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2804 (int)shift_bits);
2805 x_size += a_size;
2806 x_digits[x_size++] = rem;
2807 }
2808 else {
2809 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2810 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2811 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2812 a_size - shift_digits, (int)shift_bits);
2813 x_size = a_size - shift_digits;
2814 /* For correct rounding below, we need the least significant
2815 bit of x to be 'sticky' for this shift: if any of the bits
2816 shifted out was nonzero, we set the least significant bit
2817 of x. */
2818 if (rem)
2819 x_digits[0] |= 1;
2820 else
2821 while (shift_digits > 0)
2822 if (a->ob_digit[--shift_digits]) {
2823 x_digits[0] |= 1;
2824 break;
2825 }
2826 }
Victor Stinner63941882011-09-29 00:42:28 +02002827 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 /* Round, and convert to double. */
2830 x_digits[0] += half_even_correction[x_digits[0] & 7];
2831 dx = x_digits[--x_size];
2832 while (x_size > 0)
2833 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 /* Rescale; make correction if result is 1.0. */
2836 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2837 if (dx == 1.0) {
2838 if (a_bits == PY_SSIZE_T_MAX)
2839 goto overflow;
2840 dx = 0.5;
2841 a_bits += 1;
2842 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 *e = a_bits;
2845 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002846
2847 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 /* exponent > PY_SSIZE_T_MAX */
2849 PyErr_SetString(PyExc_OverflowError,
2850 "huge integer: number of bits overflows a Py_ssize_t");
2851 *e = 0;
2852 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002853}
2854
Serhiy Storchaka95949422013-08-27 19:40:23 +03002855/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002856 using the round-half-to-even rule in the case of a tie. */
2857
2858double
2859PyLong_AsDouble(PyObject *v)
2860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 Py_ssize_t exponent;
2862 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002863
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002864 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 PyErr_BadInternalCall();
2866 return -1.0;
2867 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002868 if (!PyLong_Check(v)) {
2869 PyErr_SetString(PyExc_TypeError, "an integer is required");
2870 return -1.0;
2871 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002872 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002873 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002874 to double. This improves performance of FP/long operations
2875 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002876 */
2877 return (double)MEDIUM_VALUE((PyLongObject *)v);
2878 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2880 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2881 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002882 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 return -1.0;
2884 }
2885 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002886}
2887
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002888/* Methods */
2889
HongWeipeng42acb7b2019-09-18 23:10:15 +08002890/* if a < b, return a negative number
2891 if a == b, return 0
2892 if a > b, return a positive number */
2893
2894static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002895long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002896{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002897 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
2898 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002899 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08002900 sdigit diff = 0;
2901 while (--i >= 0) {
2902 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
2903 if (diff) {
2904 break;
2905 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08002907 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08002909 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002910}
2911
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002912static PyObject *
2913long_richcompare(PyObject *self, PyObject *other, int op)
2914{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002915 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 CHECK_BINOP(self, other);
2917 if (self == other)
2918 result = 0;
2919 else
2920 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01002921 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002922}
2923
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002924static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002925long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002926{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002927 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 Py_ssize_t i;
2929 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 i = Py_SIZE(v);
2932 switch(i) {
2933 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2934 case 0: return 0;
2935 case 1: return v->ob_digit[0];
2936 }
2937 sign = 1;
2938 x = 0;
2939 if (i < 0) {
2940 sign = -1;
2941 i = -(i);
2942 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002944 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2945 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2946 _PyHASH_MODULUS.
2947
2948 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2949 amounts to a rotation of the bits of x. To see this, write
2950
2951 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2952
2953 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2954 PyLong_SHIFT bits of x (those that are shifted out of the
2955 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2956 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2957 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2958 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2959 congruent to y modulo _PyHASH_MODULUS. So
2960
2961 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2962
2963 The right-hand side is just the result of rotating the
2964 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2965 not all _PyHASH_BITS bits of x are 1s, the same is true
2966 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2967 the reduction of x*2**PyLong_SHIFT modulo
2968 _PyHASH_MODULUS. */
2969 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2970 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002972 if (x >= _PyHASH_MODULUS)
2973 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 }
2975 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002976 if (x == (Py_uhash_t)-1)
2977 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002978 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002979}
2980
2981
Serhiy Storchaka95949422013-08-27 19:40:23 +03002982/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002983
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002984static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002985x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002986{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002987 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 PyLongObject *z;
2989 Py_ssize_t i;
2990 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 /* Ensure a is the larger of the two: */
2993 if (size_a < size_b) {
2994 { PyLongObject *temp = a; a = b; b = temp; }
2995 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002996 size_a = size_b;
2997 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 }
2999 z = _PyLong_New(size_a+1);
3000 if (z == NULL)
3001 return NULL;
3002 for (i = 0; i < size_b; ++i) {
3003 carry += a->ob_digit[i] + b->ob_digit[i];
3004 z->ob_digit[i] = carry & PyLong_MASK;
3005 carry >>= PyLong_SHIFT;
3006 }
3007 for (; i < size_a; ++i) {
3008 carry += a->ob_digit[i];
3009 z->ob_digit[i] = carry & PyLong_MASK;
3010 carry >>= PyLong_SHIFT;
3011 }
3012 z->ob_digit[i] = carry;
3013 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003014}
3015
3016/* Subtract the absolute values of two integers. */
3017
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003018static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003019x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003020{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003021 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 PyLongObject *z;
3023 Py_ssize_t i;
3024 int sign = 1;
3025 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 /* Ensure a is the larger of the two: */
3028 if (size_a < size_b) {
3029 sign = -1;
3030 { PyLongObject *temp = a; a = b; b = temp; }
3031 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003032 size_a = size_b;
3033 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 }
3035 else if (size_a == size_b) {
3036 /* Find highest digit where a and b differ: */
3037 i = size_a;
3038 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3039 ;
3040 if (i < 0)
3041 return (PyLongObject *)PyLong_FromLong(0);
3042 if (a->ob_digit[i] < b->ob_digit[i]) {
3043 sign = -1;
3044 { PyLongObject *temp = a; a = b; b = temp; }
3045 }
3046 size_a = size_b = i+1;
3047 }
3048 z = _PyLong_New(size_a);
3049 if (z == NULL)
3050 return NULL;
3051 for (i = 0; i < size_b; ++i) {
3052 /* The following assumes unsigned arithmetic
3053 works module 2**N for some N>PyLong_SHIFT. */
3054 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3055 z->ob_digit[i] = borrow & PyLong_MASK;
3056 borrow >>= PyLong_SHIFT;
3057 borrow &= 1; /* Keep only one sign bit */
3058 }
3059 for (; i < size_a; ++i) {
3060 borrow = a->ob_digit[i] - borrow;
3061 z->ob_digit[i] = borrow & PyLong_MASK;
3062 borrow >>= PyLong_SHIFT;
3063 borrow &= 1; /* Keep only one sign bit */
3064 }
3065 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003066 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003067 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02003068 }
HongWeipeng036fe852019-11-26 15:54:49 +08003069 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003070}
3071
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003072static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003073long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003078
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003079 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003080 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 }
3082 if (Py_SIZE(a) < 0) {
3083 if (Py_SIZE(b) < 0) {
3084 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003085 if (z != NULL) {
3086 /* x_add received at least one multiple-digit int,
3087 and thus z must be a multiple-digit int.
3088 That also means z is not an element of
3089 small_ints, so negating it in-place is safe. */
3090 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003091 Py_SET_SIZE(z, -(Py_SIZE(z)));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003092 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 }
3094 else
3095 z = x_sub(b, a);
3096 }
3097 else {
3098 if (Py_SIZE(b) < 0)
3099 z = x_sub(a, b);
3100 else
3101 z = x_add(a, b);
3102 }
3103 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003104}
3105
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003106static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003107long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003112
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003113 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003114 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 }
3116 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003117 if (Py_SIZE(b) < 0) {
3118 z = x_sub(b, a);
3119 }
3120 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003122 if (z != NULL) {
3123 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003124 Py_SET_SIZE(z, -(Py_SIZE(z)));
HongWeipeng036fe852019-11-26 15:54:49 +08003125 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003126 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 }
3128 else {
3129 if (Py_SIZE(b) < 0)
3130 z = x_add(a, b);
3131 else
3132 z = x_sub(a, b);
3133 }
3134 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003135}
3136
Tim Peters5af4e6c2002-08-12 02:31:19 +00003137/* Grade school multiplication, ignoring the signs.
3138 * Returns the absolute value of the product, or NULL if error.
3139 */
3140static PyLongObject *
3141x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003144 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3145 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 z = _PyLong_New(size_a + size_b);
3149 if (z == NULL)
3150 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3153 if (a == b) {
3154 /* Efficient squaring per HAC, Algorithm 14.16:
3155 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3156 * Gives slightly less than a 2x speedup when a == b,
3157 * via exploiting that each entry in the multiplication
3158 * pyramid appears twice (except for the size_a squares).
3159 */
3160 for (i = 0; i < size_a; ++i) {
3161 twodigits carry;
3162 twodigits f = a->ob_digit[i];
3163 digit *pz = z->ob_digit + (i << 1);
3164 digit *pa = a->ob_digit + i + 1;
3165 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003168 Py_DECREF(z);
3169 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003170 });
Tim Peters0973b992004-08-29 22:16:50 +00003171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 carry = *pz + f * f;
3173 *pz++ = (digit)(carry & PyLong_MASK);
3174 carry >>= PyLong_SHIFT;
3175 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 /* Now f is added in twice in each column of the
3178 * pyramid it appears. Same as adding f<<1 once.
3179 */
3180 f <<= 1;
3181 while (pa < paend) {
3182 carry += *pz + *pa++ * f;
3183 *pz++ = (digit)(carry & PyLong_MASK);
3184 carry >>= PyLong_SHIFT;
3185 assert(carry <= (PyLong_MASK << 1));
3186 }
3187 if (carry) {
3188 carry += *pz;
3189 *pz++ = (digit)(carry & PyLong_MASK);
3190 carry >>= PyLong_SHIFT;
3191 }
3192 if (carry)
3193 *pz += (digit)(carry & PyLong_MASK);
3194 assert((carry >> PyLong_SHIFT) == 0);
3195 }
3196 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003197 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 for (i = 0; i < size_a; ++i) {
3199 twodigits carry = 0;
3200 twodigits f = a->ob_digit[i];
3201 digit *pz = z->ob_digit + i;
3202 digit *pb = b->ob_digit;
3203 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003206 Py_DECREF(z);
3207 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003208 });
Tim Peters0973b992004-08-29 22:16:50 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 while (pb < pbend) {
3211 carry += *pz + *pb++ * f;
3212 *pz++ = (digit)(carry & PyLong_MASK);
3213 carry >>= PyLong_SHIFT;
3214 assert(carry <= PyLong_MASK);
3215 }
3216 if (carry)
3217 *pz += (digit)(carry & PyLong_MASK);
3218 assert((carry >> PyLong_SHIFT) == 0);
3219 }
3220 }
3221 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003222}
3223
3224/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003225 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003226 split, and sets low and high such that abs(n) == (high << size) + low,
3227 viewing the shift as being by digits. The sign bit is ignored, and
3228 the return values are >= 0.
3229 Returns 0 on success, -1 on failure.
3230*/
3231static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003232kmul_split(PyLongObject *n,
3233 Py_ssize_t size,
3234 PyLongObject **high,
3235 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 PyLongObject *hi, *lo;
3238 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003239 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003240
Victor Stinner640c35c2013-06-04 23:14:37 +02003241 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 if ((hi = _PyLong_New(size_hi)) == NULL)
3245 return -1;
3246 if ((lo = _PyLong_New(size_lo)) == NULL) {
3247 Py_DECREF(hi);
3248 return -1;
3249 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3252 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 *high = long_normalize(hi);
3255 *low = long_normalize(lo);
3256 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003257}
3258
Tim Peters60004642002-08-12 22:01:34 +00003259static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3260
Tim Peters5af4e6c2002-08-12 02:31:19 +00003261/* Karatsuba multiplication. Ignores the input signs, and returns the
3262 * absolute value of the product (or NULL if error).
3263 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3264 */
3265static PyLongObject *
3266k_mul(PyLongObject *a, PyLongObject *b)
3267{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003268 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3269 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 PyLongObject *ah = NULL;
3271 PyLongObject *al = NULL;
3272 PyLongObject *bh = NULL;
3273 PyLongObject *bl = NULL;
3274 PyLongObject *ret = NULL;
3275 PyLongObject *t1, *t2, *t3;
3276 Py_ssize_t shift; /* the number of digits we split off */
3277 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3280 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3281 * Then the original product is
3282 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3283 * By picking X to be a power of 2, "*X" is just shifting, and it's
3284 * been reduced to 3 multiplies on numbers half the size.
3285 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 /* We want to split based on the larger number; fiddle so that b
3288 * is largest.
3289 */
3290 if (asize > bsize) {
3291 t1 = a;
3292 a = b;
3293 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 i = asize;
3296 asize = bsize;
3297 bsize = i;
3298 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 /* Use gradeschool math when either number is too small. */
3301 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3302 if (asize <= i) {
3303 if (asize == 0)
3304 return (PyLongObject *)PyLong_FromLong(0);
3305 else
3306 return x_mul(a, b);
3307 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 /* If a is small compared to b, splitting on b gives a degenerate
3310 * case with ah==0, and Karatsuba may be (even much) less efficient
3311 * than "grade school" then. However, we can still win, by viewing
3312 * b as a string of "big digits", each of width a->ob_size. That
3313 * leads to a sequence of balanced calls to k_mul.
3314 */
3315 if (2 * asize <= bsize)
3316 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 /* Split a & b into hi & lo pieces. */
3319 shift = bsize >> 1;
3320 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3321 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 if (a == b) {
3324 bh = ah;
3325 bl = al;
3326 Py_INCREF(bh);
3327 Py_INCREF(bl);
3328 }
3329 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 /* The plan:
3332 * 1. Allocate result space (asize + bsize digits: that's always
3333 * enough).
3334 * 2. Compute ah*bh, and copy into result at 2*shift.
3335 * 3. Compute al*bl, and copy into result at 0. Note that this
3336 * can't overlap with #2.
3337 * 4. Subtract al*bl from the result, starting at shift. This may
3338 * underflow (borrow out of the high digit), but we don't care:
3339 * we're effectively doing unsigned arithmetic mod
3340 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3341 * borrows and carries out of the high digit can be ignored.
3342 * 5. Subtract ah*bh from the result, starting at shift.
3343 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3344 * at shift.
3345 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 /* 1. Allocate result space. */
3348 ret = _PyLong_New(asize + bsize);
3349 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003350#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 /* Fill with trash, to catch reference to uninitialized digits. */
3352 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003353#endif
Tim Peters44121a62002-08-12 06:17:58 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3356 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3357 assert(Py_SIZE(t1) >= 0);
3358 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3359 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3360 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 /* Zero-out the digits higher than the ah*bh copy. */
3363 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3364 if (i)
3365 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3366 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 /* 3. t2 <- al*bl, and copy into the low digits. */
3369 if ((t2 = k_mul(al, bl)) == NULL) {
3370 Py_DECREF(t1);
3371 goto fail;
3372 }
3373 assert(Py_SIZE(t2) >= 0);
3374 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3375 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 /* Zero out remaining digits. */
3378 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3379 if (i)
3380 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3383 * because it's fresher in cache.
3384 */
3385 i = Py_SIZE(ret) - shift; /* # digits after shift */
3386 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3387 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3390 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3393 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3394 Py_DECREF(ah);
3395 Py_DECREF(al);
3396 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 if (a == b) {
3399 t2 = t1;
3400 Py_INCREF(t2);
3401 }
3402 else if ((t2 = x_add(bh, bl)) == NULL) {
3403 Py_DECREF(t1);
3404 goto fail;
3405 }
3406 Py_DECREF(bh);
3407 Py_DECREF(bl);
3408 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 t3 = k_mul(t1, t2);
3411 Py_DECREF(t1);
3412 Py_DECREF(t2);
3413 if (t3 == NULL) goto fail;
3414 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 /* Add t3. It's not obvious why we can't run out of room here.
3417 * See the (*) comment after this function.
3418 */
3419 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3420 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003423
Mark Dickinson22b20182010-05-10 21:27:53 +00003424 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 Py_XDECREF(ret);
3426 Py_XDECREF(ah);
3427 Py_XDECREF(al);
3428 Py_XDECREF(bh);
3429 Py_XDECREF(bl);
3430 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003431}
3432
Tim Petersd6974a52002-08-13 20:37:51 +00003433/* (*) Why adding t3 can't "run out of room" above.
3434
Tim Petersab86c2b2002-08-15 20:06:00 +00003435Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3436to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003437
Tim Petersab86c2b2002-08-15 20:06:00 +000034381. For any integer i, i = c(i/2) + f(i/2). In particular,
3439 bsize = c(bsize/2) + f(bsize/2).
34402. shift = f(bsize/2)
34413. asize <= bsize
34424. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3443 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003444
Tim Petersab86c2b2002-08-15 20:06:00 +00003445We allocated asize + bsize result digits, and add t3 into them at an offset
3446of shift. This leaves asize+bsize-shift allocated digit positions for t3
3447to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3448asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003449
Tim Petersab86c2b2002-08-15 20:06:00 +00003450bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3451at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003452
Tim Petersab86c2b2002-08-15 20:06:00 +00003453If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3454digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3455most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003456
Tim Petersab86c2b2002-08-15 20:06:00 +00003457The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003458
Tim Petersab86c2b2002-08-15 20:06:00 +00003459 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003460
Tim Petersab86c2b2002-08-15 20:06:00 +00003461and we have asize + c(bsize/2) available digit positions. We need to show
3462this is always enough. An instance of c(bsize/2) cancels out in both, so
3463the question reduces to whether asize digits is enough to hold
3464(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3465then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3466asize 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 +00003467digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003468asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003469c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3470is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3471bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003472
Tim Peters48d52c02002-08-14 17:07:32 +00003473Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3474clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3475ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003476*/
3477
Tim Peters60004642002-08-12 22:01:34 +00003478/* b has at least twice the digits of a, and a is big enough that Karatsuba
3479 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3480 * of slices, each with a->ob_size digits, and multiply the slices by a,
3481 * one at a time. This gives k_mul balanced inputs to work with, and is
3482 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003483 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003484 * single-width slice overlap between successive partial sums).
3485 */
3486static PyLongObject *
3487k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3488{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003489 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3490 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 Py_ssize_t nbdone; /* # of b digits already multiplied */
3492 PyLongObject *ret;
3493 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 assert(asize > KARATSUBA_CUTOFF);
3496 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 /* Allocate result space, and zero it out. */
3499 ret = _PyLong_New(asize + bsize);
3500 if (ret == NULL)
3501 return NULL;
3502 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 /* Successive slices of b are copied into bslice. */
3505 bslice = _PyLong_New(asize);
3506 if (bslice == NULL)
3507 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 nbdone = 0;
3510 while (bsize > 0) {
3511 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003512 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 /* Multiply the next slice of b by a. */
3515 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3516 nbtouse * sizeof(digit));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003517 Py_SET_SIZE(bslice, nbtouse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 product = k_mul(a, bslice);
3519 if (product == NULL)
3520 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 /* Add into result. */
3523 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3524 product->ob_digit, Py_SIZE(product));
3525 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 bsize -= nbtouse;
3528 nbdone += nbtouse;
3529 }
Tim Peters60004642002-08-12 22:01:34 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 Py_DECREF(bslice);
3532 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003533
Mark Dickinson22b20182010-05-10 21:27:53 +00003534 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 Py_DECREF(ret);
3536 Py_XDECREF(bslice);
3537 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003538}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003539
3540static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003541long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003548 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003550 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 z = k_mul(a, b);
3554 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003555 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3556 _PyLong_Negate(&z);
3557 if (z == NULL)
3558 return NULL;
3559 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003561}
3562
Yury Selivanove0b23092016-02-11 10:26:27 -05003563/* Fast modulo division for single-digit longs. */
3564static PyObject *
3565fast_mod(PyLongObject *a, PyLongObject *b)
3566{
3567 sdigit left = a->ob_digit[0];
3568 sdigit right = b->ob_digit[0];
3569 sdigit mod;
3570
3571 assert(Py_ABS(Py_SIZE(a)) == 1);
3572 assert(Py_ABS(Py_SIZE(b)) == 1);
3573
3574 if (Py_SIZE(a) == Py_SIZE(b)) {
3575 /* 'a' and 'b' have the same sign. */
3576 mod = left % right;
3577 }
3578 else {
3579 /* Either 'a' or 'b' is negative. */
3580 mod = right - 1 - (left - 1) % right;
3581 }
3582
Victor Stinnerf963c132016-03-23 18:36:54 +01003583 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003584}
3585
3586/* Fast floor division for single-digit longs. */
3587static PyObject *
3588fast_floor_div(PyLongObject *a, PyLongObject *b)
3589{
3590 sdigit left = a->ob_digit[0];
3591 sdigit right = b->ob_digit[0];
3592 sdigit div;
3593
3594 assert(Py_ABS(Py_SIZE(a)) == 1);
3595 assert(Py_ABS(Py_SIZE(b)) == 1);
3596
3597 if (Py_SIZE(a) == Py_SIZE(b)) {
3598 /* 'a' and 'b' have the same sign. */
3599 div = left / right;
3600 }
3601 else {
3602 /* Either 'a' or 'b' is negative. */
3603 div = -1 - (left - 1) / right;
3604 }
3605
3606 return PyLong_FromLong(div);
3607}
3608
Guido van Rossume32e0141992-01-19 16:31:05 +00003609/* The / and % operators are now defined in terms of divmod().
3610 The expression a mod b has the value a - b*floor(a/b).
3611 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003612 |a| by |b|, with the sign of a. This is also expressed
3613 as a - b*trunc(a/b), if trunc truncates towards zero.
3614 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 a b a rem b a mod b
3616 13 10 3 3
3617 -13 10 -3 7
3618 13 -10 3 -7
3619 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003620 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003621 have different signs. We then subtract one from the 'div'
3622 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003623
Tim Peters47e52ee2004-08-30 02:44:38 +00003624/* Compute
3625 * *pdiv, *pmod = divmod(v, w)
3626 * NULL can be passed for pdiv or pmod, in which case that part of
3627 * the result is simply thrown away. The caller owns a reference to
3628 * each of these it requests (does not pass NULL for).
3629 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003630static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003631l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003635
Yury Selivanove0b23092016-02-11 10:26:27 -05003636 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3637 /* Fast path for single-digit longs */
3638 div = NULL;
3639 if (pdiv != NULL) {
3640 div = (PyLongObject *)fast_floor_div(v, w);
3641 if (div == NULL) {
3642 return -1;
3643 }
3644 }
3645 if (pmod != NULL) {
3646 mod = (PyLongObject *)fast_mod(v, w);
3647 if (mod == NULL) {
3648 Py_XDECREF(div);
3649 return -1;
3650 }
3651 *pmod = mod;
3652 }
3653 if (pdiv != NULL) {
3654 /* We only want to set `*pdiv` when `*pmod` is
3655 set successfully. */
3656 *pdiv = div;
3657 }
3658 return 0;
3659 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 if (long_divrem(v, w, &div, &mod) < 0)
3661 return -1;
3662 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3663 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3664 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 temp = (PyLongObject *) long_add(mod, w);
3666 Py_DECREF(mod);
3667 mod = temp;
3668 if (mod == NULL) {
3669 Py_DECREF(div);
3670 return -1;
3671 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003672 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3673 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 Py_DECREF(mod);
3675 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 return -1;
3677 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 Py_DECREF(div);
3679 div = temp;
3680 }
3681 if (pdiv != NULL)
3682 *pdiv = div;
3683 else
3684 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 if (pmod != NULL)
3687 *pmod = mod;
3688 else
3689 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003692}
3693
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003694static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003695long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003700
3701 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3702 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3703 }
3704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3706 div = NULL;
3707 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003708}
3709
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003710/* PyLong/PyLong -> float, with correctly rounded result. */
3711
3712#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3713#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3714
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003715static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003716long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 PyLongObject *a, *b, *x;
3719 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3720 digit mask, low;
3721 int inexact, negate, a_is_small, b_is_small;
3722 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 CHECK_BINOP(v, w);
3725 a = (PyLongObject *)v;
3726 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 /*
3729 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3732 1. choose a suitable integer 'shift'
3733 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3734 3. adjust x for correct rounding
3735 4. convert x to a double dx with the same value
3736 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3741 returns either 0.0 or -0.0, depending on the sign of b. For a and
3742 b both nonzero, ignore signs of a and b, and add the sign back in
3743 at the end. Now write a_bits and b_bits for the bit lengths of a
3744 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3745 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3750 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3751 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3752 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 1. The integer 'shift' is chosen so that x has the right number of
3757 bits for a double, plus two or three extra bits that will be used
3758 in the rounding decisions. Writing a_bits and b_bits for the
3759 number of significant bits in a and b respectively, a
3760 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 This is fine in the usual case, but if a/b is smaller than the
3765 smallest normal float then it can lead to double rounding on an
3766 IEEE 754 platform, giving incorrectly rounded results. So we
3767 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 2. The quantity x is computed by first shifting a (left -shift bits
3772 if shift <= 0, right shift bits if shift > 0) and then dividing by
3773 b. For both the shift and the division, we keep track of whether
3774 the result is inexact, in a flag 'inexact'; this information is
3775 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 With the choice of shift above, together with our assumption that
3778 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3779 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3782 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 For float representability, we need x/2**extra_bits <
3787 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3788 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 To round, we just modify the bottom digit of x in-place; this can
3793 end up giving a digit with value > PyLONG_MASK, but that's not a
3794 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 With the original choices for shift above, extra_bits will always
3797 be 2 or 3. Then rounding under the round-half-to-even rule, we
3798 round up iff the most significant of the extra bits is 1, and
3799 either: (a) the computation of x in step 2 had an inexact result,
3800 or (b) at least one other of the extra bits is 1, or (c) the least
3801 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 4. Conversion to a double is straightforward; all floating-point
3804 operations involved in the conversion are exact, so there's no
3805 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3808 The result will always be exactly representable as a double, except
3809 in the case that it overflows. To avoid dependence on the exact
3810 behaviour of ldexp on overflow, we check for overflow before
3811 applying ldexp. The result of ldexp is adjusted for sign before
3812 returning.
3813 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003816 a_size = Py_ABS(Py_SIZE(a));
3817 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3819 if (b_size == 0) {
3820 PyErr_SetString(PyExc_ZeroDivisionError,
3821 "division by zero");
3822 goto error;
3823 }
3824 if (a_size == 0)
3825 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 /* Fast path for a and b small (exactly representable in a double).
3828 Relies on floating-point division being correctly rounded; results
3829 may be subject to double rounding on x86 machines that operate with
3830 the x87 FPU set to 64-bit precision. */
3831 a_is_small = a_size <= MANT_DIG_DIGITS ||
3832 (a_size == MANT_DIG_DIGITS+1 &&
3833 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3834 b_is_small = b_size <= MANT_DIG_DIGITS ||
3835 (b_size == MANT_DIG_DIGITS+1 &&
3836 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3837 if (a_is_small && b_is_small) {
3838 double da, db;
3839 da = a->ob_digit[--a_size];
3840 while (a_size > 0)
3841 da = da * PyLong_BASE + a->ob_digit[--a_size];
3842 db = b->ob_digit[--b_size];
3843 while (b_size > 0)
3844 db = db * PyLong_BASE + b->ob_digit[--b_size];
3845 result = da / db;
3846 goto success;
3847 }
Tim Peterse2a60002001-09-04 06:17:36 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 /* Catch obvious cases of underflow and overflow */
3850 diff = a_size - b_size;
3851 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3852 /* Extreme overflow */
3853 goto overflow;
3854 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3855 /* Extreme underflow */
3856 goto underflow_or_zero;
3857 /* Next line is now safe from overflowing a Py_ssize_t */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02003858 diff = diff * PyLong_SHIFT + bit_length_digit(a->ob_digit[a_size - 1]) -
3859 bit_length_digit(b->ob_digit[b_size - 1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 /* Now diff = a_bits - b_bits. */
3861 if (diff > DBL_MAX_EXP)
3862 goto overflow;
3863 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3864 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003867 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 /* x = abs(a * 2**-shift) */
3872 if (shift <= 0) {
3873 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3874 digit rem;
3875 /* x = a << -shift */
3876 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3877 /* In practice, it's probably impossible to end up
3878 here. Both a and b would have to be enormous,
3879 using close to SIZE_T_MAX bytes of memory each. */
3880 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003881 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 goto error;
3883 }
3884 x = _PyLong_New(a_size + shift_digits + 1);
3885 if (x == NULL)
3886 goto error;
3887 for (i = 0; i < shift_digits; i++)
3888 x->ob_digit[i] = 0;
3889 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3890 a_size, -shift % PyLong_SHIFT);
3891 x->ob_digit[a_size + shift_digits] = rem;
3892 }
3893 else {
3894 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3895 digit rem;
3896 /* x = a >> shift */
3897 assert(a_size >= shift_digits);
3898 x = _PyLong_New(a_size - shift_digits);
3899 if (x == NULL)
3900 goto error;
3901 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3902 a_size - shift_digits, shift % PyLong_SHIFT);
3903 /* set inexact if any of the bits shifted out is nonzero */
3904 if (rem)
3905 inexact = 1;
3906 while (!inexact && shift_digits > 0)
3907 if (a->ob_digit[--shift_digits])
3908 inexact = 1;
3909 }
3910 long_normalize(x);
3911 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3914 reference to x, so it's safe to modify it in-place. */
3915 if (b_size == 1) {
3916 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3917 b->ob_digit[0]);
3918 long_normalize(x);
3919 if (rem)
3920 inexact = 1;
3921 }
3922 else {
3923 PyLongObject *div, *rem;
3924 div = x_divrem(x, b, &rem);
3925 Py_DECREF(x);
3926 x = div;
3927 if (x == NULL)
3928 goto error;
3929 if (Py_SIZE(rem))
3930 inexact = 1;
3931 Py_DECREF(rem);
3932 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003933 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 assert(x_size > 0); /* result of division is never zero */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02003935 x_bits = (x_size-1)*PyLong_SHIFT+bit_length_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003938 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 /* Round by directly modifying the low digit of x. */
3942 mask = (digit)1 << (extra_bits - 1);
3943 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003944 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003946 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 /* Convert x to a double dx; the conversion is exact. */
3949 dx = x->ob_digit[--x_size];
3950 while (x_size > 0)
3951 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3952 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 /* Check whether ldexp result will overflow a double. */
3955 if (shift + x_bits >= DBL_MAX_EXP &&
3956 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3957 goto overflow;
3958 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003959
3960 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003962
3963 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003965
3966 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 PyErr_SetString(PyExc_OverflowError,
3968 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003969 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003971}
3972
3973static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003974long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 CHECK_BINOP(a, b);
3979
Yury Selivanove0b23092016-02-11 10:26:27 -05003980 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3981 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
3982 }
3983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003984 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3985 mod = NULL;
3986 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003987}
3988
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003989static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003990long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003992 PyLongObject *div, *mod;
3993 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003995 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3998 return NULL;
3999 }
4000 z = PyTuple_New(2);
4001 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004002 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4003 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 }
4005 else {
4006 Py_DECREF(div);
4007 Py_DECREF(mod);
4008 }
4009 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004010}
4011
Mark Dickinsonc5299672019-06-02 10:24:06 +01004012
4013/* Compute an inverse to a modulo n, or raise ValueError if a is not
4014 invertible modulo n. Assumes n is positive. The inverse returned
4015 is whatever falls out of the extended Euclidean algorithm: it may
4016 be either positive or negative, but will be smaller than n in
4017 absolute value.
4018
4019 Pure Python equivalent for long_invmod:
4020
4021 def invmod(a, n):
4022 b, c = 1, 0
4023 while n:
4024 q, r = divmod(a, n)
4025 a, b, c, n = n, c, b - q*c, r
4026
4027 # at this point a is the gcd of the original inputs
4028 if a == 1:
4029 return b
4030 raise ValueError("Not invertible")
4031*/
4032
4033static PyLongObject *
4034long_invmod(PyLongObject *a, PyLongObject *n)
4035{
4036 PyLongObject *b, *c;
4037
4038 /* Should only ever be called for positive n */
4039 assert(Py_SIZE(n) > 0);
4040
4041 b = (PyLongObject *)PyLong_FromLong(1L);
4042 if (b == NULL) {
4043 return NULL;
4044 }
4045 c = (PyLongObject *)PyLong_FromLong(0L);
4046 if (c == NULL) {
4047 Py_DECREF(b);
4048 return NULL;
4049 }
4050 Py_INCREF(a);
4051 Py_INCREF(n);
4052
4053 /* references now owned: a, b, c, n */
4054 while (Py_SIZE(n) != 0) {
4055 PyLongObject *q, *r, *s, *t;
4056
4057 if (l_divmod(a, n, &q, &r) == -1) {
4058 goto Error;
4059 }
4060 Py_DECREF(a);
4061 a = n;
4062 n = r;
4063 t = (PyLongObject *)long_mul(q, c);
4064 Py_DECREF(q);
4065 if (t == NULL) {
4066 goto Error;
4067 }
4068 s = (PyLongObject *)long_sub(b, t);
4069 Py_DECREF(t);
4070 if (s == NULL) {
4071 goto Error;
4072 }
4073 Py_DECREF(b);
4074 b = c;
4075 c = s;
4076 }
4077 /* references now owned: a, b, c, n */
4078
4079 Py_DECREF(c);
4080 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004081 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004082 /* a != 1; we don't have an inverse. */
4083 Py_DECREF(a);
4084 Py_DECREF(b);
4085 PyErr_SetString(PyExc_ValueError,
4086 "base is not invertible for the given modulus");
4087 return NULL;
4088 }
4089 else {
4090 /* a == 1; b gives an inverse modulo n */
4091 Py_DECREF(a);
4092 return b;
4093 }
4094
4095 Error:
4096 Py_DECREF(a);
4097 Py_DECREF(b);
4098 Py_DECREF(c);
4099 Py_DECREF(n);
4100 return NULL;
4101}
4102
4103
Tim Peters47e52ee2004-08-30 02:44:38 +00004104/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004105static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004106long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4109 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 PyLongObject *z = NULL; /* accumulated result */
4112 Py_ssize_t i, j, k; /* counters */
4113 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 /* 5-ary values. If the exponent is large enough, table is
4116 * precomputed so that table[i] == a**i % c for i in range(32).
4117 */
4118 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4119 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 /* a, b, c = v, w, x */
4122 CHECK_BINOP(v, w);
4123 a = (PyLongObject*)v; Py_INCREF(a);
4124 b = (PyLongObject*)w; Py_INCREF(b);
4125 if (PyLong_Check(x)) {
4126 c = (PyLongObject *)x;
4127 Py_INCREF(x);
4128 }
4129 else if (x == Py_None)
4130 c = NULL;
4131 else {
4132 Py_DECREF(a);
4133 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004134 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 }
Tim Peters4c483c42001-09-05 06:24:58 +00004136
Mark Dickinsonc5299672019-06-02 10:24:06 +01004137 if (Py_SIZE(b) < 0 && c == NULL) {
4138 /* if exponent is negative and there's no modulus:
4139 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 that this calls float_pow() which converts its
4141 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004142 Py_DECREF(a);
4143 Py_DECREF(b);
4144 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 if (c) {
4148 /* if modulus == 0:
4149 raise ValueError() */
4150 if (Py_SIZE(c) == 0) {
4151 PyErr_SetString(PyExc_ValueError,
4152 "pow() 3rd argument cannot be 0");
4153 goto Error;
4154 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 /* if modulus < 0:
4157 negativeOutput = True
4158 modulus = -modulus */
4159 if (Py_SIZE(c) < 0) {
4160 negativeOutput = 1;
4161 temp = (PyLongObject *)_PyLong_Copy(c);
4162 if (temp == NULL)
4163 goto Error;
4164 Py_DECREF(c);
4165 c = temp;
4166 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004167 _PyLong_Negate(&c);
4168 if (c == NULL)
4169 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 /* if modulus == 1:
4173 return 0 */
4174 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4175 z = (PyLongObject *)PyLong_FromLong(0L);
4176 goto Done;
4177 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004178
Mark Dickinsonc5299672019-06-02 10:24:06 +01004179 /* if exponent is negative, negate the exponent and
4180 replace the base with a modular inverse */
4181 if (Py_SIZE(b) < 0) {
4182 temp = (PyLongObject *)_PyLong_Copy(b);
4183 if (temp == NULL)
4184 goto Error;
4185 Py_DECREF(b);
4186 b = temp;
4187 temp = NULL;
4188 _PyLong_Negate(&b);
4189 if (b == NULL)
4190 goto Error;
4191
4192 temp = long_invmod(a, c);
4193 if (temp == NULL)
4194 goto Error;
4195 Py_DECREF(a);
4196 a = temp;
4197 }
4198
Tim Peters81a93152013-10-05 16:53:52 -05004199 /* Reduce base by modulus in some cases:
4200 1. If base < 0. Forcing the base non-negative makes things easier.
4201 2. If base is obviously larger than the modulus. The "small
4202 exponent" case later can multiply directly by base repeatedly,
4203 while the "large exponent" case multiplies directly by base 31
4204 times. It can be unboundedly faster to multiply by
4205 base % modulus instead.
4206 We could _always_ do this reduction, but l_divmod() isn't cheap,
4207 so we only do it when it buys something. */
4208 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 if (l_divmod(a, c, NULL, &temp) < 0)
4210 goto Error;
4211 Py_DECREF(a);
4212 a = temp;
4213 temp = NULL;
4214 }
4215 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 /* At this point a, b, and c are guaranteed non-negative UNLESS
4218 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 z = (PyLongObject *)PyLong_FromLong(1L);
4221 if (z == NULL)
4222 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 /* Perform a modular reduction, X = X % c, but leave X alone if c
4225 * is NULL.
4226 */
4227#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004228 do { \
4229 if (c != NULL) { \
4230 if (l_divmod(X, c, NULL, &temp) < 0) \
4231 goto Error; \
4232 Py_XDECREF(X); \
4233 X = temp; \
4234 temp = NULL; \
4235 } \
4236 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 /* Multiply two values, then reduce the result:
4239 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004240#define MULT(X, Y, result) \
4241 do { \
4242 temp = (PyLongObject *)long_mul(X, Y); \
4243 if (temp == NULL) \
4244 goto Error; \
4245 Py_XDECREF(result); \
4246 result = temp; \
4247 temp = NULL; \
4248 REDUCE(result); \
4249 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4252 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4253 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4254 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4255 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004258 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004260 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 }
4262 }
4263 }
4264 else {
4265 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4266 Py_INCREF(z); /* still holds 1L */
4267 table[0] = z;
4268 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004269 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4272 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4275 const int index = (bi >> j) & 0x1f;
4276 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004277 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004279 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 }
4281 }
4282 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 if (negativeOutput && (Py_SIZE(z) != 0)) {
4285 temp = (PyLongObject *)long_sub(z, c);
4286 if (temp == NULL)
4287 goto Error;
4288 Py_DECREF(z);
4289 z = temp;
4290 temp = NULL;
4291 }
4292 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004293
Mark Dickinson22b20182010-05-10 21:27:53 +00004294 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004295 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004297 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4299 for (i = 0; i < 32; ++i)
4300 Py_XDECREF(table[i]);
4301 }
4302 Py_DECREF(a);
4303 Py_DECREF(b);
4304 Py_XDECREF(c);
4305 Py_XDECREF(temp);
4306 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004307}
4308
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004309static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004310long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 /* Implement ~x as -(x+1) */
4313 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004314 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004316 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 if (x == NULL)
4318 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004319 _PyLong_Negate(&x);
4320 /* No need for maybe_small_long here, since any small
4321 longs will have been caught in the Py_SIZE <= 1 fast path. */
4322 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004323}
4324
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004325static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004326long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004329 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330 return PyLong_FromLong(-MEDIUM_VALUE(v));
4331 z = (PyLongObject *)_PyLong_Copy(v);
4332 if (z != NULL)
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004333 Py_SET_SIZE(z, -(Py_SIZE(v)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004335}
4336
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004337static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004338long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 if (Py_SIZE(v) < 0)
4341 return long_neg(v);
4342 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004343 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004344}
4345
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004346static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004347long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004350}
4351
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004352/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4353static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004354divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004355{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004356 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004357 assert(Py_SIZE(shiftby) >= 0);
4358 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4359 if (lshiftby >= 0) {
4360 *wordshift = lshiftby / PyLong_SHIFT;
4361 *remshift = lshiftby % PyLong_SHIFT;
4362 return 0;
4363 }
4364 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4365 be that PyLong_AsSsize_t raised an OverflowError. */
4366 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4367 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004368 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004369 if (wordshift_obj == NULL) {
4370 return -1;
4371 }
4372 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4373 Py_DECREF(wordshift_obj);
4374 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4375 return 0;
4376 }
4377 PyErr_Clear();
4378 /* Clip the value. With such large wordshift the right shift
4379 returns 0 and the left shift raises an error in _PyLong_New(). */
4380 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4381 *remshift = 0;
4382 return 0;
4383}
4384
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004385static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004386long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004389 Py_ssize_t newsize, hishift, i, j;
4390 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 if (Py_SIZE(a) < 0) {
4393 /* Right shifting negative numbers is harder */
4394 PyLongObject *a1, *a2;
4395 a1 = (PyLongObject *) long_invert(a);
4396 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004397 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004398 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 Py_DECREF(a1);
4400 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004401 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 z = (PyLongObject *) long_invert(a2);
4403 Py_DECREF(a2);
4404 }
4405 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004406 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 if (newsize <= 0)
4408 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004409 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 lomask = ((digit)1 << hishift) - 1;
4411 himask = PyLong_MASK ^ lomask;
4412 z = _PyLong_New(newsize);
4413 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004414 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004416 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004418 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004420 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004422 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004423}
4424
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004425static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004426long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004427{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004428 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004429 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004432
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004433 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004435 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004437 if (Py_SIZE(a) == 0) {
4438 return PyLong_FromLong(0);
4439 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004440 if (divmod_shift(b, &wordshift, &remshift) < 0)
4441 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004442 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4443}
4444
4445/* Return a >> shiftby. */
4446PyObject *
4447_PyLong_Rshift(PyObject *a, size_t shiftby)
4448{
4449 Py_ssize_t wordshift;
4450 digit remshift;
4451
4452 assert(PyLong_Check(a));
4453 if (Py_SIZE(a) == 0) {
4454 return PyLong_FromLong(0);
4455 }
4456 wordshift = shiftby / PyLong_SHIFT;
4457 remshift = shiftby % PyLong_SHIFT;
4458 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4459}
4460
4461static PyObject *
4462long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4463{
4464 /* This version due to Tim Peters */
4465 PyLongObject *z = NULL;
4466 Py_ssize_t oldsize, newsize, i, j;
4467 twodigits accum;
4468
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004469 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 newsize = oldsize + wordshift;
4471 if (remshift)
4472 ++newsize;
4473 z = _PyLong_New(newsize);
4474 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004475 return NULL;
4476 if (Py_SIZE(a) < 0) {
4477 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004478 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02004479 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 for (i = 0; i < wordshift; i++)
4481 z->ob_digit[i] = 0;
4482 accum = 0;
4483 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4484 accum |= (twodigits)a->ob_digit[j] << remshift;
4485 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4486 accum >>= PyLong_SHIFT;
4487 }
4488 if (remshift)
4489 z->ob_digit[newsize-1] = (digit)accum;
4490 else
4491 assert(!accum);
4492 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004494}
4495
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004496static PyObject *
4497long_lshift(PyObject *a, PyObject *b)
4498{
4499 Py_ssize_t wordshift;
4500 digit remshift;
4501
4502 CHECK_BINOP(a, b);
4503
4504 if (Py_SIZE(b) < 0) {
4505 PyErr_SetString(PyExc_ValueError, "negative shift count");
4506 return NULL;
4507 }
4508 if (Py_SIZE(a) == 0) {
4509 return PyLong_FromLong(0);
4510 }
4511 if (divmod_shift(b, &wordshift, &remshift) < 0)
4512 return NULL;
4513 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4514}
4515
4516/* Return a << shiftby. */
4517PyObject *
4518_PyLong_Lshift(PyObject *a, size_t shiftby)
4519{
4520 Py_ssize_t wordshift;
4521 digit remshift;
4522
4523 assert(PyLong_Check(a));
4524 if (Py_SIZE(a) == 0) {
4525 return PyLong_FromLong(0);
4526 }
4527 wordshift = shiftby / PyLong_SHIFT;
4528 remshift = shiftby % PyLong_SHIFT;
4529 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4530}
4531
Mark Dickinson27a87a22009-10-25 20:43:34 +00004532/* Compute two's complement of digit vector a[0:m], writing result to
4533 z[0:m]. The digit vector a need not be normalized, but should not
4534 be entirely zero. a and z may point to the same digit vector. */
4535
4536static void
4537v_complement(digit *z, digit *a, Py_ssize_t m)
4538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 Py_ssize_t i;
4540 digit carry = 1;
4541 for (i = 0; i < m; ++i) {
4542 carry += a[i] ^ PyLong_MASK;
4543 z[i] = carry & PyLong_MASK;
4544 carry >>= PyLong_SHIFT;
4545 }
4546 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004547}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004548
4549/* Bitwise and/xor/or operations */
4550
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004551static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004552long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004553 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004554 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 int nega, negb, negz;
4557 Py_ssize_t size_a, size_b, size_z, i;
4558 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 /* Bitwise operations for negative numbers operate as though
4561 on a two's complement representation. So convert arguments
4562 from sign-magnitude to two's complement, and convert the
4563 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004565 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004566 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 nega = Py_SIZE(a) < 0;
4568 if (nega) {
4569 z = _PyLong_New(size_a);
4570 if (z == NULL)
4571 return NULL;
4572 v_complement(z->ob_digit, a->ob_digit, size_a);
4573 a = z;
4574 }
4575 else
4576 /* Keep reference count consistent. */
4577 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004579 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004580 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 negb = Py_SIZE(b) < 0;
4582 if (negb) {
4583 z = _PyLong_New(size_b);
4584 if (z == NULL) {
4585 Py_DECREF(a);
4586 return NULL;
4587 }
4588 v_complement(z->ob_digit, b->ob_digit, size_b);
4589 b = z;
4590 }
4591 else
4592 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 /* Swap a and b if necessary to ensure size_a >= size_b. */
4595 if (size_a < size_b) {
4596 z = a; a = b; b = z;
4597 size_z = size_a; size_a = size_b; size_b = size_z;
4598 negz = nega; nega = negb; negb = negz;
4599 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 /* JRH: The original logic here was to allocate the result value (z)
4602 as the longer of the two operands. However, there are some cases
4603 where the result is guaranteed to be shorter than that: AND of two
4604 positives, OR of two negatives: use the shorter number. AND with
4605 mixed signs: use the positive number. OR with mixed signs: use the
4606 negative number.
4607 */
4608 switch (op) {
4609 case '^':
4610 negz = nega ^ negb;
4611 size_z = size_a;
4612 break;
4613 case '&':
4614 negz = nega & negb;
4615 size_z = negb ? size_a : size_b;
4616 break;
4617 case '|':
4618 negz = nega | negb;
4619 size_z = negb ? size_b : size_a;
4620 break;
4621 default:
stratakisa10d4262019-03-18 18:59:20 +01004622 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 /* We allow an extra digit if z is negative, to make sure that
4626 the final two's complement of z doesn't overflow. */
4627 z = _PyLong_New(size_z + negz);
4628 if (z == NULL) {
4629 Py_DECREF(a);
4630 Py_DECREF(b);
4631 return NULL;
4632 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 /* Compute digits for overlap of a and b. */
4635 switch(op) {
4636 case '&':
4637 for (i = 0; i < size_b; ++i)
4638 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4639 break;
4640 case '|':
4641 for (i = 0; i < size_b; ++i)
4642 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4643 break;
4644 case '^':
4645 for (i = 0; i < size_b; ++i)
4646 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4647 break;
4648 default:
stratakisa10d4262019-03-18 18:59:20 +01004649 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 /* Copy any remaining digits of a, inverting if necessary. */
4653 if (op == '^' && negb)
4654 for (; i < size_z; ++i)
4655 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4656 else if (i < size_z)
4657 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4658 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 /* Complement result if negative. */
4661 if (negz) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004662 Py_SET_SIZE(z, -(Py_SIZE(z)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 z->ob_digit[size_z] = PyLong_MASK;
4664 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4665 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 Py_DECREF(a);
4668 Py_DECREF(b);
4669 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004670}
4671
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004672static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004673long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 PyObject *c;
4676 CHECK_BINOP(a, b);
4677 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4678 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004679}
4680
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004681static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004682long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 PyObject *c;
4685 CHECK_BINOP(a, b);
4686 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4687 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004688}
4689
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004690static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004691long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004693 PyObject *c;
4694 CHECK_BINOP(a, b);
4695 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4696 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004697}
4698
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004699static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004700long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004702 if (PyLong_CheckExact(v))
4703 Py_INCREF(v);
4704 else
4705 v = _PyLong_Copy((PyLongObject *)v);
4706 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004707}
4708
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004709PyObject *
4710_PyLong_GCD(PyObject *aarg, PyObject *barg)
4711{
4712 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4713 stwodigits x, y, q, s, t, c_carry, d_carry;
4714 stwodigits A, B, C, D, T;
4715 int nbits, k;
4716 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4717 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4718
4719 a = (PyLongObject *)aarg;
4720 b = (PyLongObject *)barg;
4721 size_a = Py_SIZE(a);
4722 size_b = Py_SIZE(b);
4723 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4724 Py_INCREF(a);
4725 Py_INCREF(b);
4726 goto simple;
4727 }
4728
4729 /* Initial reduction: make sure that 0 <= b <= a. */
4730 a = (PyLongObject *)long_abs(a);
4731 if (a == NULL)
4732 return NULL;
4733 b = (PyLongObject *)long_abs(b);
4734 if (b == NULL) {
4735 Py_DECREF(a);
4736 return NULL;
4737 }
4738 if (long_compare(a, b) < 0) {
4739 r = a;
4740 a = b;
4741 b = r;
4742 }
4743 /* We now own references to a and b */
4744
4745 alloc_a = Py_SIZE(a);
4746 alloc_b = Py_SIZE(b);
4747 /* reduce until a fits into 2 digits */
4748 while ((size_a = Py_SIZE(a)) > 2) {
Niklas Fiekas794e7d12020-06-15 14:33:48 +02004749 nbits = bit_length_digit(a->ob_digit[size_a-1]);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004750 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4751 corresponding bits of b into y */
4752 size_b = Py_SIZE(b);
4753 assert(size_b <= size_a);
4754 if (size_b == 0) {
4755 if (size_a < alloc_a) {
4756 r = (PyLongObject *)_PyLong_Copy(a);
4757 Py_DECREF(a);
4758 }
4759 else
4760 r = a;
4761 Py_DECREF(b);
4762 Py_XDECREF(c);
4763 Py_XDECREF(d);
4764 return (PyObject *)r;
4765 }
4766 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4767 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4768 (a->ob_digit[size_a-3] >> nbits));
4769
4770 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4771 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4772 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4773
4774 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4775 larger than PyLong_MASK during the algorithm. */
4776 A = 1; B = 0; C = 0; D = 1;
4777 for (k=0;; k++) {
4778 if (y-C == 0)
4779 break;
4780 q = (x+(A-1))/(y-C);
4781 s = B+q*D;
4782 t = x-q*y;
4783 if (s > t)
4784 break;
4785 x = y; y = t;
4786 t = A+q*C; A = D; B = C; C = s; D = t;
4787 }
4788
4789 if (k == 0) {
4790 /* no progress; do a Euclidean step */
4791 if (l_divmod(a, b, NULL, &r) < 0)
4792 goto error;
4793 Py_DECREF(a);
4794 a = b;
4795 b = r;
4796 alloc_a = alloc_b;
4797 alloc_b = Py_SIZE(b);
4798 continue;
4799 }
4800
4801 /*
4802 a, b = A*b-B*a, D*a-C*b if k is odd
4803 a, b = A*a-B*b, D*b-C*a if k is even
4804 */
4805 if (k&1) {
4806 T = -A; A = -B; B = T;
4807 T = -C; C = -D; D = T;
4808 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004809 if (c != NULL) {
4810 Py_SET_SIZE(c, size_a);
4811 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004812 else if (Py_REFCNT(a) == 1) {
4813 Py_INCREF(a);
4814 c = a;
4815 }
4816 else {
4817 alloc_a = size_a;
4818 c = _PyLong_New(size_a);
4819 if (c == NULL)
4820 goto error;
4821 }
4822
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004823 if (d != NULL) {
4824 Py_SET_SIZE(d, size_a);
4825 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004826 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4827 Py_INCREF(b);
4828 d = b;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004829 Py_SET_SIZE(d, size_a);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004830 }
4831 else {
4832 alloc_b = size_a;
4833 d = _PyLong_New(size_a);
4834 if (d == NULL)
4835 goto error;
4836 }
4837 a_end = a->ob_digit + size_a;
4838 b_end = b->ob_digit + size_b;
4839
4840 /* compute new a and new b in parallel */
4841 a_digit = a->ob_digit;
4842 b_digit = b->ob_digit;
4843 c_digit = c->ob_digit;
4844 d_digit = d->ob_digit;
4845 c_carry = 0;
4846 d_carry = 0;
4847 while (b_digit < b_end) {
4848 c_carry += (A * *a_digit) - (B * *b_digit);
4849 d_carry += (D * *b_digit++) - (C * *a_digit++);
4850 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4851 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4852 c_carry >>= PyLong_SHIFT;
4853 d_carry >>= PyLong_SHIFT;
4854 }
4855 while (a_digit < a_end) {
4856 c_carry += A * *a_digit;
4857 d_carry -= C * *a_digit++;
4858 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4859 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4860 c_carry >>= PyLong_SHIFT;
4861 d_carry >>= PyLong_SHIFT;
4862 }
4863 assert(c_carry == 0);
4864 assert(d_carry == 0);
4865
4866 Py_INCREF(c);
4867 Py_INCREF(d);
4868 Py_DECREF(a);
4869 Py_DECREF(b);
4870 a = long_normalize(c);
4871 b = long_normalize(d);
4872 }
4873 Py_XDECREF(c);
4874 Py_XDECREF(d);
4875
4876simple:
4877 assert(Py_REFCNT(a) > 0);
4878 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004879/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4880 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4881#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004882 /* a fits into a long, so b must too */
4883 x = PyLong_AsLong((PyObject *)a);
4884 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004885#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004886 x = PyLong_AsLongLong((PyObject *)a);
4887 y = PyLong_AsLongLong((PyObject *)b);
4888#else
4889# error "_PyLong_GCD"
4890#endif
4891 x = Py_ABS(x);
4892 y = Py_ABS(y);
4893 Py_DECREF(a);
4894 Py_DECREF(b);
4895
4896 /* usual Euclidean algorithm for longs */
4897 while (y != 0) {
4898 t = y;
4899 y = x % y;
4900 x = t;
4901 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004902#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004903 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004904#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004905 return PyLong_FromLongLong(x);
4906#else
4907# error "_PyLong_GCD"
4908#endif
4909
4910error:
4911 Py_DECREF(a);
4912 Py_DECREF(b);
4913 Py_XDECREF(c);
4914 Py_XDECREF(d);
4915 return NULL;
4916}
4917
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004918static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004919long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004921 double result;
4922 result = PyLong_AsDouble(v);
4923 if (result == -1.0 && PyErr_Occurred())
4924 return NULL;
4925 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004926}
4927
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004928static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004929long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
4930
4931/*[clinic input]
4932@classmethod
4933int.__new__ as long_new
4934 x: object(c_default="NULL") = 0
4935 /
4936 base as obase: object(c_default="NULL") = 10
4937[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004938
Tim Peters6d6c1a32001-08-02 04:15:00 +00004939static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004940long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
4941/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00004942{
Gregory P. Smitha689e522012-12-25 22:38:32 -08004943 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004945 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004946 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004947 if (x == NULL) {
4948 if (obase != NULL) {
4949 PyErr_SetString(PyExc_TypeError,
4950 "int() missing string argument");
4951 return NULL;
4952 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004953 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004954 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004955 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004956 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004957
Gregory P. Smitha689e522012-12-25 22:38:32 -08004958 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004959 if (base == -1 && PyErr_Occurred())
4960 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004961 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004962 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05304963 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004964 return NULL;
4965 }
4966
4967 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004968 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004969 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004970 const char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 if (PyByteArray_Check(x))
4972 string = PyByteArray_AS_STRING(x);
4973 else
4974 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004975 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 }
4977 else {
4978 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004979 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004980 return NULL;
4981 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004982}
4983
Serhiy Storchaka95949422013-08-27 19:40:23 +03004984/* Wimpy, slow approach to tp_new calls for subtypes of int:
4985 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004986 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004987 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004988*/
4989static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004990long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00004991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 PyLongObject *tmp, *newobj;
4993 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004996 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 if (tmp == NULL)
4998 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02004999 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 n = Py_SIZE(tmp);
5001 if (n < 0)
5002 n = -n;
5003 newobj = (PyLongObject *)type->tp_alloc(type, n);
5004 if (newobj == NULL) {
5005 Py_DECREF(tmp);
5006 return NULL;
5007 }
5008 assert(PyLong_Check(newobj));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005009 Py_SET_SIZE(newobj, Py_SIZE(tmp));
5010 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 newobj->ob_digit[i] = tmp->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005012 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 Py_DECREF(tmp);
5014 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005015}
5016
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005017/*[clinic input]
5018int.__getnewargs__
5019[clinic start generated code]*/
5020
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005021static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005022int___getnewargs___impl(PyObject *self)
5023/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005024{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005025 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005026}
5027
Guido van Rossumb43daf72007-08-01 18:08:08 +00005028static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005029long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005031 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005032}
5033
5034static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005035long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005038}
5039
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005040/*[clinic input]
5041int.__format__
5042
5043 format_spec: unicode
5044 /
5045[clinic start generated code]*/
5046
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005047static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005048int___format___impl(PyObject *self, PyObject *format_spec)
5049/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005050{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005051 _PyUnicodeWriter writer;
5052 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005053
Victor Stinner8f674cc2013-04-17 23:02:17 +02005054 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005055 ret = _PyLong_FormatAdvancedWriter(
5056 &writer,
5057 self,
5058 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5059 if (ret == -1) {
5060 _PyUnicodeWriter_Dealloc(&writer);
5061 return NULL;
5062 }
5063 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005064}
5065
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005066/* Return a pair (q, r) such that a = b * q + r, and
5067 abs(r) <= abs(b)/2, with equality possible only if q is even.
5068 In other words, q == a / b, rounded to the nearest integer using
5069 round-half-to-even. */
5070
5071PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005072_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005073{
5074 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005075 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005076 int quo_is_odd, quo_is_neg;
5077 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005078
5079 /* Equivalent Python code:
5080
5081 def divmod_near(a, b):
5082 q, r = divmod(a, b)
5083 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5084 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5085 # positive, 2 * r < b if b negative.
5086 greater_than_half = 2*r > b if b > 0 else 2*r < b
5087 exactly_half = 2*r == b
5088 if greater_than_half or exactly_half and q % 2 == 1:
5089 q += 1
5090 r -= b
5091 return q, r
5092
5093 */
5094 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5095 PyErr_SetString(PyExc_TypeError,
5096 "non-integer arguments in division");
5097 return NULL;
5098 }
5099
5100 /* Do a and b have different signs? If so, quotient is negative. */
5101 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5102
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005103 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5104 goto error;
5105
5106 /* compare twice the remainder with the divisor, to see
5107 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005108 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005109 if (twice_rem == NULL)
5110 goto error;
5111 if (quo_is_neg) {
5112 temp = long_neg((PyLongObject*)twice_rem);
5113 Py_DECREF(twice_rem);
5114 twice_rem = temp;
5115 if (twice_rem == NULL)
5116 goto error;
5117 }
5118 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5119 Py_DECREF(twice_rem);
5120
5121 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5122 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5123 /* fix up quotient */
5124 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005125 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005126 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005127 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005128 Py_DECREF(quo);
5129 quo = (PyLongObject *)temp;
5130 if (quo == NULL)
5131 goto error;
5132 /* and remainder */
5133 if (quo_is_neg)
5134 temp = long_add(rem, (PyLongObject *)b);
5135 else
5136 temp = long_sub(rem, (PyLongObject *)b);
5137 Py_DECREF(rem);
5138 rem = (PyLongObject *)temp;
5139 if (rem == NULL)
5140 goto error;
5141 }
5142
5143 result = PyTuple_New(2);
5144 if (result == NULL)
5145 goto error;
5146
5147 /* PyTuple_SET_ITEM steals references */
5148 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5149 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005150 return result;
5151
5152 error:
5153 Py_XDECREF(quo);
5154 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005155 return NULL;
5156}
5157
Eric Smith8c663262007-08-25 02:26:07 +00005158static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005159long_round(PyObject *self, PyObject *args)
5160{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005161 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005162
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005163 /* To round an integer m to the nearest 10**n (n positive), we make use of
5164 * the divmod_near operation, defined by:
5165 *
5166 * divmod_near(a, b) = (q, r)
5167 *
5168 * where q is the nearest integer to the quotient a / b (the
5169 * nearest even integer in the case of a tie) and r == a - q * b.
5170 * Hence q * b = a - r is the nearest multiple of b to a,
5171 * preferring even multiples in the case of a tie.
5172 *
5173 * So the nearest multiple of 10**n to m is:
5174 *
5175 * m - divmod_near(m, 10**n)[1].
5176 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5178 return NULL;
5179 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005180 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005181
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03005182 ndigits = _PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005183 if (ndigits == NULL)
5184 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005185
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005186 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005187 if (Py_SIZE(ndigits) >= 0) {
5188 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005189 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005190 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005191
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005192 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5193 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005195 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005197 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005198
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005199 result = PyLong_FromLong(10L);
5200 if (result == NULL) {
5201 Py_DECREF(ndigits);
5202 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005203 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005204
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005205 temp = long_pow(result, ndigits, Py_None);
5206 Py_DECREF(ndigits);
5207 Py_DECREF(result);
5208 result = temp;
5209 if (result == NULL)
5210 return NULL;
5211
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005212 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005213 Py_DECREF(result);
5214 result = temp;
5215 if (result == NULL)
5216 return NULL;
5217
5218 temp = long_sub((PyLongObject *)self,
5219 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5220 Py_DECREF(result);
5221 result = temp;
5222
5223 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005224}
5225
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005226/*[clinic input]
5227int.__sizeof__ -> Py_ssize_t
5228
5229Returns size in memory, in bytes.
5230[clinic start generated code]*/
5231
5232static Py_ssize_t
5233int___sizeof___impl(PyObject *self)
5234/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005237
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005238 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5239 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005240}
5241
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005242/*[clinic input]
5243int.bit_length
5244
5245Number of bits necessary to represent self in binary.
5246
5247>>> bin(37)
5248'0b100101'
5249>>> (37).bit_length()
52506
5251[clinic start generated code]*/
5252
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005253static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005254int_bit_length_impl(PyObject *self)
5255/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005257 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005258 Py_ssize_t ndigits;
5259 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005260 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005261
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005262 assert(self != NULL);
5263 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005264
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005265 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005266 if (ndigits == 0)
5267 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005268
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005269 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Niklas Fiekas794e7d12020-06-15 14:33:48 +02005270 msd_bits = bit_length_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5273 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 /* expression above may overflow; use Python integers instead */
5276 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5277 if (result == NULL)
5278 return NULL;
5279 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5280 if (x == NULL)
5281 goto error;
5282 y = (PyLongObject *)long_mul(result, x);
5283 Py_DECREF(x);
5284 if (y == NULL)
5285 goto error;
5286 Py_DECREF(result);
5287 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005289 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5290 if (x == NULL)
5291 goto error;
5292 y = (PyLongObject *)long_add(result, x);
5293 Py_DECREF(x);
5294 if (y == NULL)
5295 goto error;
5296 Py_DECREF(result);
5297 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005300
Mark Dickinson22b20182010-05-10 21:27:53 +00005301 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005302 Py_DECREF(result);
5303 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005304}
5305
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005306static int
5307popcount_digit(digit d)
5308{
Victor Stinnerc6b292c2020-06-08 16:30:33 +02005309 // digit can be larger than uint32_t, but only PyLong_SHIFT bits
5310 // of it will be ever used.
5311 Py_BUILD_ASSERT(PyLong_SHIFT <= 32);
5312 return _Py_popcount32((uint32_t)d);
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005313}
5314
5315/*[clinic input]
5316int.bit_count
5317
5318Number of ones in the binary representation of the absolute value of self.
5319
5320Also known as the population count.
5321
5322>>> bin(13)
5323'0b1101'
5324>>> (13).bit_count()
53253
5326[clinic start generated code]*/
5327
5328static PyObject *
5329int_bit_count_impl(PyObject *self)
5330/*[clinic end generated code: output=2e571970daf1e5c3 input=7e0adef8e8ccdf2e]*/
5331{
5332 assert(self != NULL);
5333 assert(PyLong_Check(self));
5334
5335 PyLongObject *z = (PyLongObject *)self;
5336 Py_ssize_t ndigits = Py_ABS(Py_SIZE(z));
5337 Py_ssize_t bit_count = 0;
5338
5339 /* Each digit has up to PyLong_SHIFT ones, so the accumulated bit count
5340 from the first PY_SSIZE_T_MAX/PyLong_SHIFT digits can't overflow a
5341 Py_ssize_t. */
5342 Py_ssize_t ndigits_fast = Py_MIN(ndigits, PY_SSIZE_T_MAX/PyLong_SHIFT);
5343 for (Py_ssize_t i = 0; i < ndigits_fast; i++) {
5344 bit_count += popcount_digit(z->ob_digit[i]);
5345 }
5346
5347 PyObject *result = PyLong_FromSsize_t(bit_count);
5348 if (result == NULL) {
5349 return NULL;
5350 }
5351
5352 /* Use Python integers if bit_count would overflow. */
5353 for (Py_ssize_t i = ndigits_fast; i < ndigits; i++) {
5354 PyObject *x = PyLong_FromLong(popcount_digit(z->ob_digit[i]));
5355 if (x == NULL) {
5356 goto error;
5357 }
5358 PyObject *y = long_add((PyLongObject *)result, (PyLongObject *)x);
5359 Py_DECREF(x);
5360 if (y == NULL) {
5361 goto error;
5362 }
5363 Py_DECREF(result);
5364 result = y;
5365 }
5366
5367 return result;
5368
5369 error:
5370 Py_DECREF(result);
5371 return NULL;
5372}
Christian Heimes53876d92008-04-19 00:31:39 +00005373
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005374/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005375int.as_integer_ratio
5376
5377Return integer ratio.
5378
5379Return a pair of integers, whose ratio is exactly equal to the original int
5380and with a positive denominator.
5381
5382>>> (10).as_integer_ratio()
5383(10, 1)
5384>>> (-10).as_integer_ratio()
5385(-10, 1)
5386>>> (0).as_integer_ratio()
5387(0, 1)
5388[clinic start generated code]*/
5389
5390static PyObject *
5391int_as_integer_ratio_impl(PyObject *self)
5392/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5393{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005394 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005395 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005396 if (numerator == NULL) {
5397 return NULL;
5398 }
5399 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5400 Py_DECREF(numerator);
5401 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005402}
5403
5404/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005405int.to_bytes
5406
5407 length: Py_ssize_t
5408 Length of bytes object to use. An OverflowError is raised if the
5409 integer is not representable with the given number of bytes.
5410 byteorder: unicode
5411 The byte order used to represent the integer. If byteorder is 'big',
5412 the most significant byte is at the beginning of the byte array. If
5413 byteorder is 'little', the most significant byte is at the end of the
5414 byte array. To request the native byte order of the host system, use
5415 `sys.byteorder' as the byte order value.
5416 *
5417 signed as is_signed: bool = False
5418 Determines whether two's complement is used to represent the integer.
5419 If signed is False and a negative integer is given, an OverflowError
5420 is raised.
5421
5422Return an array of bytes representing an integer.
5423[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005424
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005425static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005426int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5427 int is_signed)
5428/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005430 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005431 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005432
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005433 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005434 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005435 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 little_endian = 0;
5437 else {
5438 PyErr_SetString(PyExc_ValueError,
5439 "byteorder must be either 'little' or 'big'");
5440 return NULL;
5441 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 if (length < 0) {
5444 PyErr_SetString(PyExc_ValueError,
5445 "length argument must be non-negative");
5446 return NULL;
5447 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 bytes = PyBytes_FromStringAndSize(NULL, length);
5450 if (bytes == NULL)
5451 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005452
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005453 if (_PyLong_AsByteArray((PyLongObject *)self,
5454 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005455 length, little_endian, is_signed) < 0) {
5456 Py_DECREF(bytes);
5457 return NULL;
5458 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005461}
5462
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005463/*[clinic input]
5464@classmethod
5465int.from_bytes
5466
5467 bytes as bytes_obj: object
5468 Holds the array of bytes to convert. The argument must either
5469 support the buffer protocol or be an iterable object producing bytes.
5470 Bytes and bytearray are examples of built-in objects that support the
5471 buffer protocol.
5472 byteorder: unicode
5473 The byte order used to represent the integer. If byteorder is 'big',
5474 the most significant byte is at the beginning of the byte array. If
5475 byteorder is 'little', the most significant byte is at the end of the
5476 byte array. To request the native byte order of the host system, use
5477 `sys.byteorder' as the byte order value.
5478 *
5479 signed as is_signed: bool = False
5480 Indicates whether two's complement is used to represent the integer.
5481
5482Return the integer represented by the given array of bytes.
5483[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005484
5485static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005486int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5487 PyObject *byteorder, int is_signed)
5488/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005490 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005491 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005492
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005493 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005495 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005496 little_endian = 0;
5497 else {
5498 PyErr_SetString(PyExc_ValueError,
5499 "byteorder must be either 'little' or 'big'");
5500 return NULL;
5501 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005502
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005503 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005504 if (bytes == NULL)
5505 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 long_obj = _PyLong_FromByteArray(
5508 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5509 little_endian, is_signed);
5510 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005511
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005512 if (long_obj != NULL && type != &PyLong_Type) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005513 Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005517}
5518
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005519static PyObject *
5520long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5521{
5522 return long_long(self);
5523}
5524
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005525static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005526 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005528 INT_BIT_LENGTH_METHODDEF
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005529 INT_BIT_COUNT_METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005530 INT_TO_BYTES_METHODDEF
5531 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005532 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005533 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005535 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005537 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 "Ceiling of an Integral returns itself."},
5539 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5540 "Rounding an Integral returns itself.\n"
5541 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005542 INT___GETNEWARGS___METHODDEF
5543 INT___FORMAT___METHODDEF
5544 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005546};
5547
Guido van Rossumb43daf72007-08-01 18:08:08 +00005548static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005549 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005550 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005551 "the real part of a complex number",
5552 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005553 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005554 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005555 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005556 NULL},
5557 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005558 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005559 "the numerator of a rational number in lowest terms",
5560 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005561 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005562 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005563 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005564 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005565 {NULL} /* Sentinel */
5566};
5567
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005568PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005569"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005570int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005571\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005572Convert a number or string to an integer, or return 0 if no arguments\n\
5573are given. If x is a number, return x.__int__(). For floating point\n\
5574numbers, this truncates towards zero.\n\
5575\n\
5576If x is not a number or if base is given, then x must be a string,\n\
5577bytes, or bytearray instance representing an integer literal in the\n\
5578given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5579by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5580Base 0 means to interpret the base from the string as an integer literal.\n\
5581>>> int('0b100', base=0)\n\
55824");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005583
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005584static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005585 (binaryfunc)long_add, /*nb_add*/
5586 (binaryfunc)long_sub, /*nb_subtract*/
5587 (binaryfunc)long_mul, /*nb_multiply*/
5588 long_mod, /*nb_remainder*/
5589 long_divmod, /*nb_divmod*/
5590 long_pow, /*nb_power*/
5591 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005592 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005593 (unaryfunc)long_abs, /*tp_absolute*/
5594 (inquiry)long_bool, /*tp_bool*/
5595 (unaryfunc)long_invert, /*nb_invert*/
5596 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005597 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005598 long_and, /*nb_and*/
5599 long_xor, /*nb_xor*/
5600 long_or, /*nb_or*/
5601 long_long, /*nb_int*/
5602 0, /*nb_reserved*/
5603 long_float, /*nb_float*/
5604 0, /* nb_inplace_add */
5605 0, /* nb_inplace_subtract */
5606 0, /* nb_inplace_multiply */
5607 0, /* nb_inplace_remainder */
5608 0, /* nb_inplace_power */
5609 0, /* nb_inplace_lshift */
5610 0, /* nb_inplace_rshift */
5611 0, /* nb_inplace_and */
5612 0, /* nb_inplace_xor */
5613 0, /* nb_inplace_or */
5614 long_div, /* nb_floor_divide */
5615 long_true_divide, /* nb_true_divide */
5616 0, /* nb_inplace_floor_divide */
5617 0, /* nb_inplace_true_divide */
5618 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005619};
5620
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005621PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5623 "int", /* tp_name */
5624 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5625 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005626 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005627 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005628 0, /* tp_getattr */
5629 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005630 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 long_to_decimal_string, /* tp_repr */
5632 &long_as_number, /* tp_as_number */
5633 0, /* tp_as_sequence */
5634 0, /* tp_as_mapping */
5635 (hashfunc)long_hash, /* tp_hash */
5636 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005637 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005638 PyObject_GenericGetAttr, /* tp_getattro */
5639 0, /* tp_setattro */
5640 0, /* tp_as_buffer */
5641 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5642 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5643 long_doc, /* tp_doc */
5644 0, /* tp_traverse */
5645 0, /* tp_clear */
5646 long_richcompare, /* tp_richcompare */
5647 0, /* tp_weaklistoffset */
5648 0, /* tp_iter */
5649 0, /* tp_iternext */
5650 long_methods, /* tp_methods */
5651 0, /* tp_members */
5652 long_getset, /* tp_getset */
5653 0, /* tp_base */
5654 0, /* tp_dict */
5655 0, /* tp_descr_get */
5656 0, /* tp_descr_set */
5657 0, /* tp_dictoffset */
5658 0, /* tp_init */
5659 0, /* tp_alloc */
5660 long_new, /* tp_new */
5661 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005662};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005663
Mark Dickinsonbd792642009-03-18 20:06:12 +00005664static PyTypeObject Int_InfoType;
5665
5666PyDoc_STRVAR(int_info__doc__,
5667"sys.int_info\n\
5668\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005669A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005670internal representation of integers. The attributes are read only.");
5671
5672static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005673 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005674 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005675 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005676};
5677
5678static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 "sys.int_info", /* name */
5680 int_info__doc__, /* doc */
5681 int_info_fields, /* fields */
5682 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005683};
5684
5685PyObject *
5686PyLong_GetInfo(void)
5687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005688 PyObject* int_info;
5689 int field = 0;
5690 int_info = PyStructSequence_New(&Int_InfoType);
5691 if (int_info == NULL)
5692 return NULL;
5693 PyStructSequence_SET_ITEM(int_info, field++,
5694 PyLong_FromLong(PyLong_SHIFT));
5695 PyStructSequence_SET_ITEM(int_info, field++,
5696 PyLong_FromLong(sizeof(digit)));
5697 if (PyErr_Occurred()) {
5698 Py_CLEAR(int_info);
5699 return NULL;
5700 }
5701 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005702}
5703
Guido van Rossumddefaf32007-01-14 03:31:43 +00005704int
Victor Stinner630c8df2019-12-17 13:02:18 +01005705_PyLong_Init(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005706{
5707#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005708 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5709 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5710 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005711
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005712 PyLongObject *v = _PyLong_New(1);
5713 if (!v) {
5714 return -1;
5715 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005716
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005717 Py_SET_SIZE(v, size);
Victor Stinner12174a52014-08-15 23:17:38 +02005718 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005719
Victor Stinner630c8df2019-12-17 13:02:18 +01005720 tstate->interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005721 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005722#endif
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005723
Victor Stinner630c8df2019-12-17 13:02:18 +01005724 if (_Py_IsMainInterpreter(tstate)) {
5725 _PyLong_Zero = PyLong_FromLong(0);
5726 if (_PyLong_Zero == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005727 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005728 }
Victor Stinner630c8df2019-12-17 13:02:18 +01005729
5730 _PyLong_One = PyLong_FromLong(1);
5731 if (_PyLong_One == NULL) {
5732 return 0;
5733 }
5734
5735 /* initialize int_info */
5736 if (Int_InfoType.tp_name == NULL) {
5737 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5738 return 0;
5739 }
5740 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005741 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005743 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005744}
5745
5746void
Victor Stinner630c8df2019-12-17 13:02:18 +01005747_PyLong_Fini(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005748{
Victor Stinner630c8df2019-12-17 13:02:18 +01005749 if (_Py_IsMainInterpreter(tstate)) {
5750 Py_CLEAR(_PyLong_One);
5751 Py_CLEAR(_PyLong_Zero);
5752 }
5753
Guido van Rossumddefaf32007-01-14 03:31:43 +00005754#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005755 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinner630c8df2019-12-17 13:02:18 +01005756 Py_CLEAR(tstate->interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005757 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005758#endif
5759}