blob: d00a7a048ddce228af1a81f8f683985f958c05dc [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öwis18e16552006-02-15 17:27:45 +00002507PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002508{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002509 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002510 if (unicode == NULL)
2511 return NULL;
2512 v = PyLong_FromUnicodeObject(unicode, base);
2513 Py_DECREF(unicode);
2514 return v;
2515}
2516
2517PyObject *
2518PyLong_FromUnicodeObject(PyObject *u, int base)
2519{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002520 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002521 const char *buffer;
2522 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002523 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002524
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002525 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002526 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002528 assert(PyUnicode_IS_ASCII(asciidig));
2529 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002530 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002531 assert(buffer != NULL);
2532
2533 result = PyLong_FromString(buffer, &end, base);
2534 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002535 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002536 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002538 Py_DECREF(asciidig);
2539 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002540 PyErr_Format(PyExc_ValueError,
2541 "invalid literal for int() with base %d: %.200R",
2542 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002543 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002544}
2545
Tim Peters9f688bf2000-07-07 15:53:28 +00002546/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002547static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002549static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002550
Serhiy Storchaka95949422013-08-27 19:40:23 +03002551/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002552
Guido van Rossume32e0141992-01-19 16:31:05 +00002553static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002554long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002556{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002557 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 if (size_b == 0) {
2561 PyErr_SetString(PyExc_ZeroDivisionError,
2562 "integer division or modulo by zero");
2563 return -1;
2564 }
2565 if (size_a < size_b ||
2566 (size_a == size_b &&
2567 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2568 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002569 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002570 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002571 return -1;
2572 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002573 Py_INCREF(_PyLong_Zero);
2574 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 return 0;
2576 }
2577 if (size_b == 1) {
2578 digit rem = 0;
2579 z = divrem1(a, b->ob_digit[0], &rem);
2580 if (z == NULL)
2581 return -1;
2582 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2583 if (*prem == NULL) {
2584 Py_DECREF(z);
2585 return -1;
2586 }
2587 }
2588 else {
2589 z = x_divrem(a, b, prem);
2590 if (z == NULL)
2591 return -1;
2592 }
2593 /* Set the signs.
2594 The quotient z has the sign of a*b;
2595 the remainder r has the sign of a,
2596 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002597 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2598 _PyLong_Negate(&z);
2599 if (z == NULL) {
2600 Py_CLEAR(*prem);
2601 return -1;
2602 }
2603 }
2604 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2605 _PyLong_Negate(prem);
2606 if (*prem == NULL) {
2607 Py_DECREF(z);
2608 Py_CLEAR(*prem);
2609 return -1;
2610 }
2611 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 *pdiv = maybe_small_long(z);
2613 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002614}
2615
Serhiy Storchaka95949422013-08-27 19:40:23 +03002616/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002617 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002618
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002619static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002620x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 PyLongObject *v, *w, *a;
2623 Py_ssize_t i, k, size_v, size_w;
2624 int d;
2625 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2626 twodigits vv;
2627 sdigit zhi;
2628 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2631 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2632 handle the special case when the initial estimate q for a quotient
2633 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2634 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002637 size_v = Py_ABS(Py_SIZE(v1));
2638 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2640 v = _PyLong_New(size_v+1);
2641 if (v == NULL) {
2642 *prem = NULL;
2643 return NULL;
2644 }
2645 w = _PyLong_New(size_w);
2646 if (w == NULL) {
2647 Py_DECREF(v);
2648 *prem = NULL;
2649 return NULL;
2650 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2653 shift v1 left by the same amount. Results go into w and v. */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02002654 d = PyLong_SHIFT - bit_length_digit(w1->ob_digit[size_w-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2656 assert(carry == 0);
2657 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2658 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2659 v->ob_digit[size_v] = carry;
2660 size_v++;
2661 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2664 at most (and usually exactly) k = size_v - size_w digits. */
2665 k = size_v - size_w;
2666 assert(k >= 0);
2667 a = _PyLong_New(k);
2668 if (a == NULL) {
2669 Py_DECREF(w);
2670 Py_DECREF(v);
2671 *prem = NULL;
2672 return NULL;
2673 }
2674 v0 = v->ob_digit;
2675 w0 = w->ob_digit;
2676 wm1 = w0[size_w-1];
2677 wm2 = w0[size_w-2];
2678 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2679 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2680 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002683 Py_DECREF(a);
2684 Py_DECREF(w);
2685 Py_DECREF(v);
2686 *prem = NULL;
2687 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002688 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 /* estimate quotient digit q; may overestimate by 1 (rare) */
2691 vtop = vk[size_w];
2692 assert(vtop <= wm1);
2693 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2694 q = (digit)(vv / wm1);
2695 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2696 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2697 | vk[size_w-2])) {
2698 --q;
2699 r += wm1;
2700 if (r >= PyLong_BASE)
2701 break;
2702 }
2703 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2706 zhi = 0;
2707 for (i = 0; i < size_w; ++i) {
2708 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2709 -PyLong_BASE * q <= z < PyLong_BASE */
2710 z = (sdigit)vk[i] + zhi -
2711 (stwodigits)q * (stwodigits)w0[i];
2712 vk[i] = (digit)z & PyLong_MASK;
2713 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002714 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 /* add w back if q was too large (this branch taken rarely) */
2718 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2719 if ((sdigit)vtop + zhi < 0) {
2720 carry = 0;
2721 for (i = 0; i < size_w; ++i) {
2722 carry += vk[i] + w0[i];
2723 vk[i] = carry & PyLong_MASK;
2724 carry >>= PyLong_SHIFT;
2725 }
2726 --q;
2727 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 /* store quotient digit */
2730 assert(q < PyLong_BASE);
2731 *--ak = q;
2732 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 /* unshift remainder; we reuse w to store the result */
2735 carry = v_rshift(w0, v0, size_w, d);
2736 assert(carry==0);
2737 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 *prem = long_normalize(w);
2740 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002741}
2742
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002743/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2744 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2745 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2746 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2747 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2748 -1.0. */
2749
2750/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2751#if DBL_MANT_DIG == 53
2752#define EXP2_DBL_MANT_DIG 9007199254740992.0
2753#else
2754#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2755#endif
2756
2757double
2758_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2761 /* See below for why x_digits is always large enough. */
Dong-hee Nab88cd582020-05-04 22:32:42 +09002762 digit rem;
2763 digit x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT] = {0,};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 double dx;
2765 /* Correction term for round-half-to-even rounding. For a digit x,
2766 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2767 multiple of 4, rounding ties to a multiple of 8. */
2768 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002769
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002770 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 if (a_size == 0) {
2772 /* Special case for 0: significand 0.0, exponent 0. */
2773 *e = 0;
2774 return 0.0;
2775 }
Niklas Fiekas794e7d12020-06-15 14:33:48 +02002776 a_bits = bit_length_digit(a->ob_digit[a_size-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 /* The following is an overflow-free version of the check
2778 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2779 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2780 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2781 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002782 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2786 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 Number of digits needed for result: write // for floor division.
2789 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2798 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2801 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2802 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 in both cases.
2809 */
2810 if (a_bits <= DBL_MANT_DIG + 2) {
2811 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2812 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
Dong-hee Nab88cd582020-05-04 22:32:42 +09002813 x_size = shift_digits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2815 (int)shift_bits);
2816 x_size += a_size;
2817 x_digits[x_size++] = rem;
2818 }
2819 else {
2820 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2821 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2822 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2823 a_size - shift_digits, (int)shift_bits);
2824 x_size = a_size - shift_digits;
2825 /* For correct rounding below, we need the least significant
2826 bit of x to be 'sticky' for this shift: if any of the bits
2827 shifted out was nonzero, we set the least significant bit
2828 of x. */
2829 if (rem)
2830 x_digits[0] |= 1;
2831 else
2832 while (shift_digits > 0)
2833 if (a->ob_digit[--shift_digits]) {
2834 x_digits[0] |= 1;
2835 break;
2836 }
2837 }
Victor Stinner63941882011-09-29 00:42:28 +02002838 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 /* Round, and convert to double. */
2841 x_digits[0] += half_even_correction[x_digits[0] & 7];
2842 dx = x_digits[--x_size];
2843 while (x_size > 0)
2844 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 /* Rescale; make correction if result is 1.0. */
2847 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2848 if (dx == 1.0) {
2849 if (a_bits == PY_SSIZE_T_MAX)
2850 goto overflow;
2851 dx = 0.5;
2852 a_bits += 1;
2853 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 *e = a_bits;
2856 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002857
2858 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 /* exponent > PY_SSIZE_T_MAX */
2860 PyErr_SetString(PyExc_OverflowError,
2861 "huge integer: number of bits overflows a Py_ssize_t");
2862 *e = 0;
2863 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002864}
2865
Serhiy Storchaka95949422013-08-27 19:40:23 +03002866/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002867 using the round-half-to-even rule in the case of a tie. */
2868
2869double
2870PyLong_AsDouble(PyObject *v)
2871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 Py_ssize_t exponent;
2873 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002874
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002875 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 PyErr_BadInternalCall();
2877 return -1.0;
2878 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002879 if (!PyLong_Check(v)) {
2880 PyErr_SetString(PyExc_TypeError, "an integer is required");
2881 return -1.0;
2882 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002883 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002884 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002885 to double. This improves performance of FP/long operations
2886 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002887 */
2888 return (double)MEDIUM_VALUE((PyLongObject *)v);
2889 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2891 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2892 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002893 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 return -1.0;
2895 }
2896 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002897}
2898
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002899/* Methods */
2900
HongWeipeng42acb7b2019-09-18 23:10:15 +08002901/* if a < b, return a negative number
2902 if a == b, return 0
2903 if a > b, return a positive number */
2904
2905static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002906long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002907{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002908 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
2909 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002910 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08002911 sdigit diff = 0;
2912 while (--i >= 0) {
2913 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
2914 if (diff) {
2915 break;
2916 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08002918 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08002920 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002921}
2922
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002923static PyObject *
2924long_richcompare(PyObject *self, PyObject *other, int op)
2925{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002926 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 CHECK_BINOP(self, other);
2928 if (self == other)
2929 result = 0;
2930 else
2931 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01002932 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002933}
2934
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002935static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002936long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002937{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002938 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 Py_ssize_t i;
2940 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 i = Py_SIZE(v);
2943 switch(i) {
2944 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2945 case 0: return 0;
2946 case 1: return v->ob_digit[0];
2947 }
2948 sign = 1;
2949 x = 0;
2950 if (i < 0) {
2951 sign = -1;
2952 i = -(i);
2953 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002955 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2956 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2957 _PyHASH_MODULUS.
2958
2959 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2960 amounts to a rotation of the bits of x. To see this, write
2961
2962 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2963
2964 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2965 PyLong_SHIFT bits of x (those that are shifted out of the
2966 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2967 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2968 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2969 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2970 congruent to y modulo _PyHASH_MODULUS. So
2971
2972 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2973
2974 The right-hand side is just the result of rotating the
2975 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2976 not all _PyHASH_BITS bits of x are 1s, the same is true
2977 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2978 the reduction of x*2**PyLong_SHIFT modulo
2979 _PyHASH_MODULUS. */
2980 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2981 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002983 if (x >= _PyHASH_MODULUS)
2984 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 }
2986 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002987 if (x == (Py_uhash_t)-1)
2988 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002989 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002990}
2991
2992
Serhiy Storchaka95949422013-08-27 19:40:23 +03002993/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002994
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002995static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002996x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002997{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002998 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 PyLongObject *z;
3000 Py_ssize_t i;
3001 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 /* Ensure a is the larger of the two: */
3004 if (size_a < size_b) {
3005 { PyLongObject *temp = a; a = b; b = temp; }
3006 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003007 size_a = size_b;
3008 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 }
3010 z = _PyLong_New(size_a+1);
3011 if (z == NULL)
3012 return NULL;
3013 for (i = 0; i < size_b; ++i) {
3014 carry += a->ob_digit[i] + b->ob_digit[i];
3015 z->ob_digit[i] = carry & PyLong_MASK;
3016 carry >>= PyLong_SHIFT;
3017 }
3018 for (; i < size_a; ++i) {
3019 carry += a->ob_digit[i];
3020 z->ob_digit[i] = carry & PyLong_MASK;
3021 carry >>= PyLong_SHIFT;
3022 }
3023 z->ob_digit[i] = carry;
3024 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003025}
3026
3027/* Subtract the absolute values of two integers. */
3028
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003029static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003030x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003031{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003032 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 PyLongObject *z;
3034 Py_ssize_t i;
3035 int sign = 1;
3036 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 /* Ensure a is the larger of the two: */
3039 if (size_a < size_b) {
3040 sign = -1;
3041 { PyLongObject *temp = a; a = b; b = temp; }
3042 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003043 size_a = size_b;
3044 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 }
3046 else if (size_a == size_b) {
3047 /* Find highest digit where a and b differ: */
3048 i = size_a;
3049 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3050 ;
3051 if (i < 0)
3052 return (PyLongObject *)PyLong_FromLong(0);
3053 if (a->ob_digit[i] < b->ob_digit[i]) {
3054 sign = -1;
3055 { PyLongObject *temp = a; a = b; b = temp; }
3056 }
3057 size_a = size_b = i+1;
3058 }
3059 z = _PyLong_New(size_a);
3060 if (z == NULL)
3061 return NULL;
3062 for (i = 0; i < size_b; ++i) {
3063 /* The following assumes unsigned arithmetic
3064 works module 2**N for some N>PyLong_SHIFT. */
3065 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3066 z->ob_digit[i] = borrow & PyLong_MASK;
3067 borrow >>= PyLong_SHIFT;
3068 borrow &= 1; /* Keep only one sign bit */
3069 }
3070 for (; i < size_a; ++i) {
3071 borrow = a->ob_digit[i] - borrow;
3072 z->ob_digit[i] = borrow & PyLong_MASK;
3073 borrow >>= PyLong_SHIFT;
3074 borrow &= 1; /* Keep only one sign bit */
3075 }
3076 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003077 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003078 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02003079 }
HongWeipeng036fe852019-11-26 15:54:49 +08003080 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003081}
3082
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003083static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003084long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003089
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003090 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003091 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 }
3093 if (Py_SIZE(a) < 0) {
3094 if (Py_SIZE(b) < 0) {
3095 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003096 if (z != NULL) {
3097 /* x_add received at least one multiple-digit int,
3098 and thus z must be a multiple-digit int.
3099 That also means z is not an element of
3100 small_ints, so negating it in-place is safe. */
3101 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003102 Py_SET_SIZE(z, -(Py_SIZE(z)));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003103 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 }
3105 else
3106 z = x_sub(b, a);
3107 }
3108 else {
3109 if (Py_SIZE(b) < 0)
3110 z = x_sub(a, b);
3111 else
3112 z = x_add(a, b);
3113 }
3114 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003115}
3116
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003117static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003118long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003123
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003124 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003125 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 }
3127 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003128 if (Py_SIZE(b) < 0) {
3129 z = x_sub(b, a);
3130 }
3131 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003133 if (z != NULL) {
3134 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003135 Py_SET_SIZE(z, -(Py_SIZE(z)));
HongWeipeng036fe852019-11-26 15:54:49 +08003136 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003137 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 }
3139 else {
3140 if (Py_SIZE(b) < 0)
3141 z = x_add(a, b);
3142 else
3143 z = x_sub(a, b);
3144 }
3145 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003146}
3147
Tim Peters5af4e6c2002-08-12 02:31:19 +00003148/* Grade school multiplication, ignoring the signs.
3149 * Returns the absolute value of the product, or NULL if error.
3150 */
3151static PyLongObject *
3152x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003155 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3156 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 z = _PyLong_New(size_a + size_b);
3160 if (z == NULL)
3161 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3164 if (a == b) {
3165 /* Efficient squaring per HAC, Algorithm 14.16:
3166 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3167 * Gives slightly less than a 2x speedup when a == b,
3168 * via exploiting that each entry in the multiplication
3169 * pyramid appears twice (except for the size_a squares).
3170 */
3171 for (i = 0; i < size_a; ++i) {
3172 twodigits carry;
3173 twodigits f = a->ob_digit[i];
3174 digit *pz = z->ob_digit + (i << 1);
3175 digit *pa = a->ob_digit + i + 1;
3176 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003179 Py_DECREF(z);
3180 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003181 });
Tim Peters0973b992004-08-29 22:16:50 +00003182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 carry = *pz + f * f;
3184 *pz++ = (digit)(carry & PyLong_MASK);
3185 carry >>= PyLong_SHIFT;
3186 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 /* Now f is added in twice in each column of the
3189 * pyramid it appears. Same as adding f<<1 once.
3190 */
3191 f <<= 1;
3192 while (pa < paend) {
3193 carry += *pz + *pa++ * f;
3194 *pz++ = (digit)(carry & PyLong_MASK);
3195 carry >>= PyLong_SHIFT;
3196 assert(carry <= (PyLong_MASK << 1));
3197 }
3198 if (carry) {
3199 carry += *pz;
3200 *pz++ = (digit)(carry & PyLong_MASK);
3201 carry >>= PyLong_SHIFT;
3202 }
3203 if (carry)
3204 *pz += (digit)(carry & PyLong_MASK);
3205 assert((carry >> PyLong_SHIFT) == 0);
3206 }
3207 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003208 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 for (i = 0; i < size_a; ++i) {
3210 twodigits carry = 0;
3211 twodigits f = a->ob_digit[i];
3212 digit *pz = z->ob_digit + i;
3213 digit *pb = b->ob_digit;
3214 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003217 Py_DECREF(z);
3218 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003219 });
Tim Peters0973b992004-08-29 22:16:50 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 while (pb < pbend) {
3222 carry += *pz + *pb++ * f;
3223 *pz++ = (digit)(carry & PyLong_MASK);
3224 carry >>= PyLong_SHIFT;
3225 assert(carry <= PyLong_MASK);
3226 }
3227 if (carry)
3228 *pz += (digit)(carry & PyLong_MASK);
3229 assert((carry >> PyLong_SHIFT) == 0);
3230 }
3231 }
3232 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003233}
3234
3235/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003236 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003237 split, and sets low and high such that abs(n) == (high << size) + low,
3238 viewing the shift as being by digits. The sign bit is ignored, and
3239 the return values are >= 0.
3240 Returns 0 on success, -1 on failure.
3241*/
3242static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003243kmul_split(PyLongObject *n,
3244 Py_ssize_t size,
3245 PyLongObject **high,
3246 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 PyLongObject *hi, *lo;
3249 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003250 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003251
Victor Stinner640c35c2013-06-04 23:14:37 +02003252 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 if ((hi = _PyLong_New(size_hi)) == NULL)
3256 return -1;
3257 if ((lo = _PyLong_New(size_lo)) == NULL) {
3258 Py_DECREF(hi);
3259 return -1;
3260 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3263 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 *high = long_normalize(hi);
3266 *low = long_normalize(lo);
3267 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003268}
3269
Tim Peters60004642002-08-12 22:01:34 +00003270static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3271
Tim Peters5af4e6c2002-08-12 02:31:19 +00003272/* Karatsuba multiplication. Ignores the input signs, and returns the
3273 * absolute value of the product (or NULL if error).
3274 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3275 */
3276static PyLongObject *
3277k_mul(PyLongObject *a, PyLongObject *b)
3278{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003279 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3280 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 PyLongObject *ah = NULL;
3282 PyLongObject *al = NULL;
3283 PyLongObject *bh = NULL;
3284 PyLongObject *bl = NULL;
3285 PyLongObject *ret = NULL;
3286 PyLongObject *t1, *t2, *t3;
3287 Py_ssize_t shift; /* the number of digits we split off */
3288 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3291 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3292 * Then the original product is
3293 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3294 * By picking X to be a power of 2, "*X" is just shifting, and it's
3295 * been reduced to 3 multiplies on numbers half the size.
3296 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 /* We want to split based on the larger number; fiddle so that b
3299 * is largest.
3300 */
3301 if (asize > bsize) {
3302 t1 = a;
3303 a = b;
3304 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 i = asize;
3307 asize = bsize;
3308 bsize = i;
3309 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 /* Use gradeschool math when either number is too small. */
3312 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3313 if (asize <= i) {
3314 if (asize == 0)
3315 return (PyLongObject *)PyLong_FromLong(0);
3316 else
3317 return x_mul(a, b);
3318 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 /* If a is small compared to b, splitting on b gives a degenerate
3321 * case with ah==0, and Karatsuba may be (even much) less efficient
3322 * than "grade school" then. However, we can still win, by viewing
3323 * b as a string of "big digits", each of width a->ob_size. That
3324 * leads to a sequence of balanced calls to k_mul.
3325 */
3326 if (2 * asize <= bsize)
3327 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 /* Split a & b into hi & lo pieces. */
3330 shift = bsize >> 1;
3331 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3332 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 if (a == b) {
3335 bh = ah;
3336 bl = al;
3337 Py_INCREF(bh);
3338 Py_INCREF(bl);
3339 }
3340 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 /* The plan:
3343 * 1. Allocate result space (asize + bsize digits: that's always
3344 * enough).
3345 * 2. Compute ah*bh, and copy into result at 2*shift.
3346 * 3. Compute al*bl, and copy into result at 0. Note that this
3347 * can't overlap with #2.
3348 * 4. Subtract al*bl from the result, starting at shift. This may
3349 * underflow (borrow out of the high digit), but we don't care:
3350 * we're effectively doing unsigned arithmetic mod
3351 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3352 * borrows and carries out of the high digit can be ignored.
3353 * 5. Subtract ah*bh from the result, starting at shift.
3354 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3355 * at shift.
3356 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 /* 1. Allocate result space. */
3359 ret = _PyLong_New(asize + bsize);
3360 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003361#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 /* Fill with trash, to catch reference to uninitialized digits. */
3363 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003364#endif
Tim Peters44121a62002-08-12 06:17:58 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3367 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3368 assert(Py_SIZE(t1) >= 0);
3369 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3370 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3371 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 /* Zero-out the digits higher than the ah*bh copy. */
3374 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3375 if (i)
3376 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3377 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 /* 3. t2 <- al*bl, and copy into the low digits. */
3380 if ((t2 = k_mul(al, bl)) == NULL) {
3381 Py_DECREF(t1);
3382 goto fail;
3383 }
3384 assert(Py_SIZE(t2) >= 0);
3385 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3386 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 /* Zero out remaining digits. */
3389 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3390 if (i)
3391 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3394 * because it's fresher in cache.
3395 */
3396 i = Py_SIZE(ret) - shift; /* # digits after shift */
3397 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3398 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3401 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3404 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3405 Py_DECREF(ah);
3406 Py_DECREF(al);
3407 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 if (a == b) {
3410 t2 = t1;
3411 Py_INCREF(t2);
3412 }
3413 else if ((t2 = x_add(bh, bl)) == NULL) {
3414 Py_DECREF(t1);
3415 goto fail;
3416 }
3417 Py_DECREF(bh);
3418 Py_DECREF(bl);
3419 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 t3 = k_mul(t1, t2);
3422 Py_DECREF(t1);
3423 Py_DECREF(t2);
3424 if (t3 == NULL) goto fail;
3425 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 /* Add t3. It's not obvious why we can't run out of room here.
3428 * See the (*) comment after this function.
3429 */
3430 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3431 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003434
Mark Dickinson22b20182010-05-10 21:27:53 +00003435 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 Py_XDECREF(ret);
3437 Py_XDECREF(ah);
3438 Py_XDECREF(al);
3439 Py_XDECREF(bh);
3440 Py_XDECREF(bl);
3441 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003442}
3443
Tim Petersd6974a52002-08-13 20:37:51 +00003444/* (*) Why adding t3 can't "run out of room" above.
3445
Tim Petersab86c2b2002-08-15 20:06:00 +00003446Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3447to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003448
Tim Petersab86c2b2002-08-15 20:06:00 +000034491. For any integer i, i = c(i/2) + f(i/2). In particular,
3450 bsize = c(bsize/2) + f(bsize/2).
34512. shift = f(bsize/2)
34523. asize <= bsize
34534. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3454 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003455
Tim Petersab86c2b2002-08-15 20:06:00 +00003456We allocated asize + bsize result digits, and add t3 into them at an offset
3457of shift. This leaves asize+bsize-shift allocated digit positions for t3
3458to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3459asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003460
Tim Petersab86c2b2002-08-15 20:06:00 +00003461bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3462at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003463
Tim Petersab86c2b2002-08-15 20:06:00 +00003464If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3465digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3466most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003467
Tim Petersab86c2b2002-08-15 20:06:00 +00003468The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003469
Tim Petersab86c2b2002-08-15 20:06:00 +00003470 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003471
Tim Petersab86c2b2002-08-15 20:06:00 +00003472and we have asize + c(bsize/2) available digit positions. We need to show
3473this is always enough. An instance of c(bsize/2) cancels out in both, so
3474the question reduces to whether asize digits is enough to hold
3475(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3476then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3477asize 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 +00003478digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003479asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003480c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3481is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3482bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003483
Tim Peters48d52c02002-08-14 17:07:32 +00003484Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3485clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3486ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003487*/
3488
Tim Peters60004642002-08-12 22:01:34 +00003489/* b has at least twice the digits of a, and a is big enough that Karatsuba
3490 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3491 * of slices, each with a->ob_size digits, and multiply the slices by a,
3492 * one at a time. This gives k_mul balanced inputs to work with, and is
3493 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003494 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003495 * single-width slice overlap between successive partial sums).
3496 */
3497static PyLongObject *
3498k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3499{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003500 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3501 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 Py_ssize_t nbdone; /* # of b digits already multiplied */
3503 PyLongObject *ret;
3504 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 assert(asize > KARATSUBA_CUTOFF);
3507 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 /* Allocate result space, and zero it out. */
3510 ret = _PyLong_New(asize + bsize);
3511 if (ret == NULL)
3512 return NULL;
3513 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 /* Successive slices of b are copied into bslice. */
3516 bslice = _PyLong_New(asize);
3517 if (bslice == NULL)
3518 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 nbdone = 0;
3521 while (bsize > 0) {
3522 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003523 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 /* Multiply the next slice of b by a. */
3526 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3527 nbtouse * sizeof(digit));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003528 Py_SET_SIZE(bslice, nbtouse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 product = k_mul(a, bslice);
3530 if (product == NULL)
3531 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 /* Add into result. */
3534 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3535 product->ob_digit, Py_SIZE(product));
3536 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 bsize -= nbtouse;
3539 nbdone += nbtouse;
3540 }
Tim Peters60004642002-08-12 22:01:34 +00003541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 Py_DECREF(bslice);
3543 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003544
Mark Dickinson22b20182010-05-10 21:27:53 +00003545 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 Py_DECREF(ret);
3547 Py_XDECREF(bslice);
3548 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003549}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003550
3551static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003552long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003559 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003561 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 z = k_mul(a, b);
3565 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003566 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3567 _PyLong_Negate(&z);
3568 if (z == NULL)
3569 return NULL;
3570 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003572}
3573
Yury Selivanove0b23092016-02-11 10:26:27 -05003574/* Fast modulo division for single-digit longs. */
3575static PyObject *
3576fast_mod(PyLongObject *a, PyLongObject *b)
3577{
3578 sdigit left = a->ob_digit[0];
3579 sdigit right = b->ob_digit[0];
3580 sdigit mod;
3581
3582 assert(Py_ABS(Py_SIZE(a)) == 1);
3583 assert(Py_ABS(Py_SIZE(b)) == 1);
3584
3585 if (Py_SIZE(a) == Py_SIZE(b)) {
3586 /* 'a' and 'b' have the same sign. */
3587 mod = left % right;
3588 }
3589 else {
3590 /* Either 'a' or 'b' is negative. */
3591 mod = right - 1 - (left - 1) % right;
3592 }
3593
Victor Stinnerf963c132016-03-23 18:36:54 +01003594 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003595}
3596
3597/* Fast floor division for single-digit longs. */
3598static PyObject *
3599fast_floor_div(PyLongObject *a, PyLongObject *b)
3600{
3601 sdigit left = a->ob_digit[0];
3602 sdigit right = b->ob_digit[0];
3603 sdigit div;
3604
3605 assert(Py_ABS(Py_SIZE(a)) == 1);
3606 assert(Py_ABS(Py_SIZE(b)) == 1);
3607
3608 if (Py_SIZE(a) == Py_SIZE(b)) {
3609 /* 'a' and 'b' have the same sign. */
3610 div = left / right;
3611 }
3612 else {
3613 /* Either 'a' or 'b' is negative. */
3614 div = -1 - (left - 1) / right;
3615 }
3616
3617 return PyLong_FromLong(div);
3618}
3619
Guido van Rossume32e0141992-01-19 16:31:05 +00003620/* The / and % operators are now defined in terms of divmod().
3621 The expression a mod b has the value a - b*floor(a/b).
3622 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003623 |a| by |b|, with the sign of a. This is also expressed
3624 as a - b*trunc(a/b), if trunc truncates towards zero.
3625 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 a b a rem b a mod b
3627 13 10 3 3
3628 -13 10 -3 7
3629 13 -10 3 -7
3630 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003631 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003632 have different signs. We then subtract one from the 'div'
3633 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003634
Tim Peters47e52ee2004-08-30 02:44:38 +00003635/* Compute
3636 * *pdiv, *pmod = divmod(v, w)
3637 * NULL can be passed for pdiv or pmod, in which case that part of
3638 * the result is simply thrown away. The caller owns a reference to
3639 * each of these it requests (does not pass NULL for).
3640 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003641static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003642l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003646
Yury Selivanove0b23092016-02-11 10:26:27 -05003647 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3648 /* Fast path for single-digit longs */
3649 div = NULL;
3650 if (pdiv != NULL) {
3651 div = (PyLongObject *)fast_floor_div(v, w);
3652 if (div == NULL) {
3653 return -1;
3654 }
3655 }
3656 if (pmod != NULL) {
3657 mod = (PyLongObject *)fast_mod(v, w);
3658 if (mod == NULL) {
3659 Py_XDECREF(div);
3660 return -1;
3661 }
3662 *pmod = mod;
3663 }
3664 if (pdiv != NULL) {
3665 /* We only want to set `*pdiv` when `*pmod` is
3666 set successfully. */
3667 *pdiv = div;
3668 }
3669 return 0;
3670 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 if (long_divrem(v, w, &div, &mod) < 0)
3672 return -1;
3673 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3674 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3675 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 temp = (PyLongObject *) long_add(mod, w);
3677 Py_DECREF(mod);
3678 mod = temp;
3679 if (mod == NULL) {
3680 Py_DECREF(div);
3681 return -1;
3682 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003683 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3684 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 Py_DECREF(mod);
3686 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 return -1;
3688 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 Py_DECREF(div);
3690 div = temp;
3691 }
3692 if (pdiv != NULL)
3693 *pdiv = div;
3694 else
3695 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 if (pmod != NULL)
3698 *pmod = mod;
3699 else
3700 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003703}
3704
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003705static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003706long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003711
3712 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3713 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3714 }
3715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3717 div = NULL;
3718 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003719}
3720
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003721/* PyLong/PyLong -> float, with correctly rounded result. */
3722
3723#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3724#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3725
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003726static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003727long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 PyLongObject *a, *b, *x;
3730 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3731 digit mask, low;
3732 int inexact, negate, a_is_small, b_is_small;
3733 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 CHECK_BINOP(v, w);
3736 a = (PyLongObject *)v;
3737 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 /*
3740 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3743 1. choose a suitable integer 'shift'
3744 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3745 3. adjust x for correct rounding
3746 4. convert x to a double dx with the same value
3747 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3752 returns either 0.0 or -0.0, depending on the sign of b. For a and
3753 b both nonzero, ignore signs of a and b, and add the sign back in
3754 at the end. Now write a_bits and b_bits for the bit lengths of a
3755 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3756 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3761 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3762 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3763 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 1. The integer 'shift' is chosen so that x has the right number of
3768 bits for a double, plus two or three extra bits that will be used
3769 in the rounding decisions. Writing a_bits and b_bits for the
3770 number of significant bits in a and b respectively, a
3771 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 This is fine in the usual case, but if a/b is smaller than the
3776 smallest normal float then it can lead to double rounding on an
3777 IEEE 754 platform, giving incorrectly rounded results. So we
3778 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 2. The quantity x is computed by first shifting a (left -shift bits
3783 if shift <= 0, right shift bits if shift > 0) and then dividing by
3784 b. For both the shift and the division, we keep track of whether
3785 the result is inexact, in a flag 'inexact'; this information is
3786 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 With the choice of shift above, together with our assumption that
3789 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3790 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3793 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 For float representability, we need x/2**extra_bits <
3798 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3799 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 To round, we just modify the bottom digit of x in-place; this can
3804 end up giving a digit with value > PyLONG_MASK, but that's not a
3805 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 With the original choices for shift above, extra_bits will always
3808 be 2 or 3. Then rounding under the round-half-to-even rule, we
3809 round up iff the most significant of the extra bits is 1, and
3810 either: (a) the computation of x in step 2 had an inexact result,
3811 or (b) at least one other of the extra bits is 1, or (c) the least
3812 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 4. Conversion to a double is straightforward; all floating-point
3815 operations involved in the conversion are exact, so there's no
3816 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3819 The result will always be exactly representable as a double, except
3820 in the case that it overflows. To avoid dependence on the exact
3821 behaviour of ldexp on overflow, we check for overflow before
3822 applying ldexp. The result of ldexp is adjusted for sign before
3823 returning.
3824 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003827 a_size = Py_ABS(Py_SIZE(a));
3828 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3830 if (b_size == 0) {
3831 PyErr_SetString(PyExc_ZeroDivisionError,
3832 "division by zero");
3833 goto error;
3834 }
3835 if (a_size == 0)
3836 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 /* Fast path for a and b small (exactly representable in a double).
3839 Relies on floating-point division being correctly rounded; results
3840 may be subject to double rounding on x86 machines that operate with
3841 the x87 FPU set to 64-bit precision. */
3842 a_is_small = a_size <= MANT_DIG_DIGITS ||
3843 (a_size == MANT_DIG_DIGITS+1 &&
3844 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3845 b_is_small = b_size <= MANT_DIG_DIGITS ||
3846 (b_size == MANT_DIG_DIGITS+1 &&
3847 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3848 if (a_is_small && b_is_small) {
3849 double da, db;
3850 da = a->ob_digit[--a_size];
3851 while (a_size > 0)
3852 da = da * PyLong_BASE + a->ob_digit[--a_size];
3853 db = b->ob_digit[--b_size];
3854 while (b_size > 0)
3855 db = db * PyLong_BASE + b->ob_digit[--b_size];
3856 result = da / db;
3857 goto success;
3858 }
Tim Peterse2a60002001-09-04 06:17:36 +00003859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 /* Catch obvious cases of underflow and overflow */
3861 diff = a_size - b_size;
3862 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3863 /* Extreme overflow */
3864 goto overflow;
3865 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3866 /* Extreme underflow */
3867 goto underflow_or_zero;
3868 /* Next line is now safe from overflowing a Py_ssize_t */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02003869 diff = diff * PyLong_SHIFT + bit_length_digit(a->ob_digit[a_size - 1]) -
3870 bit_length_digit(b->ob_digit[b_size - 1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 /* Now diff = a_bits - b_bits. */
3872 if (diff > DBL_MAX_EXP)
3873 goto overflow;
3874 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3875 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003878 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 /* x = abs(a * 2**-shift) */
3883 if (shift <= 0) {
3884 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3885 digit rem;
3886 /* x = a << -shift */
3887 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3888 /* In practice, it's probably impossible to end up
3889 here. Both a and b would have to be enormous,
3890 using close to SIZE_T_MAX bytes of memory each. */
3891 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003892 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 goto error;
3894 }
3895 x = _PyLong_New(a_size + shift_digits + 1);
3896 if (x == NULL)
3897 goto error;
3898 for (i = 0; i < shift_digits; i++)
3899 x->ob_digit[i] = 0;
3900 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3901 a_size, -shift % PyLong_SHIFT);
3902 x->ob_digit[a_size + shift_digits] = rem;
3903 }
3904 else {
3905 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3906 digit rem;
3907 /* x = a >> shift */
3908 assert(a_size >= shift_digits);
3909 x = _PyLong_New(a_size - shift_digits);
3910 if (x == NULL)
3911 goto error;
3912 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3913 a_size - shift_digits, shift % PyLong_SHIFT);
3914 /* set inexact if any of the bits shifted out is nonzero */
3915 if (rem)
3916 inexact = 1;
3917 while (!inexact && shift_digits > 0)
3918 if (a->ob_digit[--shift_digits])
3919 inexact = 1;
3920 }
3921 long_normalize(x);
3922 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3925 reference to x, so it's safe to modify it in-place. */
3926 if (b_size == 1) {
3927 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3928 b->ob_digit[0]);
3929 long_normalize(x);
3930 if (rem)
3931 inexact = 1;
3932 }
3933 else {
3934 PyLongObject *div, *rem;
3935 div = x_divrem(x, b, &rem);
3936 Py_DECREF(x);
3937 x = div;
3938 if (x == NULL)
3939 goto error;
3940 if (Py_SIZE(rem))
3941 inexact = 1;
3942 Py_DECREF(rem);
3943 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003944 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 assert(x_size > 0); /* result of division is never zero */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02003946 x_bits = (x_size-1)*PyLong_SHIFT+bit_length_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003949 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 /* Round by directly modifying the low digit of x. */
3953 mask = (digit)1 << (extra_bits - 1);
3954 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003955 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003957 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 /* Convert x to a double dx; the conversion is exact. */
3960 dx = x->ob_digit[--x_size];
3961 while (x_size > 0)
3962 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3963 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 /* Check whether ldexp result will overflow a double. */
3966 if (shift + x_bits >= DBL_MAX_EXP &&
3967 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3968 goto overflow;
3969 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003970
3971 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003973
3974 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003976
3977 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 PyErr_SetString(PyExc_OverflowError,
3979 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003980 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003982}
3983
3984static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003985long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 CHECK_BINOP(a, b);
3990
Yury Selivanove0b23092016-02-11 10:26:27 -05003991 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3992 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
3993 }
3994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003995 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3996 mod = NULL;
3997 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003998}
3999
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004000static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004001long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 PyLongObject *div, *mod;
4004 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4009 return NULL;
4010 }
4011 z = PyTuple_New(2);
4012 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004013 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4014 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 }
4016 else {
4017 Py_DECREF(div);
4018 Py_DECREF(mod);
4019 }
4020 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004021}
4022
Mark Dickinsonc5299672019-06-02 10:24:06 +01004023
4024/* Compute an inverse to a modulo n, or raise ValueError if a is not
4025 invertible modulo n. Assumes n is positive. The inverse returned
4026 is whatever falls out of the extended Euclidean algorithm: it may
4027 be either positive or negative, but will be smaller than n in
4028 absolute value.
4029
4030 Pure Python equivalent for long_invmod:
4031
4032 def invmod(a, n):
4033 b, c = 1, 0
4034 while n:
4035 q, r = divmod(a, n)
4036 a, b, c, n = n, c, b - q*c, r
4037
4038 # at this point a is the gcd of the original inputs
4039 if a == 1:
4040 return b
4041 raise ValueError("Not invertible")
4042*/
4043
4044static PyLongObject *
4045long_invmod(PyLongObject *a, PyLongObject *n)
4046{
4047 PyLongObject *b, *c;
4048
4049 /* Should only ever be called for positive n */
4050 assert(Py_SIZE(n) > 0);
4051
4052 b = (PyLongObject *)PyLong_FromLong(1L);
4053 if (b == NULL) {
4054 return NULL;
4055 }
4056 c = (PyLongObject *)PyLong_FromLong(0L);
4057 if (c == NULL) {
4058 Py_DECREF(b);
4059 return NULL;
4060 }
4061 Py_INCREF(a);
4062 Py_INCREF(n);
4063
4064 /* references now owned: a, b, c, n */
4065 while (Py_SIZE(n) != 0) {
4066 PyLongObject *q, *r, *s, *t;
4067
4068 if (l_divmod(a, n, &q, &r) == -1) {
4069 goto Error;
4070 }
4071 Py_DECREF(a);
4072 a = n;
4073 n = r;
4074 t = (PyLongObject *)long_mul(q, c);
4075 Py_DECREF(q);
4076 if (t == NULL) {
4077 goto Error;
4078 }
4079 s = (PyLongObject *)long_sub(b, t);
4080 Py_DECREF(t);
4081 if (s == NULL) {
4082 goto Error;
4083 }
4084 Py_DECREF(b);
4085 b = c;
4086 c = s;
4087 }
4088 /* references now owned: a, b, c, n */
4089
4090 Py_DECREF(c);
4091 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004092 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004093 /* a != 1; we don't have an inverse. */
4094 Py_DECREF(a);
4095 Py_DECREF(b);
4096 PyErr_SetString(PyExc_ValueError,
4097 "base is not invertible for the given modulus");
4098 return NULL;
4099 }
4100 else {
4101 /* a == 1; b gives an inverse modulo n */
4102 Py_DECREF(a);
4103 return b;
4104 }
4105
4106 Error:
4107 Py_DECREF(a);
4108 Py_DECREF(b);
4109 Py_DECREF(c);
4110 Py_DECREF(n);
4111 return NULL;
4112}
4113
4114
Tim Peters47e52ee2004-08-30 02:44:38 +00004115/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004116static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004117long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4120 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 PyLongObject *z = NULL; /* accumulated result */
4123 Py_ssize_t i, j, k; /* counters */
4124 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 /* 5-ary values. If the exponent is large enough, table is
4127 * precomputed so that table[i] == a**i % c for i in range(32).
4128 */
4129 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4130 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 /* a, b, c = v, w, x */
4133 CHECK_BINOP(v, w);
4134 a = (PyLongObject*)v; Py_INCREF(a);
4135 b = (PyLongObject*)w; Py_INCREF(b);
4136 if (PyLong_Check(x)) {
4137 c = (PyLongObject *)x;
4138 Py_INCREF(x);
4139 }
4140 else if (x == Py_None)
4141 c = NULL;
4142 else {
4143 Py_DECREF(a);
4144 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004145 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 }
Tim Peters4c483c42001-09-05 06:24:58 +00004147
Mark Dickinsonc5299672019-06-02 10:24:06 +01004148 if (Py_SIZE(b) < 0 && c == NULL) {
4149 /* if exponent is negative and there's no modulus:
4150 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 that this calls float_pow() which converts its
4152 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004153 Py_DECREF(a);
4154 Py_DECREF(b);
4155 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 if (c) {
4159 /* if modulus == 0:
4160 raise ValueError() */
4161 if (Py_SIZE(c) == 0) {
4162 PyErr_SetString(PyExc_ValueError,
4163 "pow() 3rd argument cannot be 0");
4164 goto Error;
4165 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 /* if modulus < 0:
4168 negativeOutput = True
4169 modulus = -modulus */
4170 if (Py_SIZE(c) < 0) {
4171 negativeOutput = 1;
4172 temp = (PyLongObject *)_PyLong_Copy(c);
4173 if (temp == NULL)
4174 goto Error;
4175 Py_DECREF(c);
4176 c = temp;
4177 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004178 _PyLong_Negate(&c);
4179 if (c == NULL)
4180 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 /* if modulus == 1:
4184 return 0 */
4185 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4186 z = (PyLongObject *)PyLong_FromLong(0L);
4187 goto Done;
4188 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004189
Mark Dickinsonc5299672019-06-02 10:24:06 +01004190 /* if exponent is negative, negate the exponent and
4191 replace the base with a modular inverse */
4192 if (Py_SIZE(b) < 0) {
4193 temp = (PyLongObject *)_PyLong_Copy(b);
4194 if (temp == NULL)
4195 goto Error;
4196 Py_DECREF(b);
4197 b = temp;
4198 temp = NULL;
4199 _PyLong_Negate(&b);
4200 if (b == NULL)
4201 goto Error;
4202
4203 temp = long_invmod(a, c);
4204 if (temp == NULL)
4205 goto Error;
4206 Py_DECREF(a);
4207 a = temp;
4208 }
4209
Tim Peters81a93152013-10-05 16:53:52 -05004210 /* Reduce base by modulus in some cases:
4211 1. If base < 0. Forcing the base non-negative makes things easier.
4212 2. If base is obviously larger than the modulus. The "small
4213 exponent" case later can multiply directly by base repeatedly,
4214 while the "large exponent" case multiplies directly by base 31
4215 times. It can be unboundedly faster to multiply by
4216 base % modulus instead.
4217 We could _always_ do this reduction, but l_divmod() isn't cheap,
4218 so we only do it when it buys something. */
4219 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 if (l_divmod(a, c, NULL, &temp) < 0)
4221 goto Error;
4222 Py_DECREF(a);
4223 a = temp;
4224 temp = NULL;
4225 }
4226 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 /* At this point a, b, and c are guaranteed non-negative UNLESS
4229 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 z = (PyLongObject *)PyLong_FromLong(1L);
4232 if (z == NULL)
4233 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 /* Perform a modular reduction, X = X % c, but leave X alone if c
4236 * is NULL.
4237 */
4238#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004239 do { \
4240 if (c != NULL) { \
4241 if (l_divmod(X, c, NULL, &temp) < 0) \
4242 goto Error; \
4243 Py_XDECREF(X); \
4244 X = temp; \
4245 temp = NULL; \
4246 } \
4247 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 /* Multiply two values, then reduce the result:
4250 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004251#define MULT(X, Y, result) \
4252 do { \
4253 temp = (PyLongObject *)long_mul(X, Y); \
4254 if (temp == NULL) \
4255 goto Error; \
4256 Py_XDECREF(result); \
4257 result = temp; \
4258 temp = NULL; \
4259 REDUCE(result); \
4260 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4263 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4264 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4265 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4266 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004269 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004271 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 }
4273 }
4274 }
4275 else {
4276 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4277 Py_INCREF(z); /* still holds 1L */
4278 table[0] = z;
4279 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004280 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4283 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4286 const int index = (bi >> j) & 0x1f;
4287 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004288 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004290 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004291 }
4292 }
4293 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004295 if (negativeOutput && (Py_SIZE(z) != 0)) {
4296 temp = (PyLongObject *)long_sub(z, c);
4297 if (temp == NULL)
4298 goto Error;
4299 Py_DECREF(z);
4300 z = temp;
4301 temp = NULL;
4302 }
4303 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004304
Mark Dickinson22b20182010-05-10 21:27:53 +00004305 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004306 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004308 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4310 for (i = 0; i < 32; ++i)
4311 Py_XDECREF(table[i]);
4312 }
4313 Py_DECREF(a);
4314 Py_DECREF(b);
4315 Py_XDECREF(c);
4316 Py_XDECREF(temp);
4317 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004318}
4319
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004320static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004321long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 /* Implement ~x as -(x+1) */
4324 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004325 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004327 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 if (x == NULL)
4329 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004330 _PyLong_Negate(&x);
4331 /* No need for maybe_small_long here, since any small
4332 longs will have been caught in the Py_SIZE <= 1 fast path. */
4333 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004334}
4335
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004336static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004337long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004340 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 return PyLong_FromLong(-MEDIUM_VALUE(v));
4342 z = (PyLongObject *)_PyLong_Copy(v);
4343 if (z != NULL)
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004344 Py_SET_SIZE(z, -(Py_SIZE(v)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004346}
4347
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004348static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004349long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 if (Py_SIZE(v) < 0)
4352 return long_neg(v);
4353 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004354 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004355}
4356
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004357static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004358long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004361}
4362
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004363/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4364static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004365divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004366{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004367 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004368 assert(Py_SIZE(shiftby) >= 0);
4369 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4370 if (lshiftby >= 0) {
4371 *wordshift = lshiftby / PyLong_SHIFT;
4372 *remshift = lshiftby % PyLong_SHIFT;
4373 return 0;
4374 }
4375 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4376 be that PyLong_AsSsize_t raised an OverflowError. */
4377 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4378 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004379 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004380 if (wordshift_obj == NULL) {
4381 return -1;
4382 }
4383 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4384 Py_DECREF(wordshift_obj);
4385 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4386 return 0;
4387 }
4388 PyErr_Clear();
4389 /* Clip the value. With such large wordshift the right shift
4390 returns 0 and the left shift raises an error in _PyLong_New(). */
4391 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4392 *remshift = 0;
4393 return 0;
4394}
4395
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004396static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004397long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004400 Py_ssize_t newsize, hishift, i, j;
4401 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 if (Py_SIZE(a) < 0) {
4404 /* Right shifting negative numbers is harder */
4405 PyLongObject *a1, *a2;
4406 a1 = (PyLongObject *) long_invert(a);
4407 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004408 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004409 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 Py_DECREF(a1);
4411 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004412 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 z = (PyLongObject *) long_invert(a2);
4414 Py_DECREF(a2);
4415 }
4416 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004417 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 if (newsize <= 0)
4419 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004420 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 lomask = ((digit)1 << hishift) - 1;
4422 himask = PyLong_MASK ^ lomask;
4423 z = _PyLong_New(newsize);
4424 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004425 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004427 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004429 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004431 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004433 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004434}
4435
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004436static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004437long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004438{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004439 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004440 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004443
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004444 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004446 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004448 if (Py_SIZE(a) == 0) {
4449 return PyLong_FromLong(0);
4450 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004451 if (divmod_shift(b, &wordshift, &remshift) < 0)
4452 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004453 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4454}
4455
4456/* Return a >> shiftby. */
4457PyObject *
4458_PyLong_Rshift(PyObject *a, size_t shiftby)
4459{
4460 Py_ssize_t wordshift;
4461 digit remshift;
4462
4463 assert(PyLong_Check(a));
4464 if (Py_SIZE(a) == 0) {
4465 return PyLong_FromLong(0);
4466 }
4467 wordshift = shiftby / PyLong_SHIFT;
4468 remshift = shiftby % PyLong_SHIFT;
4469 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4470}
4471
4472static PyObject *
4473long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4474{
4475 /* This version due to Tim Peters */
4476 PyLongObject *z = NULL;
4477 Py_ssize_t oldsize, newsize, i, j;
4478 twodigits accum;
4479
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004480 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 newsize = oldsize + wordshift;
4482 if (remshift)
4483 ++newsize;
4484 z = _PyLong_New(newsize);
4485 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004486 return NULL;
4487 if (Py_SIZE(a) < 0) {
4488 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004489 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02004490 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 for (i = 0; i < wordshift; i++)
4492 z->ob_digit[i] = 0;
4493 accum = 0;
4494 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4495 accum |= (twodigits)a->ob_digit[j] << remshift;
4496 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4497 accum >>= PyLong_SHIFT;
4498 }
4499 if (remshift)
4500 z->ob_digit[newsize-1] = (digit)accum;
4501 else
4502 assert(!accum);
4503 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004505}
4506
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004507static PyObject *
4508long_lshift(PyObject *a, PyObject *b)
4509{
4510 Py_ssize_t wordshift;
4511 digit remshift;
4512
4513 CHECK_BINOP(a, b);
4514
4515 if (Py_SIZE(b) < 0) {
4516 PyErr_SetString(PyExc_ValueError, "negative shift count");
4517 return NULL;
4518 }
4519 if (Py_SIZE(a) == 0) {
4520 return PyLong_FromLong(0);
4521 }
4522 if (divmod_shift(b, &wordshift, &remshift) < 0)
4523 return NULL;
4524 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4525}
4526
4527/* Return a << shiftby. */
4528PyObject *
4529_PyLong_Lshift(PyObject *a, size_t shiftby)
4530{
4531 Py_ssize_t wordshift;
4532 digit remshift;
4533
4534 assert(PyLong_Check(a));
4535 if (Py_SIZE(a) == 0) {
4536 return PyLong_FromLong(0);
4537 }
4538 wordshift = shiftby / PyLong_SHIFT;
4539 remshift = shiftby % PyLong_SHIFT;
4540 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4541}
4542
Mark Dickinson27a87a22009-10-25 20:43:34 +00004543/* Compute two's complement of digit vector a[0:m], writing result to
4544 z[0:m]. The digit vector a need not be normalized, but should not
4545 be entirely zero. a and z may point to the same digit vector. */
4546
4547static void
4548v_complement(digit *z, digit *a, Py_ssize_t m)
4549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 Py_ssize_t i;
4551 digit carry = 1;
4552 for (i = 0; i < m; ++i) {
4553 carry += a[i] ^ PyLong_MASK;
4554 z[i] = carry & PyLong_MASK;
4555 carry >>= PyLong_SHIFT;
4556 }
4557 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004558}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004559
4560/* Bitwise and/xor/or operations */
4561
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004562static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004563long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004564 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004565 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 int nega, negb, negz;
4568 Py_ssize_t size_a, size_b, size_z, i;
4569 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 /* Bitwise operations for negative numbers operate as though
4572 on a two's complement representation. So convert arguments
4573 from sign-magnitude to two's complement, and convert the
4574 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004577 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 nega = Py_SIZE(a) < 0;
4579 if (nega) {
4580 z = _PyLong_New(size_a);
4581 if (z == NULL)
4582 return NULL;
4583 v_complement(z->ob_digit, a->ob_digit, size_a);
4584 a = z;
4585 }
4586 else
4587 /* Keep reference count consistent. */
4588 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004591 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 negb = Py_SIZE(b) < 0;
4593 if (negb) {
4594 z = _PyLong_New(size_b);
4595 if (z == NULL) {
4596 Py_DECREF(a);
4597 return NULL;
4598 }
4599 v_complement(z->ob_digit, b->ob_digit, size_b);
4600 b = z;
4601 }
4602 else
4603 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 /* Swap a and b if necessary to ensure size_a >= size_b. */
4606 if (size_a < size_b) {
4607 z = a; a = b; b = z;
4608 size_z = size_a; size_a = size_b; size_b = size_z;
4609 negz = nega; nega = negb; negb = negz;
4610 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 /* JRH: The original logic here was to allocate the result value (z)
4613 as the longer of the two operands. However, there are some cases
4614 where the result is guaranteed to be shorter than that: AND of two
4615 positives, OR of two negatives: use the shorter number. AND with
4616 mixed signs: use the positive number. OR with mixed signs: use the
4617 negative number.
4618 */
4619 switch (op) {
4620 case '^':
4621 negz = nega ^ negb;
4622 size_z = size_a;
4623 break;
4624 case '&':
4625 negz = nega & negb;
4626 size_z = negb ? size_a : size_b;
4627 break;
4628 case '|':
4629 negz = nega | negb;
4630 size_z = negb ? size_b : size_a;
4631 break;
4632 default:
stratakisa10d4262019-03-18 18:59:20 +01004633 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 /* We allow an extra digit if z is negative, to make sure that
4637 the final two's complement of z doesn't overflow. */
4638 z = _PyLong_New(size_z + negz);
4639 if (z == NULL) {
4640 Py_DECREF(a);
4641 Py_DECREF(b);
4642 return NULL;
4643 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004645 /* Compute digits for overlap of a and b. */
4646 switch(op) {
4647 case '&':
4648 for (i = 0; i < size_b; ++i)
4649 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4650 break;
4651 case '|':
4652 for (i = 0; i < size_b; ++i)
4653 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4654 break;
4655 case '^':
4656 for (i = 0; i < size_b; ++i)
4657 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4658 break;
4659 default:
stratakisa10d4262019-03-18 18:59:20 +01004660 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 /* Copy any remaining digits of a, inverting if necessary. */
4664 if (op == '^' && negb)
4665 for (; i < size_z; ++i)
4666 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4667 else if (i < size_z)
4668 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4669 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 /* Complement result if negative. */
4672 if (negz) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004673 Py_SET_SIZE(z, -(Py_SIZE(z)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 z->ob_digit[size_z] = PyLong_MASK;
4675 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4676 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 Py_DECREF(a);
4679 Py_DECREF(b);
4680 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004681}
4682
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004683static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004684long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 PyObject *c;
4687 CHECK_BINOP(a, b);
4688 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4689 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004690}
4691
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004692static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004693long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 PyObject *c;
4696 CHECK_BINOP(a, b);
4697 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4698 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004699}
4700
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004701static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004702long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704 PyObject *c;
4705 CHECK_BINOP(a, b);
4706 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4707 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004708}
4709
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004710static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004711long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 if (PyLong_CheckExact(v))
4714 Py_INCREF(v);
4715 else
4716 v = _PyLong_Copy((PyLongObject *)v);
4717 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004718}
4719
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004720PyObject *
4721_PyLong_GCD(PyObject *aarg, PyObject *barg)
4722{
4723 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4724 stwodigits x, y, q, s, t, c_carry, d_carry;
4725 stwodigits A, B, C, D, T;
4726 int nbits, k;
4727 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4728 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4729
4730 a = (PyLongObject *)aarg;
4731 b = (PyLongObject *)barg;
4732 size_a = Py_SIZE(a);
4733 size_b = Py_SIZE(b);
4734 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4735 Py_INCREF(a);
4736 Py_INCREF(b);
4737 goto simple;
4738 }
4739
4740 /* Initial reduction: make sure that 0 <= b <= a. */
4741 a = (PyLongObject *)long_abs(a);
4742 if (a == NULL)
4743 return NULL;
4744 b = (PyLongObject *)long_abs(b);
4745 if (b == NULL) {
4746 Py_DECREF(a);
4747 return NULL;
4748 }
4749 if (long_compare(a, b) < 0) {
4750 r = a;
4751 a = b;
4752 b = r;
4753 }
4754 /* We now own references to a and b */
4755
4756 alloc_a = Py_SIZE(a);
4757 alloc_b = Py_SIZE(b);
4758 /* reduce until a fits into 2 digits */
4759 while ((size_a = Py_SIZE(a)) > 2) {
Niklas Fiekas794e7d12020-06-15 14:33:48 +02004760 nbits = bit_length_digit(a->ob_digit[size_a-1]);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004761 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4762 corresponding bits of b into y */
4763 size_b = Py_SIZE(b);
4764 assert(size_b <= size_a);
4765 if (size_b == 0) {
4766 if (size_a < alloc_a) {
4767 r = (PyLongObject *)_PyLong_Copy(a);
4768 Py_DECREF(a);
4769 }
4770 else
4771 r = a;
4772 Py_DECREF(b);
4773 Py_XDECREF(c);
4774 Py_XDECREF(d);
4775 return (PyObject *)r;
4776 }
4777 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4778 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4779 (a->ob_digit[size_a-3] >> nbits));
4780
4781 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4782 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4783 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4784
4785 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4786 larger than PyLong_MASK during the algorithm. */
4787 A = 1; B = 0; C = 0; D = 1;
4788 for (k=0;; k++) {
4789 if (y-C == 0)
4790 break;
4791 q = (x+(A-1))/(y-C);
4792 s = B+q*D;
4793 t = x-q*y;
4794 if (s > t)
4795 break;
4796 x = y; y = t;
4797 t = A+q*C; A = D; B = C; C = s; D = t;
4798 }
4799
4800 if (k == 0) {
4801 /* no progress; do a Euclidean step */
4802 if (l_divmod(a, b, NULL, &r) < 0)
4803 goto error;
4804 Py_DECREF(a);
4805 a = b;
4806 b = r;
4807 alloc_a = alloc_b;
4808 alloc_b = Py_SIZE(b);
4809 continue;
4810 }
4811
4812 /*
4813 a, b = A*b-B*a, D*a-C*b if k is odd
4814 a, b = A*a-B*b, D*b-C*a if k is even
4815 */
4816 if (k&1) {
4817 T = -A; A = -B; B = T;
4818 T = -C; C = -D; D = T;
4819 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004820 if (c != NULL) {
4821 Py_SET_SIZE(c, size_a);
4822 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004823 else if (Py_REFCNT(a) == 1) {
4824 Py_INCREF(a);
4825 c = a;
4826 }
4827 else {
4828 alloc_a = size_a;
4829 c = _PyLong_New(size_a);
4830 if (c == NULL)
4831 goto error;
4832 }
4833
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004834 if (d != NULL) {
4835 Py_SET_SIZE(d, size_a);
4836 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004837 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4838 Py_INCREF(b);
4839 d = b;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004840 Py_SET_SIZE(d, size_a);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004841 }
4842 else {
4843 alloc_b = size_a;
4844 d = _PyLong_New(size_a);
4845 if (d == NULL)
4846 goto error;
4847 }
4848 a_end = a->ob_digit + size_a;
4849 b_end = b->ob_digit + size_b;
4850
4851 /* compute new a and new b in parallel */
4852 a_digit = a->ob_digit;
4853 b_digit = b->ob_digit;
4854 c_digit = c->ob_digit;
4855 d_digit = d->ob_digit;
4856 c_carry = 0;
4857 d_carry = 0;
4858 while (b_digit < b_end) {
4859 c_carry += (A * *a_digit) - (B * *b_digit);
4860 d_carry += (D * *b_digit++) - (C * *a_digit++);
4861 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4862 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4863 c_carry >>= PyLong_SHIFT;
4864 d_carry >>= PyLong_SHIFT;
4865 }
4866 while (a_digit < a_end) {
4867 c_carry += A * *a_digit;
4868 d_carry -= C * *a_digit++;
4869 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4870 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4871 c_carry >>= PyLong_SHIFT;
4872 d_carry >>= PyLong_SHIFT;
4873 }
4874 assert(c_carry == 0);
4875 assert(d_carry == 0);
4876
4877 Py_INCREF(c);
4878 Py_INCREF(d);
4879 Py_DECREF(a);
4880 Py_DECREF(b);
4881 a = long_normalize(c);
4882 b = long_normalize(d);
4883 }
4884 Py_XDECREF(c);
4885 Py_XDECREF(d);
4886
4887simple:
4888 assert(Py_REFCNT(a) > 0);
4889 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004890/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4891 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4892#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004893 /* a fits into a long, so b must too */
4894 x = PyLong_AsLong((PyObject *)a);
4895 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004896#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004897 x = PyLong_AsLongLong((PyObject *)a);
4898 y = PyLong_AsLongLong((PyObject *)b);
4899#else
4900# error "_PyLong_GCD"
4901#endif
4902 x = Py_ABS(x);
4903 y = Py_ABS(y);
4904 Py_DECREF(a);
4905 Py_DECREF(b);
4906
4907 /* usual Euclidean algorithm for longs */
4908 while (y != 0) {
4909 t = y;
4910 y = x % y;
4911 x = t;
4912 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004913#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004914 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004915#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004916 return PyLong_FromLongLong(x);
4917#else
4918# error "_PyLong_GCD"
4919#endif
4920
4921error:
4922 Py_DECREF(a);
4923 Py_DECREF(b);
4924 Py_XDECREF(c);
4925 Py_XDECREF(d);
4926 return NULL;
4927}
4928
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004929static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004930long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004932 double result;
4933 result = PyLong_AsDouble(v);
4934 if (result == -1.0 && PyErr_Occurred())
4935 return NULL;
4936 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004937}
4938
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004939static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004940long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
4941
4942/*[clinic input]
4943@classmethod
4944int.__new__ as long_new
4945 x: object(c_default="NULL") = 0
4946 /
4947 base as obase: object(c_default="NULL") = 10
4948[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004949
Tim Peters6d6c1a32001-08-02 04:15:00 +00004950static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004951long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
4952/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00004953{
Gregory P. Smitha689e522012-12-25 22:38:32 -08004954 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004956 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004957 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004958 if (x == NULL) {
4959 if (obase != NULL) {
4960 PyErr_SetString(PyExc_TypeError,
4961 "int() missing string argument");
4962 return NULL;
4963 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004965 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004966 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004967 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004968
Gregory P. Smitha689e522012-12-25 22:38:32 -08004969 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004970 if (base == -1 && PyErr_Occurred())
4971 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004972 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004973 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05304974 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004975 return NULL;
4976 }
4977
4978 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004979 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004980 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004981 const char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004982 if (PyByteArray_Check(x))
4983 string = PyByteArray_AS_STRING(x);
4984 else
4985 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004986 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 }
4988 else {
4989 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004990 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 return NULL;
4992 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004993}
4994
Serhiy Storchaka95949422013-08-27 19:40:23 +03004995/* Wimpy, slow approach to tp_new calls for subtypes of int:
4996 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004997 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004998 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004999*/
5000static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005001long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 PyLongObject *tmp, *newobj;
5004 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005006 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005007 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 if (tmp == NULL)
5009 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005010 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 n = Py_SIZE(tmp);
5012 if (n < 0)
5013 n = -n;
5014 newobj = (PyLongObject *)type->tp_alloc(type, n);
5015 if (newobj == NULL) {
5016 Py_DECREF(tmp);
5017 return NULL;
5018 }
5019 assert(PyLong_Check(newobj));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005020 Py_SET_SIZE(newobj, Py_SIZE(tmp));
5021 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 newobj->ob_digit[i] = tmp->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005023 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005024 Py_DECREF(tmp);
5025 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005026}
5027
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005028/*[clinic input]
5029int.__getnewargs__
5030[clinic start generated code]*/
5031
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005032static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005033int___getnewargs___impl(PyObject *self)
5034/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005035{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005036 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005037}
5038
Guido van Rossumb43daf72007-08-01 18:08:08 +00005039static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005040long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005043}
5044
5045static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005046long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005049}
5050
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005051/*[clinic input]
5052int.__format__
5053
5054 format_spec: unicode
5055 /
5056[clinic start generated code]*/
5057
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005058static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005059int___format___impl(PyObject *self, PyObject *format_spec)
5060/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005061{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005062 _PyUnicodeWriter writer;
5063 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005064
Victor Stinner8f674cc2013-04-17 23:02:17 +02005065 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005066 ret = _PyLong_FormatAdvancedWriter(
5067 &writer,
5068 self,
5069 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5070 if (ret == -1) {
5071 _PyUnicodeWriter_Dealloc(&writer);
5072 return NULL;
5073 }
5074 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005075}
5076
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005077/* Return a pair (q, r) such that a = b * q + r, and
5078 abs(r) <= abs(b)/2, with equality possible only if q is even.
5079 In other words, q == a / b, rounded to the nearest integer using
5080 round-half-to-even. */
5081
5082PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005083_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005084{
5085 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005086 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005087 int quo_is_odd, quo_is_neg;
5088 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005089
5090 /* Equivalent Python code:
5091
5092 def divmod_near(a, b):
5093 q, r = divmod(a, b)
5094 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5095 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5096 # positive, 2 * r < b if b negative.
5097 greater_than_half = 2*r > b if b > 0 else 2*r < b
5098 exactly_half = 2*r == b
5099 if greater_than_half or exactly_half and q % 2 == 1:
5100 q += 1
5101 r -= b
5102 return q, r
5103
5104 */
5105 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5106 PyErr_SetString(PyExc_TypeError,
5107 "non-integer arguments in division");
5108 return NULL;
5109 }
5110
5111 /* Do a and b have different signs? If so, quotient is negative. */
5112 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5113
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005114 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5115 goto error;
5116
5117 /* compare twice the remainder with the divisor, to see
5118 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005119 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005120 if (twice_rem == NULL)
5121 goto error;
5122 if (quo_is_neg) {
5123 temp = long_neg((PyLongObject*)twice_rem);
5124 Py_DECREF(twice_rem);
5125 twice_rem = temp;
5126 if (twice_rem == NULL)
5127 goto error;
5128 }
5129 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5130 Py_DECREF(twice_rem);
5131
5132 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5133 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5134 /* fix up quotient */
5135 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005136 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005137 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005138 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005139 Py_DECREF(quo);
5140 quo = (PyLongObject *)temp;
5141 if (quo == NULL)
5142 goto error;
5143 /* and remainder */
5144 if (quo_is_neg)
5145 temp = long_add(rem, (PyLongObject *)b);
5146 else
5147 temp = long_sub(rem, (PyLongObject *)b);
5148 Py_DECREF(rem);
5149 rem = (PyLongObject *)temp;
5150 if (rem == NULL)
5151 goto error;
5152 }
5153
5154 result = PyTuple_New(2);
5155 if (result == NULL)
5156 goto error;
5157
5158 /* PyTuple_SET_ITEM steals references */
5159 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5160 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005161 return result;
5162
5163 error:
5164 Py_XDECREF(quo);
5165 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005166 return NULL;
5167}
5168
Eric Smith8c663262007-08-25 02:26:07 +00005169static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005170long_round(PyObject *self, PyObject *args)
5171{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005172 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005173
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005174 /* To round an integer m to the nearest 10**n (n positive), we make use of
5175 * the divmod_near operation, defined by:
5176 *
5177 * divmod_near(a, b) = (q, r)
5178 *
5179 * where q is the nearest integer to the quotient a / b (the
5180 * nearest even integer in the case of a tie) and r == a - q * b.
5181 * Hence q * b = a - r is the nearest multiple of b to a,
5182 * preferring even multiples in the case of a tie.
5183 *
5184 * So the nearest multiple of 10**n to m is:
5185 *
5186 * m - divmod_near(m, 10**n)[1].
5187 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005188 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5189 return NULL;
5190 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005191 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005192
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03005193 ndigits = _PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 if (ndigits == NULL)
5195 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005196
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005197 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 if (Py_SIZE(ndigits) >= 0) {
5199 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005200 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005202
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005203 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5204 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005206 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005208 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005209
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005210 result = PyLong_FromLong(10L);
5211 if (result == NULL) {
5212 Py_DECREF(ndigits);
5213 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005215
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005216 temp = long_pow(result, ndigits, Py_None);
5217 Py_DECREF(ndigits);
5218 Py_DECREF(result);
5219 result = temp;
5220 if (result == NULL)
5221 return NULL;
5222
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005223 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005224 Py_DECREF(result);
5225 result = temp;
5226 if (result == NULL)
5227 return NULL;
5228
5229 temp = long_sub((PyLongObject *)self,
5230 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5231 Py_DECREF(result);
5232 result = temp;
5233
5234 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005235}
5236
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005237/*[clinic input]
5238int.__sizeof__ -> Py_ssize_t
5239
5240Returns size in memory, in bytes.
5241[clinic start generated code]*/
5242
5243static Py_ssize_t
5244int___sizeof___impl(PyObject *self)
5245/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005247 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005248
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005249 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5250 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005251}
5252
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005253/*[clinic input]
5254int.bit_length
5255
5256Number of bits necessary to represent self in binary.
5257
5258>>> bin(37)
5259'0b100101'
5260>>> (37).bit_length()
52616
5262[clinic start generated code]*/
5263
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005264static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005265int_bit_length_impl(PyObject *self)
5266/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005269 Py_ssize_t ndigits;
5270 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005272
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005273 assert(self != NULL);
5274 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005275
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005276 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277 if (ndigits == 0)
5278 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005279
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005280 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Niklas Fiekas794e7d12020-06-15 14:33:48 +02005281 msd_bits = bit_length_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5284 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005286 /* expression above may overflow; use Python integers instead */
5287 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5288 if (result == NULL)
5289 return NULL;
5290 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5291 if (x == NULL)
5292 goto error;
5293 y = (PyLongObject *)long_mul(result, x);
5294 Py_DECREF(x);
5295 if (y == NULL)
5296 goto error;
5297 Py_DECREF(result);
5298 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5301 if (x == NULL)
5302 goto error;
5303 y = (PyLongObject *)long_add(result, x);
5304 Py_DECREF(x);
5305 if (y == NULL)
5306 goto error;
5307 Py_DECREF(result);
5308 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005310 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005311
Mark Dickinson22b20182010-05-10 21:27:53 +00005312 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 Py_DECREF(result);
5314 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005315}
5316
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005317static int
5318popcount_digit(digit d)
5319{
Victor Stinnerc6b292c2020-06-08 16:30:33 +02005320 // digit can be larger than uint32_t, but only PyLong_SHIFT bits
5321 // of it will be ever used.
5322 Py_BUILD_ASSERT(PyLong_SHIFT <= 32);
5323 return _Py_popcount32((uint32_t)d);
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005324}
5325
5326/*[clinic input]
5327int.bit_count
5328
5329Number of ones in the binary representation of the absolute value of self.
5330
5331Also known as the population count.
5332
5333>>> bin(13)
5334'0b1101'
5335>>> (13).bit_count()
53363
5337[clinic start generated code]*/
5338
5339static PyObject *
5340int_bit_count_impl(PyObject *self)
5341/*[clinic end generated code: output=2e571970daf1e5c3 input=7e0adef8e8ccdf2e]*/
5342{
5343 assert(self != NULL);
5344 assert(PyLong_Check(self));
5345
5346 PyLongObject *z = (PyLongObject *)self;
5347 Py_ssize_t ndigits = Py_ABS(Py_SIZE(z));
5348 Py_ssize_t bit_count = 0;
5349
5350 /* Each digit has up to PyLong_SHIFT ones, so the accumulated bit count
5351 from the first PY_SSIZE_T_MAX/PyLong_SHIFT digits can't overflow a
5352 Py_ssize_t. */
5353 Py_ssize_t ndigits_fast = Py_MIN(ndigits, PY_SSIZE_T_MAX/PyLong_SHIFT);
5354 for (Py_ssize_t i = 0; i < ndigits_fast; i++) {
5355 bit_count += popcount_digit(z->ob_digit[i]);
5356 }
5357
5358 PyObject *result = PyLong_FromSsize_t(bit_count);
5359 if (result == NULL) {
5360 return NULL;
5361 }
5362
5363 /* Use Python integers if bit_count would overflow. */
5364 for (Py_ssize_t i = ndigits_fast; i < ndigits; i++) {
5365 PyObject *x = PyLong_FromLong(popcount_digit(z->ob_digit[i]));
5366 if (x == NULL) {
5367 goto error;
5368 }
5369 PyObject *y = long_add((PyLongObject *)result, (PyLongObject *)x);
5370 Py_DECREF(x);
5371 if (y == NULL) {
5372 goto error;
5373 }
5374 Py_DECREF(result);
5375 result = y;
5376 }
5377
5378 return result;
5379
5380 error:
5381 Py_DECREF(result);
5382 return NULL;
5383}
Christian Heimes53876d92008-04-19 00:31:39 +00005384
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005385/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005386int.as_integer_ratio
5387
5388Return integer ratio.
5389
5390Return a pair of integers, whose ratio is exactly equal to the original int
5391and with a positive denominator.
5392
5393>>> (10).as_integer_ratio()
5394(10, 1)
5395>>> (-10).as_integer_ratio()
5396(-10, 1)
5397>>> (0).as_integer_ratio()
5398(0, 1)
5399[clinic start generated code]*/
5400
5401static PyObject *
5402int_as_integer_ratio_impl(PyObject *self)
5403/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5404{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005405 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005406 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005407 if (numerator == NULL) {
5408 return NULL;
5409 }
5410 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5411 Py_DECREF(numerator);
5412 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005413}
5414
5415/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005416int.to_bytes
5417
5418 length: Py_ssize_t
5419 Length of bytes object to use. An OverflowError is raised if the
5420 integer is not representable with the given number of bytes.
5421 byteorder: unicode
5422 The byte order used to represent the integer. If byteorder is 'big',
5423 the most significant byte is at the beginning of the byte array. If
5424 byteorder is 'little', the most significant byte is at the end of the
5425 byte array. To request the native byte order of the host system, use
5426 `sys.byteorder' as the byte order value.
5427 *
5428 signed as is_signed: bool = False
5429 Determines whether two's complement is used to represent the integer.
5430 If signed is False and a negative integer is given, an OverflowError
5431 is raised.
5432
5433Return an array of bytes representing an integer.
5434[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005435
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005436static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005437int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5438 int is_signed)
5439/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005443
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005444 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005446 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 little_endian = 0;
5448 else {
5449 PyErr_SetString(PyExc_ValueError,
5450 "byteorder must be either 'little' or 'big'");
5451 return NULL;
5452 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005454 if (length < 0) {
5455 PyErr_SetString(PyExc_ValueError,
5456 "length argument must be non-negative");
5457 return NULL;
5458 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 bytes = PyBytes_FromStringAndSize(NULL, length);
5461 if (bytes == NULL)
5462 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005463
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005464 if (_PyLong_AsByteArray((PyLongObject *)self,
5465 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 length, little_endian, is_signed) < 0) {
5467 Py_DECREF(bytes);
5468 return NULL;
5469 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005472}
5473
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005474/*[clinic input]
5475@classmethod
5476int.from_bytes
5477
5478 bytes as bytes_obj: object
5479 Holds the array of bytes to convert. The argument must either
5480 support the buffer protocol or be an iterable object producing bytes.
5481 Bytes and bytearray are examples of built-in objects that support the
5482 buffer protocol.
5483 byteorder: unicode
5484 The byte order used to represent the integer. If byteorder is 'big',
5485 the most significant byte is at the beginning of the byte array. If
5486 byteorder is 'little', the most significant byte is at the end of the
5487 byte array. To request the native byte order of the host system, use
5488 `sys.byteorder' as the byte order value.
5489 *
5490 signed as is_signed: bool = False
5491 Indicates whether two's complement is used to represent the integer.
5492
5493Return the integer represented by the given array of bytes.
5494[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005495
5496static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005497int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5498 PyObject *byteorder, int is_signed)
5499/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005502 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005503
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005504 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005506 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 little_endian = 0;
5508 else {
5509 PyErr_SetString(PyExc_ValueError,
5510 "byteorder must be either 'little' or 'big'");
5511 return NULL;
5512 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005513
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005514 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005515 if (bytes == NULL)
5516 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 long_obj = _PyLong_FromByteArray(
5519 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5520 little_endian, is_signed);
5521 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005522
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005523 if (long_obj != NULL && type != &PyLong_Type) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005524 Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005528}
5529
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005530static PyObject *
5531long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5532{
5533 return long_long(self);
5534}
5535
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005536static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005537 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005539 INT_BIT_LENGTH_METHODDEF
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005540 INT_BIT_COUNT_METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005541 INT_TO_BYTES_METHODDEF
5542 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005543 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005544 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005546 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005548 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 "Ceiling of an Integral returns itself."},
5550 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5551 "Rounding an Integral returns itself.\n"
5552 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005553 INT___GETNEWARGS___METHODDEF
5554 INT___FORMAT___METHODDEF
5555 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005557};
5558
Guido van Rossumb43daf72007-08-01 18:08:08 +00005559static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005560 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005561 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005562 "the real part of a complex number",
5563 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005564 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005565 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005566 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005567 NULL},
5568 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005569 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005570 "the numerator of a rational number in lowest terms",
5571 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005572 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005573 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005574 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005575 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005576 {NULL} /* Sentinel */
5577};
5578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005579PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005580"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005581int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005582\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005583Convert a number or string to an integer, or return 0 if no arguments\n\
5584are given. If x is a number, return x.__int__(). For floating point\n\
5585numbers, this truncates towards zero.\n\
5586\n\
5587If x is not a number or if base is given, then x must be a string,\n\
5588bytes, or bytearray instance representing an integer literal in the\n\
5589given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5590by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5591Base 0 means to interpret the base from the string as an integer literal.\n\
5592>>> int('0b100', base=0)\n\
55934");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005594
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005595static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005596 (binaryfunc)long_add, /*nb_add*/
5597 (binaryfunc)long_sub, /*nb_subtract*/
5598 (binaryfunc)long_mul, /*nb_multiply*/
5599 long_mod, /*nb_remainder*/
5600 long_divmod, /*nb_divmod*/
5601 long_pow, /*nb_power*/
5602 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005603 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005604 (unaryfunc)long_abs, /*tp_absolute*/
5605 (inquiry)long_bool, /*tp_bool*/
5606 (unaryfunc)long_invert, /*nb_invert*/
5607 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005608 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005609 long_and, /*nb_and*/
5610 long_xor, /*nb_xor*/
5611 long_or, /*nb_or*/
5612 long_long, /*nb_int*/
5613 0, /*nb_reserved*/
5614 long_float, /*nb_float*/
5615 0, /* nb_inplace_add */
5616 0, /* nb_inplace_subtract */
5617 0, /* nb_inplace_multiply */
5618 0, /* nb_inplace_remainder */
5619 0, /* nb_inplace_power */
5620 0, /* nb_inplace_lshift */
5621 0, /* nb_inplace_rshift */
5622 0, /* nb_inplace_and */
5623 0, /* nb_inplace_xor */
5624 0, /* nb_inplace_or */
5625 long_div, /* nb_floor_divide */
5626 long_true_divide, /* nb_true_divide */
5627 0, /* nb_inplace_floor_divide */
5628 0, /* nb_inplace_true_divide */
5629 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005630};
5631
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005632PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005633 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5634 "int", /* tp_name */
5635 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5636 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005637 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005638 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005639 0, /* tp_getattr */
5640 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005641 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005642 long_to_decimal_string, /* tp_repr */
5643 &long_as_number, /* tp_as_number */
5644 0, /* tp_as_sequence */
5645 0, /* tp_as_mapping */
5646 (hashfunc)long_hash, /* tp_hash */
5647 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005648 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005649 PyObject_GenericGetAttr, /* tp_getattro */
5650 0, /* tp_setattro */
5651 0, /* tp_as_buffer */
5652 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5653 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5654 long_doc, /* tp_doc */
5655 0, /* tp_traverse */
5656 0, /* tp_clear */
5657 long_richcompare, /* tp_richcompare */
5658 0, /* tp_weaklistoffset */
5659 0, /* tp_iter */
5660 0, /* tp_iternext */
5661 long_methods, /* tp_methods */
5662 0, /* tp_members */
5663 long_getset, /* tp_getset */
5664 0, /* tp_base */
5665 0, /* tp_dict */
5666 0, /* tp_descr_get */
5667 0, /* tp_descr_set */
5668 0, /* tp_dictoffset */
5669 0, /* tp_init */
5670 0, /* tp_alloc */
5671 long_new, /* tp_new */
5672 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005673};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005674
Mark Dickinsonbd792642009-03-18 20:06:12 +00005675static PyTypeObject Int_InfoType;
5676
5677PyDoc_STRVAR(int_info__doc__,
5678"sys.int_info\n\
5679\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005680A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005681internal representation of integers. The attributes are read only.");
5682
5683static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005685 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005687};
5688
5689static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 "sys.int_info", /* name */
5691 int_info__doc__, /* doc */
5692 int_info_fields, /* fields */
5693 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005694};
5695
5696PyObject *
5697PyLong_GetInfo(void)
5698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 PyObject* int_info;
5700 int field = 0;
5701 int_info = PyStructSequence_New(&Int_InfoType);
5702 if (int_info == NULL)
5703 return NULL;
5704 PyStructSequence_SET_ITEM(int_info, field++,
5705 PyLong_FromLong(PyLong_SHIFT));
5706 PyStructSequence_SET_ITEM(int_info, field++,
5707 PyLong_FromLong(sizeof(digit)));
5708 if (PyErr_Occurred()) {
5709 Py_CLEAR(int_info);
5710 return NULL;
5711 }
5712 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005713}
5714
Guido van Rossumddefaf32007-01-14 03:31:43 +00005715int
Victor Stinner630c8df2019-12-17 13:02:18 +01005716_PyLong_Init(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005717{
5718#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005719 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5720 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5721 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005722
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005723 PyLongObject *v = _PyLong_New(1);
5724 if (!v) {
5725 return -1;
5726 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005727
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005728 Py_SET_SIZE(v, size);
Victor Stinner12174a52014-08-15 23:17:38 +02005729 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005730
Victor Stinner630c8df2019-12-17 13:02:18 +01005731 tstate->interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005732 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005733#endif
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005734
Victor Stinner630c8df2019-12-17 13:02:18 +01005735 if (_Py_IsMainInterpreter(tstate)) {
5736 _PyLong_Zero = PyLong_FromLong(0);
5737 if (_PyLong_Zero == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005738 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005739 }
Victor Stinner630c8df2019-12-17 13:02:18 +01005740
5741 _PyLong_One = PyLong_FromLong(1);
5742 if (_PyLong_One == NULL) {
5743 return 0;
5744 }
5745
5746 /* initialize int_info */
5747 if (Int_InfoType.tp_name == NULL) {
5748 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5749 return 0;
5750 }
5751 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005752 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005755}
5756
5757void
Victor Stinner630c8df2019-12-17 13:02:18 +01005758_PyLong_Fini(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005759{
Victor Stinner630c8df2019-12-17 13:02:18 +01005760 if (_Py_IsMainInterpreter(tstate)) {
5761 Py_CLEAR(_PyLong_One);
5762 Py_CLEAR(_PyLong_Zero);
5763 }
5764
Guido van Rossumddefaf32007-01-14 03:31:43 +00005765#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005766 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinner630c8df2019-12-17 13:02:18 +01005767 Py_CLEAR(tstate->interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005769#endif
5770}