blob: d92a9c56a720846a0dd659ce77be58e3c5c84854 [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
8#include "pycore_pystate.h" // _Py_IsMainInterpreter()
Guido van Rossumedcc38a1991-05-05 20:09:44 +00009#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +000010
Mark Dickinsonc6300392009-04-20 21:38:00 +000011#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000012#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000013#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000014
Serhiy Storchaka495e8802017-02-01 23:12:20 +020015#include "clinic/longobject.c.h"
16/*[clinic input]
17class int "PyObject *" "&PyLong_Type"
18[clinic start generated code]*/
19/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
20
Victor Stinner630c8df2019-12-17 13:02:18 +010021#define NSMALLPOSINTS _PY_NSMALLPOSINTS
22#define NSMALLNEGINTS _PY_NSMALLNEGINTS
Facundo Batista6e6f59b2008-07-24 18:57:11 +000023
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020024_Py_IDENTIFIER(little);
25_Py_IDENTIFIER(big);
26
Mark Dickinsone4416742009-02-15 15:14:57 +000027/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020028#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
29 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 (Py_SIZE(x) == 0 ? (sdigit)0 : \
31 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000032
Serhiy Storchakaba85d692017-03-30 09:09:41 +030033PyObject *_PyLong_Zero = NULL;
34PyObject *_PyLong_One = NULL;
35
Guido van Rossumddefaf32007-01-14 03:31:43 +000036#if NSMALLNEGINTS + NSMALLPOSINTS > 0
animalize6b519982019-09-06 14:00:56 +080037#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050038#define IS_SMALL_UINT(ival) ((ival) < NSMALLPOSINTS)
Greg Price5e63ab02019-08-24 10:19:37 -070039
Guido van Rossum7eaf8222007-06-18 17:58:50 +000040static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000041get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000042{
animalize6b519982019-09-06 14:00:56 +080043 assert(IS_SMALL_INT(ival));
Victor Stinner1bcc32f2020-06-10 20:08:26 +020044 PyInterpreterState *interp = _PyInterpreterState_GET();
45 PyObject *v = (PyObject*)interp->small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048}
Guido van Rossumddefaf32007-01-14 03:31:43 +000049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000051maybe_small_long(PyLongObject *v)
52{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020053 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080055 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 Py_DECREF(v);
57 return (PyLongObject *)get_small_int(ival);
58 }
59 }
60 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000061}
Guido van Rossumddefaf32007-01-14 03:31:43 +000062#else
animalize6b519982019-09-06 14:00:56 +080063#define IS_SMALL_INT(ival) 0
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050064#define IS_SMALL_UINT(ival) 0
animalize6b519982019-09-06 14:00:56 +080065#define get_small_int(ival) (Py_UNREACHABLE(), NULL)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000066#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000067#endif
68
Serhiy Storchaka95949422013-08-27 19:40:23 +030069/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000070 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020071Py_LOCAL_INLINE(void)
72_PyLong_Negate(PyLongObject **x_p)
73{
74 PyLongObject *x;
75
76 x = (PyLongObject *)*x_p;
77 if (Py_REFCNT(x) == 1) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +010078 Py_SET_SIZE(x, -Py_SIZE(x));
Victor Stinner8aed6f12013-07-17 22:31:17 +020079 return;
80 }
81
82 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
83 Py_DECREF(x);
84}
85
Serhiy Storchaka95949422013-08-27 19:40:23 +030086/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000087 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030088 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000089 */
Tim Peters0973b992004-08-29 22:16:50 +000090#define KARATSUBA_CUTOFF 70
91#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000092
Tim Peters47e52ee2004-08-30 02:44:38 +000093/* For exponentiation, use the binary left-to-right algorithm
94 * unless the exponent contains more than FIVEARY_CUTOFF digits.
95 * In that case, do 5 bits at a time. The potential drawback is that
96 * a table of 2**5 intermediate results is computed.
97 */
98#define FIVEARY_CUTOFF 8
99
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000100#define SIGCHECK(PyTryBlock) \
101 do { \
102 if (PyErr_CheckSignals()) PyTryBlock \
103 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000104
Serhiy Storchaka95949422013-08-27 19:40:23 +0300105/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000106 Doesn't attempt to free the storage--in most cases, due to the nature
107 of the algorithms used, this could save at most be one word anyway. */
108
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200110long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000111{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200112 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 while (i > 0 && v->ob_digit[i-1] == 0)
116 --i;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100117 if (i != j) {
118 Py_SET_SIZE(v, (Py_SIZE(v) < 0) ? -(i) : i);
119 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000121}
122
Serhiy Storchaka95949422013-08-27 19:40:23 +0300123/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000124 Return NULL and set exception if we run out of memory. */
125
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000126#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000128
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000129PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000130_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 PyLongObject *result;
133 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
134 sizeof(digit)*size. Previous incarnations of this code used
135 sizeof(PyVarObject) instead of the offsetof, but this risks being
136 incorrect in the presence of padding between the PyVarObject header
137 and the digits. */
138 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
139 PyErr_SetString(PyExc_OverflowError,
140 "too many digits in integer");
141 return NULL;
142 }
143 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
144 size*sizeof(digit));
145 if (!result) {
146 PyErr_NoMemory();
147 return NULL;
148 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100149 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000150}
151
Tim Peters64b5ce32001-09-10 20:52:51 +0000152PyObject *
153_PyLong_Copy(PyLongObject *src)
154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 PyLongObject *result;
156 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 assert(src != NULL);
159 i = Py_SIZE(src);
160 if (i < 0)
161 i = -(i);
162 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100163 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800164 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700165 return get_small_int(ival);
166 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 }
168 result = _PyLong_New(i);
169 if (result != NULL) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100170 Py_SET_SIZE(result, Py_SIZE(src));
171 while (--i >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 result->ob_digit[i] = src->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100173 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 }
175 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000176}
177
Serhiy Storchaka95949422013-08-27 19:40:23 +0300178/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000179
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000180PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000181PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 PyLongObject *v;
184 unsigned long abs_ival;
185 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
186 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100187 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000188
animalize6b519982019-09-06 14:00:56 +0800189 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700190 return get_small_int((sdigit)ival);
191 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 if (ival < 0) {
194 /* negate: can't write this as abs_ival = -ival since that
195 invokes undefined behaviour when ival is LONG_MIN */
196 abs_ival = 0U-(unsigned long)ival;
197 sign = -1;
198 }
199 else {
200 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100201 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 /* Fast path for single-digit ints */
205 if (!(abs_ival >> PyLong_SHIFT)) {
206 v = _PyLong_New(1);
207 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100208 Py_SET_SIZE(v, sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 v->ob_digit[0] = Py_SAFE_DOWNCAST(
210 abs_ival, unsigned long, digit);
211 }
212 return (PyObject*)v;
213 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000214
Mark Dickinson249b8982009-04-27 19:41:00 +0000215#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 /* 2 digits */
217 if (!(abs_ival >> 2*PyLong_SHIFT)) {
218 v = _PyLong_New(2);
219 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100220 Py_SET_SIZE(v, 2 * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 v->ob_digit[0] = Py_SAFE_DOWNCAST(
222 abs_ival & PyLong_MASK, unsigned long, digit);
223 v->ob_digit[1] = Py_SAFE_DOWNCAST(
224 abs_ival >> PyLong_SHIFT, unsigned long, digit);
225 }
226 return (PyObject*)v;
227 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000228#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 /* Larger numbers: loop to determine number of digits */
231 t = abs_ival;
232 while (t) {
233 ++ndigits;
234 t >>= PyLong_SHIFT;
235 }
236 v = _PyLong_New(ndigits);
237 if (v != NULL) {
238 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100239 Py_SET_SIZE(v, ndigits * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 t = abs_ival;
241 while (t) {
242 *p++ = Py_SAFE_DOWNCAST(
243 t & PyLong_MASK, unsigned long, digit);
244 t >>= PyLong_SHIFT;
245 }
246 }
247 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000248}
249
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500250#define PYLONG_FROM_UINT(INT_TYPE, ival) \
251 do { \
252 if (IS_SMALL_UINT(ival)) { \
Victor Stinner6314abc2019-10-01 13:29:53 +0200253 return get_small_int((sdigit)(ival)); \
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500254 } \
255 /* Count the number of Python digits. */ \
256 Py_ssize_t ndigits = 0; \
257 INT_TYPE t = (ival); \
258 while (t) { \
259 ++ndigits; \
260 t >>= PyLong_SHIFT; \
261 } \
262 PyLongObject *v = _PyLong_New(ndigits); \
263 if (v == NULL) { \
264 return NULL; \
265 } \
266 digit *p = v->ob_digit; \
267 while ((ival)) { \
268 *p++ = (digit)((ival) & PyLong_MASK); \
269 (ival) >>= PyLong_SHIFT; \
270 } \
271 return (PyObject *)v; \
272 } while(0)
273
Serhiy Storchaka95949422013-08-27 19:40:23 +0300274/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000275
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000276PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000277PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000278{
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500279 PYLONG_FROM_UINT(unsigned long, ival);
280}
Tim Petersce9de2f2001-06-14 04:56:19 +0000281
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500282/* Create a new int object from a C unsigned long long int. */
283
284PyObject *
285PyLong_FromUnsignedLongLong(unsigned long long ival)
286{
287 PYLONG_FROM_UINT(unsigned long long, ival);
288}
289
290/* Create a new int object from a C size_t. */
291
292PyObject *
293PyLong_FromSize_t(size_t ival)
294{
295 PYLONG_FROM_UINT(size_t, ival);
Guido van Rossum53756b11997-01-03 17:14:46 +0000296}
297
Serhiy Storchaka95949422013-08-27 19:40:23 +0300298/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000299
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000300PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000301PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000302{
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500303 /* Try to get out cheap if this fits in a long. When a finite value of real
304 * floating type is converted to an integer type, the value is truncated
305 * toward zero. If the value of the integral part cannot be represented by
306 * the integer type, the behavior is undefined. Thus, we must check that
307 * value is in range (LONG_MIN - 1, LONG_MAX + 1). If a long has more bits
308 * of precision than a double, casting LONG_MIN - 1 to double may yield an
309 * approximation, but LONG_MAX + 1 is a power of two and can be represented
310 * as double exactly (assuming FLT_RADIX is 2 or 16), so for simplicity
311 * check against [-(LONG_MAX + 1), LONG_MAX + 1).
312 */
313 const double int_max = (unsigned long)LONG_MAX + 1;
314 if (-int_max < dval && dval < int_max) {
315 return PyLong_FromLong((long)dval);
316 }
317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 PyLongObject *v;
319 double frac;
320 int i, ndig, expo, neg;
321 neg = 0;
322 if (Py_IS_INFINITY(dval)) {
323 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000324 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 return NULL;
326 }
327 if (Py_IS_NAN(dval)) {
328 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000329 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return NULL;
331 }
332 if (dval < 0.0) {
333 neg = 1;
334 dval = -dval;
335 }
336 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500337 assert(expo > 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
339 v = _PyLong_New(ndig);
340 if (v == NULL)
341 return NULL;
342 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
343 for (i = ndig; --i >= 0; ) {
344 digit bits = (digit)frac;
345 v->ob_digit[i] = bits;
346 frac = frac - (double)bits;
347 frac = ldexp(frac, PyLong_SHIFT);
348 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100349 if (neg) {
350 Py_SET_SIZE(v, -(Py_SIZE(v)));
351 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000353}
354
Thomas Wouters89f507f2006-12-13 04:49:30 +0000355/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
356 * anything about what happens when a signed integer operation overflows,
357 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700358 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000359 * (unsigned long)LONG_MAX, and for the smallest negative signed long
360 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
361 * However, some other compilers warn about applying unary minus to an
362 * unsigned operand. Hence the weird "0-".
363 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
365#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000366
Mark Dickinson20941de2020-05-27 13:43:17 +0100367/* Get a C long int from an int object or any object that has an __index__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100368 method.
369
370 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
371 the result. Otherwise *overflow is 0.
372
373 For other errors (e.g., TypeError), return -1 and set an error condition.
374 In this case *overflow will be 0.
375*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000376
377long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000378PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200381 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 unsigned long x, prev;
383 long res;
384 Py_ssize_t i;
385 int sign;
Mark Dickinson20941de2020-05-27 13:43:17 +0100386 int do_decref = 0; /* if PyNumber_Index was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 *overflow = 0;
389 if (vv == NULL) {
390 PyErr_BadInternalCall();
391 return -1;
392 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000393
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200394 if (PyLong_Check(vv)) {
395 v = (PyLongObject *)vv;
396 }
397 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300398 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200399 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 return -1;
401 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 switch (i) {
408 case -1:
409 res = -(sdigit)v->ob_digit[0];
410 break;
411 case 0:
412 res = 0;
413 break;
414 case 1:
415 res = v->ob_digit[0];
416 break;
417 default:
418 sign = 1;
419 x = 0;
420 if (i < 0) {
421 sign = -1;
422 i = -(i);
423 }
424 while (--i >= 0) {
425 prev = x;
426 x = (x << PyLong_SHIFT) | v->ob_digit[i];
427 if ((x >> PyLong_SHIFT) != prev) {
428 *overflow = sign;
429 goto exit;
430 }
431 }
432 /* Haven't lost any bits, but casting to long requires extra
433 * care (see comment above).
434 */
435 if (x <= (unsigned long)LONG_MAX) {
436 res = (long)x * sign;
437 }
438 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
439 res = LONG_MIN;
440 }
441 else {
442 *overflow = sign;
443 /* res is already set to -1 */
444 }
445 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000446 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200448 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 }
450 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000451}
452
Mark Dickinson20941de2020-05-27 13:43:17 +0100453/* Get a C long int from an int object or any object that has an __index__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100454 method. Return -1 and set an error if overflow occurs. */
455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000457PyLong_AsLong(PyObject *obj)
458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 int overflow;
460 long result = PyLong_AsLongAndOverflow(obj, &overflow);
461 if (overflow) {
462 /* XXX: could be cute and give a different
463 message for overflow == -1 */
464 PyErr_SetString(PyExc_OverflowError,
465 "Python int too large to convert to C long");
466 }
467 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000468}
469
Mark Dickinson20941de2020-05-27 13:43:17 +0100470/* Get a C int from an int object or any object that has an __index__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200471 method. Return -1 and set an error if overflow occurs. */
472
473int
474_PyLong_AsInt(PyObject *obj)
475{
476 int overflow;
477 long result = PyLong_AsLongAndOverflow(obj, &overflow);
478 if (overflow || result > INT_MAX || result < INT_MIN) {
479 /* XXX: could be cute and give a different
480 message for overflow == -1 */
481 PyErr_SetString(PyExc_OverflowError,
482 "Python int too large to convert to C int");
483 return -1;
484 }
485 return (int)result;
486}
487
Serhiy Storchaka95949422013-08-27 19:40:23 +0300488/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000489 Returns -1 and sets an error condition if overflow occurs. */
490
491Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000492PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200493 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 size_t x, prev;
495 Py_ssize_t i;
496 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 if (vv == NULL) {
499 PyErr_BadInternalCall();
500 return -1;
501 }
502 if (!PyLong_Check(vv)) {
503 PyErr_SetString(PyExc_TypeError, "an integer is required");
504 return -1;
505 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 v = (PyLongObject *)vv;
508 i = Py_SIZE(v);
509 switch (i) {
510 case -1: return -(sdigit)v->ob_digit[0];
511 case 0: return 0;
512 case 1: return v->ob_digit[0];
513 }
514 sign = 1;
515 x = 0;
516 if (i < 0) {
517 sign = -1;
518 i = -(i);
519 }
520 while (--i >= 0) {
521 prev = x;
522 x = (x << PyLong_SHIFT) | v->ob_digit[i];
523 if ((x >> PyLong_SHIFT) != prev)
524 goto overflow;
525 }
526 /* Haven't lost any bits, but casting to a signed type requires
527 * extra care (see comment above).
528 */
529 if (x <= (size_t)PY_SSIZE_T_MAX) {
530 return (Py_ssize_t)x * sign;
531 }
532 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
533 return PY_SSIZE_T_MIN;
534 }
535 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000536
Mark Dickinson22b20182010-05-10 21:27:53 +0000537 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 PyErr_SetString(PyExc_OverflowError,
539 "Python int too large to convert to C ssize_t");
540 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000541}
542
Serhiy Storchaka95949422013-08-27 19:40:23 +0300543/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000544 Returns -1 and sets an error condition if overflow occurs. */
545
546unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000547PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000548{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200549 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 unsigned long x, prev;
551 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 if (vv == NULL) {
554 PyErr_BadInternalCall();
555 return (unsigned long)-1;
556 }
557 if (!PyLong_Check(vv)) {
558 PyErr_SetString(PyExc_TypeError, "an integer is required");
559 return (unsigned long)-1;
560 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 v = (PyLongObject *)vv;
563 i = Py_SIZE(v);
564 x = 0;
565 if (i < 0) {
566 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000567 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 return (unsigned long) -1;
569 }
570 switch (i) {
571 case 0: return 0;
572 case 1: return v->ob_digit[0];
573 }
574 while (--i >= 0) {
575 prev = x;
576 x = (x << PyLong_SHIFT) | v->ob_digit[i];
577 if ((x >> PyLong_SHIFT) != prev) {
578 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100579 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000580 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return (unsigned long) -1;
582 }
583 }
584 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000585}
586
Serhiy Storchaka95949422013-08-27 19:40:23 +0300587/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200588 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000589
590size_t
591PyLong_AsSize_t(PyObject *vv)
592{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200593 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 size_t x, prev;
595 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 if (vv == NULL) {
598 PyErr_BadInternalCall();
599 return (size_t) -1;
600 }
601 if (!PyLong_Check(vv)) {
602 PyErr_SetString(PyExc_TypeError, "an integer is required");
603 return (size_t)-1;
604 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 v = (PyLongObject *)vv;
607 i = Py_SIZE(v);
608 x = 0;
609 if (i < 0) {
610 PyErr_SetString(PyExc_OverflowError,
611 "can't convert negative value to size_t");
612 return (size_t) -1;
613 }
614 switch (i) {
615 case 0: return 0;
616 case 1: return v->ob_digit[0];
617 }
618 while (--i >= 0) {
619 prev = x;
620 x = (x << PyLong_SHIFT) | v->ob_digit[i];
621 if ((x >> PyLong_SHIFT) != prev) {
622 PyErr_SetString(PyExc_OverflowError,
623 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200624 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 }
626 }
627 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000628}
629
Serhiy Storchaka95949422013-08-27 19:40:23 +0300630/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000631 Returns -1 and sets an error condition if an error occurs. */
632
Guido van Rossumddefaf32007-01-14 03:31:43 +0000633static unsigned long
634_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000635{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200636 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 unsigned long x;
638 Py_ssize_t i;
639 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if (vv == NULL || !PyLong_Check(vv)) {
642 PyErr_BadInternalCall();
643 return (unsigned long) -1;
644 }
645 v = (PyLongObject *)vv;
646 i = Py_SIZE(v);
647 switch (i) {
648 case 0: return 0;
649 case 1: return v->ob_digit[0];
650 }
651 sign = 1;
652 x = 0;
653 if (i < 0) {
654 sign = -1;
655 i = -i;
656 }
657 while (--i >= 0) {
658 x = (x << PyLong_SHIFT) | v->ob_digit[i];
659 }
660 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000661}
662
Guido van Rossumddefaf32007-01-14 03:31:43 +0000663unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200664PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 PyLongObject *lo;
667 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000668
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200669 if (op == NULL) {
670 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 return (unsigned long)-1;
672 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000673
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200674 if (PyLong_Check(op)) {
675 return _PyLong_AsUnsignedLongMask(op);
676 }
677
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300678 lo = (PyLongObject *)_PyNumber_Index(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 if (lo == NULL)
680 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200681
682 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
683 Py_DECREF(lo);
684 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000685}
686
Tim Peters5b8132f2003-01-31 15:52:05 +0000687int
688_PyLong_Sign(PyObject *vv)
689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 assert(v != NULL);
693 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000696}
697
Niklas Fiekas794e7d12020-06-15 14:33:48 +0200698static int
699bit_length_digit(digit x)
700{
701 Py_BUILD_ASSERT(PyLong_SHIFT <= sizeof(unsigned long) * 8);
702 return _Py_bit_length((unsigned long)x);
703}
704
Tim Petersbaefd9e2003-01-28 20:37:45 +0000705size_t
706_PyLong_NumBits(PyObject *vv)
707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyLongObject *v = (PyLongObject *)vv;
709 size_t result = 0;
710 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200711 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 assert(v != NULL);
714 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200715 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
717 if (ndigits > 0) {
718 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700719 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100721 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Niklas Fiekas794e7d12020-06-15 14:33:48 +0200722 msd_bits = bit_length_digit(msd);
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200723 if (SIZE_MAX - msd_bits < result)
724 goto Overflow;
725 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 }
727 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000728
Mark Dickinson22b20182010-05-10 21:27:53 +0000729 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
731 "to express in a platform size_t");
732 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000733}
734
Tim Peters2a9b3672001-06-11 21:23:58 +0000735PyObject *
736_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000738{
Mark Dickinson22b20182010-05-10 21:27:53 +0000739 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 int incr; /* direction to move pstartbyte */
741 const unsigned char* pendbyte; /* MSB of bytes */
742 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300743 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 PyLongObject* v; /* result */
745 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 if (n == 0)
748 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 if (little_endian) {
751 pstartbyte = bytes;
752 pendbyte = bytes + n - 1;
753 incr = 1;
754 }
755 else {
756 pstartbyte = bytes + n - 1;
757 pendbyte = bytes;
758 incr = -1;
759 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 if (is_signed)
762 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200765 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 is positive, and leading 0xff bytes if negative. */
767 {
768 size_t i;
769 const unsigned char* p = pendbyte;
770 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000771 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000774 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 break;
776 }
777 numsignificantbytes = n - i;
778 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
779 actually has 2 significant bytes. OTOH, 0xff0001 ==
780 -0x00ffff, so we wouldn't *need* to bump it there; but we
781 do for 0xffff = -0x0001. To be safe without bothering to
782 check every case, bump it regardless. */
783 if (is_signed && numsignificantbytes < n)
784 ++numsignificantbytes;
785 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000786
Serhiy Storchaka95949422013-08-27 19:40:23 +0300787 /* How many Python int digits do we need? We have
788 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
790 /* catch overflow before it happens */
791 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
792 PyErr_SetString(PyExc_OverflowError,
793 "byte array too long to convert to int");
794 return NULL;
795 }
796 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
797 v = _PyLong_New(ndigits);
798 if (v == NULL)
799 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 /* Copy the bits over. The tricky parts are computing 2's-comp on
802 the fly for signed numbers, and dealing with the mismatch between
803 8-bit bytes and (probably) 15-bit Python digits.*/
804 {
805 size_t i;
806 twodigits carry = 1; /* for 2's-comp calculation */
807 twodigits accum = 0; /* sliding register */
808 unsigned int accumbits = 0; /* number of bits in accum */
809 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
812 twodigits thisbyte = *p;
813 /* Compute correction for 2's comp, if needed. */
814 if (is_signed) {
815 thisbyte = (0xff ^ thisbyte) + carry;
816 carry = thisbyte >> 8;
817 thisbyte &= 0xff;
818 }
819 /* Because we're going LSB to MSB, thisbyte is
820 more significant than what's already in accum,
821 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200822 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 accumbits += 8;
824 if (accumbits >= PyLong_SHIFT) {
825 /* There's enough to fill a Python digit. */
826 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000827 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 ++idigit;
829 accum >>= PyLong_SHIFT;
830 accumbits -= PyLong_SHIFT;
831 assert(accumbits < PyLong_SHIFT);
832 }
833 }
834 assert(accumbits < PyLong_SHIFT);
835 if (accumbits) {
836 assert(idigit < ndigits);
837 v->ob_digit[idigit] = (digit)accum;
838 ++idigit;
839 }
840 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000841
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100842 Py_SET_SIZE(v, is_signed ? -idigit : idigit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000844}
845
846int
847_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 unsigned char* bytes, size_t n,
849 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000852 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000854 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
856 digit carry; /* for computing 2's-comp */
857 size_t j; /* # bytes filled */
858 unsigned char* p; /* pointer to next byte in bytes */
859 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 if (Py_SIZE(v) < 0) {
864 ndigits = -(Py_SIZE(v));
865 if (!is_signed) {
866 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000867 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 return -1;
869 }
870 do_twos_comp = 1;
871 }
872 else {
873 ndigits = Py_SIZE(v);
874 do_twos_comp = 0;
875 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 if (little_endian) {
878 p = bytes;
879 pincr = 1;
880 }
881 else {
882 p = bytes + n - 1;
883 pincr = -1;
884 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 /* Copy over all the Python digits.
887 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300888 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 normalized. */
890 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
891 j = 0;
892 accum = 0;
893 accumbits = 0;
894 carry = do_twos_comp ? 1 : 0;
895 for (i = 0; i < ndigits; ++i) {
896 digit thisdigit = v->ob_digit[i];
897 if (do_twos_comp) {
898 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
899 carry = thisdigit >> PyLong_SHIFT;
900 thisdigit &= PyLong_MASK;
901 }
902 /* Because we're going LSB to MSB, thisdigit is more
903 significant than what's already in accum, so needs to be
904 prepended to accum. */
905 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 /* The most-significant digit may be (probably is) at least
908 partly empty. */
909 if (i == ndigits - 1) {
910 /* Count # of sign bits -- they needn't be stored,
911 * although for signed conversion we need later to
912 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000913 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 while (s != 0) {
915 s >>= 1;
916 accumbits++;
917 }
918 }
919 else
920 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* Store as many bytes as possible. */
923 while (accumbits >= 8) {
924 if (j >= n)
925 goto Overflow;
926 ++j;
927 *p = (unsigned char)(accum & 0xff);
928 p += pincr;
929 accumbits -= 8;
930 accum >>= 8;
931 }
932 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 /* Store the straggler (if any). */
935 assert(accumbits < 8);
936 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
937 if (accumbits > 0) {
938 if (j >= n)
939 goto Overflow;
940 ++j;
941 if (do_twos_comp) {
942 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300943 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 infinite supply of sign bits). */
945 accum |= (~(twodigits)0) << accumbits;
946 }
947 *p = (unsigned char)(accum & 0xff);
948 p += pincr;
949 }
950 else if (j == n && n > 0 && is_signed) {
951 /* The main loop filled the byte array exactly, so the code
952 just above didn't get to ensure there's a sign bit, and the
953 loop below wouldn't add one either. Make sure a sign bit
954 exists. */
955 unsigned char msb = *(p - pincr);
956 int sign_bit_set = msb >= 0x80;
957 assert(accumbits == 0);
958 if (sign_bit_set == do_twos_comp)
959 return 0;
960 else
961 goto Overflow;
962 }
Tim Peters05607ad2001-06-13 21:01:27 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 /* Fill remaining bytes with copies of the sign bit. */
965 {
966 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
967 for ( ; j < n; ++j, p += pincr)
968 *p = signbyte;
969 }
Tim Peters05607ad2001-06-13 21:01:27 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000972
Mark Dickinson22b20182010-05-10 21:27:53 +0000973 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
975 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000976
Tim Peters2a9b3672001-06-11 21:23:58 +0000977}
978
Serhiy Storchaka95949422013-08-27 19:40:23 +0300979/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000980
981PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000982PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000983{
Mark Dickinson91044792012-10-18 19:21:43 +0100984#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -0700985 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100986#else
987
Tim Peters70128a12001-06-16 08:48:40 +0000988#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700989# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000990#endif
Benjamin Petersonca470632016-09-06 13:47:26 -0700991 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100992#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000993
Guido van Rossum78694d91998-09-18 14:14:13 +0000994}
995
Serhiy Storchaka95949422013-08-27 19:40:23 +0300996/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000997
998void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000999PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001000{
Tim Peters70128a12001-06-16 08:48:40 +00001001#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1005 x = PyLong_AsLong(vv);
1006 else
1007 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001008#else
Tim Peters70128a12001-06-16 08:48:40 +00001009
Tim Peters70128a12001-06-16 08:48:40 +00001010#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001011# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001012#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001013 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1016 x = PyLong_AsLongLong(vv);
1017 else
1018 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001019
1020#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (x == -1 && PyErr_Occurred())
1023 return NULL;
1024 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001025}
1026
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001027/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001028 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001029 */
1030
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001031#define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001032
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001033/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001034
1035PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001036PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001039 unsigned long long abs_ival;
1040 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 int ndigits = 0;
1042 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001043
animalize6b519982019-09-06 14:00:56 +08001044 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001045 return get_small_int((sdigit)ival);
1046 }
1047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (ival < 0) {
1049 /* avoid signed overflow on negation; see comments
1050 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001051 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 negative = 1;
1053 }
1054 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001055 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 /* Count the number of Python digits.
1059 We used to pick 5 ("big enough for anything"), but that's a
1060 waste of time and space given that 5*15 = 75 bits are rarely
1061 needed. */
1062 t = abs_ival;
1063 while (t) {
1064 ++ndigits;
1065 t >>= PyLong_SHIFT;
1066 }
1067 v = _PyLong_New(ndigits);
1068 if (v != NULL) {
1069 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001070 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 t = abs_ival;
1072 while (t) {
1073 *p++ = (digit)(t & PyLong_MASK);
1074 t >>= PyLong_SHIFT;
1075 }
1076 }
1077 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001078}
1079
Serhiy Storchaka95949422013-08-27 19:40:23 +03001080/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001081
1082PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001083PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 PyLongObject *v;
1086 size_t abs_ival;
1087 size_t t; /* unsigned so >> doesn't propagate sign bit */
1088 int ndigits = 0;
1089 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001090
animalize6b519982019-09-06 14:00:56 +08001091 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001092 return get_small_int((sdigit)ival);
1093 }
1094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 if (ival < 0) {
1096 /* avoid signed overflow when ival = SIZE_T_MIN */
1097 abs_ival = (size_t)(-1-ival)+1;
1098 negative = 1;
1099 }
1100 else {
1101 abs_ival = (size_t)ival;
1102 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 /* Count the number of Python digits. */
1105 t = abs_ival;
1106 while (t) {
1107 ++ndigits;
1108 t >>= PyLong_SHIFT;
1109 }
1110 v = _PyLong_New(ndigits);
1111 if (v != NULL) {
1112 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001113 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 t = abs_ival;
1115 while (t) {
1116 *p++ = (digit)(t & PyLong_MASK);
1117 t >>= PyLong_SHIFT;
1118 }
1119 }
1120 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001121}
1122
Serhiy Storchaka95949422013-08-27 19:40:23 +03001123/* Get a C long long int from an int object or any object that has an
Mark Dickinson20941de2020-05-27 13:43:17 +01001124 __index__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001125
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001126long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001127PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001130 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 int res;
Mark Dickinson20941de2020-05-27 13:43:17 +01001132 int do_decref = 0; /* if PyNumber_Index was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 if (vv == NULL) {
1135 PyErr_BadInternalCall();
1136 return -1;
1137 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001138
1139 if (PyLong_Check(vv)) {
1140 v = (PyLongObject *)vv;
1141 }
1142 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001143 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001144 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001146 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001148
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001149 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001151 case -1:
1152 bytes = -(sdigit)v->ob_digit[0];
1153 break;
1154 case 0:
1155 bytes = 0;
1156 break;
1157 case 1:
1158 bytes = v->ob_digit[0];
1159 break;
1160 default:
1161 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001162 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001164 if (do_decref) {
1165 Py_DECREF(v);
1166 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001167
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001168 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001170 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 else
1172 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001173}
1174
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001175/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001176 Return -1 and set an error if overflow occurs. */
1177
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001178unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001179PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001182 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001184
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001185 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001187 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001189 if (!PyLong_Check(vv)) {
1190 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001191 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001192 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 v = (PyLongObject*)vv;
1195 switch(Py_SIZE(v)) {
1196 case 0: return 0;
1197 case 1: return v->ob_digit[0];
1198 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001199
Mark Dickinson22b20182010-05-10 21:27:53 +00001200 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001201 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001202
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001203 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001205 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 else
1207 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001208}
Tim Petersd1a7da62001-06-13 00:35:57 +00001209
Serhiy Storchaka95949422013-08-27 19:40:23 +03001210/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001211 Returns -1 and sets an error condition if an error occurs. */
1212
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001213static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001214_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001215{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001216 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001217 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 Py_ssize_t i;
1219 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 if (vv == NULL || !PyLong_Check(vv)) {
1222 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001223 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 }
1225 v = (PyLongObject *)vv;
1226 switch(Py_SIZE(v)) {
1227 case 0: return 0;
1228 case 1: return v->ob_digit[0];
1229 }
1230 i = Py_SIZE(v);
1231 sign = 1;
1232 x = 0;
1233 if (i < 0) {
1234 sign = -1;
1235 i = -i;
1236 }
1237 while (--i >= 0) {
1238 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1239 }
1240 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001241}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001242
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001243unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001244PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001247 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001248
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001249 if (op == NULL) {
1250 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001251 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001253
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001254 if (PyLong_Check(op)) {
1255 return _PyLong_AsUnsignedLongLongMask(op);
1256 }
1257
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001258 lo = (PyLongObject *)_PyNumber_Index(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001260 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001261
1262 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1263 Py_DECREF(lo);
1264 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001265}
Tim Petersd1a7da62001-06-13 00:35:57 +00001266
Serhiy Storchaka95949422013-08-27 19:40:23 +03001267/* Get a C long long int from an int object or any object that has an
Mark Dickinson20941de2020-05-27 13:43:17 +01001268 __index__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001269
Mark Dickinson8d48b432011-10-23 20:47:14 +01001270 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1271 the result. Otherwise *overflow is 0.
1272
1273 For other errors (e.g., TypeError), return -1 and set an error condition.
1274 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001275*/
1276
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001277long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001278PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001281 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001282 unsigned long long x, prev;
1283 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 Py_ssize_t i;
1285 int sign;
Mark Dickinson20941de2020-05-27 13:43:17 +01001286 int do_decref = 0; /* if PyNumber_Index was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 *overflow = 0;
1289 if (vv == NULL) {
1290 PyErr_BadInternalCall();
1291 return -1;
1292 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001293
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001294 if (PyLong_Check(vv)) {
1295 v = (PyLongObject *)vv;
1296 }
1297 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001298 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001299 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 return -1;
1301 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 switch (i) {
1308 case -1:
1309 res = -(sdigit)v->ob_digit[0];
1310 break;
1311 case 0:
1312 res = 0;
1313 break;
1314 case 1:
1315 res = v->ob_digit[0];
1316 break;
1317 default:
1318 sign = 1;
1319 x = 0;
1320 if (i < 0) {
1321 sign = -1;
1322 i = -(i);
1323 }
1324 while (--i >= 0) {
1325 prev = x;
1326 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1327 if ((x >> PyLong_SHIFT) != prev) {
1328 *overflow = sign;
1329 goto exit;
1330 }
1331 }
1332 /* Haven't lost any bits, but casting to long requires extra
1333 * care (see comment above).
1334 */
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001335 if (x <= (unsigned long long)LLONG_MAX) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001336 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 }
1338 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001339 res = LLONG_MIN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 }
1341 else {
1342 *overflow = sign;
1343 /* res is already set to -1 */
1344 }
1345 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001346 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001348 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 }
1350 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001351}
1352
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001353int
1354_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1355{
1356 unsigned long uval;
1357
1358 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1359 PyErr_SetString(PyExc_ValueError, "value must be positive");
1360 return 0;
1361 }
1362 uval = PyLong_AsUnsignedLong(obj);
1363 if (uval == (unsigned long)-1 && PyErr_Occurred())
1364 return 0;
1365 if (uval > USHRT_MAX) {
1366 PyErr_SetString(PyExc_OverflowError,
1367 "Python int too large for C unsigned short");
1368 return 0;
1369 }
1370
1371 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1372 return 1;
1373}
1374
1375int
1376_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1377{
1378 unsigned long uval;
1379
1380 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1381 PyErr_SetString(PyExc_ValueError, "value must be positive");
1382 return 0;
1383 }
1384 uval = PyLong_AsUnsignedLong(obj);
1385 if (uval == (unsigned long)-1 && PyErr_Occurred())
1386 return 0;
1387 if (uval > UINT_MAX) {
1388 PyErr_SetString(PyExc_OverflowError,
1389 "Python int too large for C unsigned int");
1390 return 0;
1391 }
1392
1393 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1394 return 1;
1395}
1396
1397int
1398_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1399{
1400 unsigned long uval;
1401
1402 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1403 PyErr_SetString(PyExc_ValueError, "value must be positive");
1404 return 0;
1405 }
1406 uval = PyLong_AsUnsignedLong(obj);
1407 if (uval == (unsigned long)-1 && PyErr_Occurred())
1408 return 0;
1409
1410 *(unsigned long *)ptr = uval;
1411 return 1;
1412}
1413
1414int
1415_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1416{
1417 unsigned long long uval;
1418
1419 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1420 PyErr_SetString(PyExc_ValueError, "value must be positive");
1421 return 0;
1422 }
1423 uval = PyLong_AsUnsignedLongLong(obj);
1424 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1425 return 0;
1426
1427 *(unsigned long long *)ptr = uval;
1428 return 1;
1429}
1430
1431int
1432_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1433{
1434 size_t uval;
1435
1436 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1437 PyErr_SetString(PyExc_ValueError, "value must be positive");
1438 return 0;
1439 }
1440 uval = PyLong_AsSize_t(obj);
1441 if (uval == (size_t)-1 && PyErr_Occurred())
1442 return 0;
1443
1444 *(size_t *)ptr = uval;
1445 return 1;
1446}
1447
1448
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001449#define CHECK_BINOP(v,w) \
1450 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001451 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1452 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001453 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001454
Tim Peters877a2122002-08-12 05:09:36 +00001455/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1456 * is modified in place, by adding y to it. Carries are propagated as far as
1457 * x[m-1], and the remaining carry (0 or 1) is returned.
1458 */
1459static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001460v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 Py_ssize_t i;
1463 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 assert(m >= n);
1466 for (i = 0; i < n; ++i) {
1467 carry += x[i] + y[i];
1468 x[i] = carry & PyLong_MASK;
1469 carry >>= PyLong_SHIFT;
1470 assert((carry & 1) == carry);
1471 }
1472 for (; carry && i < m; ++i) {
1473 carry += x[i];
1474 x[i] = carry & PyLong_MASK;
1475 carry >>= PyLong_SHIFT;
1476 assert((carry & 1) == carry);
1477 }
1478 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001479}
1480
1481/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1482 * is modified in place, by subtracting y from it. Borrows are propagated as
1483 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1484 */
1485static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001486v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 Py_ssize_t i;
1489 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 assert(m >= n);
1492 for (i = 0; i < n; ++i) {
1493 borrow = x[i] - y[i] - borrow;
1494 x[i] = borrow & PyLong_MASK;
1495 borrow >>= PyLong_SHIFT;
1496 borrow &= 1; /* keep only 1 sign bit */
1497 }
1498 for (; borrow && i < m; ++i) {
1499 borrow = x[i] - borrow;
1500 x[i] = borrow & PyLong_MASK;
1501 borrow >>= PyLong_SHIFT;
1502 borrow &= 1;
1503 }
1504 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001505}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001506
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001507/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1508 * result in z[0:m], and return the d bits shifted out of the top.
1509 */
1510static digit
1511v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 Py_ssize_t i;
1514 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 assert(0 <= d && d < PyLong_SHIFT);
1517 for (i=0; i < m; i++) {
1518 twodigits acc = (twodigits)a[i] << d | carry;
1519 z[i] = (digit)acc & PyLong_MASK;
1520 carry = (digit)(acc >> PyLong_SHIFT);
1521 }
1522 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001523}
1524
1525/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1526 * result in z[0:m], and return the d bits shifted out of the bottom.
1527 */
1528static digit
1529v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 Py_ssize_t i;
1532 digit carry = 0;
1533 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 assert(0 <= d && d < PyLong_SHIFT);
1536 for (i=m; i-- > 0;) {
1537 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1538 carry = (digit)acc & mask;
1539 z[i] = (digit)(acc >> d);
1540 }
1541 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001542}
1543
Tim Peters212e6142001-07-14 12:23:19 +00001544/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1545 in pout, and returning the remainder. pin and pout point at the LSD.
1546 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001547 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001548 immutable. */
1549
1550static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001551inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 assert(n > 0 && n <= PyLong_MASK);
1556 pin += size;
1557 pout += size;
1558 while (--size >= 0) {
1559 digit hi;
1560 rem = (rem << PyLong_SHIFT) | *--pin;
1561 *--pout = hi = (digit)(rem / n);
1562 rem -= (twodigits)hi * n;
1563 }
1564 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001565}
1566
Serhiy Storchaka95949422013-08-27 19:40:23 +03001567/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001568 (as function result) and the remainder (through *prem).
1569 The sign of a is ignored; n should not be zero. */
1570
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001571static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001572divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001573{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001574 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 assert(n > 0 && n <= PyLong_MASK);
1578 z = _PyLong_New(size);
1579 if (z == NULL)
1580 return NULL;
1581 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1582 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001583}
1584
Serhiy Storchaka95949422013-08-27 19:40:23 +03001585/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001586 string. (Return value is non-shared so that callers can modify the
1587 returned value if necessary.) */
1588
Victor Stinnerd3f08822012-05-29 12:57:52 +02001589static int
1590long_to_decimal_string_internal(PyObject *aa,
1591 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001592 _PyUnicodeWriter *writer,
1593 _PyBytesWriter *bytes_writer,
1594 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001597 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 Py_ssize_t size, strlen, size_a, i, j;
1599 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001601 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001602 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 a = (PyLongObject *)aa;
1605 if (a == NULL || !PyLong_Check(a)) {
1606 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001607 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001609 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 /* quick and dirty upper bound for the number of digits
1613 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 But log2(a) < size_a * PyLong_SHIFT, and
1618 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001619 > 3.3 * _PyLong_DECIMAL_SHIFT
1620
1621 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1622 size_a + size_a / d < size_a + size_a / floor(d),
1623 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1624 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001626 d = (33 * _PyLong_DECIMAL_SHIFT) /
1627 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1628 assert(size_a < PY_SSIZE_T_MAX/2);
1629 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 scratch = _PyLong_New(size);
1631 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001632 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 /* convert array of base _PyLong_BASE digits in pin to an array of
1635 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1636 Volume 2 (3rd edn), section 4.4, Method 1b). */
1637 pin = a->ob_digit;
1638 pout = scratch->ob_digit;
1639 size = 0;
1640 for (i = size_a; --i >= 0; ) {
1641 digit hi = pin[i];
1642 for (j = 0; j < size; j++) {
1643 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1644 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1645 pout[j] = (digit)(z - (twodigits)hi *
1646 _PyLong_DECIMAL_BASE);
1647 }
1648 while (hi) {
1649 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1650 hi /= _PyLong_DECIMAL_BASE;
1651 }
1652 /* check for keyboard interrupt */
1653 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001654 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001655 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001656 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 }
1658 /* pout should have at least one digit, so that the case when a = 0
1659 works correctly */
1660 if (size == 0)
1661 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 /* calculate exact length of output string, and allocate */
1664 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1665 tenpow = 10;
1666 rem = pout[size-1];
1667 while (rem >= tenpow) {
1668 tenpow *= 10;
1669 strlen++;
1670 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001671 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001672 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1673 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001674 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001675 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001676 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001678 else if (bytes_writer) {
1679 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1680 if (*bytes_str == NULL) {
1681 Py_DECREF(scratch);
1682 return -1;
1683 }
1684 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001685 else {
1686 str = PyUnicode_New(strlen, '9');
1687 if (str == NULL) {
1688 Py_DECREF(scratch);
1689 return -1;
1690 }
1691 kind = PyUnicode_KIND(str);
1692 }
1693
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001694#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001695 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001696 /* pout[0] through pout[size-2] contribute exactly \
1697 _PyLong_DECIMAL_SHIFT digits each */ \
1698 for (i=0; i < size - 1; i++) { \
1699 rem = pout[i]; \
1700 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1701 *--p = '0' + rem % 10; \
1702 rem /= 10; \
1703 } \
1704 } \
1705 /* pout[size-1]: always produce at least one decimal digit */ \
1706 rem = pout[i]; \
1707 do { \
1708 *--p = '0' + rem % 10; \
1709 rem /= 10; \
1710 } while (rem != 0); \
1711 \
1712 /* and sign */ \
1713 if (negative) \
1714 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001715 } while (0)
1716
1717#define WRITE_UNICODE_DIGITS(TYPE) \
1718 do { \
1719 if (writer) \
1720 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1721 else \
1722 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1723 \
1724 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001725 \
1726 /* check we've counted correctly */ \
1727 if (writer) \
1728 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1729 else \
1730 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1731 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001734 if (bytes_writer) {
1735 char *p = *bytes_str + strlen;
1736 WRITE_DIGITS(p);
1737 assert(p == *bytes_str);
1738 }
1739 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001740 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001741 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001743 else if (kind == PyUnicode_2BYTE_KIND) {
1744 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001745 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001746 }
1747 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001748 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001749 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001750 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001751 }
1752#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001753#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001756 if (writer) {
1757 writer->pos += strlen;
1758 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001759 else if (bytes_writer) {
1760 (*bytes_str) += strlen;
1761 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001762 else {
1763 assert(_PyUnicode_CheckConsistency(str, 1));
1764 *p_output = (PyObject *)str;
1765 }
1766 return 0;
1767}
1768
1769static PyObject *
1770long_to_decimal_string(PyObject *aa)
1771{
1772 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001773 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001774 return NULL;
1775 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001776}
1777
Serhiy Storchaka95949422013-08-27 19:40:23 +03001778/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001779 which should be one of 2, 8 or 16. Return a string object.
1780 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1781 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001782
Victor Stinnerd3f08822012-05-29 12:57:52 +02001783static int
1784long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001785 PyObject **p_output, _PyUnicodeWriter *writer,
1786 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001787{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001788 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001789 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001790 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001792 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001793 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001795
Victor Stinnerd3f08822012-05-29 12:57:52 +02001796 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 if (a == NULL || !PyLong_Check(a)) {
1798 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001799 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001801 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001802 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /* Compute a rough upper bound for the length of the string */
1805 switch (base) {
1806 case 16:
1807 bits = 4;
1808 break;
1809 case 8:
1810 bits = 3;
1811 break;
1812 case 2:
1813 bits = 1;
1814 break;
1815 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001816 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001818
Mark Dickinsone2846542012-04-20 21:21:24 +01001819 /* Compute exact length 'sz' of output string. */
1820 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001821 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001822 }
1823 else {
1824 Py_ssize_t size_a_in_bits;
1825 /* Ensure overflow doesn't occur during computation of sz. */
1826 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1827 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001828 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001829 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001830 }
1831 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
Niklas Fiekas794e7d12020-06-15 14:33:48 +02001832 bit_length_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001833 /* Allow 1 character for a '-' sign. */
1834 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1835 }
1836 if (alternate) {
1837 /* 2 characters for prefix */
1838 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001839 }
1840
Victor Stinnerd3f08822012-05-29 12:57:52 +02001841 if (writer) {
1842 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1843 return -1;
1844 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001846 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001847 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1848 if (*bytes_str == NULL)
1849 return -1;
1850 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001852 v = PyUnicode_New(sz, 'x');
1853 if (v == NULL)
1854 return -1;
1855 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001857
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001858#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001859 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001860 if (size_a == 0) { \
1861 *--p = '0'; \
1862 } \
1863 else { \
1864 /* JRH: special case for power-of-2 bases */ \
1865 twodigits accum = 0; \
1866 int accumbits = 0; /* # of bits in accum */ \
1867 Py_ssize_t i; \
1868 for (i = 0; i < size_a; ++i) { \
1869 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1870 accumbits += PyLong_SHIFT; \
1871 assert(accumbits >= bits); \
1872 do { \
1873 char cdigit; \
1874 cdigit = (char)(accum & (base - 1)); \
1875 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1876 *--p = cdigit; \
1877 accumbits -= bits; \
1878 accum >>= bits; \
1879 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1880 } \
1881 } \
1882 \
1883 if (alternate) { \
1884 if (base == 16) \
1885 *--p = 'x'; \
1886 else if (base == 8) \
1887 *--p = 'o'; \
1888 else /* (base == 2) */ \
1889 *--p = 'b'; \
1890 *--p = '0'; \
1891 } \
1892 if (negative) \
1893 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001894 } while (0)
1895
1896#define WRITE_UNICODE_DIGITS(TYPE) \
1897 do { \
1898 if (writer) \
1899 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1900 else \
1901 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1902 \
1903 WRITE_DIGITS(p); \
1904 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001905 if (writer) \
1906 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1907 else \
1908 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1909 } while (0)
1910
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001911 if (bytes_writer) {
1912 char *p = *bytes_str + sz;
1913 WRITE_DIGITS(p);
1914 assert(p == *bytes_str);
1915 }
1916 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001917 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001918 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001919 }
1920 else if (kind == PyUnicode_2BYTE_KIND) {
1921 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001922 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001923 }
1924 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001925 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001926 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001927 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001928 }
1929#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001930#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02001931
1932 if (writer) {
1933 writer->pos += sz;
1934 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001935 else if (bytes_writer) {
1936 (*bytes_str) += sz;
1937 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001938 else {
1939 assert(_PyUnicode_CheckConsistency(v, 1));
1940 *p_output = v;
1941 }
1942 return 0;
1943}
1944
1945PyObject *
1946_PyLong_Format(PyObject *obj, int base)
1947{
1948 PyObject *str;
1949 int err;
1950 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001951 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001952 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001953 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001954 if (err == -1)
1955 return NULL;
1956 return str;
1957}
1958
1959int
1960_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1961 PyObject *obj,
1962 int base, int alternate)
1963{
1964 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001965 return long_to_decimal_string_internal(obj, NULL, writer,
1966 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001967 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001968 return long_format_binary(obj, base, alternate, NULL, writer,
1969 NULL, NULL);
1970}
1971
1972char*
1973_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
1974 PyObject *obj,
1975 int base, int alternate)
1976{
1977 char *str2;
1978 int res;
1979 str2 = str;
1980 if (base == 10)
1981 res = long_to_decimal_string_internal(obj, NULL, NULL,
1982 writer, &str2);
1983 else
1984 res = long_format_binary(obj, base, alternate, NULL, NULL,
1985 writer, &str2);
1986 if (res < 0)
1987 return NULL;
1988 assert(str2 != NULL);
1989 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001990}
1991
Thomas Wouters477c8d52006-05-27 19:21:47 +00001992/* Table of digit values for 8-bit string -> integer conversion.
1993 * '0' maps to 0, ..., '9' maps to 9.
1994 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1995 * All other indices map to 37.
1996 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001997 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001998 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001999unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2001 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2002 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2003 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2004 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2005 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2009 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 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,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002016};
2017
2018/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002019 * 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 +03002020 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002021 * The point to this routine is that it takes time linear in the number of
2022 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002023 *
2024 * Return values:
2025 * -1 on syntax error (exception needs to be set, *res is untouched)
2026 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002027 */
Brett Cannona721aba2016-09-09 14:57:09 -07002028static int
2029long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002030{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002031 const char *p = *str;
2032 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002033 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002034 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 int bits_per_char;
2036 Py_ssize_t n;
2037 PyLongObject *z;
2038 twodigits accum;
2039 int bits_in_accum;
2040 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2043 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002044 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002046 }
2047 /* count digits and set p to end-of-string */
2048 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2049 if (*p == '_') {
2050 if (prev == '_') {
2051 *str = p - 1;
2052 return -1;
2053 }
2054 } else {
2055 ++digits;
2056 }
2057 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002059 }
2060 if (prev == '_') {
2061 /* Trailing underscore not allowed. */
2062 *str = p - 1;
2063 return -1;
2064 }
2065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002067 /* n <- the number of Python digits needed,
2068 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2069 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 PyErr_SetString(PyExc_ValueError,
2071 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002072 *res = NULL;
2073 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002075 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002077 if (z == NULL) {
2078 *res = NULL;
2079 return 0;
2080 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002081 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 * from least to most significant in both.
2083 */
2084 accum = 0;
2085 bits_in_accum = 0;
2086 pdigit = z->ob_digit;
2087 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002088 int k;
2089 if (*p == '_') {
2090 continue;
2091 }
2092 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 assert(k >= 0 && k < base);
2094 accum |= (twodigits)k << bits_in_accum;
2095 bits_in_accum += bits_per_char;
2096 if (bits_in_accum >= PyLong_SHIFT) {
2097 *pdigit++ = (digit)(accum & PyLong_MASK);
2098 assert(pdigit - z->ob_digit <= n);
2099 accum >>= PyLong_SHIFT;
2100 bits_in_accum -= PyLong_SHIFT;
2101 assert(bits_in_accum < PyLong_SHIFT);
2102 }
2103 }
2104 if (bits_in_accum) {
2105 assert(bits_in_accum <= PyLong_SHIFT);
2106 *pdigit++ = (digit)accum;
2107 assert(pdigit - z->ob_digit <= n);
2108 }
2109 while (pdigit - z->ob_digit < n)
2110 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002111 *res = long_normalize(z);
2112 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002113}
2114
Serhiy Storchaka95949422013-08-27 19:40:23 +03002115/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002116 * ignored.
2117 *
2118 * If successful, a PyLong object will be returned and 'pend' will be pointing
2119 * to the first unused byte unless it's NULL.
2120 *
2121 * If unsuccessful, NULL will be returned.
2122 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002123PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002124PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002127 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 PyLongObject *z = NULL;
2129 PyObject *strobj;
2130 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 if ((base != 0 && base < 2) || base > 36) {
2133 PyErr_SetString(PyExc_ValueError,
2134 "int() arg 2 must be >= 2 and <= 36");
2135 return NULL;
2136 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002137 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002139 }
2140 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002142 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 else if (*str == '-') {
2144 ++str;
2145 sign = -1;
2146 }
2147 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002148 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002150 }
2151 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002153 }
2154 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002156 }
2157 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002159 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 else {
2161 /* "old" (C-style) octal literal, now invalid.
2162 it might still be zero though */
2163 error_if_nonzero = 1;
2164 base = 10;
2165 }
2166 }
2167 if (str[0] == '0' &&
2168 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2169 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002170 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002172 /* One underscore allowed here. */
2173 if (*str == '_') {
2174 ++str;
2175 }
2176 }
2177 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002178 /* May not start with underscores. */
2179 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002180 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002183 if ((base & (base - 1)) == 0) {
2184 int res = long_from_binary_base(&str, base, &z);
2185 if (res < 0) {
2186 /* Syntax error. */
2187 goto onError;
2188 }
2189 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002191/***
2192Binary bases can be converted in time linear in the number of digits, because
2193Python's representation base is binary. Other bases (including decimal!) use
2194the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002195
Thomas Wouters477c8d52006-05-27 19:21:47 +00002196First some math: the largest integer that can be expressed in N base-B digits
2197is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2198case number of Python digits needed to hold it is the smallest integer n s.t.
2199
2200 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2201 BASE**n >= B**N [taking logs to base BASE]
2202 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2203
2204The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002205this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002206and the result is computed into it.
2207
2208The input string is actually treated as being in base base**i (i.e., i digits
2209are processed at a time), where two more static arrays hold:
2210
2211 convwidth_base[base] = the largest integer i such that base**i <= BASE
2212 convmultmax_base[base] = base ** convwidth_base[base]
2213
2214The first of these is the largest i such that i consecutive input digits
2215must fit in a single Python digit. The second is effectively the input
2216base we're really using.
2217
2218Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2219convmultmax_base[base], the result is "simply"
2220
2221 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2222
2223where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002224
2225Error analysis: as above, the number of Python digits `n` needed is worst-
2226case
2227
2228 n >= N * log(B)/log(BASE)
2229
2230where `N` is the number of input digits in base `B`. This is computed via
2231
2232 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2233
2234below. Two numeric concerns are how much space this can waste, and whether
2235the computed result can be too small. To be concrete, assume BASE = 2**15,
2236which is the default (and it's unlikely anyone changes that).
2237
2238Waste isn't a problem: provided the first input digit isn't 0, the difference
2239between the worst-case input with N digits and the smallest input with N
2240digits is about a factor of B, but B is small compared to BASE so at most
2241one allocated Python digit can remain unused on that count. If
2242N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2243and adding 1 returns a result 1 larger than necessary. However, that can't
2244happen: whenever B is a power of 2, long_from_binary_base() is called
2245instead, and it's impossible for B**i to be an integer power of 2**15 when
2246B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2247an exact integer when B is not a power of 2, since B**i has a prime factor
2248other than 2 in that case, but (2**15)**j's only prime factor is 2).
2249
2250The computed result can be too small if the true value of N*log(B)/log(BASE)
2251is a little bit larger than an exact integer, but due to roundoff errors (in
2252computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2253yields a numeric result a little less than that integer. Unfortunately, "how
2254close can a transcendental function get to an integer over some range?"
2255questions are generally theoretically intractable. Computer analysis via
2256continued fractions is practical: expand log(B)/log(BASE) via continued
2257fractions, giving a sequence i/j of "the best" rational approximations. Then
2258j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2259we can get very close to being in trouble, but very rarely. For example,
226076573 is a denominator in one of the continued-fraction approximations to
2261log(10)/log(2**15), and indeed:
2262
2263 >>> log(10)/log(2**15)*76573
2264 16958.000000654003
2265
2266is very close to an integer. If we were working with IEEE single-precision,
2267rounding errors could kill us. Finding worst cases in IEEE double-precision
2268requires better-than-double-precision log() functions, and Tim didn't bother.
2269Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002270new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002271This should happen extremely rarely, and in fact I don't have a test case
2272that triggers it(!). Instead the code was tested by artificially allocating
2273just 1 digit at the start, so that the copying code was exercised for every
2274digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002275***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002276 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002278 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 int i;
2280 int convwidth;
2281 twodigits convmultmax, convmult;
2282 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002283 const char *scan, *lastdigit;
2284 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 static double log_base_BASE[37] = {0.0e0,};
2287 static int convwidth_base[37] = {0,};
2288 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 if (log_base_BASE[base] == 0.0) {
2291 twodigits convmax = base;
2292 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002293
Mark Dickinson22b20182010-05-10 21:27:53 +00002294 log_base_BASE[base] = (log((double)base) /
2295 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 for (;;) {
2297 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002298 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002300 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 convmax = next;
2302 ++i;
2303 }
2304 convmultmax_base[base] = convmax;
2305 assert(i > 0);
2306 convwidth_base[base] = i;
2307 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 /* Find length of the string of numeric characters. */
2310 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002311 lastdigit = str;
2312
2313 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2314 if (*scan == '_') {
2315 if (prev == '_') {
2316 /* Only one underscore allowed. */
2317 str = lastdigit + 1;
2318 goto onError;
2319 }
2320 }
2321 else {
2322 ++digits;
2323 lastdigit = scan;
2324 }
2325 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002327 }
2328 if (prev == '_') {
2329 /* Trailing underscore not allowed. */
2330 /* Set error pointer to first underscore. */
2331 str = lastdigit + 1;
2332 goto onError;
2333 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002334
Serhiy Storchaka95949422013-08-27 19:40:23 +03002335 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 * integer with this base and length. Note that there's no
2337 * need to initialize z->ob_digit -- no slot is read up before
2338 * being stored into.
2339 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002340 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2341 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002342 /* The same exception as in _PyLong_New(). */
2343 PyErr_SetString(PyExc_OverflowError,
2344 "too many digits in integer");
2345 return NULL;
2346 }
2347 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 /* Uncomment next line to test exceedingly rare copy code */
2349 /* size_z = 1; */
2350 assert(size_z > 0);
2351 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002352 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002354 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002355 Py_SET_SIZE(z, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 /* `convwidth` consecutive input digits are treated as a single
2358 * digit in base `convmultmax`.
2359 */
2360 convwidth = convwidth_base[base];
2361 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* Work ;-) */
2364 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002365 if (*str == '_') {
2366 str++;
2367 continue;
2368 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 /* grab up to convwidth digits from the input string */
2370 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002371 for (i = 1; i < convwidth && str != scan; ++str) {
2372 if (*str == '_') {
2373 continue;
2374 }
2375 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002377 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 assert(c < PyLong_BASE);
2379 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 convmult = convmultmax;
2382 /* Calculate the shift only if we couldn't get
2383 * convwidth digits.
2384 */
2385 if (i != convwidth) {
2386 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002387 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002389 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 /* Multiply z by convmult, and add c. */
2393 pz = z->ob_digit;
2394 pzstop = pz + Py_SIZE(z);
2395 for (; pz < pzstop; ++pz) {
2396 c += (twodigits)*pz * convmult;
2397 *pz = (digit)(c & PyLong_MASK);
2398 c >>= PyLong_SHIFT;
2399 }
2400 /* carry off the current end? */
2401 if (c) {
2402 assert(c < PyLong_BASE);
2403 if (Py_SIZE(z) < size_z) {
2404 *pz = (digit)c;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002405 Py_SET_SIZE(z, Py_SIZE(z) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 }
2407 else {
2408 PyLongObject *tmp;
2409 /* Extremely rare. Get more space. */
2410 assert(Py_SIZE(z) == size_z);
2411 tmp = _PyLong_New(size_z + 1);
2412 if (tmp == NULL) {
2413 Py_DECREF(z);
2414 return NULL;
2415 }
2416 memcpy(tmp->ob_digit,
2417 z->ob_digit,
2418 sizeof(digit) * size_z);
2419 Py_DECREF(z);
2420 z = tmp;
2421 z->ob_digit[size_z] = (digit)c;
2422 ++size_z;
2423 }
2424 }
2425 }
2426 }
Brett Cannona721aba2016-09-09 14:57:09 -07002427 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002429 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 if (error_if_nonzero) {
2431 /* reset the base to 0, else the exception message
2432 doesn't make too much sense */
2433 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002434 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002436 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 /* there might still be other problems, therefore base
2438 remains zero here for the same reason */
2439 }
Brett Cannona721aba2016-09-09 14:57:09 -07002440 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002442 }
2443 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002444 Py_SET_SIZE(z, -(Py_SIZE(z)));
Brett Cannona721aba2016-09-09 14:57:09 -07002445 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002446 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002448 }
2449 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002453 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002454 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002455 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002456 }
2457 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002458 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002459 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002460 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002461
Mark Dickinson22b20182010-05-10 21:27:53 +00002462 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002463 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002464 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 Py_XDECREF(z);
2467 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2468 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002469 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002471 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002473 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 base, strobj);
2475 Py_DECREF(strobj);
2476 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002477}
2478
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002479/* Since PyLong_FromString doesn't have a length parameter,
2480 * check here for possible NULs in the string.
2481 *
2482 * Reports an invalid literal as a bytes object.
2483 */
2484PyObject *
2485_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2486{
2487 PyObject *result, *strobj;
2488 char *end = NULL;
2489
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002490 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002491 if (end == NULL || (result != NULL && end == s + len))
2492 return result;
2493 Py_XDECREF(result);
2494 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2495 if (strobj != NULL) {
2496 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002497 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002498 base, strobj);
2499 Py_DECREF(strobj);
2500 }
2501 return NULL;
2502}
2503
Guido van Rossum9e896b32000-04-05 20:11:21 +00002504PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002505PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002506{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002507 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002508 if (unicode == NULL)
2509 return NULL;
2510 v = PyLong_FromUnicodeObject(unicode, base);
2511 Py_DECREF(unicode);
2512 return v;
2513}
2514
2515PyObject *
2516PyLong_FromUnicodeObject(PyObject *u, int base)
2517{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002518 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002519 const char *buffer;
2520 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002521 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002522
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002523 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002524 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002526 assert(PyUnicode_IS_ASCII(asciidig));
2527 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002528 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002529 assert(buffer != NULL);
2530
2531 result = PyLong_FromString(buffer, &end, base);
2532 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002533 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002534 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002536 Py_DECREF(asciidig);
2537 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002538 PyErr_Format(PyExc_ValueError,
2539 "invalid literal for int() with base %d: %.200R",
2540 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002541 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002542}
2543
Tim Peters9f688bf2000-07-07 15:53:28 +00002544/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002545static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002547static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002548
Serhiy Storchaka95949422013-08-27 19:40:23 +03002549/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002550
Guido van Rossume32e0141992-01-19 16:31:05 +00002551static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002552long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002554{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002555 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 if (size_b == 0) {
2559 PyErr_SetString(PyExc_ZeroDivisionError,
2560 "integer division or modulo by zero");
2561 return -1;
2562 }
2563 if (size_a < size_b ||
2564 (size_a == size_b &&
2565 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2566 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002567 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002568 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002569 return -1;
2570 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002571 Py_INCREF(_PyLong_Zero);
2572 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 return 0;
2574 }
2575 if (size_b == 1) {
2576 digit rem = 0;
2577 z = divrem1(a, b->ob_digit[0], &rem);
2578 if (z == NULL)
2579 return -1;
2580 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2581 if (*prem == NULL) {
2582 Py_DECREF(z);
2583 return -1;
2584 }
2585 }
2586 else {
2587 z = x_divrem(a, b, prem);
2588 if (z == NULL)
2589 return -1;
2590 }
2591 /* Set the signs.
2592 The quotient z has the sign of a*b;
2593 the remainder r has the sign of a,
2594 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002595 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2596 _PyLong_Negate(&z);
2597 if (z == NULL) {
2598 Py_CLEAR(*prem);
2599 return -1;
2600 }
2601 }
2602 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2603 _PyLong_Negate(prem);
2604 if (*prem == NULL) {
2605 Py_DECREF(z);
2606 Py_CLEAR(*prem);
2607 return -1;
2608 }
2609 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 *pdiv = maybe_small_long(z);
2611 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002612}
2613
Serhiy Storchaka95949422013-08-27 19:40:23 +03002614/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002615 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002616
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002617static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002618x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 PyLongObject *v, *w, *a;
2621 Py_ssize_t i, k, size_v, size_w;
2622 int d;
2623 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2624 twodigits vv;
2625 sdigit zhi;
2626 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2629 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2630 handle the special case when the initial estimate q for a quotient
2631 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2632 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002635 size_v = Py_ABS(Py_SIZE(v1));
2636 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2638 v = _PyLong_New(size_v+1);
2639 if (v == NULL) {
2640 *prem = NULL;
2641 return NULL;
2642 }
2643 w = _PyLong_New(size_w);
2644 if (w == NULL) {
2645 Py_DECREF(v);
2646 *prem = NULL;
2647 return NULL;
2648 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2651 shift v1 left by the same amount. Results go into w and v. */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02002652 d = PyLong_SHIFT - bit_length_digit(w1->ob_digit[size_w-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2654 assert(carry == 0);
2655 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2656 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2657 v->ob_digit[size_v] = carry;
2658 size_v++;
2659 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2662 at most (and usually exactly) k = size_v - size_w digits. */
2663 k = size_v - size_w;
2664 assert(k >= 0);
2665 a = _PyLong_New(k);
2666 if (a == NULL) {
2667 Py_DECREF(w);
2668 Py_DECREF(v);
2669 *prem = NULL;
2670 return NULL;
2671 }
2672 v0 = v->ob_digit;
2673 w0 = w->ob_digit;
2674 wm1 = w0[size_w-1];
2675 wm2 = w0[size_w-2];
2676 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2677 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2678 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002681 Py_DECREF(a);
2682 Py_DECREF(w);
2683 Py_DECREF(v);
2684 *prem = NULL;
2685 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002686 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 /* estimate quotient digit q; may overestimate by 1 (rare) */
2689 vtop = vk[size_w];
2690 assert(vtop <= wm1);
2691 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2692 q = (digit)(vv / wm1);
2693 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2694 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2695 | vk[size_w-2])) {
2696 --q;
2697 r += wm1;
2698 if (r >= PyLong_BASE)
2699 break;
2700 }
2701 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2704 zhi = 0;
2705 for (i = 0; i < size_w; ++i) {
2706 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2707 -PyLong_BASE * q <= z < PyLong_BASE */
2708 z = (sdigit)vk[i] + zhi -
2709 (stwodigits)q * (stwodigits)w0[i];
2710 vk[i] = (digit)z & PyLong_MASK;
2711 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002712 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 /* add w back if q was too large (this branch taken rarely) */
2716 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2717 if ((sdigit)vtop + zhi < 0) {
2718 carry = 0;
2719 for (i = 0; i < size_w; ++i) {
2720 carry += vk[i] + w0[i];
2721 vk[i] = carry & PyLong_MASK;
2722 carry >>= PyLong_SHIFT;
2723 }
2724 --q;
2725 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 /* store quotient digit */
2728 assert(q < PyLong_BASE);
2729 *--ak = q;
2730 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 /* unshift remainder; we reuse w to store the result */
2733 carry = v_rshift(w0, v0, size_w, d);
2734 assert(carry==0);
2735 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 *prem = long_normalize(w);
2738 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002739}
2740
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002741/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2742 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2743 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2744 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2745 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2746 -1.0. */
2747
2748/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2749#if DBL_MANT_DIG == 53
2750#define EXP2_DBL_MANT_DIG 9007199254740992.0
2751#else
2752#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2753#endif
2754
2755double
2756_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2759 /* See below for why x_digits is always large enough. */
Dong-hee Nab88cd582020-05-04 22:32:42 +09002760 digit rem;
2761 digit x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT] = {0,};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 double dx;
2763 /* Correction term for round-half-to-even rounding. For a digit x,
2764 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2765 multiple of 4, rounding ties to a multiple of 8. */
2766 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002767
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002768 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 if (a_size == 0) {
2770 /* Special case for 0: significand 0.0, exponent 0. */
2771 *e = 0;
2772 return 0.0;
2773 }
Niklas Fiekas794e7d12020-06-15 14:33:48 +02002774 a_bits = bit_length_digit(a->ob_digit[a_size-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 /* The following is an overflow-free version of the check
2776 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2777 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2778 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2779 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002780 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2784 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 Number of digits needed for result: write // for floor division.
2787 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2796 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2799 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2800 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 in both cases.
2807 */
2808 if (a_bits <= DBL_MANT_DIG + 2) {
2809 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2810 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
Dong-hee Nab88cd582020-05-04 22:32:42 +09002811 x_size = shift_digits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2813 (int)shift_bits);
2814 x_size += a_size;
2815 x_digits[x_size++] = rem;
2816 }
2817 else {
2818 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2819 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2820 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2821 a_size - shift_digits, (int)shift_bits);
2822 x_size = a_size - shift_digits;
2823 /* For correct rounding below, we need the least significant
2824 bit of x to be 'sticky' for this shift: if any of the bits
2825 shifted out was nonzero, we set the least significant bit
2826 of x. */
2827 if (rem)
2828 x_digits[0] |= 1;
2829 else
2830 while (shift_digits > 0)
2831 if (a->ob_digit[--shift_digits]) {
2832 x_digits[0] |= 1;
2833 break;
2834 }
2835 }
Victor Stinner63941882011-09-29 00:42:28 +02002836 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 /* Round, and convert to double. */
2839 x_digits[0] += half_even_correction[x_digits[0] & 7];
2840 dx = x_digits[--x_size];
2841 while (x_size > 0)
2842 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 /* Rescale; make correction if result is 1.0. */
2845 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2846 if (dx == 1.0) {
2847 if (a_bits == PY_SSIZE_T_MAX)
2848 goto overflow;
2849 dx = 0.5;
2850 a_bits += 1;
2851 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 *e = a_bits;
2854 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002855
2856 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 /* exponent > PY_SSIZE_T_MAX */
2858 PyErr_SetString(PyExc_OverflowError,
2859 "huge integer: number of bits overflows a Py_ssize_t");
2860 *e = 0;
2861 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002862}
2863
Serhiy Storchaka95949422013-08-27 19:40:23 +03002864/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002865 using the round-half-to-even rule in the case of a tie. */
2866
2867double
2868PyLong_AsDouble(PyObject *v)
2869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 Py_ssize_t exponent;
2871 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002872
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002873 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 PyErr_BadInternalCall();
2875 return -1.0;
2876 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002877 if (!PyLong_Check(v)) {
2878 PyErr_SetString(PyExc_TypeError, "an integer is required");
2879 return -1.0;
2880 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002881 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002882 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002883 to double. This improves performance of FP/long operations
2884 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002885 */
2886 return (double)MEDIUM_VALUE((PyLongObject *)v);
2887 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2889 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2890 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002891 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 return -1.0;
2893 }
2894 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002895}
2896
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002897/* Methods */
2898
HongWeipeng42acb7b2019-09-18 23:10:15 +08002899/* if a < b, return a negative number
2900 if a == b, return 0
2901 if a > b, return a positive number */
2902
2903static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002904long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002905{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002906 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
2907 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002908 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08002909 sdigit diff = 0;
2910 while (--i >= 0) {
2911 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
2912 if (diff) {
2913 break;
2914 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08002916 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08002918 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002919}
2920
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002921static PyObject *
2922long_richcompare(PyObject *self, PyObject *other, int op)
2923{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002924 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 CHECK_BINOP(self, other);
2926 if (self == other)
2927 result = 0;
2928 else
2929 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01002930 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002931}
2932
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002933static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002934long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002935{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002936 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 Py_ssize_t i;
2938 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 i = Py_SIZE(v);
2941 switch(i) {
2942 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2943 case 0: return 0;
2944 case 1: return v->ob_digit[0];
2945 }
2946 sign = 1;
2947 x = 0;
2948 if (i < 0) {
2949 sign = -1;
2950 i = -(i);
2951 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002953 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2954 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2955 _PyHASH_MODULUS.
2956
2957 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2958 amounts to a rotation of the bits of x. To see this, write
2959
2960 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2961
2962 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2963 PyLong_SHIFT bits of x (those that are shifted out of the
2964 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2965 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2966 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2967 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2968 congruent to y modulo _PyHASH_MODULUS. So
2969
2970 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2971
2972 The right-hand side is just the result of rotating the
2973 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2974 not all _PyHASH_BITS bits of x are 1s, the same is true
2975 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2976 the reduction of x*2**PyLong_SHIFT modulo
2977 _PyHASH_MODULUS. */
2978 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2979 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002981 if (x >= _PyHASH_MODULUS)
2982 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 }
2984 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002985 if (x == (Py_uhash_t)-1)
2986 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002987 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002988}
2989
2990
Serhiy Storchaka95949422013-08-27 19:40:23 +03002991/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002992
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002993static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002994x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002995{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002996 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 PyLongObject *z;
2998 Py_ssize_t i;
2999 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 /* Ensure a is the larger of the two: */
3002 if (size_a < size_b) {
3003 { PyLongObject *temp = a; a = b; b = temp; }
3004 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003005 size_a = size_b;
3006 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 }
3008 z = _PyLong_New(size_a+1);
3009 if (z == NULL)
3010 return NULL;
3011 for (i = 0; i < size_b; ++i) {
3012 carry += a->ob_digit[i] + b->ob_digit[i];
3013 z->ob_digit[i] = carry & PyLong_MASK;
3014 carry >>= PyLong_SHIFT;
3015 }
3016 for (; i < size_a; ++i) {
3017 carry += a->ob_digit[i];
3018 z->ob_digit[i] = carry & PyLong_MASK;
3019 carry >>= PyLong_SHIFT;
3020 }
3021 z->ob_digit[i] = carry;
3022 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003023}
3024
3025/* Subtract the absolute values of two integers. */
3026
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003027static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003028x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003029{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003030 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 PyLongObject *z;
3032 Py_ssize_t i;
3033 int sign = 1;
3034 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 /* Ensure a is the larger of the two: */
3037 if (size_a < size_b) {
3038 sign = -1;
3039 { PyLongObject *temp = a; a = b; b = temp; }
3040 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003041 size_a = size_b;
3042 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 }
3044 else if (size_a == size_b) {
3045 /* Find highest digit where a and b differ: */
3046 i = size_a;
3047 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3048 ;
3049 if (i < 0)
3050 return (PyLongObject *)PyLong_FromLong(0);
3051 if (a->ob_digit[i] < b->ob_digit[i]) {
3052 sign = -1;
3053 { PyLongObject *temp = a; a = b; b = temp; }
3054 }
3055 size_a = size_b = i+1;
3056 }
3057 z = _PyLong_New(size_a);
3058 if (z == NULL)
3059 return NULL;
3060 for (i = 0; i < size_b; ++i) {
3061 /* The following assumes unsigned arithmetic
3062 works module 2**N for some N>PyLong_SHIFT. */
3063 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3064 z->ob_digit[i] = borrow & PyLong_MASK;
3065 borrow >>= PyLong_SHIFT;
3066 borrow &= 1; /* Keep only one sign bit */
3067 }
3068 for (; i < size_a; ++i) {
3069 borrow = a->ob_digit[i] - borrow;
3070 z->ob_digit[i] = borrow & PyLong_MASK;
3071 borrow >>= PyLong_SHIFT;
3072 borrow &= 1; /* Keep only one sign bit */
3073 }
3074 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003075 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003076 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02003077 }
HongWeipeng036fe852019-11-26 15:54:49 +08003078 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003079}
3080
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003081static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003082long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003087
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003088 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003089 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 }
3091 if (Py_SIZE(a) < 0) {
3092 if (Py_SIZE(b) < 0) {
3093 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003094 if (z != NULL) {
3095 /* x_add received at least one multiple-digit int,
3096 and thus z must be a multiple-digit int.
3097 That also means z is not an element of
3098 small_ints, so negating it in-place is safe. */
3099 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003100 Py_SET_SIZE(z, -(Py_SIZE(z)));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003101 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 }
3103 else
3104 z = x_sub(b, a);
3105 }
3106 else {
3107 if (Py_SIZE(b) < 0)
3108 z = x_sub(a, b);
3109 else
3110 z = x_add(a, b);
3111 }
3112 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003113}
3114
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003115static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003116long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003121
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003122 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003123 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 }
3125 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003126 if (Py_SIZE(b) < 0) {
3127 z = x_sub(b, a);
3128 }
3129 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003131 if (z != NULL) {
3132 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003133 Py_SET_SIZE(z, -(Py_SIZE(z)));
HongWeipeng036fe852019-11-26 15:54:49 +08003134 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003135 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 }
3137 else {
3138 if (Py_SIZE(b) < 0)
3139 z = x_add(a, b);
3140 else
3141 z = x_sub(a, b);
3142 }
3143 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003144}
3145
Tim Peters5af4e6c2002-08-12 02:31:19 +00003146/* Grade school multiplication, ignoring the signs.
3147 * Returns the absolute value of the product, or NULL if error.
3148 */
3149static PyLongObject *
3150x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003153 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3154 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 z = _PyLong_New(size_a + size_b);
3158 if (z == NULL)
3159 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3162 if (a == b) {
3163 /* Efficient squaring per HAC, Algorithm 14.16:
3164 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3165 * Gives slightly less than a 2x speedup when a == b,
3166 * via exploiting that each entry in the multiplication
3167 * pyramid appears twice (except for the size_a squares).
3168 */
3169 for (i = 0; i < size_a; ++i) {
3170 twodigits carry;
3171 twodigits f = a->ob_digit[i];
3172 digit *pz = z->ob_digit + (i << 1);
3173 digit *pa = a->ob_digit + i + 1;
3174 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003177 Py_DECREF(z);
3178 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003179 });
Tim Peters0973b992004-08-29 22:16:50 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 carry = *pz + f * f;
3182 *pz++ = (digit)(carry & PyLong_MASK);
3183 carry >>= PyLong_SHIFT;
3184 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 /* Now f is added in twice in each column of the
3187 * pyramid it appears. Same as adding f<<1 once.
3188 */
3189 f <<= 1;
3190 while (pa < paend) {
3191 carry += *pz + *pa++ * f;
3192 *pz++ = (digit)(carry & PyLong_MASK);
3193 carry >>= PyLong_SHIFT;
3194 assert(carry <= (PyLong_MASK << 1));
3195 }
3196 if (carry) {
3197 carry += *pz;
3198 *pz++ = (digit)(carry & PyLong_MASK);
3199 carry >>= PyLong_SHIFT;
3200 }
3201 if (carry)
3202 *pz += (digit)(carry & PyLong_MASK);
3203 assert((carry >> PyLong_SHIFT) == 0);
3204 }
3205 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003206 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 for (i = 0; i < size_a; ++i) {
3208 twodigits carry = 0;
3209 twodigits f = a->ob_digit[i];
3210 digit *pz = z->ob_digit + i;
3211 digit *pb = b->ob_digit;
3212 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003215 Py_DECREF(z);
3216 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003217 });
Tim Peters0973b992004-08-29 22:16:50 +00003218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 while (pb < pbend) {
3220 carry += *pz + *pb++ * f;
3221 *pz++ = (digit)(carry & PyLong_MASK);
3222 carry >>= PyLong_SHIFT;
3223 assert(carry <= PyLong_MASK);
3224 }
3225 if (carry)
3226 *pz += (digit)(carry & PyLong_MASK);
3227 assert((carry >> PyLong_SHIFT) == 0);
3228 }
3229 }
3230 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003231}
3232
3233/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003234 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003235 split, and sets low and high such that abs(n) == (high << size) + low,
3236 viewing the shift as being by digits. The sign bit is ignored, and
3237 the return values are >= 0.
3238 Returns 0 on success, -1 on failure.
3239*/
3240static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003241kmul_split(PyLongObject *n,
3242 Py_ssize_t size,
3243 PyLongObject **high,
3244 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 PyLongObject *hi, *lo;
3247 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003248 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003249
Victor Stinner640c35c2013-06-04 23:14:37 +02003250 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 if ((hi = _PyLong_New(size_hi)) == NULL)
3254 return -1;
3255 if ((lo = _PyLong_New(size_lo)) == NULL) {
3256 Py_DECREF(hi);
3257 return -1;
3258 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3261 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 *high = long_normalize(hi);
3264 *low = long_normalize(lo);
3265 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003266}
3267
Tim Peters60004642002-08-12 22:01:34 +00003268static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3269
Tim Peters5af4e6c2002-08-12 02:31:19 +00003270/* Karatsuba multiplication. Ignores the input signs, and returns the
3271 * absolute value of the product (or NULL if error).
3272 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3273 */
3274static PyLongObject *
3275k_mul(PyLongObject *a, PyLongObject *b)
3276{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003277 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3278 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 PyLongObject *ah = NULL;
3280 PyLongObject *al = NULL;
3281 PyLongObject *bh = NULL;
3282 PyLongObject *bl = NULL;
3283 PyLongObject *ret = NULL;
3284 PyLongObject *t1, *t2, *t3;
3285 Py_ssize_t shift; /* the number of digits we split off */
3286 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3289 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3290 * Then the original product is
3291 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3292 * By picking X to be a power of 2, "*X" is just shifting, and it's
3293 * been reduced to 3 multiplies on numbers half the size.
3294 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 /* We want to split based on the larger number; fiddle so that b
3297 * is largest.
3298 */
3299 if (asize > bsize) {
3300 t1 = a;
3301 a = b;
3302 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 i = asize;
3305 asize = bsize;
3306 bsize = i;
3307 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 /* Use gradeschool math when either number is too small. */
3310 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3311 if (asize <= i) {
3312 if (asize == 0)
3313 return (PyLongObject *)PyLong_FromLong(0);
3314 else
3315 return x_mul(a, b);
3316 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 /* If a is small compared to b, splitting on b gives a degenerate
3319 * case with ah==0, and Karatsuba may be (even much) less efficient
3320 * than "grade school" then. However, we can still win, by viewing
3321 * b as a string of "big digits", each of width a->ob_size. That
3322 * leads to a sequence of balanced calls to k_mul.
3323 */
3324 if (2 * asize <= bsize)
3325 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 /* Split a & b into hi & lo pieces. */
3328 shift = bsize >> 1;
3329 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3330 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 if (a == b) {
3333 bh = ah;
3334 bl = al;
3335 Py_INCREF(bh);
3336 Py_INCREF(bl);
3337 }
3338 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 /* The plan:
3341 * 1. Allocate result space (asize + bsize digits: that's always
3342 * enough).
3343 * 2. Compute ah*bh, and copy into result at 2*shift.
3344 * 3. Compute al*bl, and copy into result at 0. Note that this
3345 * can't overlap with #2.
3346 * 4. Subtract al*bl from the result, starting at shift. This may
3347 * underflow (borrow out of the high digit), but we don't care:
3348 * we're effectively doing unsigned arithmetic mod
3349 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3350 * borrows and carries out of the high digit can be ignored.
3351 * 5. Subtract ah*bh from the result, starting at shift.
3352 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3353 * at shift.
3354 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 /* 1. Allocate result space. */
3357 ret = _PyLong_New(asize + bsize);
3358 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003359#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 /* Fill with trash, to catch reference to uninitialized digits. */
3361 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003362#endif
Tim Peters44121a62002-08-12 06:17:58 +00003363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3365 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3366 assert(Py_SIZE(t1) >= 0);
3367 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3368 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3369 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 /* Zero-out the digits higher than the ah*bh copy. */
3372 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3373 if (i)
3374 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3375 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 /* 3. t2 <- al*bl, and copy into the low digits. */
3378 if ((t2 = k_mul(al, bl)) == NULL) {
3379 Py_DECREF(t1);
3380 goto fail;
3381 }
3382 assert(Py_SIZE(t2) >= 0);
3383 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3384 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 /* Zero out remaining digits. */
3387 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3388 if (i)
3389 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3392 * because it's fresher in cache.
3393 */
3394 i = Py_SIZE(ret) - shift; /* # digits after shift */
3395 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3396 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3399 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3402 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3403 Py_DECREF(ah);
3404 Py_DECREF(al);
3405 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 if (a == b) {
3408 t2 = t1;
3409 Py_INCREF(t2);
3410 }
3411 else if ((t2 = x_add(bh, bl)) == NULL) {
3412 Py_DECREF(t1);
3413 goto fail;
3414 }
3415 Py_DECREF(bh);
3416 Py_DECREF(bl);
3417 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 t3 = k_mul(t1, t2);
3420 Py_DECREF(t1);
3421 Py_DECREF(t2);
3422 if (t3 == NULL) goto fail;
3423 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 /* Add t3. It's not obvious why we can't run out of room here.
3426 * See the (*) comment after this function.
3427 */
3428 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3429 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003432
Mark Dickinson22b20182010-05-10 21:27:53 +00003433 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 Py_XDECREF(ret);
3435 Py_XDECREF(ah);
3436 Py_XDECREF(al);
3437 Py_XDECREF(bh);
3438 Py_XDECREF(bl);
3439 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003440}
3441
Tim Petersd6974a52002-08-13 20:37:51 +00003442/* (*) Why adding t3 can't "run out of room" above.
3443
Tim Petersab86c2b2002-08-15 20:06:00 +00003444Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3445to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003446
Tim Petersab86c2b2002-08-15 20:06:00 +000034471. For any integer i, i = c(i/2) + f(i/2). In particular,
3448 bsize = c(bsize/2) + f(bsize/2).
34492. shift = f(bsize/2)
34503. asize <= bsize
34514. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3452 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003453
Tim Petersab86c2b2002-08-15 20:06:00 +00003454We allocated asize + bsize result digits, and add t3 into them at an offset
3455of shift. This leaves asize+bsize-shift allocated digit positions for t3
3456to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3457asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003458
Tim Petersab86c2b2002-08-15 20:06:00 +00003459bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3460at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003461
Tim Petersab86c2b2002-08-15 20:06:00 +00003462If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3463digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3464most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003465
Tim Petersab86c2b2002-08-15 20:06:00 +00003466The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003467
Tim Petersab86c2b2002-08-15 20:06:00 +00003468 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003469
Tim Petersab86c2b2002-08-15 20:06:00 +00003470and we have asize + c(bsize/2) available digit positions. We need to show
3471this is always enough. An instance of c(bsize/2) cancels out in both, so
3472the question reduces to whether asize digits is enough to hold
3473(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3474then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3475asize 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 +00003476digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003477asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003478c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3479is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3480bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003481
Tim Peters48d52c02002-08-14 17:07:32 +00003482Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3483clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3484ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003485*/
3486
Tim Peters60004642002-08-12 22:01:34 +00003487/* b has at least twice the digits of a, and a is big enough that Karatsuba
3488 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3489 * of slices, each with a->ob_size digits, and multiply the slices by a,
3490 * one at a time. This gives k_mul balanced inputs to work with, and is
3491 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003492 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003493 * single-width slice overlap between successive partial sums).
3494 */
3495static PyLongObject *
3496k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3497{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003498 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3499 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 Py_ssize_t nbdone; /* # of b digits already multiplied */
3501 PyLongObject *ret;
3502 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 assert(asize > KARATSUBA_CUTOFF);
3505 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 /* Allocate result space, and zero it out. */
3508 ret = _PyLong_New(asize + bsize);
3509 if (ret == NULL)
3510 return NULL;
3511 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 /* Successive slices of b are copied into bslice. */
3514 bslice = _PyLong_New(asize);
3515 if (bslice == NULL)
3516 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 nbdone = 0;
3519 while (bsize > 0) {
3520 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003521 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 /* Multiply the next slice of b by a. */
3524 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3525 nbtouse * sizeof(digit));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003526 Py_SET_SIZE(bslice, nbtouse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 product = k_mul(a, bslice);
3528 if (product == NULL)
3529 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 /* Add into result. */
3532 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3533 product->ob_digit, Py_SIZE(product));
3534 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 bsize -= nbtouse;
3537 nbdone += nbtouse;
3538 }
Tim Peters60004642002-08-12 22:01:34 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 Py_DECREF(bslice);
3541 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003542
Mark Dickinson22b20182010-05-10 21:27:53 +00003543 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 Py_DECREF(ret);
3545 Py_XDECREF(bslice);
3546 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003547}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003548
3549static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003550long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003557 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003559 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 z = k_mul(a, b);
3563 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003564 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3565 _PyLong_Negate(&z);
3566 if (z == NULL)
3567 return NULL;
3568 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003570}
3571
Yury Selivanove0b23092016-02-11 10:26:27 -05003572/* Fast modulo division for single-digit longs. */
3573static PyObject *
3574fast_mod(PyLongObject *a, PyLongObject *b)
3575{
3576 sdigit left = a->ob_digit[0];
3577 sdigit right = b->ob_digit[0];
3578 sdigit mod;
3579
3580 assert(Py_ABS(Py_SIZE(a)) == 1);
3581 assert(Py_ABS(Py_SIZE(b)) == 1);
3582
3583 if (Py_SIZE(a) == Py_SIZE(b)) {
3584 /* 'a' and 'b' have the same sign. */
3585 mod = left % right;
3586 }
3587 else {
3588 /* Either 'a' or 'b' is negative. */
3589 mod = right - 1 - (left - 1) % right;
3590 }
3591
Victor Stinnerf963c132016-03-23 18:36:54 +01003592 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003593}
3594
3595/* Fast floor division for single-digit longs. */
3596static PyObject *
3597fast_floor_div(PyLongObject *a, PyLongObject *b)
3598{
3599 sdigit left = a->ob_digit[0];
3600 sdigit right = b->ob_digit[0];
3601 sdigit div;
3602
3603 assert(Py_ABS(Py_SIZE(a)) == 1);
3604 assert(Py_ABS(Py_SIZE(b)) == 1);
3605
3606 if (Py_SIZE(a) == Py_SIZE(b)) {
3607 /* 'a' and 'b' have the same sign. */
3608 div = left / right;
3609 }
3610 else {
3611 /* Either 'a' or 'b' is negative. */
3612 div = -1 - (left - 1) / right;
3613 }
3614
3615 return PyLong_FromLong(div);
3616}
3617
Guido van Rossume32e0141992-01-19 16:31:05 +00003618/* The / and % operators are now defined in terms of divmod().
3619 The expression a mod b has the value a - b*floor(a/b).
3620 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003621 |a| by |b|, with the sign of a. This is also expressed
3622 as a - b*trunc(a/b), if trunc truncates towards zero.
3623 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 a b a rem b a mod b
3625 13 10 3 3
3626 -13 10 -3 7
3627 13 -10 3 -7
3628 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003629 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003630 have different signs. We then subtract one from the 'div'
3631 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003632
Tim Peters47e52ee2004-08-30 02:44:38 +00003633/* Compute
3634 * *pdiv, *pmod = divmod(v, w)
3635 * NULL can be passed for pdiv or pmod, in which case that part of
3636 * the result is simply thrown away. The caller owns a reference to
3637 * each of these it requests (does not pass NULL for).
3638 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003639static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003640l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003644
Yury Selivanove0b23092016-02-11 10:26:27 -05003645 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3646 /* Fast path for single-digit longs */
3647 div = NULL;
3648 if (pdiv != NULL) {
3649 div = (PyLongObject *)fast_floor_div(v, w);
3650 if (div == NULL) {
3651 return -1;
3652 }
3653 }
3654 if (pmod != NULL) {
3655 mod = (PyLongObject *)fast_mod(v, w);
3656 if (mod == NULL) {
3657 Py_XDECREF(div);
3658 return -1;
3659 }
3660 *pmod = mod;
3661 }
3662 if (pdiv != NULL) {
3663 /* We only want to set `*pdiv` when `*pmod` is
3664 set successfully. */
3665 *pdiv = div;
3666 }
3667 return 0;
3668 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 if (long_divrem(v, w, &div, &mod) < 0)
3670 return -1;
3671 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3672 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3673 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 temp = (PyLongObject *) long_add(mod, w);
3675 Py_DECREF(mod);
3676 mod = temp;
3677 if (mod == NULL) {
3678 Py_DECREF(div);
3679 return -1;
3680 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003681 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3682 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 Py_DECREF(mod);
3684 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 return -1;
3686 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 Py_DECREF(div);
3688 div = temp;
3689 }
3690 if (pdiv != NULL)
3691 *pdiv = div;
3692 else
3693 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 if (pmod != NULL)
3696 *pmod = mod;
3697 else
3698 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003701}
3702
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003703static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003704long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003709
3710 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3711 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3712 }
3713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3715 div = NULL;
3716 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003717}
3718
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003719/* PyLong/PyLong -> float, with correctly rounded result. */
3720
3721#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3722#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3723
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003724static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003725long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 PyLongObject *a, *b, *x;
3728 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3729 digit mask, low;
3730 int inexact, negate, a_is_small, b_is_small;
3731 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 CHECK_BINOP(v, w);
3734 a = (PyLongObject *)v;
3735 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 /*
3738 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3741 1. choose a suitable integer 'shift'
3742 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3743 3. adjust x for correct rounding
3744 4. convert x to a double dx with the same value
3745 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3750 returns either 0.0 or -0.0, depending on the sign of b. For a and
3751 b both nonzero, ignore signs of a and b, and add the sign back in
3752 at the end. Now write a_bits and b_bits for the bit lengths of a
3753 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3754 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3759 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3760 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3761 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 1. The integer 'shift' is chosen so that x has the right number of
3766 bits for a double, plus two or three extra bits that will be used
3767 in the rounding decisions. Writing a_bits and b_bits for the
3768 number of significant bits in a and b respectively, a
3769 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 This is fine in the usual case, but if a/b is smaller than the
3774 smallest normal float then it can lead to double rounding on an
3775 IEEE 754 platform, giving incorrectly rounded results. So we
3776 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 2. The quantity x is computed by first shifting a (left -shift bits
3781 if shift <= 0, right shift bits if shift > 0) and then dividing by
3782 b. For both the shift and the division, we keep track of whether
3783 the result is inexact, in a flag 'inexact'; this information is
3784 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 With the choice of shift above, together with our assumption that
3787 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3788 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3791 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 For float representability, we need x/2**extra_bits <
3796 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3797 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 To round, we just modify the bottom digit of x in-place; this can
3802 end up giving a digit with value > PyLONG_MASK, but that's not a
3803 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 With the original choices for shift above, extra_bits will always
3806 be 2 or 3. Then rounding under the round-half-to-even rule, we
3807 round up iff the most significant of the extra bits is 1, and
3808 either: (a) the computation of x in step 2 had an inexact result,
3809 or (b) at least one other of the extra bits is 1, or (c) the least
3810 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 4. Conversion to a double is straightforward; all floating-point
3813 operations involved in the conversion are exact, so there's no
3814 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3817 The result will always be exactly representable as a double, except
3818 in the case that it overflows. To avoid dependence on the exact
3819 behaviour of ldexp on overflow, we check for overflow before
3820 applying ldexp. The result of ldexp is adjusted for sign before
3821 returning.
3822 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003825 a_size = Py_ABS(Py_SIZE(a));
3826 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3828 if (b_size == 0) {
3829 PyErr_SetString(PyExc_ZeroDivisionError,
3830 "division by zero");
3831 goto error;
3832 }
3833 if (a_size == 0)
3834 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 /* Fast path for a and b small (exactly representable in a double).
3837 Relies on floating-point division being correctly rounded; results
3838 may be subject to double rounding on x86 machines that operate with
3839 the x87 FPU set to 64-bit precision. */
3840 a_is_small = a_size <= MANT_DIG_DIGITS ||
3841 (a_size == MANT_DIG_DIGITS+1 &&
3842 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3843 b_is_small = b_size <= MANT_DIG_DIGITS ||
3844 (b_size == MANT_DIG_DIGITS+1 &&
3845 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3846 if (a_is_small && b_is_small) {
3847 double da, db;
3848 da = a->ob_digit[--a_size];
3849 while (a_size > 0)
3850 da = da * PyLong_BASE + a->ob_digit[--a_size];
3851 db = b->ob_digit[--b_size];
3852 while (b_size > 0)
3853 db = db * PyLong_BASE + b->ob_digit[--b_size];
3854 result = da / db;
3855 goto success;
3856 }
Tim Peterse2a60002001-09-04 06:17:36 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 /* Catch obvious cases of underflow and overflow */
3859 diff = a_size - b_size;
3860 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3861 /* Extreme overflow */
3862 goto overflow;
3863 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3864 /* Extreme underflow */
3865 goto underflow_or_zero;
3866 /* Next line is now safe from overflowing a Py_ssize_t */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02003867 diff = diff * PyLong_SHIFT + bit_length_digit(a->ob_digit[a_size - 1]) -
3868 bit_length_digit(b->ob_digit[b_size - 1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 /* Now diff = a_bits - b_bits. */
3870 if (diff > DBL_MAX_EXP)
3871 goto overflow;
3872 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3873 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003876 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 /* x = abs(a * 2**-shift) */
3881 if (shift <= 0) {
3882 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3883 digit rem;
3884 /* x = a << -shift */
3885 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3886 /* In practice, it's probably impossible to end up
3887 here. Both a and b would have to be enormous,
3888 using close to SIZE_T_MAX bytes of memory each. */
3889 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003890 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 goto error;
3892 }
3893 x = _PyLong_New(a_size + shift_digits + 1);
3894 if (x == NULL)
3895 goto error;
3896 for (i = 0; i < shift_digits; i++)
3897 x->ob_digit[i] = 0;
3898 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3899 a_size, -shift % PyLong_SHIFT);
3900 x->ob_digit[a_size + shift_digits] = rem;
3901 }
3902 else {
3903 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3904 digit rem;
3905 /* x = a >> shift */
3906 assert(a_size >= shift_digits);
3907 x = _PyLong_New(a_size - shift_digits);
3908 if (x == NULL)
3909 goto error;
3910 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3911 a_size - shift_digits, shift % PyLong_SHIFT);
3912 /* set inexact if any of the bits shifted out is nonzero */
3913 if (rem)
3914 inexact = 1;
3915 while (!inexact && shift_digits > 0)
3916 if (a->ob_digit[--shift_digits])
3917 inexact = 1;
3918 }
3919 long_normalize(x);
3920 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3923 reference to x, so it's safe to modify it in-place. */
3924 if (b_size == 1) {
3925 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3926 b->ob_digit[0]);
3927 long_normalize(x);
3928 if (rem)
3929 inexact = 1;
3930 }
3931 else {
3932 PyLongObject *div, *rem;
3933 div = x_divrem(x, b, &rem);
3934 Py_DECREF(x);
3935 x = div;
3936 if (x == NULL)
3937 goto error;
3938 if (Py_SIZE(rem))
3939 inexact = 1;
3940 Py_DECREF(rem);
3941 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003942 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 assert(x_size > 0); /* result of division is never zero */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02003944 x_bits = (x_size-1)*PyLong_SHIFT+bit_length_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003947 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 /* Round by directly modifying the low digit of x. */
3951 mask = (digit)1 << (extra_bits - 1);
3952 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003953 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003955 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 /* Convert x to a double dx; the conversion is exact. */
3958 dx = x->ob_digit[--x_size];
3959 while (x_size > 0)
3960 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3961 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 /* Check whether ldexp result will overflow a double. */
3964 if (shift + x_bits >= DBL_MAX_EXP &&
3965 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3966 goto overflow;
3967 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003968
3969 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003971
3972 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003974
3975 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 PyErr_SetString(PyExc_OverflowError,
3977 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003978 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003980}
3981
3982static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003983long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 CHECK_BINOP(a, b);
3988
Yury Selivanove0b23092016-02-11 10:26:27 -05003989 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3990 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
3991 }
3992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3994 mod = NULL;
3995 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003996}
3997
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003998static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003999long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 PyLongObject *div, *mod;
4002 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4007 return NULL;
4008 }
4009 z = PyTuple_New(2);
4010 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004011 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4012 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 }
4014 else {
4015 Py_DECREF(div);
4016 Py_DECREF(mod);
4017 }
4018 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004019}
4020
Mark Dickinsonc5299672019-06-02 10:24:06 +01004021
4022/* Compute an inverse to a modulo n, or raise ValueError if a is not
4023 invertible modulo n. Assumes n is positive. The inverse returned
4024 is whatever falls out of the extended Euclidean algorithm: it may
4025 be either positive or negative, but will be smaller than n in
4026 absolute value.
4027
4028 Pure Python equivalent for long_invmod:
4029
4030 def invmod(a, n):
4031 b, c = 1, 0
4032 while n:
4033 q, r = divmod(a, n)
4034 a, b, c, n = n, c, b - q*c, r
4035
4036 # at this point a is the gcd of the original inputs
4037 if a == 1:
4038 return b
4039 raise ValueError("Not invertible")
4040*/
4041
4042static PyLongObject *
4043long_invmod(PyLongObject *a, PyLongObject *n)
4044{
4045 PyLongObject *b, *c;
4046
4047 /* Should only ever be called for positive n */
4048 assert(Py_SIZE(n) > 0);
4049
4050 b = (PyLongObject *)PyLong_FromLong(1L);
4051 if (b == NULL) {
4052 return NULL;
4053 }
4054 c = (PyLongObject *)PyLong_FromLong(0L);
4055 if (c == NULL) {
4056 Py_DECREF(b);
4057 return NULL;
4058 }
4059 Py_INCREF(a);
4060 Py_INCREF(n);
4061
4062 /* references now owned: a, b, c, n */
4063 while (Py_SIZE(n) != 0) {
4064 PyLongObject *q, *r, *s, *t;
4065
4066 if (l_divmod(a, n, &q, &r) == -1) {
4067 goto Error;
4068 }
4069 Py_DECREF(a);
4070 a = n;
4071 n = r;
4072 t = (PyLongObject *)long_mul(q, c);
4073 Py_DECREF(q);
4074 if (t == NULL) {
4075 goto Error;
4076 }
4077 s = (PyLongObject *)long_sub(b, t);
4078 Py_DECREF(t);
4079 if (s == NULL) {
4080 goto Error;
4081 }
4082 Py_DECREF(b);
4083 b = c;
4084 c = s;
4085 }
4086 /* references now owned: a, b, c, n */
4087
4088 Py_DECREF(c);
4089 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004090 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004091 /* a != 1; we don't have an inverse. */
4092 Py_DECREF(a);
4093 Py_DECREF(b);
4094 PyErr_SetString(PyExc_ValueError,
4095 "base is not invertible for the given modulus");
4096 return NULL;
4097 }
4098 else {
4099 /* a == 1; b gives an inverse modulo n */
4100 Py_DECREF(a);
4101 return b;
4102 }
4103
4104 Error:
4105 Py_DECREF(a);
4106 Py_DECREF(b);
4107 Py_DECREF(c);
4108 Py_DECREF(n);
4109 return NULL;
4110}
4111
4112
Tim Peters47e52ee2004-08-30 02:44:38 +00004113/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004114static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004115long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4118 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 PyLongObject *z = NULL; /* accumulated result */
4121 Py_ssize_t i, j, k; /* counters */
4122 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 /* 5-ary values. If the exponent is large enough, table is
4125 * precomputed so that table[i] == a**i % c for i in range(32).
4126 */
4127 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4128 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 /* a, b, c = v, w, x */
4131 CHECK_BINOP(v, w);
4132 a = (PyLongObject*)v; Py_INCREF(a);
4133 b = (PyLongObject*)w; Py_INCREF(b);
4134 if (PyLong_Check(x)) {
4135 c = (PyLongObject *)x;
4136 Py_INCREF(x);
4137 }
4138 else if (x == Py_None)
4139 c = NULL;
4140 else {
4141 Py_DECREF(a);
4142 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004143 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 }
Tim Peters4c483c42001-09-05 06:24:58 +00004145
Mark Dickinsonc5299672019-06-02 10:24:06 +01004146 if (Py_SIZE(b) < 0 && c == NULL) {
4147 /* if exponent is negative and there's no modulus:
4148 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 that this calls float_pow() which converts its
4150 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004151 Py_DECREF(a);
4152 Py_DECREF(b);
4153 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 if (c) {
4157 /* if modulus == 0:
4158 raise ValueError() */
4159 if (Py_SIZE(c) == 0) {
4160 PyErr_SetString(PyExc_ValueError,
4161 "pow() 3rd argument cannot be 0");
4162 goto Error;
4163 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 /* if modulus < 0:
4166 negativeOutput = True
4167 modulus = -modulus */
4168 if (Py_SIZE(c) < 0) {
4169 negativeOutput = 1;
4170 temp = (PyLongObject *)_PyLong_Copy(c);
4171 if (temp == NULL)
4172 goto Error;
4173 Py_DECREF(c);
4174 c = temp;
4175 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004176 _PyLong_Negate(&c);
4177 if (c == NULL)
4178 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 /* if modulus == 1:
4182 return 0 */
4183 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4184 z = (PyLongObject *)PyLong_FromLong(0L);
4185 goto Done;
4186 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004187
Mark Dickinsonc5299672019-06-02 10:24:06 +01004188 /* if exponent is negative, negate the exponent and
4189 replace the base with a modular inverse */
4190 if (Py_SIZE(b) < 0) {
4191 temp = (PyLongObject *)_PyLong_Copy(b);
4192 if (temp == NULL)
4193 goto Error;
4194 Py_DECREF(b);
4195 b = temp;
4196 temp = NULL;
4197 _PyLong_Negate(&b);
4198 if (b == NULL)
4199 goto Error;
4200
4201 temp = long_invmod(a, c);
4202 if (temp == NULL)
4203 goto Error;
4204 Py_DECREF(a);
4205 a = temp;
4206 }
4207
Tim Peters81a93152013-10-05 16:53:52 -05004208 /* Reduce base by modulus in some cases:
4209 1. If base < 0. Forcing the base non-negative makes things easier.
4210 2. If base is obviously larger than the modulus. The "small
4211 exponent" case later can multiply directly by base repeatedly,
4212 while the "large exponent" case multiplies directly by base 31
4213 times. It can be unboundedly faster to multiply by
4214 base % modulus instead.
4215 We could _always_ do this reduction, but l_divmod() isn't cheap,
4216 so we only do it when it buys something. */
4217 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 if (l_divmod(a, c, NULL, &temp) < 0)
4219 goto Error;
4220 Py_DECREF(a);
4221 a = temp;
4222 temp = NULL;
4223 }
4224 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 /* At this point a, b, and c are guaranteed non-negative UNLESS
4227 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 z = (PyLongObject *)PyLong_FromLong(1L);
4230 if (z == NULL)
4231 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004233 /* Perform a modular reduction, X = X % c, but leave X alone if c
4234 * is NULL.
4235 */
4236#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004237 do { \
4238 if (c != NULL) { \
4239 if (l_divmod(X, c, NULL, &temp) < 0) \
4240 goto Error; \
4241 Py_XDECREF(X); \
4242 X = temp; \
4243 temp = NULL; \
4244 } \
4245 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 /* Multiply two values, then reduce the result:
4248 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004249#define MULT(X, Y, result) \
4250 do { \
4251 temp = (PyLongObject *)long_mul(X, Y); \
4252 if (temp == NULL) \
4253 goto Error; \
4254 Py_XDECREF(result); \
4255 result = temp; \
4256 temp = NULL; \
4257 REDUCE(result); \
4258 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4261 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4262 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4263 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4264 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004267 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004269 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 }
4271 }
4272 }
4273 else {
4274 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4275 Py_INCREF(z); /* still holds 1L */
4276 table[0] = z;
4277 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004278 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4281 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4284 const int index = (bi >> j) & 0x1f;
4285 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004286 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004288 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 }
4290 }
4291 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 if (negativeOutput && (Py_SIZE(z) != 0)) {
4294 temp = (PyLongObject *)long_sub(z, c);
4295 if (temp == NULL)
4296 goto Error;
4297 Py_DECREF(z);
4298 z = temp;
4299 temp = NULL;
4300 }
4301 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004302
Mark Dickinson22b20182010-05-10 21:27:53 +00004303 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004304 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004306 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4308 for (i = 0; i < 32; ++i)
4309 Py_XDECREF(table[i]);
4310 }
4311 Py_DECREF(a);
4312 Py_DECREF(b);
4313 Py_XDECREF(c);
4314 Py_XDECREF(temp);
4315 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004316}
4317
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004318static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004319long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 /* Implement ~x as -(x+1) */
4322 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004323 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004325 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 if (x == NULL)
4327 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004328 _PyLong_Negate(&x);
4329 /* No need for maybe_small_long here, since any small
4330 longs will have been caught in the Py_SIZE <= 1 fast path. */
4331 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004332}
4333
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004334static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004335long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004338 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 return PyLong_FromLong(-MEDIUM_VALUE(v));
4340 z = (PyLongObject *)_PyLong_Copy(v);
4341 if (z != NULL)
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004342 Py_SET_SIZE(z, -(Py_SIZE(v)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004344}
4345
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004346static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004347long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 if (Py_SIZE(v) < 0)
4350 return long_neg(v);
4351 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004352 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004353}
4354
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004355static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004356long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004359}
4360
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004361/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4362static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004363divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004364{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004365 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004366 assert(Py_SIZE(shiftby) >= 0);
4367 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4368 if (lshiftby >= 0) {
4369 *wordshift = lshiftby / PyLong_SHIFT;
4370 *remshift = lshiftby % PyLong_SHIFT;
4371 return 0;
4372 }
4373 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4374 be that PyLong_AsSsize_t raised an OverflowError. */
4375 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4376 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004377 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004378 if (wordshift_obj == NULL) {
4379 return -1;
4380 }
4381 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4382 Py_DECREF(wordshift_obj);
4383 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4384 return 0;
4385 }
4386 PyErr_Clear();
4387 /* Clip the value. With such large wordshift the right shift
4388 returns 0 and the left shift raises an error in _PyLong_New(). */
4389 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4390 *remshift = 0;
4391 return 0;
4392}
4393
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004394static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004395long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004398 Py_ssize_t newsize, hishift, i, j;
4399 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 if (Py_SIZE(a) < 0) {
4402 /* Right shifting negative numbers is harder */
4403 PyLongObject *a1, *a2;
4404 a1 = (PyLongObject *) long_invert(a);
4405 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004406 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004407 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 Py_DECREF(a1);
4409 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004410 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 z = (PyLongObject *) long_invert(a2);
4412 Py_DECREF(a2);
4413 }
4414 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004415 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 if (newsize <= 0)
4417 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004418 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 lomask = ((digit)1 << hishift) - 1;
4420 himask = PyLong_MASK ^ lomask;
4421 z = _PyLong_New(newsize);
4422 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004423 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004425 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004427 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004429 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004431 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004432}
4433
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004434static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004435long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004436{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004437 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004438 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004441
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004442 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004444 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004446 if (Py_SIZE(a) == 0) {
4447 return PyLong_FromLong(0);
4448 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004449 if (divmod_shift(b, &wordshift, &remshift) < 0)
4450 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004451 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4452}
4453
4454/* Return a >> shiftby. */
4455PyObject *
4456_PyLong_Rshift(PyObject *a, size_t shiftby)
4457{
4458 Py_ssize_t wordshift;
4459 digit remshift;
4460
4461 assert(PyLong_Check(a));
4462 if (Py_SIZE(a) == 0) {
4463 return PyLong_FromLong(0);
4464 }
4465 wordshift = shiftby / PyLong_SHIFT;
4466 remshift = shiftby % PyLong_SHIFT;
4467 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4468}
4469
4470static PyObject *
4471long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4472{
4473 /* This version due to Tim Peters */
4474 PyLongObject *z = NULL;
4475 Py_ssize_t oldsize, newsize, i, j;
4476 twodigits accum;
4477
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004478 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 newsize = oldsize + wordshift;
4480 if (remshift)
4481 ++newsize;
4482 z = _PyLong_New(newsize);
4483 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004484 return NULL;
4485 if (Py_SIZE(a) < 0) {
4486 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004487 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02004488 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 for (i = 0; i < wordshift; i++)
4490 z->ob_digit[i] = 0;
4491 accum = 0;
4492 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4493 accum |= (twodigits)a->ob_digit[j] << remshift;
4494 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4495 accum >>= PyLong_SHIFT;
4496 }
4497 if (remshift)
4498 z->ob_digit[newsize-1] = (digit)accum;
4499 else
4500 assert(!accum);
4501 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004503}
4504
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004505static PyObject *
4506long_lshift(PyObject *a, PyObject *b)
4507{
4508 Py_ssize_t wordshift;
4509 digit remshift;
4510
4511 CHECK_BINOP(a, b);
4512
4513 if (Py_SIZE(b) < 0) {
4514 PyErr_SetString(PyExc_ValueError, "negative shift count");
4515 return NULL;
4516 }
4517 if (Py_SIZE(a) == 0) {
4518 return PyLong_FromLong(0);
4519 }
4520 if (divmod_shift(b, &wordshift, &remshift) < 0)
4521 return NULL;
4522 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4523}
4524
4525/* Return a << shiftby. */
4526PyObject *
4527_PyLong_Lshift(PyObject *a, size_t shiftby)
4528{
4529 Py_ssize_t wordshift;
4530 digit remshift;
4531
4532 assert(PyLong_Check(a));
4533 if (Py_SIZE(a) == 0) {
4534 return PyLong_FromLong(0);
4535 }
4536 wordshift = shiftby / PyLong_SHIFT;
4537 remshift = shiftby % PyLong_SHIFT;
4538 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4539}
4540
Mark Dickinson27a87a22009-10-25 20:43:34 +00004541/* Compute two's complement of digit vector a[0:m], writing result to
4542 z[0:m]. The digit vector a need not be normalized, but should not
4543 be entirely zero. a and z may point to the same digit vector. */
4544
4545static void
4546v_complement(digit *z, digit *a, Py_ssize_t m)
4547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 Py_ssize_t i;
4549 digit carry = 1;
4550 for (i = 0; i < m; ++i) {
4551 carry += a[i] ^ PyLong_MASK;
4552 z[i] = carry & PyLong_MASK;
4553 carry >>= PyLong_SHIFT;
4554 }
4555 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004556}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004557
4558/* Bitwise and/xor/or operations */
4559
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004560static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004561long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004562 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004563 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004565 int nega, negb, negz;
4566 Py_ssize_t size_a, size_b, size_z, i;
4567 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004569 /* Bitwise operations for negative numbers operate as though
4570 on a two's complement representation. So convert arguments
4571 from sign-magnitude to two's complement, and convert the
4572 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004575 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 nega = Py_SIZE(a) < 0;
4577 if (nega) {
4578 z = _PyLong_New(size_a);
4579 if (z == NULL)
4580 return NULL;
4581 v_complement(z->ob_digit, a->ob_digit, size_a);
4582 a = z;
4583 }
4584 else
4585 /* Keep reference count consistent. */
4586 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004589 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 negb = Py_SIZE(b) < 0;
4591 if (negb) {
4592 z = _PyLong_New(size_b);
4593 if (z == NULL) {
4594 Py_DECREF(a);
4595 return NULL;
4596 }
4597 v_complement(z->ob_digit, b->ob_digit, size_b);
4598 b = z;
4599 }
4600 else
4601 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004603 /* Swap a and b if necessary to ensure size_a >= size_b. */
4604 if (size_a < size_b) {
4605 z = a; a = b; b = z;
4606 size_z = size_a; size_a = size_b; size_b = size_z;
4607 negz = nega; nega = negb; negb = negz;
4608 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004610 /* JRH: The original logic here was to allocate the result value (z)
4611 as the longer of the two operands. However, there are some cases
4612 where the result is guaranteed to be shorter than that: AND of two
4613 positives, OR of two negatives: use the shorter number. AND with
4614 mixed signs: use the positive number. OR with mixed signs: use the
4615 negative number.
4616 */
4617 switch (op) {
4618 case '^':
4619 negz = nega ^ negb;
4620 size_z = size_a;
4621 break;
4622 case '&':
4623 negz = nega & negb;
4624 size_z = negb ? size_a : size_b;
4625 break;
4626 case '|':
4627 negz = nega | negb;
4628 size_z = negb ? size_b : size_a;
4629 break;
4630 default:
stratakisa10d4262019-03-18 18:59:20 +01004631 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 /* We allow an extra digit if z is negative, to make sure that
4635 the final two's complement of z doesn't overflow. */
4636 z = _PyLong_New(size_z + negz);
4637 if (z == NULL) {
4638 Py_DECREF(a);
4639 Py_DECREF(b);
4640 return NULL;
4641 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 /* Compute digits for overlap of a and b. */
4644 switch(op) {
4645 case '&':
4646 for (i = 0; i < size_b; ++i)
4647 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4648 break;
4649 case '|':
4650 for (i = 0; i < size_b; ++i)
4651 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4652 break;
4653 case '^':
4654 for (i = 0; i < size_b; ++i)
4655 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4656 break;
4657 default:
stratakisa10d4262019-03-18 18:59:20 +01004658 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 /* Copy any remaining digits of a, inverting if necessary. */
4662 if (op == '^' && negb)
4663 for (; i < size_z; ++i)
4664 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4665 else if (i < size_z)
4666 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4667 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 /* Complement result if negative. */
4670 if (negz) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004671 Py_SET_SIZE(z, -(Py_SIZE(z)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 z->ob_digit[size_z] = PyLong_MASK;
4673 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4674 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 Py_DECREF(a);
4677 Py_DECREF(b);
4678 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004679}
4680
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004681static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004682long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 PyObject *c;
4685 CHECK_BINOP(a, b);
4686 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4687 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004688}
4689
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004690static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004691long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004693 PyObject *c;
4694 CHECK_BINOP(a, b);
4695 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4696 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004697}
4698
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004699static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004700long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004702 PyObject *c;
4703 CHECK_BINOP(a, b);
4704 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4705 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004706}
4707
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004708static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004709long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 if (PyLong_CheckExact(v))
4712 Py_INCREF(v);
4713 else
4714 v = _PyLong_Copy((PyLongObject *)v);
4715 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004716}
4717
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004718PyObject *
4719_PyLong_GCD(PyObject *aarg, PyObject *barg)
4720{
4721 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4722 stwodigits x, y, q, s, t, c_carry, d_carry;
4723 stwodigits A, B, C, D, T;
4724 int nbits, k;
4725 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4726 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4727
4728 a = (PyLongObject *)aarg;
4729 b = (PyLongObject *)barg;
4730 size_a = Py_SIZE(a);
4731 size_b = Py_SIZE(b);
4732 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4733 Py_INCREF(a);
4734 Py_INCREF(b);
4735 goto simple;
4736 }
4737
4738 /* Initial reduction: make sure that 0 <= b <= a. */
4739 a = (PyLongObject *)long_abs(a);
4740 if (a == NULL)
4741 return NULL;
4742 b = (PyLongObject *)long_abs(b);
4743 if (b == NULL) {
4744 Py_DECREF(a);
4745 return NULL;
4746 }
4747 if (long_compare(a, b) < 0) {
4748 r = a;
4749 a = b;
4750 b = r;
4751 }
4752 /* We now own references to a and b */
4753
4754 alloc_a = Py_SIZE(a);
4755 alloc_b = Py_SIZE(b);
4756 /* reduce until a fits into 2 digits */
4757 while ((size_a = Py_SIZE(a)) > 2) {
Niklas Fiekas794e7d12020-06-15 14:33:48 +02004758 nbits = bit_length_digit(a->ob_digit[size_a-1]);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004759 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4760 corresponding bits of b into y */
4761 size_b = Py_SIZE(b);
4762 assert(size_b <= size_a);
4763 if (size_b == 0) {
4764 if (size_a < alloc_a) {
4765 r = (PyLongObject *)_PyLong_Copy(a);
4766 Py_DECREF(a);
4767 }
4768 else
4769 r = a;
4770 Py_DECREF(b);
4771 Py_XDECREF(c);
4772 Py_XDECREF(d);
4773 return (PyObject *)r;
4774 }
4775 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4776 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4777 (a->ob_digit[size_a-3] >> nbits));
4778
4779 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4780 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4781 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4782
4783 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4784 larger than PyLong_MASK during the algorithm. */
4785 A = 1; B = 0; C = 0; D = 1;
4786 for (k=0;; k++) {
4787 if (y-C == 0)
4788 break;
4789 q = (x+(A-1))/(y-C);
4790 s = B+q*D;
4791 t = x-q*y;
4792 if (s > t)
4793 break;
4794 x = y; y = t;
4795 t = A+q*C; A = D; B = C; C = s; D = t;
4796 }
4797
4798 if (k == 0) {
4799 /* no progress; do a Euclidean step */
4800 if (l_divmod(a, b, NULL, &r) < 0)
4801 goto error;
4802 Py_DECREF(a);
4803 a = b;
4804 b = r;
4805 alloc_a = alloc_b;
4806 alloc_b = Py_SIZE(b);
4807 continue;
4808 }
4809
4810 /*
4811 a, b = A*b-B*a, D*a-C*b if k is odd
4812 a, b = A*a-B*b, D*b-C*a if k is even
4813 */
4814 if (k&1) {
4815 T = -A; A = -B; B = T;
4816 T = -C; C = -D; D = T;
4817 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004818 if (c != NULL) {
4819 Py_SET_SIZE(c, size_a);
4820 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004821 else if (Py_REFCNT(a) == 1) {
4822 Py_INCREF(a);
4823 c = a;
4824 }
4825 else {
4826 alloc_a = size_a;
4827 c = _PyLong_New(size_a);
4828 if (c == NULL)
4829 goto error;
4830 }
4831
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004832 if (d != NULL) {
4833 Py_SET_SIZE(d, size_a);
4834 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004835 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4836 Py_INCREF(b);
4837 d = b;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004838 Py_SET_SIZE(d, size_a);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004839 }
4840 else {
4841 alloc_b = size_a;
4842 d = _PyLong_New(size_a);
4843 if (d == NULL)
4844 goto error;
4845 }
4846 a_end = a->ob_digit + size_a;
4847 b_end = b->ob_digit + size_b;
4848
4849 /* compute new a and new b in parallel */
4850 a_digit = a->ob_digit;
4851 b_digit = b->ob_digit;
4852 c_digit = c->ob_digit;
4853 d_digit = d->ob_digit;
4854 c_carry = 0;
4855 d_carry = 0;
4856 while (b_digit < b_end) {
4857 c_carry += (A * *a_digit) - (B * *b_digit);
4858 d_carry += (D * *b_digit++) - (C * *a_digit++);
4859 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4860 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4861 c_carry >>= PyLong_SHIFT;
4862 d_carry >>= PyLong_SHIFT;
4863 }
4864 while (a_digit < a_end) {
4865 c_carry += A * *a_digit;
4866 d_carry -= C * *a_digit++;
4867 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4868 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4869 c_carry >>= PyLong_SHIFT;
4870 d_carry >>= PyLong_SHIFT;
4871 }
4872 assert(c_carry == 0);
4873 assert(d_carry == 0);
4874
4875 Py_INCREF(c);
4876 Py_INCREF(d);
4877 Py_DECREF(a);
4878 Py_DECREF(b);
4879 a = long_normalize(c);
4880 b = long_normalize(d);
4881 }
4882 Py_XDECREF(c);
4883 Py_XDECREF(d);
4884
4885simple:
4886 assert(Py_REFCNT(a) > 0);
4887 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004888/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4889 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4890#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004891 /* a fits into a long, so b must too */
4892 x = PyLong_AsLong((PyObject *)a);
4893 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004894#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004895 x = PyLong_AsLongLong((PyObject *)a);
4896 y = PyLong_AsLongLong((PyObject *)b);
4897#else
4898# error "_PyLong_GCD"
4899#endif
4900 x = Py_ABS(x);
4901 y = Py_ABS(y);
4902 Py_DECREF(a);
4903 Py_DECREF(b);
4904
4905 /* usual Euclidean algorithm for longs */
4906 while (y != 0) {
4907 t = y;
4908 y = x % y;
4909 x = t;
4910 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004911#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004912 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004913#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004914 return PyLong_FromLongLong(x);
4915#else
4916# error "_PyLong_GCD"
4917#endif
4918
4919error:
4920 Py_DECREF(a);
4921 Py_DECREF(b);
4922 Py_XDECREF(c);
4923 Py_XDECREF(d);
4924 return NULL;
4925}
4926
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004927static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004928long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004930 double result;
4931 result = PyLong_AsDouble(v);
4932 if (result == -1.0 && PyErr_Occurred())
4933 return NULL;
4934 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004935}
4936
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004937static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004938long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
4939
4940/*[clinic input]
4941@classmethod
4942int.__new__ as long_new
4943 x: object(c_default="NULL") = 0
4944 /
4945 base as obase: object(c_default="NULL") = 10
4946[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004947
Tim Peters6d6c1a32001-08-02 04:15:00 +00004948static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004949long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
4950/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00004951{
Gregory P. Smitha689e522012-12-25 22:38:32 -08004952 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004955 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004956 if (x == NULL) {
4957 if (obase != NULL) {
4958 PyErr_SetString(PyExc_TypeError,
4959 "int() missing string argument");
4960 return NULL;
4961 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004963 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004964 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004966
Gregory P. Smitha689e522012-12-25 22:38:32 -08004967 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004968 if (base == -1 && PyErr_Occurred())
4969 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004970 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004971 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05304972 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004973 return NULL;
4974 }
4975
4976 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004977 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004978 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004979 const char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004980 if (PyByteArray_Check(x))
4981 string = PyByteArray_AS_STRING(x);
4982 else
4983 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004984 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 }
4986 else {
4987 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004988 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 return NULL;
4990 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004991}
4992
Serhiy Storchaka95949422013-08-27 19:40:23 +03004993/* Wimpy, slow approach to tp_new calls for subtypes of int:
4994 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004995 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004996 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004997*/
4998static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004999long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 PyLongObject *tmp, *newobj;
5002 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005004 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005005 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005006 if (tmp == NULL)
5007 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005008 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 n = Py_SIZE(tmp);
5010 if (n < 0)
5011 n = -n;
5012 newobj = (PyLongObject *)type->tp_alloc(type, n);
5013 if (newobj == NULL) {
5014 Py_DECREF(tmp);
5015 return NULL;
5016 }
5017 assert(PyLong_Check(newobj));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005018 Py_SET_SIZE(newobj, Py_SIZE(tmp));
5019 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 newobj->ob_digit[i] = tmp->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005021 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 Py_DECREF(tmp);
5023 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005024}
5025
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005026/*[clinic input]
5027int.__getnewargs__
5028[clinic start generated code]*/
5029
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005030static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005031int___getnewargs___impl(PyObject *self)
5032/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005033{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005034 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005035}
5036
Guido van Rossumb43daf72007-08-01 18:08:08 +00005037static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005038long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005040 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005041}
5042
5043static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005044long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005047}
5048
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005049/*[clinic input]
5050int.__format__
5051
5052 format_spec: unicode
5053 /
5054[clinic start generated code]*/
5055
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005056static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005057int___format___impl(PyObject *self, PyObject *format_spec)
5058/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005059{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005060 _PyUnicodeWriter writer;
5061 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005062
Victor Stinner8f674cc2013-04-17 23:02:17 +02005063 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005064 ret = _PyLong_FormatAdvancedWriter(
5065 &writer,
5066 self,
5067 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5068 if (ret == -1) {
5069 _PyUnicodeWriter_Dealloc(&writer);
5070 return NULL;
5071 }
5072 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005073}
5074
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005075/* Return a pair (q, r) such that a = b * q + r, and
5076 abs(r) <= abs(b)/2, with equality possible only if q is even.
5077 In other words, q == a / b, rounded to the nearest integer using
5078 round-half-to-even. */
5079
5080PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005081_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005082{
5083 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005084 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005085 int quo_is_odd, quo_is_neg;
5086 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005087
5088 /* Equivalent Python code:
5089
5090 def divmod_near(a, b):
5091 q, r = divmod(a, b)
5092 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5093 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5094 # positive, 2 * r < b if b negative.
5095 greater_than_half = 2*r > b if b > 0 else 2*r < b
5096 exactly_half = 2*r == b
5097 if greater_than_half or exactly_half and q % 2 == 1:
5098 q += 1
5099 r -= b
5100 return q, r
5101
5102 */
5103 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5104 PyErr_SetString(PyExc_TypeError,
5105 "non-integer arguments in division");
5106 return NULL;
5107 }
5108
5109 /* Do a and b have different signs? If so, quotient is negative. */
5110 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5111
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005112 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5113 goto error;
5114
5115 /* compare twice the remainder with the divisor, to see
5116 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005117 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005118 if (twice_rem == NULL)
5119 goto error;
5120 if (quo_is_neg) {
5121 temp = long_neg((PyLongObject*)twice_rem);
5122 Py_DECREF(twice_rem);
5123 twice_rem = temp;
5124 if (twice_rem == NULL)
5125 goto error;
5126 }
5127 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5128 Py_DECREF(twice_rem);
5129
5130 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5131 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5132 /* fix up quotient */
5133 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005134 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005135 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005136 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005137 Py_DECREF(quo);
5138 quo = (PyLongObject *)temp;
5139 if (quo == NULL)
5140 goto error;
5141 /* and remainder */
5142 if (quo_is_neg)
5143 temp = long_add(rem, (PyLongObject *)b);
5144 else
5145 temp = long_sub(rem, (PyLongObject *)b);
5146 Py_DECREF(rem);
5147 rem = (PyLongObject *)temp;
5148 if (rem == NULL)
5149 goto error;
5150 }
5151
5152 result = PyTuple_New(2);
5153 if (result == NULL)
5154 goto error;
5155
5156 /* PyTuple_SET_ITEM steals references */
5157 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5158 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005159 return result;
5160
5161 error:
5162 Py_XDECREF(quo);
5163 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005164 return NULL;
5165}
5166
Eric Smith8c663262007-08-25 02:26:07 +00005167static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005168long_round(PyObject *self, PyObject *args)
5169{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005170 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005171
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005172 /* To round an integer m to the nearest 10**n (n positive), we make use of
5173 * the divmod_near operation, defined by:
5174 *
5175 * divmod_near(a, b) = (q, r)
5176 *
5177 * where q is the nearest integer to the quotient a / b (the
5178 * nearest even integer in the case of a tie) and r == a - q * b.
5179 * Hence q * b = a - r is the nearest multiple of b to a,
5180 * preferring even multiples in the case of a tie.
5181 *
5182 * So the nearest multiple of 10**n to m is:
5183 *
5184 * m - divmod_near(m, 10**n)[1].
5185 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005186 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5187 return NULL;
5188 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005189 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005190
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03005191 ndigits = _PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 if (ndigits == NULL)
5193 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005194
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005195 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 if (Py_SIZE(ndigits) >= 0) {
5197 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005198 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005199 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005200
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005201 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5202 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005203 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005204 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005206 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005207
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005208 result = PyLong_FromLong(10L);
5209 if (result == NULL) {
5210 Py_DECREF(ndigits);
5211 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005212 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005213
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005214 temp = long_pow(result, ndigits, Py_None);
5215 Py_DECREF(ndigits);
5216 Py_DECREF(result);
5217 result = temp;
5218 if (result == NULL)
5219 return NULL;
5220
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005221 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005222 Py_DECREF(result);
5223 result = temp;
5224 if (result == NULL)
5225 return NULL;
5226
5227 temp = long_sub((PyLongObject *)self,
5228 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5229 Py_DECREF(result);
5230 result = temp;
5231
5232 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005233}
5234
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005235/*[clinic input]
5236int.__sizeof__ -> Py_ssize_t
5237
5238Returns size in memory, in bytes.
5239[clinic start generated code]*/
5240
5241static Py_ssize_t
5242int___sizeof___impl(PyObject *self)
5243/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005245 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005246
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005247 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5248 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005249}
5250
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005251/*[clinic input]
5252int.bit_length
5253
5254Number of bits necessary to represent self in binary.
5255
5256>>> bin(37)
5257'0b100101'
5258>>> (37).bit_length()
52596
5260[clinic start generated code]*/
5261
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005262static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005263int_bit_length_impl(PyObject *self)
5264/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005266 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005267 Py_ssize_t ndigits;
5268 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005269 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005270
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005271 assert(self != NULL);
5272 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005273
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005274 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 if (ndigits == 0)
5276 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005277
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005278 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Niklas Fiekas794e7d12020-06-15 14:33:48 +02005279 msd_bits = bit_length_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5282 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005284 /* expression above may overflow; use Python integers instead */
5285 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5286 if (result == NULL)
5287 return NULL;
5288 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5289 if (x == NULL)
5290 goto error;
5291 y = (PyLongObject *)long_mul(result, x);
5292 Py_DECREF(x);
5293 if (y == NULL)
5294 goto error;
5295 Py_DECREF(result);
5296 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5299 if (x == NULL)
5300 goto error;
5301 y = (PyLongObject *)long_add(result, x);
5302 Py_DECREF(x);
5303 if (y == NULL)
5304 goto error;
5305 Py_DECREF(result);
5306 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005309
Mark Dickinson22b20182010-05-10 21:27:53 +00005310 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005311 Py_DECREF(result);
5312 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005313}
5314
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005315static int
5316popcount_digit(digit d)
5317{
Victor Stinnerc6b292c2020-06-08 16:30:33 +02005318 // digit can be larger than uint32_t, but only PyLong_SHIFT bits
5319 // of it will be ever used.
5320 Py_BUILD_ASSERT(PyLong_SHIFT <= 32);
5321 return _Py_popcount32((uint32_t)d);
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005322}
5323
5324/*[clinic input]
5325int.bit_count
5326
5327Number of ones in the binary representation of the absolute value of self.
5328
5329Also known as the population count.
5330
5331>>> bin(13)
5332'0b1101'
5333>>> (13).bit_count()
53343
5335[clinic start generated code]*/
5336
5337static PyObject *
5338int_bit_count_impl(PyObject *self)
5339/*[clinic end generated code: output=2e571970daf1e5c3 input=7e0adef8e8ccdf2e]*/
5340{
5341 assert(self != NULL);
5342 assert(PyLong_Check(self));
5343
5344 PyLongObject *z = (PyLongObject *)self;
5345 Py_ssize_t ndigits = Py_ABS(Py_SIZE(z));
5346 Py_ssize_t bit_count = 0;
5347
5348 /* Each digit has up to PyLong_SHIFT ones, so the accumulated bit count
5349 from the first PY_SSIZE_T_MAX/PyLong_SHIFT digits can't overflow a
5350 Py_ssize_t. */
5351 Py_ssize_t ndigits_fast = Py_MIN(ndigits, PY_SSIZE_T_MAX/PyLong_SHIFT);
5352 for (Py_ssize_t i = 0; i < ndigits_fast; i++) {
5353 bit_count += popcount_digit(z->ob_digit[i]);
5354 }
5355
5356 PyObject *result = PyLong_FromSsize_t(bit_count);
5357 if (result == NULL) {
5358 return NULL;
5359 }
5360
5361 /* Use Python integers if bit_count would overflow. */
5362 for (Py_ssize_t i = ndigits_fast; i < ndigits; i++) {
5363 PyObject *x = PyLong_FromLong(popcount_digit(z->ob_digit[i]));
5364 if (x == NULL) {
5365 goto error;
5366 }
5367 PyObject *y = long_add((PyLongObject *)result, (PyLongObject *)x);
5368 Py_DECREF(x);
5369 if (y == NULL) {
5370 goto error;
5371 }
5372 Py_DECREF(result);
5373 result = y;
5374 }
5375
5376 return result;
5377
5378 error:
5379 Py_DECREF(result);
5380 return NULL;
5381}
Christian Heimes53876d92008-04-19 00:31:39 +00005382
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005383/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005384int.as_integer_ratio
5385
5386Return integer ratio.
5387
5388Return a pair of integers, whose ratio is exactly equal to the original int
5389and with a positive denominator.
5390
5391>>> (10).as_integer_ratio()
5392(10, 1)
5393>>> (-10).as_integer_ratio()
5394(-10, 1)
5395>>> (0).as_integer_ratio()
5396(0, 1)
5397[clinic start generated code]*/
5398
5399static PyObject *
5400int_as_integer_ratio_impl(PyObject *self)
5401/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5402{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005403 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005404 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005405 if (numerator == NULL) {
5406 return NULL;
5407 }
5408 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5409 Py_DECREF(numerator);
5410 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005411}
5412
5413/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005414int.to_bytes
5415
5416 length: Py_ssize_t
5417 Length of bytes object to use. An OverflowError is raised if the
5418 integer is not representable with the given number of bytes.
5419 byteorder: unicode
5420 The byte order used to represent the integer. If byteorder is 'big',
5421 the most significant byte is at the beginning of the byte array. If
5422 byteorder is 'little', the most significant byte is at the end of the
5423 byte array. To request the native byte order of the host system, use
5424 `sys.byteorder' as the byte order value.
5425 *
5426 signed as is_signed: bool = False
5427 Determines whether two's complement is used to represent the integer.
5428 If signed is False and a negative integer is given, an OverflowError
5429 is raised.
5430
5431Return an array of bytes representing an integer.
5432[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005433
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005434static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005435int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5436 int is_signed)
5437/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005441
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005442 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005444 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 little_endian = 0;
5446 else {
5447 PyErr_SetString(PyExc_ValueError,
5448 "byteorder must be either 'little' or 'big'");
5449 return NULL;
5450 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005452 if (length < 0) {
5453 PyErr_SetString(PyExc_ValueError,
5454 "length argument must be non-negative");
5455 return NULL;
5456 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 bytes = PyBytes_FromStringAndSize(NULL, length);
5459 if (bytes == NULL)
5460 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005461
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005462 if (_PyLong_AsByteArray((PyLongObject *)self,
5463 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005464 length, little_endian, is_signed) < 0) {
5465 Py_DECREF(bytes);
5466 return NULL;
5467 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005470}
5471
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005472/*[clinic input]
5473@classmethod
5474int.from_bytes
5475
5476 bytes as bytes_obj: object
5477 Holds the array of bytes to convert. The argument must either
5478 support the buffer protocol or be an iterable object producing bytes.
5479 Bytes and bytearray are examples of built-in objects that support the
5480 buffer protocol.
5481 byteorder: unicode
5482 The byte order used to represent the integer. If byteorder is 'big',
5483 the most significant byte is at the beginning of the byte array. If
5484 byteorder is 'little', the most significant byte is at the end of the
5485 byte array. To request the native byte order of the host system, use
5486 `sys.byteorder' as the byte order value.
5487 *
5488 signed as is_signed: bool = False
5489 Indicates whether two's complement is used to represent the integer.
5490
5491Return the integer represented by the given array of bytes.
5492[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005493
5494static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005495int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5496 PyObject *byteorder, int is_signed)
5497/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005500 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005501
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005502 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005503 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005504 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 little_endian = 0;
5506 else {
5507 PyErr_SetString(PyExc_ValueError,
5508 "byteorder must be either 'little' or 'big'");
5509 return NULL;
5510 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005511
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005512 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 if (bytes == NULL)
5514 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 long_obj = _PyLong_FromByteArray(
5517 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5518 little_endian, is_signed);
5519 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005520
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005521 if (long_obj != NULL && type != &PyLong_Type) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005522 Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005526}
5527
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005528static PyObject *
5529long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5530{
5531 return long_long(self);
5532}
5533
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005534static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005535 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005537 INT_BIT_LENGTH_METHODDEF
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005538 INT_BIT_COUNT_METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005539 INT_TO_BYTES_METHODDEF
5540 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005541 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005542 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005544 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005546 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 "Ceiling of an Integral returns itself."},
5548 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5549 "Rounding an Integral returns itself.\n"
5550 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005551 INT___GETNEWARGS___METHODDEF
5552 INT___FORMAT___METHODDEF
5553 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005555};
5556
Guido van Rossumb43daf72007-08-01 18:08:08 +00005557static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005558 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005559 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005560 "the real part of a complex number",
5561 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005562 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005563 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005564 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005565 NULL},
5566 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005567 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005568 "the numerator of a rational number in lowest terms",
5569 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005570 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005571 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005572 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005573 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005574 {NULL} /* Sentinel */
5575};
5576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005577PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005578"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005579int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005580\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005581Convert a number or string to an integer, or return 0 if no arguments\n\
5582are given. If x is a number, return x.__int__(). For floating point\n\
5583numbers, this truncates towards zero.\n\
5584\n\
5585If x is not a number or if base is given, then x must be a string,\n\
5586bytes, or bytearray instance representing an integer literal in the\n\
5587given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5588by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5589Base 0 means to interpret the base from the string as an integer literal.\n\
5590>>> int('0b100', base=0)\n\
55914");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005592
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005593static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005594 (binaryfunc)long_add, /*nb_add*/
5595 (binaryfunc)long_sub, /*nb_subtract*/
5596 (binaryfunc)long_mul, /*nb_multiply*/
5597 long_mod, /*nb_remainder*/
5598 long_divmod, /*nb_divmod*/
5599 long_pow, /*nb_power*/
5600 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005601 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005602 (unaryfunc)long_abs, /*tp_absolute*/
5603 (inquiry)long_bool, /*tp_bool*/
5604 (unaryfunc)long_invert, /*nb_invert*/
5605 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005606 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005607 long_and, /*nb_and*/
5608 long_xor, /*nb_xor*/
5609 long_or, /*nb_or*/
5610 long_long, /*nb_int*/
5611 0, /*nb_reserved*/
5612 long_float, /*nb_float*/
5613 0, /* nb_inplace_add */
5614 0, /* nb_inplace_subtract */
5615 0, /* nb_inplace_multiply */
5616 0, /* nb_inplace_remainder */
5617 0, /* nb_inplace_power */
5618 0, /* nb_inplace_lshift */
5619 0, /* nb_inplace_rshift */
5620 0, /* nb_inplace_and */
5621 0, /* nb_inplace_xor */
5622 0, /* nb_inplace_or */
5623 long_div, /* nb_floor_divide */
5624 long_true_divide, /* nb_true_divide */
5625 0, /* nb_inplace_floor_divide */
5626 0, /* nb_inplace_true_divide */
5627 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005628};
5629
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005630PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5632 "int", /* tp_name */
5633 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5634 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005635 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005636 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637 0, /* tp_getattr */
5638 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005639 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005640 long_to_decimal_string, /* tp_repr */
5641 &long_as_number, /* tp_as_number */
5642 0, /* tp_as_sequence */
5643 0, /* tp_as_mapping */
5644 (hashfunc)long_hash, /* tp_hash */
5645 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005646 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005647 PyObject_GenericGetAttr, /* tp_getattro */
5648 0, /* tp_setattro */
5649 0, /* tp_as_buffer */
5650 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5651 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5652 long_doc, /* tp_doc */
5653 0, /* tp_traverse */
5654 0, /* tp_clear */
5655 long_richcompare, /* tp_richcompare */
5656 0, /* tp_weaklistoffset */
5657 0, /* tp_iter */
5658 0, /* tp_iternext */
5659 long_methods, /* tp_methods */
5660 0, /* tp_members */
5661 long_getset, /* tp_getset */
5662 0, /* tp_base */
5663 0, /* tp_dict */
5664 0, /* tp_descr_get */
5665 0, /* tp_descr_set */
5666 0, /* tp_dictoffset */
5667 0, /* tp_init */
5668 0, /* tp_alloc */
5669 long_new, /* tp_new */
5670 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005671};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005672
Mark Dickinsonbd792642009-03-18 20:06:12 +00005673static PyTypeObject Int_InfoType;
5674
5675PyDoc_STRVAR(int_info__doc__,
5676"sys.int_info\n\
5677\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005678A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005679internal representation of integers. The attributes are read only.");
5680
5681static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005683 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005685};
5686
5687static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005688 "sys.int_info", /* name */
5689 int_info__doc__, /* doc */
5690 int_info_fields, /* fields */
5691 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005692};
5693
5694PyObject *
5695PyLong_GetInfo(void)
5696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 PyObject* int_info;
5698 int field = 0;
5699 int_info = PyStructSequence_New(&Int_InfoType);
5700 if (int_info == NULL)
5701 return NULL;
5702 PyStructSequence_SET_ITEM(int_info, field++,
5703 PyLong_FromLong(PyLong_SHIFT));
5704 PyStructSequence_SET_ITEM(int_info, field++,
5705 PyLong_FromLong(sizeof(digit)));
5706 if (PyErr_Occurred()) {
5707 Py_CLEAR(int_info);
5708 return NULL;
5709 }
5710 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005711}
5712
Guido van Rossumddefaf32007-01-14 03:31:43 +00005713int
Victor Stinner630c8df2019-12-17 13:02:18 +01005714_PyLong_Init(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005715{
5716#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005717 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5718 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5719 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005720
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005721 PyLongObject *v = _PyLong_New(1);
5722 if (!v) {
5723 return -1;
5724 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005725
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005726 Py_SET_SIZE(v, size);
Victor Stinner12174a52014-08-15 23:17:38 +02005727 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005728
Victor Stinner630c8df2019-12-17 13:02:18 +01005729 tstate->interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005730 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005731#endif
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005732
Victor Stinner630c8df2019-12-17 13:02:18 +01005733 if (_Py_IsMainInterpreter(tstate)) {
5734 _PyLong_Zero = PyLong_FromLong(0);
5735 if (_PyLong_Zero == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005736 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005737 }
Victor Stinner630c8df2019-12-17 13:02:18 +01005738
5739 _PyLong_One = PyLong_FromLong(1);
5740 if (_PyLong_One == NULL) {
5741 return 0;
5742 }
5743
5744 /* initialize int_info */
5745 if (Int_InfoType.tp_name == NULL) {
5746 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5747 return 0;
5748 }
5749 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005750 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005753}
5754
5755void
Victor Stinner630c8df2019-12-17 13:02:18 +01005756_PyLong_Fini(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005757{
Victor Stinner630c8df2019-12-17 13:02:18 +01005758 if (_Py_IsMainInterpreter(tstate)) {
5759 Py_CLEAR(_PyLong_One);
5760 Py_CLEAR(_PyLong_Zero);
5761 }
5762
Guido van Rossumddefaf32007-01-14 03:31:43 +00005763#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005764 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinner630c8df2019-12-17 13:02:18 +01005765 Py_CLEAR(tstate->interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005766 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005767#endif
5768}