blob: e1c1191e648daedbb6c44f88118c43a638834d7a [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Victor Stinnerc6b292c2020-06-08 16:30:33 +02006#include "pycore_bitutils.h" // _Py_popcount32()
7#include "pycore_interp.h" // _PY_NSMALLPOSINTS
Victor Stinner8e3b9f92020-10-27 00:00:03 +01008#include "pycore_long.h" // __PyLong_GetSmallInt_internal()
Victor Stinner04fc4f22020-06-16 01:28:07 +02009#include "pycore_object.h" // _PyObject_InitVar()
Victor Stinnerc6b292c2020-06-08 16:30:33 +020010#include "pycore_pystate.h" // _Py_IsMainInterpreter()
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +000012
Mark Dickinsonc6300392009-04-20 21:38:00 +000013#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000014#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000015#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000016
Serhiy Storchaka495e8802017-02-01 23:12:20 +020017#include "clinic/longobject.c.h"
18/*[clinic input]
19class int "PyObject *" "&PyLong_Type"
20[clinic start generated code]*/
21/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
22
Victor Stinner630c8df2019-12-17 13:02:18 +010023#define NSMALLNEGINTS _PY_NSMALLNEGINTS
Victor Stinner8e3b9f92020-10-27 00:00:03 +010024#define NSMALLPOSINTS _PY_NSMALLPOSINTS
Facundo Batista6e6f59b2008-07-24 18:57:11 +000025
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020026_Py_IDENTIFIER(little);
27_Py_IDENTIFIER(big);
28
Mark Dickinsone4416742009-02-15 15:14:57 +000029/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020030#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
31 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000032 (Py_SIZE(x) == 0 ? (sdigit)0 : \
33 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000034
animalize6b519982019-09-06 14:00:56 +080035#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050036#define IS_SMALL_UINT(ival) ((ival) < NSMALLPOSINTS)
Greg Price5e63ab02019-08-24 10:19:37 -070037
Guido van Rossum7eaf8222007-06-18 17:58:50 +000038static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000039get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000040{
animalize6b519982019-09-06 14:00:56 +080041 assert(IS_SMALL_INT(ival));
Victor Stinner8e3b9f92020-10-27 00:00:03 +010042 PyObject *v = __PyLong_GetSmallInt_internal(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000045}
Guido van Rossumddefaf32007-01-14 03:31:43 +000046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000048maybe_small_long(PyLongObject *v)
49{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020050 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080052 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 Py_DECREF(v);
54 return (PyLongObject *)get_small_int(ival);
55 }
56 }
57 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000058}
Guido van Rossumddefaf32007-01-14 03:31:43 +000059
Serhiy Storchaka95949422013-08-27 19:40:23 +030060/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000061 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020062Py_LOCAL_INLINE(void)
63_PyLong_Negate(PyLongObject **x_p)
64{
65 PyLongObject *x;
66
67 x = (PyLongObject *)*x_p;
68 if (Py_REFCNT(x) == 1) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +010069 Py_SET_SIZE(x, -Py_SIZE(x));
Victor Stinner8aed6f12013-07-17 22:31:17 +020070 return;
71 }
72
73 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
74 Py_DECREF(x);
75}
76
Serhiy Storchaka95949422013-08-27 19:40:23 +030077/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000078 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030079 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000080 */
Tim Peters0973b992004-08-29 22:16:50 +000081#define KARATSUBA_CUTOFF 70
82#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000083
Tim Peters47e52ee2004-08-30 02:44:38 +000084/* For exponentiation, use the binary left-to-right algorithm
85 * unless the exponent contains more than FIVEARY_CUTOFF digits.
86 * In that case, do 5 bits at a time. The potential drawback is that
87 * a table of 2**5 intermediate results is computed.
88 */
89#define FIVEARY_CUTOFF 8
90
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000091#define SIGCHECK(PyTryBlock) \
92 do { \
93 if (PyErr_CheckSignals()) PyTryBlock \
94 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000095
Serhiy Storchaka95949422013-08-27 19:40:23 +030096/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +000097 Doesn't attempt to free the storage--in most cases, due to the nature
98 of the algorithms used, this could save at most be one word anyway. */
99
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000100static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200101long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200103 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 while (i > 0 && v->ob_digit[i-1] == 0)
107 --i;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100108 if (i != j) {
109 Py_SET_SIZE(v, (Py_SIZE(v) < 0) ? -(i) : i);
110 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000112}
113
Serhiy Storchaka95949422013-08-27 19:40:23 +0300114/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000115 Return NULL and set exception if we run out of memory. */
116
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000117#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000119
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000120PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000121_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 PyLongObject *result;
124 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
125 sizeof(digit)*size. Previous incarnations of this code used
126 sizeof(PyVarObject) instead of the offsetof, but this risks being
127 incorrect in the presence of padding between the PyVarObject header
128 and the digits. */
129 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
130 PyErr_SetString(PyExc_OverflowError,
131 "too many digits in integer");
132 return NULL;
133 }
Victor Stinner32bd68c2020-12-01 10:37:39 +0100134 result = PyObject_Malloc(offsetof(PyLongObject, ob_digit) +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 size*sizeof(digit));
136 if (!result) {
137 PyErr_NoMemory();
138 return NULL;
139 }
Victor Stinner04fc4f22020-06-16 01:28:07 +0200140 _PyObject_InitVar((PyVarObject*)result, &PyLong_Type, size);
141 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000142}
143
Tim Peters64b5ce32001-09-10 20:52:51 +0000144PyObject *
145_PyLong_Copy(PyLongObject *src)
146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 PyLongObject *result;
148 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 assert(src != NULL);
151 i = Py_SIZE(src);
152 if (i < 0)
153 i = -(i);
154 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100155 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800156 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700157 return get_small_int(ival);
158 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 }
160 result = _PyLong_New(i);
161 if (result != NULL) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100162 Py_SET_SIZE(result, Py_SIZE(src));
163 while (--i >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 result->ob_digit[i] = src->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100165 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 }
167 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000168}
169
Serhiy Storchaka95949422013-08-27 19:40:23 +0300170/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000171
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000172PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000173PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 PyLongObject *v;
176 unsigned long abs_ival;
177 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
178 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100179 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000180
animalize6b519982019-09-06 14:00:56 +0800181 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700182 return get_small_int((sdigit)ival);
183 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 if (ival < 0) {
186 /* negate: can't write this as abs_ival = -ival since that
187 invokes undefined behaviour when ival is LONG_MIN */
188 abs_ival = 0U-(unsigned long)ival;
189 sign = -1;
190 }
191 else {
192 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100193 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Fast path for single-digit ints */
197 if (!(abs_ival >> PyLong_SHIFT)) {
198 v = _PyLong_New(1);
199 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100200 Py_SET_SIZE(v, sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 v->ob_digit[0] = Py_SAFE_DOWNCAST(
202 abs_ival, unsigned long, digit);
203 }
204 return (PyObject*)v;
205 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000206
Mark Dickinson249b8982009-04-27 19:41:00 +0000207#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 /* 2 digits */
209 if (!(abs_ival >> 2*PyLong_SHIFT)) {
210 v = _PyLong_New(2);
211 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100212 Py_SET_SIZE(v, 2 * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 v->ob_digit[0] = Py_SAFE_DOWNCAST(
214 abs_ival & PyLong_MASK, unsigned long, digit);
215 v->ob_digit[1] = Py_SAFE_DOWNCAST(
216 abs_ival >> PyLong_SHIFT, unsigned long, digit);
217 }
218 return (PyObject*)v;
219 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000220#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 /* Larger numbers: loop to determine number of digits */
223 t = abs_ival;
224 while (t) {
225 ++ndigits;
226 t >>= PyLong_SHIFT;
227 }
228 v = _PyLong_New(ndigits);
229 if (v != NULL) {
230 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100231 Py_SET_SIZE(v, ndigits * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 t = abs_ival;
233 while (t) {
234 *p++ = Py_SAFE_DOWNCAST(
235 t & PyLong_MASK, unsigned long, digit);
236 t >>= PyLong_SHIFT;
237 }
238 }
239 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000240}
241
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500242#define PYLONG_FROM_UINT(INT_TYPE, ival) \
243 do { \
244 if (IS_SMALL_UINT(ival)) { \
Victor Stinner6314abc2019-10-01 13:29:53 +0200245 return get_small_int((sdigit)(ival)); \
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500246 } \
247 /* Count the number of Python digits. */ \
248 Py_ssize_t ndigits = 0; \
249 INT_TYPE t = (ival); \
250 while (t) { \
251 ++ndigits; \
252 t >>= PyLong_SHIFT; \
253 } \
254 PyLongObject *v = _PyLong_New(ndigits); \
255 if (v == NULL) { \
256 return NULL; \
257 } \
258 digit *p = v->ob_digit; \
259 while ((ival)) { \
260 *p++ = (digit)((ival) & PyLong_MASK); \
261 (ival) >>= PyLong_SHIFT; \
262 } \
263 return (PyObject *)v; \
264 } while(0)
265
Serhiy Storchaka95949422013-08-27 19:40:23 +0300266/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000267
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000268PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000269PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000270{
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500271 PYLONG_FROM_UINT(unsigned long, ival);
272}
Tim Petersce9de2f2001-06-14 04:56:19 +0000273
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500274/* Create a new int object from a C unsigned long long int. */
275
276PyObject *
277PyLong_FromUnsignedLongLong(unsigned long long ival)
278{
279 PYLONG_FROM_UINT(unsigned long long, ival);
280}
281
282/* Create a new int object from a C size_t. */
283
284PyObject *
285PyLong_FromSize_t(size_t ival)
286{
287 PYLONG_FROM_UINT(size_t, ival);
Guido van Rossum53756b11997-01-03 17:14:46 +0000288}
289
Serhiy Storchaka95949422013-08-27 19:40:23 +0300290/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000291
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000292PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000293PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000294{
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500295 /* Try to get out cheap if this fits in a long. When a finite value of real
296 * floating type is converted to an integer type, the value is truncated
297 * toward zero. If the value of the integral part cannot be represented by
298 * the integer type, the behavior is undefined. Thus, we must check that
299 * value is in range (LONG_MIN - 1, LONG_MAX + 1). If a long has more bits
300 * of precision than a double, casting LONG_MIN - 1 to double may yield an
301 * approximation, but LONG_MAX + 1 is a power of two and can be represented
302 * as double exactly (assuming FLT_RADIX is 2 or 16), so for simplicity
303 * check against [-(LONG_MAX + 1), LONG_MAX + 1).
304 */
305 const double int_max = (unsigned long)LONG_MAX + 1;
306 if (-int_max < dval && dval < int_max) {
307 return PyLong_FromLong((long)dval);
308 }
309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 PyLongObject *v;
311 double frac;
312 int i, ndig, expo, neg;
313 neg = 0;
314 if (Py_IS_INFINITY(dval)) {
315 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000316 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 return NULL;
318 }
319 if (Py_IS_NAN(dval)) {
320 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000321 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 return NULL;
323 }
324 if (dval < 0.0) {
325 neg = 1;
326 dval = -dval;
327 }
328 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500329 assert(expo > 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
331 v = _PyLong_New(ndig);
332 if (v == NULL)
333 return NULL;
334 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
335 for (i = ndig; --i >= 0; ) {
336 digit bits = (digit)frac;
337 v->ob_digit[i] = bits;
338 frac = frac - (double)bits;
339 frac = ldexp(frac, PyLong_SHIFT);
340 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100341 if (neg) {
342 Py_SET_SIZE(v, -(Py_SIZE(v)));
343 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000345}
346
Thomas Wouters89f507f2006-12-13 04:49:30 +0000347/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
348 * anything about what happens when a signed integer operation overflows,
349 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700350 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000351 * (unsigned long)LONG_MAX, and for the smallest negative signed long
352 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
353 * However, some other compilers warn about applying unary minus to an
354 * unsigned operand. Hence the weird "0-".
355 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
357#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000358
Mark Dickinson20941de2020-05-27 13:43:17 +0100359/* Get a C long int from an int object or any object that has an __index__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100360 method.
361
362 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
363 the result. Otherwise *overflow is 0.
364
365 For other errors (e.g., TypeError), return -1 and set an error condition.
366 In this case *overflow will be 0.
367*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000368
369long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000370PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200373 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 unsigned long x, prev;
375 long res;
376 Py_ssize_t i;
377 int sign;
Mark Dickinson20941de2020-05-27 13:43:17 +0100378 int do_decref = 0; /* if PyNumber_Index was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 *overflow = 0;
381 if (vv == NULL) {
382 PyErr_BadInternalCall();
383 return -1;
384 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000385
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200386 if (PyLong_Check(vv)) {
387 v = (PyLongObject *)vv;
388 }
389 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300390 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200391 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 return -1;
393 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 switch (i) {
400 case -1:
401 res = -(sdigit)v->ob_digit[0];
402 break;
403 case 0:
404 res = 0;
405 break;
406 case 1:
407 res = v->ob_digit[0];
408 break;
409 default:
410 sign = 1;
411 x = 0;
412 if (i < 0) {
413 sign = -1;
414 i = -(i);
415 }
416 while (--i >= 0) {
417 prev = x;
418 x = (x << PyLong_SHIFT) | v->ob_digit[i];
419 if ((x >> PyLong_SHIFT) != prev) {
420 *overflow = sign;
421 goto exit;
422 }
423 }
424 /* Haven't lost any bits, but casting to long requires extra
425 * care (see comment above).
426 */
427 if (x <= (unsigned long)LONG_MAX) {
428 res = (long)x * sign;
429 }
430 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
431 res = LONG_MIN;
432 }
433 else {
434 *overflow = sign;
435 /* res is already set to -1 */
436 }
437 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000438 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200440 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 }
442 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000443}
444
Mark Dickinson20941de2020-05-27 13:43:17 +0100445/* Get a C long int from an int object or any object that has an __index__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100446 method. Return -1 and set an error if overflow occurs. */
447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000449PyLong_AsLong(PyObject *obj)
450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 int overflow;
452 long result = PyLong_AsLongAndOverflow(obj, &overflow);
453 if (overflow) {
454 /* XXX: could be cute and give a different
455 message for overflow == -1 */
456 PyErr_SetString(PyExc_OverflowError,
457 "Python int too large to convert to C long");
458 }
459 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000460}
461
Mark Dickinson20941de2020-05-27 13:43:17 +0100462/* Get a C int from an int object or any object that has an __index__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200463 method. Return -1 and set an error if overflow occurs. */
464
465int
466_PyLong_AsInt(PyObject *obj)
467{
468 int overflow;
469 long result = PyLong_AsLongAndOverflow(obj, &overflow);
470 if (overflow || result > INT_MAX || result < INT_MIN) {
471 /* XXX: could be cute and give a different
472 message for overflow == -1 */
473 PyErr_SetString(PyExc_OverflowError,
474 "Python int too large to convert to C int");
475 return -1;
476 }
477 return (int)result;
478}
479
Serhiy Storchaka95949422013-08-27 19:40:23 +0300480/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000481 Returns -1 and sets an error condition if overflow occurs. */
482
483Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000484PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200485 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 size_t x, prev;
487 Py_ssize_t i;
488 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (vv == NULL) {
491 PyErr_BadInternalCall();
492 return -1;
493 }
494 if (!PyLong_Check(vv)) {
495 PyErr_SetString(PyExc_TypeError, "an integer is required");
496 return -1;
497 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 v = (PyLongObject *)vv;
500 i = Py_SIZE(v);
501 switch (i) {
502 case -1: return -(sdigit)v->ob_digit[0];
503 case 0: return 0;
504 case 1: return v->ob_digit[0];
505 }
506 sign = 1;
507 x = 0;
508 if (i < 0) {
509 sign = -1;
510 i = -(i);
511 }
512 while (--i >= 0) {
513 prev = x;
514 x = (x << PyLong_SHIFT) | v->ob_digit[i];
515 if ((x >> PyLong_SHIFT) != prev)
516 goto overflow;
517 }
518 /* Haven't lost any bits, but casting to a signed type requires
519 * extra care (see comment above).
520 */
521 if (x <= (size_t)PY_SSIZE_T_MAX) {
522 return (Py_ssize_t)x * sign;
523 }
524 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
525 return PY_SSIZE_T_MIN;
526 }
527 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000528
Mark Dickinson22b20182010-05-10 21:27:53 +0000529 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 PyErr_SetString(PyExc_OverflowError,
531 "Python int too large to convert to C ssize_t");
532 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000533}
534
Serhiy Storchaka95949422013-08-27 19:40:23 +0300535/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000536 Returns -1 and sets an error condition if overflow occurs. */
537
538unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000539PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000540{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200541 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 unsigned long x, prev;
543 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 if (vv == NULL) {
546 PyErr_BadInternalCall();
547 return (unsigned long)-1;
548 }
549 if (!PyLong_Check(vv)) {
550 PyErr_SetString(PyExc_TypeError, "an integer is required");
551 return (unsigned long)-1;
552 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 v = (PyLongObject *)vv;
555 i = Py_SIZE(v);
556 x = 0;
557 if (i < 0) {
558 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000559 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return (unsigned long) -1;
561 }
562 switch (i) {
563 case 0: return 0;
564 case 1: return v->ob_digit[0];
565 }
566 while (--i >= 0) {
567 prev = x;
568 x = (x << PyLong_SHIFT) | v->ob_digit[i];
569 if ((x >> PyLong_SHIFT) != prev) {
570 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100571 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000572 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 return (unsigned long) -1;
574 }
575 }
576 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000577}
578
Serhiy Storchaka95949422013-08-27 19:40:23 +0300579/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200580 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000581
582size_t
583PyLong_AsSize_t(PyObject *vv)
584{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200585 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 size_t x, prev;
587 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (vv == NULL) {
590 PyErr_BadInternalCall();
591 return (size_t) -1;
592 }
593 if (!PyLong_Check(vv)) {
594 PyErr_SetString(PyExc_TypeError, "an integer is required");
595 return (size_t)-1;
596 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 v = (PyLongObject *)vv;
599 i = Py_SIZE(v);
600 x = 0;
601 if (i < 0) {
602 PyErr_SetString(PyExc_OverflowError,
603 "can't convert negative value to size_t");
604 return (size_t) -1;
605 }
606 switch (i) {
607 case 0: return 0;
608 case 1: return v->ob_digit[0];
609 }
610 while (--i >= 0) {
611 prev = x;
612 x = (x << PyLong_SHIFT) | v->ob_digit[i];
613 if ((x >> PyLong_SHIFT) != prev) {
614 PyErr_SetString(PyExc_OverflowError,
615 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200616 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 }
618 }
619 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000620}
621
Serhiy Storchaka95949422013-08-27 19:40:23 +0300622/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000623 Returns -1 and sets an error condition if an error occurs. */
624
Guido van Rossumddefaf32007-01-14 03:31:43 +0000625static unsigned long
626_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000627{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200628 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 unsigned long x;
630 Py_ssize_t i;
631 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 if (vv == NULL || !PyLong_Check(vv)) {
634 PyErr_BadInternalCall();
635 return (unsigned long) -1;
636 }
637 v = (PyLongObject *)vv;
638 i = Py_SIZE(v);
639 switch (i) {
640 case 0: return 0;
641 case 1: return v->ob_digit[0];
642 }
643 sign = 1;
644 x = 0;
645 if (i < 0) {
646 sign = -1;
647 i = -i;
648 }
649 while (--i >= 0) {
650 x = (x << PyLong_SHIFT) | v->ob_digit[i];
651 }
652 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000653}
654
Guido van Rossumddefaf32007-01-14 03:31:43 +0000655unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200656PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyLongObject *lo;
659 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000660
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200661 if (op == NULL) {
662 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 return (unsigned long)-1;
664 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000665
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200666 if (PyLong_Check(op)) {
667 return _PyLong_AsUnsignedLongMask(op);
668 }
669
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300670 lo = (PyLongObject *)_PyNumber_Index(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (lo == NULL)
672 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200673
674 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
675 Py_DECREF(lo);
676 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000677}
678
Tim Peters5b8132f2003-01-31 15:52:05 +0000679int
680_PyLong_Sign(PyObject *vv)
681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 assert(v != NULL);
685 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000688}
689
Niklas Fiekas794e7d12020-06-15 14:33:48 +0200690static int
691bit_length_digit(digit x)
692{
693 Py_BUILD_ASSERT(PyLong_SHIFT <= sizeof(unsigned long) * 8);
694 return _Py_bit_length((unsigned long)x);
695}
696
Tim Petersbaefd9e2003-01-28 20:37:45 +0000697size_t
698_PyLong_NumBits(PyObject *vv)
699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 PyLongObject *v = (PyLongObject *)vv;
701 size_t result = 0;
702 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200703 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 assert(v != NULL);
706 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200707 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
709 if (ndigits > 0) {
710 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700711 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100713 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Niklas Fiekas794e7d12020-06-15 14:33:48 +0200714 msd_bits = bit_length_digit(msd);
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200715 if (SIZE_MAX - msd_bits < result)
716 goto Overflow;
717 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 }
719 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000720
Mark Dickinson22b20182010-05-10 21:27:53 +0000721 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
723 "to express in a platform size_t");
724 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000725}
726
Tim Peters2a9b3672001-06-11 21:23:58 +0000727PyObject *
728_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000730{
Mark Dickinson22b20182010-05-10 21:27:53 +0000731 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 int incr; /* direction to move pstartbyte */
733 const unsigned char* pendbyte; /* MSB of bytes */
734 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300735 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyLongObject* v; /* result */
737 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (n == 0)
740 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 if (little_endian) {
743 pstartbyte = bytes;
744 pendbyte = bytes + n - 1;
745 incr = 1;
746 }
747 else {
748 pstartbyte = bytes + n - 1;
749 pendbyte = bytes;
750 incr = -1;
751 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (is_signed)
754 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200757 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 is positive, and leading 0xff bytes if negative. */
759 {
760 size_t i;
761 const unsigned char* p = pendbyte;
762 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000763 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000766 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 break;
768 }
769 numsignificantbytes = n - i;
770 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
771 actually has 2 significant bytes. OTOH, 0xff0001 ==
772 -0x00ffff, so we wouldn't *need* to bump it there; but we
773 do for 0xffff = -0x0001. To be safe without bothering to
774 check every case, bump it regardless. */
775 if (is_signed && numsignificantbytes < n)
776 ++numsignificantbytes;
777 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000778
Serhiy Storchaka95949422013-08-27 19:40:23 +0300779 /* How many Python int digits do we need? We have
780 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
782 /* catch overflow before it happens */
783 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
784 PyErr_SetString(PyExc_OverflowError,
785 "byte array too long to convert to int");
786 return NULL;
787 }
788 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
789 v = _PyLong_New(ndigits);
790 if (v == NULL)
791 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 /* Copy the bits over. The tricky parts are computing 2's-comp on
794 the fly for signed numbers, and dealing with the mismatch between
795 8-bit bytes and (probably) 15-bit Python digits.*/
796 {
797 size_t i;
798 twodigits carry = 1; /* for 2's-comp calculation */
799 twodigits accum = 0; /* sliding register */
800 unsigned int accumbits = 0; /* number of bits in accum */
801 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
804 twodigits thisbyte = *p;
805 /* Compute correction for 2's comp, if needed. */
806 if (is_signed) {
807 thisbyte = (0xff ^ thisbyte) + carry;
808 carry = thisbyte >> 8;
809 thisbyte &= 0xff;
810 }
811 /* Because we're going LSB to MSB, thisbyte is
812 more significant than what's already in accum,
813 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200814 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 accumbits += 8;
816 if (accumbits >= PyLong_SHIFT) {
817 /* There's enough to fill a Python digit. */
818 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000819 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 ++idigit;
821 accum >>= PyLong_SHIFT;
822 accumbits -= PyLong_SHIFT;
823 assert(accumbits < PyLong_SHIFT);
824 }
825 }
826 assert(accumbits < PyLong_SHIFT);
827 if (accumbits) {
828 assert(idigit < ndigits);
829 v->ob_digit[idigit] = (digit)accum;
830 ++idigit;
831 }
832 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000833
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100834 Py_SET_SIZE(v, is_signed ? -idigit : idigit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000836}
837
838int
839_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 unsigned char* bytes, size_t n,
841 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000844 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000846 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
848 digit carry; /* for computing 2's-comp */
849 size_t j; /* # bytes filled */
850 unsigned char* p; /* pointer to next byte in bytes */
851 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (Py_SIZE(v) < 0) {
856 ndigits = -(Py_SIZE(v));
857 if (!is_signed) {
858 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000859 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 return -1;
861 }
862 do_twos_comp = 1;
863 }
864 else {
865 ndigits = Py_SIZE(v);
866 do_twos_comp = 0;
867 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 if (little_endian) {
870 p = bytes;
871 pincr = 1;
872 }
873 else {
874 p = bytes + n - 1;
875 pincr = -1;
876 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 /* Copy over all the Python digits.
879 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300880 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 normalized. */
882 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
883 j = 0;
884 accum = 0;
885 accumbits = 0;
886 carry = do_twos_comp ? 1 : 0;
887 for (i = 0; i < ndigits; ++i) {
888 digit thisdigit = v->ob_digit[i];
889 if (do_twos_comp) {
890 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
891 carry = thisdigit >> PyLong_SHIFT;
892 thisdigit &= PyLong_MASK;
893 }
894 /* Because we're going LSB to MSB, thisdigit is more
895 significant than what's already in accum, so needs to be
896 prepended to accum. */
897 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 /* The most-significant digit may be (probably is) at least
900 partly empty. */
901 if (i == ndigits - 1) {
902 /* Count # of sign bits -- they needn't be stored,
903 * although for signed conversion we need later to
904 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000905 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 while (s != 0) {
907 s >>= 1;
908 accumbits++;
909 }
910 }
911 else
912 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* Store as many bytes as possible. */
915 while (accumbits >= 8) {
916 if (j >= n)
917 goto Overflow;
918 ++j;
919 *p = (unsigned char)(accum & 0xff);
920 p += pincr;
921 accumbits -= 8;
922 accum >>= 8;
923 }
924 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* Store the straggler (if any). */
927 assert(accumbits < 8);
928 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
929 if (accumbits > 0) {
930 if (j >= n)
931 goto Overflow;
932 ++j;
933 if (do_twos_comp) {
934 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300935 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 infinite supply of sign bits). */
937 accum |= (~(twodigits)0) << accumbits;
938 }
939 *p = (unsigned char)(accum & 0xff);
940 p += pincr;
941 }
942 else if (j == n && n > 0 && is_signed) {
943 /* The main loop filled the byte array exactly, so the code
944 just above didn't get to ensure there's a sign bit, and the
945 loop below wouldn't add one either. Make sure a sign bit
946 exists. */
947 unsigned char msb = *(p - pincr);
948 int sign_bit_set = msb >= 0x80;
949 assert(accumbits == 0);
950 if (sign_bit_set == do_twos_comp)
951 return 0;
952 else
953 goto Overflow;
954 }
Tim Peters05607ad2001-06-13 21:01:27 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 /* Fill remaining bytes with copies of the sign bit. */
957 {
958 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
959 for ( ; j < n; ++j, p += pincr)
960 *p = signbyte;
961 }
Tim Peters05607ad2001-06-13 21:01:27 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000964
Mark Dickinson22b20182010-05-10 21:27:53 +0000965 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
967 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000968
Tim Peters2a9b3672001-06-11 21:23:58 +0000969}
970
Serhiy Storchaka95949422013-08-27 19:40:23 +0300971/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000972
973PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000974PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000975{
Mark Dickinson91044792012-10-18 19:21:43 +0100976#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -0700977 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100978#else
979
Tim Peters70128a12001-06-16 08:48:40 +0000980#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700981# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000982#endif
Benjamin Petersonca470632016-09-06 13:47:26 -0700983 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100984#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000985
Guido van Rossum78694d91998-09-18 14:14:13 +0000986}
987
Serhiy Storchaka95949422013-08-27 19:40:23 +0300988/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000989
990void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000991PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000992{
Tim Peters70128a12001-06-16 08:48:40 +0000993#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
997 x = PyLong_AsLong(vv);
998 else
999 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001000#else
Tim Peters70128a12001-06-16 08:48:40 +00001001
Tim Peters70128a12001-06-16 08:48:40 +00001002#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001003# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001004#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001005 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1008 x = PyLong_AsLongLong(vv);
1009 else
1010 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001011
1012#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (x == -1 && PyErr_Occurred())
1015 return NULL;
1016 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001017}
1018
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001019/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001020 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001021 */
1022
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001023#define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001024
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001025/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001026
1027PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001028PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001031 unsigned long long abs_ival;
1032 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 int ndigits = 0;
1034 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001035
animalize6b519982019-09-06 14:00:56 +08001036 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001037 return get_small_int((sdigit)ival);
1038 }
1039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 if (ival < 0) {
1041 /* avoid signed overflow on negation; see comments
1042 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001043 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 negative = 1;
1045 }
1046 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001047 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 /* Count the number of Python digits.
1051 We used to pick 5 ("big enough for anything"), but that's a
1052 waste of time and space given that 5*15 = 75 bits are rarely
1053 needed. */
1054 t = abs_ival;
1055 while (t) {
1056 ++ndigits;
1057 t >>= PyLong_SHIFT;
1058 }
1059 v = _PyLong_New(ndigits);
1060 if (v != NULL) {
1061 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001062 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 t = abs_ival;
1064 while (t) {
1065 *p++ = (digit)(t & PyLong_MASK);
1066 t >>= PyLong_SHIFT;
1067 }
1068 }
1069 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001070}
1071
Serhiy Storchaka95949422013-08-27 19:40:23 +03001072/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001073
1074PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001075PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 PyLongObject *v;
1078 size_t abs_ival;
1079 size_t t; /* unsigned so >> doesn't propagate sign bit */
1080 int ndigits = 0;
1081 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001082
animalize6b519982019-09-06 14:00:56 +08001083 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001084 return get_small_int((sdigit)ival);
1085 }
1086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 if (ival < 0) {
1088 /* avoid signed overflow when ival = SIZE_T_MIN */
1089 abs_ival = (size_t)(-1-ival)+1;
1090 negative = 1;
1091 }
1092 else {
1093 abs_ival = (size_t)ival;
1094 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 /* Count the number of Python digits. */
1097 t = abs_ival;
1098 while (t) {
1099 ++ndigits;
1100 t >>= PyLong_SHIFT;
1101 }
1102 v = _PyLong_New(ndigits);
1103 if (v != NULL) {
1104 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001105 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 t = abs_ival;
1107 while (t) {
1108 *p++ = (digit)(t & PyLong_MASK);
1109 t >>= PyLong_SHIFT;
1110 }
1111 }
1112 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001113}
1114
Serhiy Storchaka95949422013-08-27 19:40:23 +03001115/* Get a C long long int from an int object or any object that has an
Mark Dickinson20941de2020-05-27 13:43:17 +01001116 __index__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001117
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001118long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001119PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001122 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 int res;
Mark Dickinson20941de2020-05-27 13:43:17 +01001124 int do_decref = 0; /* if PyNumber_Index was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (vv == NULL) {
1127 PyErr_BadInternalCall();
1128 return -1;
1129 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001130
1131 if (PyLong_Check(vv)) {
1132 v = (PyLongObject *)vv;
1133 }
1134 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001135 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001136 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001138 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001140
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001141 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001143 case -1:
1144 bytes = -(sdigit)v->ob_digit[0];
1145 break;
1146 case 0:
1147 bytes = 0;
1148 break;
1149 case 1:
1150 bytes = v->ob_digit[0];
1151 break;
1152 default:
1153 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001154 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001156 if (do_decref) {
1157 Py_DECREF(v);
1158 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001159
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001160 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001162 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 else
1164 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001165}
1166
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001167/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001168 Return -1 and set an error if overflow occurs. */
1169
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001170unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001171PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001174 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001176
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001177 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001179 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001181 if (!PyLong_Check(vv)) {
1182 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001183 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001184 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 v = (PyLongObject*)vv;
1187 switch(Py_SIZE(v)) {
1188 case 0: return 0;
1189 case 1: return v->ob_digit[0];
1190 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001191
Mark Dickinson22b20182010-05-10 21:27:53 +00001192 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001193 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001194
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001195 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001197 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 else
1199 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001200}
Tim Petersd1a7da62001-06-13 00:35:57 +00001201
Serhiy Storchaka95949422013-08-27 19:40:23 +03001202/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001203 Returns -1 and sets an error condition if an error occurs. */
1204
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001205static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001206_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001207{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001208 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001209 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 Py_ssize_t i;
1211 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (vv == NULL || !PyLong_Check(vv)) {
1214 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001215 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 }
1217 v = (PyLongObject *)vv;
1218 switch(Py_SIZE(v)) {
1219 case 0: return 0;
1220 case 1: return v->ob_digit[0];
1221 }
1222 i = Py_SIZE(v);
1223 sign = 1;
1224 x = 0;
1225 if (i < 0) {
1226 sign = -1;
1227 i = -i;
1228 }
1229 while (--i >= 0) {
1230 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1231 }
1232 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001233}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001234
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001235unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001236PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001239 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001240
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001241 if (op == NULL) {
1242 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001243 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001245
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001246 if (PyLong_Check(op)) {
1247 return _PyLong_AsUnsignedLongLongMask(op);
1248 }
1249
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001250 lo = (PyLongObject *)_PyNumber_Index(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001252 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001253
1254 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1255 Py_DECREF(lo);
1256 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001257}
Tim Petersd1a7da62001-06-13 00:35:57 +00001258
Serhiy Storchaka95949422013-08-27 19:40:23 +03001259/* Get a C long long int from an int object or any object that has an
Mark Dickinson20941de2020-05-27 13:43:17 +01001260 __index__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001261
Mark Dickinson8d48b432011-10-23 20:47:14 +01001262 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1263 the result. Otherwise *overflow is 0.
1264
1265 For other errors (e.g., TypeError), return -1 and set an error condition.
1266 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001267*/
1268
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001269long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001270PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001273 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001274 unsigned long long x, prev;
1275 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 Py_ssize_t i;
1277 int sign;
Mark Dickinson20941de2020-05-27 13:43:17 +01001278 int do_decref = 0; /* if PyNumber_Index was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 *overflow = 0;
1281 if (vv == NULL) {
1282 PyErr_BadInternalCall();
1283 return -1;
1284 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001285
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001286 if (PyLong_Check(vv)) {
1287 v = (PyLongObject *)vv;
1288 }
1289 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001290 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001291 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 return -1;
1293 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 switch (i) {
1300 case -1:
1301 res = -(sdigit)v->ob_digit[0];
1302 break;
1303 case 0:
1304 res = 0;
1305 break;
1306 case 1:
1307 res = v->ob_digit[0];
1308 break;
1309 default:
1310 sign = 1;
1311 x = 0;
1312 if (i < 0) {
1313 sign = -1;
1314 i = -(i);
1315 }
1316 while (--i >= 0) {
1317 prev = x;
1318 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1319 if ((x >> PyLong_SHIFT) != prev) {
1320 *overflow = sign;
1321 goto exit;
1322 }
1323 }
1324 /* Haven't lost any bits, but casting to long requires extra
1325 * care (see comment above).
1326 */
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001327 if (x <= (unsigned long long)LLONG_MAX) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001328 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 }
1330 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001331 res = LLONG_MIN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 }
1333 else {
1334 *overflow = sign;
1335 /* res is already set to -1 */
1336 }
1337 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001338 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001340 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 }
1342 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001343}
1344
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001345int
1346_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1347{
1348 unsigned long uval;
1349
1350 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1351 PyErr_SetString(PyExc_ValueError, "value must be positive");
1352 return 0;
1353 }
1354 uval = PyLong_AsUnsignedLong(obj);
1355 if (uval == (unsigned long)-1 && PyErr_Occurred())
1356 return 0;
1357 if (uval > USHRT_MAX) {
1358 PyErr_SetString(PyExc_OverflowError,
1359 "Python int too large for C unsigned short");
1360 return 0;
1361 }
1362
1363 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1364 return 1;
1365}
1366
1367int
1368_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1369{
1370 unsigned long uval;
1371
1372 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1373 PyErr_SetString(PyExc_ValueError, "value must be positive");
1374 return 0;
1375 }
1376 uval = PyLong_AsUnsignedLong(obj);
1377 if (uval == (unsigned long)-1 && PyErr_Occurred())
1378 return 0;
1379 if (uval > UINT_MAX) {
1380 PyErr_SetString(PyExc_OverflowError,
1381 "Python int too large for C unsigned int");
1382 return 0;
1383 }
1384
1385 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1386 return 1;
1387}
1388
1389int
1390_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1391{
1392 unsigned long uval;
1393
1394 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1395 PyErr_SetString(PyExc_ValueError, "value must be positive");
1396 return 0;
1397 }
1398 uval = PyLong_AsUnsignedLong(obj);
1399 if (uval == (unsigned long)-1 && PyErr_Occurred())
1400 return 0;
1401
1402 *(unsigned long *)ptr = uval;
1403 return 1;
1404}
1405
1406int
1407_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1408{
1409 unsigned long long uval;
1410
1411 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1412 PyErr_SetString(PyExc_ValueError, "value must be positive");
1413 return 0;
1414 }
1415 uval = PyLong_AsUnsignedLongLong(obj);
1416 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1417 return 0;
1418
1419 *(unsigned long long *)ptr = uval;
1420 return 1;
1421}
1422
1423int
1424_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1425{
1426 size_t uval;
1427
1428 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1429 PyErr_SetString(PyExc_ValueError, "value must be positive");
1430 return 0;
1431 }
1432 uval = PyLong_AsSize_t(obj);
1433 if (uval == (size_t)-1 && PyErr_Occurred())
1434 return 0;
1435
1436 *(size_t *)ptr = uval;
1437 return 1;
1438}
1439
1440
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001441#define CHECK_BINOP(v,w) \
1442 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001443 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1444 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001445 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001446
Tim Peters877a2122002-08-12 05:09:36 +00001447/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1448 * is modified in place, by adding y to it. Carries are propagated as far as
1449 * x[m-1], and the remaining carry (0 or 1) is returned.
1450 */
1451static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001452v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 Py_ssize_t i;
1455 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 assert(m >= n);
1458 for (i = 0; i < n; ++i) {
1459 carry += x[i] + y[i];
1460 x[i] = carry & PyLong_MASK;
1461 carry >>= PyLong_SHIFT;
1462 assert((carry & 1) == carry);
1463 }
1464 for (; carry && i < m; ++i) {
1465 carry += x[i];
1466 x[i] = carry & PyLong_MASK;
1467 carry >>= PyLong_SHIFT;
1468 assert((carry & 1) == carry);
1469 }
1470 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001471}
1472
1473/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1474 * is modified in place, by subtracting y from it. Borrows are propagated as
1475 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1476 */
1477static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001478v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 Py_ssize_t i;
1481 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 assert(m >= n);
1484 for (i = 0; i < n; ++i) {
1485 borrow = x[i] - y[i] - borrow;
1486 x[i] = borrow & PyLong_MASK;
1487 borrow >>= PyLong_SHIFT;
1488 borrow &= 1; /* keep only 1 sign bit */
1489 }
1490 for (; borrow && i < m; ++i) {
1491 borrow = x[i] - borrow;
1492 x[i] = borrow & PyLong_MASK;
1493 borrow >>= PyLong_SHIFT;
1494 borrow &= 1;
1495 }
1496 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001497}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001498
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001499/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1500 * result in z[0:m], and return the d bits shifted out of the top.
1501 */
1502static digit
1503v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 Py_ssize_t i;
1506 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 assert(0 <= d && d < PyLong_SHIFT);
1509 for (i=0; i < m; i++) {
1510 twodigits acc = (twodigits)a[i] << d | carry;
1511 z[i] = (digit)acc & PyLong_MASK;
1512 carry = (digit)(acc >> PyLong_SHIFT);
1513 }
1514 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001515}
1516
1517/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1518 * result in z[0:m], and return the d bits shifted out of the bottom.
1519 */
1520static digit
1521v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 Py_ssize_t i;
1524 digit carry = 0;
1525 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 assert(0 <= d && d < PyLong_SHIFT);
1528 for (i=m; i-- > 0;) {
1529 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1530 carry = (digit)acc & mask;
1531 z[i] = (digit)(acc >> d);
1532 }
1533 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001534}
1535
Tim Peters212e6142001-07-14 12:23:19 +00001536/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1537 in pout, and returning the remainder. pin and pout point at the LSD.
1538 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001539 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001540 immutable. */
1541
1542static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001543inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 assert(n > 0 && n <= PyLong_MASK);
1548 pin += size;
1549 pout += size;
1550 while (--size >= 0) {
1551 digit hi;
1552 rem = (rem << PyLong_SHIFT) | *--pin;
1553 *--pout = hi = (digit)(rem / n);
1554 rem -= (twodigits)hi * n;
1555 }
1556 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001557}
1558
Serhiy Storchaka95949422013-08-27 19:40:23 +03001559/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001560 (as function result) and the remainder (through *prem).
1561 The sign of a is ignored; n should not be zero. */
1562
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001563static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001564divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001565{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001566 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 assert(n > 0 && n <= PyLong_MASK);
1570 z = _PyLong_New(size);
1571 if (z == NULL)
1572 return NULL;
1573 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1574 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001575}
1576
Serhiy Storchaka95949422013-08-27 19:40:23 +03001577/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001578 string. (Return value is non-shared so that callers can modify the
1579 returned value if necessary.) */
1580
Victor Stinnerd3f08822012-05-29 12:57:52 +02001581static int
1582long_to_decimal_string_internal(PyObject *aa,
1583 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001584 _PyUnicodeWriter *writer,
1585 _PyBytesWriter *bytes_writer,
1586 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001589 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 Py_ssize_t size, strlen, size_a, i, j;
1591 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001593 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001594 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 a = (PyLongObject *)aa;
1597 if (a == NULL || !PyLong_Check(a)) {
1598 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001599 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001601 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 /* quick and dirty upper bound for the number of digits
1605 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 But log2(a) < size_a * PyLong_SHIFT, and
1610 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001611 > 3.3 * _PyLong_DECIMAL_SHIFT
1612
1613 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1614 size_a + size_a / d < size_a + size_a / floor(d),
1615 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1616 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001618 d = (33 * _PyLong_DECIMAL_SHIFT) /
1619 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1620 assert(size_a < PY_SSIZE_T_MAX/2);
1621 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 scratch = _PyLong_New(size);
1623 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001624 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 /* convert array of base _PyLong_BASE digits in pin to an array of
1627 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1628 Volume 2 (3rd edn), section 4.4, Method 1b). */
1629 pin = a->ob_digit;
1630 pout = scratch->ob_digit;
1631 size = 0;
1632 for (i = size_a; --i >= 0; ) {
1633 digit hi = pin[i];
1634 for (j = 0; j < size; j++) {
1635 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1636 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1637 pout[j] = (digit)(z - (twodigits)hi *
1638 _PyLong_DECIMAL_BASE);
1639 }
1640 while (hi) {
1641 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1642 hi /= _PyLong_DECIMAL_BASE;
1643 }
1644 /* check for keyboard interrupt */
1645 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001646 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001647 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001648 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 }
1650 /* pout should have at least one digit, so that the case when a = 0
1651 works correctly */
1652 if (size == 0)
1653 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 /* calculate exact length of output string, and allocate */
1656 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1657 tenpow = 10;
1658 rem = pout[size-1];
1659 while (rem >= tenpow) {
1660 tenpow *= 10;
1661 strlen++;
1662 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001663 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001664 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1665 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001666 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001667 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001668 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001670 else if (bytes_writer) {
1671 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1672 if (*bytes_str == NULL) {
1673 Py_DECREF(scratch);
1674 return -1;
1675 }
1676 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001677 else {
1678 str = PyUnicode_New(strlen, '9');
1679 if (str == NULL) {
1680 Py_DECREF(scratch);
1681 return -1;
1682 }
1683 kind = PyUnicode_KIND(str);
1684 }
1685
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001686#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001687 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001688 /* pout[0] through pout[size-2] contribute exactly \
1689 _PyLong_DECIMAL_SHIFT digits each */ \
1690 for (i=0; i < size - 1; i++) { \
1691 rem = pout[i]; \
1692 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1693 *--p = '0' + rem % 10; \
1694 rem /= 10; \
1695 } \
1696 } \
1697 /* pout[size-1]: always produce at least one decimal digit */ \
1698 rem = pout[i]; \
1699 do { \
1700 *--p = '0' + rem % 10; \
1701 rem /= 10; \
1702 } while (rem != 0); \
1703 \
1704 /* and sign */ \
1705 if (negative) \
1706 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001707 } while (0)
1708
1709#define WRITE_UNICODE_DIGITS(TYPE) \
1710 do { \
1711 if (writer) \
1712 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1713 else \
1714 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1715 \
1716 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001717 \
1718 /* check we've counted correctly */ \
1719 if (writer) \
1720 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1721 else \
1722 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1723 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001726 if (bytes_writer) {
1727 char *p = *bytes_str + strlen;
1728 WRITE_DIGITS(p);
1729 assert(p == *bytes_str);
1730 }
1731 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001732 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001733 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001735 else if (kind == PyUnicode_2BYTE_KIND) {
1736 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001737 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001738 }
1739 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001740 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001741 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001742 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001743 }
1744#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001745#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001748 if (writer) {
1749 writer->pos += strlen;
1750 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001751 else if (bytes_writer) {
1752 (*bytes_str) += strlen;
1753 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001754 else {
1755 assert(_PyUnicode_CheckConsistency(str, 1));
1756 *p_output = (PyObject *)str;
1757 }
1758 return 0;
1759}
1760
1761static PyObject *
1762long_to_decimal_string(PyObject *aa)
1763{
1764 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001765 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001766 return NULL;
1767 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001768}
1769
Serhiy Storchaka95949422013-08-27 19:40:23 +03001770/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001771 which should be one of 2, 8 or 16. Return a string object.
1772 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1773 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001774
Victor Stinnerd3f08822012-05-29 12:57:52 +02001775static int
1776long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001777 PyObject **p_output, _PyUnicodeWriter *writer,
1778 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001779{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001780 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001781 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001782 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001784 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001785 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001787
Victor Stinnerd3f08822012-05-29 12:57:52 +02001788 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (a == NULL || !PyLong_Check(a)) {
1790 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001791 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001793 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001794 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 /* Compute a rough upper bound for the length of the string */
1797 switch (base) {
1798 case 16:
1799 bits = 4;
1800 break;
1801 case 8:
1802 bits = 3;
1803 break;
1804 case 2:
1805 bits = 1;
1806 break;
1807 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001808 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001810
Mark Dickinsone2846542012-04-20 21:21:24 +01001811 /* Compute exact length 'sz' of output string. */
1812 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001813 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001814 }
1815 else {
1816 Py_ssize_t size_a_in_bits;
1817 /* Ensure overflow doesn't occur during computation of sz. */
1818 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1819 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001820 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001821 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001822 }
1823 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
Niklas Fiekas794e7d12020-06-15 14:33:48 +02001824 bit_length_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001825 /* Allow 1 character for a '-' sign. */
1826 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1827 }
1828 if (alternate) {
1829 /* 2 characters for prefix */
1830 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001831 }
1832
Victor Stinnerd3f08822012-05-29 12:57:52 +02001833 if (writer) {
1834 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1835 return -1;
1836 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001838 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001839 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1840 if (*bytes_str == NULL)
1841 return -1;
1842 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001844 v = PyUnicode_New(sz, 'x');
1845 if (v == NULL)
1846 return -1;
1847 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001849
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001850#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001851 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001852 if (size_a == 0) { \
1853 *--p = '0'; \
1854 } \
1855 else { \
1856 /* JRH: special case for power-of-2 bases */ \
1857 twodigits accum = 0; \
1858 int accumbits = 0; /* # of bits in accum */ \
1859 Py_ssize_t i; \
1860 for (i = 0; i < size_a; ++i) { \
1861 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1862 accumbits += PyLong_SHIFT; \
1863 assert(accumbits >= bits); \
1864 do { \
1865 char cdigit; \
1866 cdigit = (char)(accum & (base - 1)); \
1867 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1868 *--p = cdigit; \
1869 accumbits -= bits; \
1870 accum >>= bits; \
1871 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1872 } \
1873 } \
1874 \
1875 if (alternate) { \
1876 if (base == 16) \
1877 *--p = 'x'; \
1878 else if (base == 8) \
1879 *--p = 'o'; \
1880 else /* (base == 2) */ \
1881 *--p = 'b'; \
1882 *--p = '0'; \
1883 } \
1884 if (negative) \
1885 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001886 } while (0)
1887
1888#define WRITE_UNICODE_DIGITS(TYPE) \
1889 do { \
1890 if (writer) \
1891 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1892 else \
1893 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1894 \
1895 WRITE_DIGITS(p); \
1896 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001897 if (writer) \
1898 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1899 else \
1900 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1901 } while (0)
1902
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001903 if (bytes_writer) {
1904 char *p = *bytes_str + sz;
1905 WRITE_DIGITS(p);
1906 assert(p == *bytes_str);
1907 }
1908 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001909 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001910 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001911 }
1912 else if (kind == PyUnicode_2BYTE_KIND) {
1913 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001914 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001915 }
1916 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001917 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001918 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001919 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001920 }
1921#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001922#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02001923
1924 if (writer) {
1925 writer->pos += sz;
1926 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001927 else if (bytes_writer) {
1928 (*bytes_str) += sz;
1929 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001930 else {
1931 assert(_PyUnicode_CheckConsistency(v, 1));
1932 *p_output = v;
1933 }
1934 return 0;
1935}
1936
1937PyObject *
1938_PyLong_Format(PyObject *obj, int base)
1939{
1940 PyObject *str;
1941 int err;
1942 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001943 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001944 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001945 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001946 if (err == -1)
1947 return NULL;
1948 return str;
1949}
1950
1951int
1952_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1953 PyObject *obj,
1954 int base, int alternate)
1955{
1956 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001957 return long_to_decimal_string_internal(obj, NULL, writer,
1958 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001959 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001960 return long_format_binary(obj, base, alternate, NULL, writer,
1961 NULL, NULL);
1962}
1963
1964char*
1965_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
1966 PyObject *obj,
1967 int base, int alternate)
1968{
1969 char *str2;
1970 int res;
1971 str2 = str;
1972 if (base == 10)
1973 res = long_to_decimal_string_internal(obj, NULL, NULL,
1974 writer, &str2);
1975 else
1976 res = long_format_binary(obj, base, alternate, NULL, NULL,
1977 writer, &str2);
1978 if (res < 0)
1979 return NULL;
1980 assert(str2 != NULL);
1981 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001982}
1983
Thomas Wouters477c8d52006-05-27 19:21:47 +00001984/* Table of digit values for 8-bit string -> integer conversion.
1985 * '0' maps to 0, ..., '9' maps to 9.
1986 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1987 * All other indices map to 37.
1988 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001989 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001990 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001991unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1993 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1994 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1995 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1996 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1997 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1998 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1999 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2000 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2001 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2002 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2003 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2004 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2005 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2006 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2007 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002008};
2009
2010/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002011 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
Serhiy Storchaka95949422013-08-27 19:40:23 +03002012 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002013 * The point to this routine is that it takes time linear in the number of
2014 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002015 *
2016 * Return values:
2017 * -1 on syntax error (exception needs to be set, *res is untouched)
2018 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002019 */
Brett Cannona721aba2016-09-09 14:57:09 -07002020static int
2021long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002022{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002023 const char *p = *str;
2024 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002025 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002026 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 int bits_per_char;
2028 Py_ssize_t n;
2029 PyLongObject *z;
2030 twodigits accum;
2031 int bits_in_accum;
2032 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2035 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002036 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002038 }
2039 /* count digits and set p to end-of-string */
2040 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2041 if (*p == '_') {
2042 if (prev == '_') {
2043 *str = p - 1;
2044 return -1;
2045 }
2046 } else {
2047 ++digits;
2048 }
2049 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002051 }
2052 if (prev == '_') {
2053 /* Trailing underscore not allowed. */
2054 *str = p - 1;
2055 return -1;
2056 }
2057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002059 /* n <- the number of Python digits needed,
2060 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2061 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 PyErr_SetString(PyExc_ValueError,
2063 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002064 *res = NULL;
2065 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002067 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002069 if (z == NULL) {
2070 *res = NULL;
2071 return 0;
2072 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002073 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 * from least to most significant in both.
2075 */
2076 accum = 0;
2077 bits_in_accum = 0;
2078 pdigit = z->ob_digit;
2079 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002080 int k;
2081 if (*p == '_') {
2082 continue;
2083 }
2084 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 assert(k >= 0 && k < base);
2086 accum |= (twodigits)k << bits_in_accum;
2087 bits_in_accum += bits_per_char;
2088 if (bits_in_accum >= PyLong_SHIFT) {
2089 *pdigit++ = (digit)(accum & PyLong_MASK);
2090 assert(pdigit - z->ob_digit <= n);
2091 accum >>= PyLong_SHIFT;
2092 bits_in_accum -= PyLong_SHIFT;
2093 assert(bits_in_accum < PyLong_SHIFT);
2094 }
2095 }
2096 if (bits_in_accum) {
2097 assert(bits_in_accum <= PyLong_SHIFT);
2098 *pdigit++ = (digit)accum;
2099 assert(pdigit - z->ob_digit <= n);
2100 }
2101 while (pdigit - z->ob_digit < n)
2102 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002103 *res = long_normalize(z);
2104 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002105}
2106
Serhiy Storchaka95949422013-08-27 19:40:23 +03002107/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002108 * ignored.
2109 *
2110 * If successful, a PyLong object will be returned and 'pend' will be pointing
2111 * to the first unused byte unless it's NULL.
2112 *
2113 * If unsuccessful, NULL will be returned.
2114 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002115PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002116PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002119 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 PyLongObject *z = NULL;
2121 PyObject *strobj;
2122 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 if ((base != 0 && base < 2) || base > 36) {
2125 PyErr_SetString(PyExc_ValueError,
2126 "int() arg 2 must be >= 2 and <= 36");
2127 return NULL;
2128 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002129 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002131 }
2132 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002134 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 else if (*str == '-') {
2136 ++str;
2137 sign = -1;
2138 }
2139 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002140 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002142 }
2143 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002145 }
2146 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002148 }
2149 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002151 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 else {
2153 /* "old" (C-style) octal literal, now invalid.
2154 it might still be zero though */
2155 error_if_nonzero = 1;
2156 base = 10;
2157 }
2158 }
2159 if (str[0] == '0' &&
2160 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2161 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002162 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002164 /* One underscore allowed here. */
2165 if (*str == '_') {
2166 ++str;
2167 }
2168 }
2169 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002170 /* May not start with underscores. */
2171 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002172 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002175 if ((base & (base - 1)) == 0) {
2176 int res = long_from_binary_base(&str, base, &z);
2177 if (res < 0) {
2178 /* Syntax error. */
2179 goto onError;
2180 }
2181 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002183/***
2184Binary bases can be converted in time linear in the number of digits, because
2185Python's representation base is binary. Other bases (including decimal!) use
2186the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002187
Thomas Wouters477c8d52006-05-27 19:21:47 +00002188First some math: the largest integer that can be expressed in N base-B digits
2189is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2190case number of Python digits needed to hold it is the smallest integer n s.t.
2191
2192 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2193 BASE**n >= B**N [taking logs to base BASE]
2194 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2195
2196The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002197this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002198and the result is computed into it.
2199
2200The input string is actually treated as being in base base**i (i.e., i digits
2201are processed at a time), where two more static arrays hold:
2202
2203 convwidth_base[base] = the largest integer i such that base**i <= BASE
2204 convmultmax_base[base] = base ** convwidth_base[base]
2205
2206The first of these is the largest i such that i consecutive input digits
2207must fit in a single Python digit. The second is effectively the input
2208base we're really using.
2209
2210Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2211convmultmax_base[base], the result is "simply"
2212
2213 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2214
2215where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002216
2217Error analysis: as above, the number of Python digits `n` needed is worst-
2218case
2219
2220 n >= N * log(B)/log(BASE)
2221
2222where `N` is the number of input digits in base `B`. This is computed via
2223
2224 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2225
2226below. Two numeric concerns are how much space this can waste, and whether
2227the computed result can be too small. To be concrete, assume BASE = 2**15,
2228which is the default (and it's unlikely anyone changes that).
2229
2230Waste isn't a problem: provided the first input digit isn't 0, the difference
2231between the worst-case input with N digits and the smallest input with N
2232digits is about a factor of B, but B is small compared to BASE so at most
2233one allocated Python digit can remain unused on that count. If
2234N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2235and adding 1 returns a result 1 larger than necessary. However, that can't
2236happen: whenever B is a power of 2, long_from_binary_base() is called
2237instead, and it's impossible for B**i to be an integer power of 2**15 when
2238B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2239an exact integer when B is not a power of 2, since B**i has a prime factor
2240other than 2 in that case, but (2**15)**j's only prime factor is 2).
2241
2242The computed result can be too small if the true value of N*log(B)/log(BASE)
2243is a little bit larger than an exact integer, but due to roundoff errors (in
2244computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2245yields a numeric result a little less than that integer. Unfortunately, "how
2246close can a transcendental function get to an integer over some range?"
2247questions are generally theoretically intractable. Computer analysis via
2248continued fractions is practical: expand log(B)/log(BASE) via continued
2249fractions, giving a sequence i/j of "the best" rational approximations. Then
2250j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2251we can get very close to being in trouble, but very rarely. For example,
225276573 is a denominator in one of the continued-fraction approximations to
2253log(10)/log(2**15), and indeed:
2254
2255 >>> log(10)/log(2**15)*76573
2256 16958.000000654003
2257
2258is very close to an integer. If we were working with IEEE single-precision,
2259rounding errors could kill us. Finding worst cases in IEEE double-precision
2260requires better-than-double-precision log() functions, and Tim didn't bother.
2261Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002262new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002263This should happen extremely rarely, and in fact I don't have a test case
2264that triggers it(!). Instead the code was tested by artificially allocating
2265just 1 digit at the start, so that the copying code was exercised for every
2266digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002267***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002268 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002270 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 int i;
2272 int convwidth;
2273 twodigits convmultmax, convmult;
2274 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002275 const char *scan, *lastdigit;
2276 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 static double log_base_BASE[37] = {0.0e0,};
2279 static int convwidth_base[37] = {0,};
2280 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 if (log_base_BASE[base] == 0.0) {
2283 twodigits convmax = base;
2284 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002285
Mark Dickinson22b20182010-05-10 21:27:53 +00002286 log_base_BASE[base] = (log((double)base) /
2287 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 for (;;) {
2289 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002290 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002292 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 convmax = next;
2294 ++i;
2295 }
2296 convmultmax_base[base] = convmax;
2297 assert(i > 0);
2298 convwidth_base[base] = i;
2299 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* Find length of the string of numeric characters. */
2302 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002303 lastdigit = str;
2304
2305 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2306 if (*scan == '_') {
2307 if (prev == '_') {
2308 /* Only one underscore allowed. */
2309 str = lastdigit + 1;
2310 goto onError;
2311 }
2312 }
2313 else {
2314 ++digits;
2315 lastdigit = scan;
2316 }
2317 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002319 }
2320 if (prev == '_') {
2321 /* Trailing underscore not allowed. */
2322 /* Set error pointer to first underscore. */
2323 str = lastdigit + 1;
2324 goto onError;
2325 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002326
Serhiy Storchaka95949422013-08-27 19:40:23 +03002327 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 * integer with this base and length. Note that there's no
2329 * need to initialize z->ob_digit -- no slot is read up before
2330 * being stored into.
2331 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002332 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2333 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002334 /* The same exception as in _PyLong_New(). */
2335 PyErr_SetString(PyExc_OverflowError,
2336 "too many digits in integer");
2337 return NULL;
2338 }
2339 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 /* Uncomment next line to test exceedingly rare copy code */
2341 /* size_z = 1; */
2342 assert(size_z > 0);
2343 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002344 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002346 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002347 Py_SET_SIZE(z, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* `convwidth` consecutive input digits are treated as a single
2350 * digit in base `convmultmax`.
2351 */
2352 convwidth = convwidth_base[base];
2353 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 /* Work ;-) */
2356 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002357 if (*str == '_') {
2358 str++;
2359 continue;
2360 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 /* grab up to convwidth digits from the input string */
2362 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002363 for (i = 1; i < convwidth && str != scan; ++str) {
2364 if (*str == '_') {
2365 continue;
2366 }
2367 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002369 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 assert(c < PyLong_BASE);
2371 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 convmult = convmultmax;
2374 /* Calculate the shift only if we couldn't get
2375 * convwidth digits.
2376 */
2377 if (i != convwidth) {
2378 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002379 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002381 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 /* Multiply z by convmult, and add c. */
2385 pz = z->ob_digit;
2386 pzstop = pz + Py_SIZE(z);
2387 for (; pz < pzstop; ++pz) {
2388 c += (twodigits)*pz * convmult;
2389 *pz = (digit)(c & PyLong_MASK);
2390 c >>= PyLong_SHIFT;
2391 }
2392 /* carry off the current end? */
2393 if (c) {
2394 assert(c < PyLong_BASE);
2395 if (Py_SIZE(z) < size_z) {
2396 *pz = (digit)c;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002397 Py_SET_SIZE(z, Py_SIZE(z) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 }
2399 else {
2400 PyLongObject *tmp;
2401 /* Extremely rare. Get more space. */
2402 assert(Py_SIZE(z) == size_z);
2403 tmp = _PyLong_New(size_z + 1);
2404 if (tmp == NULL) {
2405 Py_DECREF(z);
2406 return NULL;
2407 }
2408 memcpy(tmp->ob_digit,
2409 z->ob_digit,
2410 sizeof(digit) * size_z);
2411 Py_DECREF(z);
2412 z = tmp;
2413 z->ob_digit[size_z] = (digit)c;
2414 ++size_z;
2415 }
2416 }
2417 }
2418 }
Brett Cannona721aba2016-09-09 14:57:09 -07002419 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002421 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 if (error_if_nonzero) {
2423 /* reset the base to 0, else the exception message
2424 doesn't make too much sense */
2425 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002426 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 /* there might still be other problems, therefore base
2430 remains zero here for the same reason */
2431 }
Brett Cannona721aba2016-09-09 14:57:09 -07002432 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002434 }
2435 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002436 Py_SET_SIZE(z, -(Py_SIZE(z)));
Brett Cannona721aba2016-09-09 14:57:09 -07002437 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002438 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002440 }
2441 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002443 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002445 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002446 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002447 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002448 }
2449 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002450 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002451 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002452 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002453
Mark Dickinson22b20182010-05-10 21:27:53 +00002454 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002455 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002456 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 Py_XDECREF(z);
2459 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2460 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002461 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002463 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002465 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 base, strobj);
2467 Py_DECREF(strobj);
2468 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002469}
2470
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002471/* Since PyLong_FromString doesn't have a length parameter,
2472 * check here for possible NULs in the string.
2473 *
2474 * Reports an invalid literal as a bytes object.
2475 */
2476PyObject *
2477_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2478{
2479 PyObject *result, *strobj;
2480 char *end = NULL;
2481
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002482 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002483 if (end == NULL || (result != NULL && end == s + len))
2484 return result;
2485 Py_XDECREF(result);
2486 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2487 if (strobj != NULL) {
2488 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002489 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002490 base, strobj);
2491 Py_DECREF(strobj);
2492 }
2493 return NULL;
2494}
2495
Guido van Rossum9e896b32000-04-05 20:11:21 +00002496PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002497PyLong_FromUnicodeObject(PyObject *u, int base)
2498{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002499 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002500 const char *buffer;
2501 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002502 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002503
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002504 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002505 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002507 assert(PyUnicode_IS_ASCII(asciidig));
2508 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002509 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002510 assert(buffer != NULL);
2511
2512 result = PyLong_FromString(buffer, &end, base);
2513 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002514 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002515 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002517 Py_DECREF(asciidig);
2518 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002519 PyErr_Format(PyExc_ValueError,
2520 "invalid literal for int() with base %d: %.200R",
2521 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002522 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002523}
2524
Tim Peters9f688bf2000-07-07 15:53:28 +00002525/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002526static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002528static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002529
Serhiy Storchaka95949422013-08-27 19:40:23 +03002530/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002531
Guido van Rossume32e0141992-01-19 16:31:05 +00002532static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002533long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002535{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002536 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 if (size_b == 0) {
2540 PyErr_SetString(PyExc_ZeroDivisionError,
2541 "integer division or modulo by zero");
2542 return -1;
2543 }
2544 if (size_a < size_b ||
2545 (size_a == size_b &&
2546 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2547 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002548 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002549 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002550 return -1;
2551 }
Victor Stinner8e3b9f92020-10-27 00:00:03 +01002552 PyObject *zero = _PyLong_GetZero();
2553 Py_INCREF(zero);
2554 *pdiv = (PyLongObject*)zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 return 0;
2556 }
2557 if (size_b == 1) {
2558 digit rem = 0;
2559 z = divrem1(a, b->ob_digit[0], &rem);
2560 if (z == NULL)
2561 return -1;
2562 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2563 if (*prem == NULL) {
2564 Py_DECREF(z);
2565 return -1;
2566 }
2567 }
2568 else {
2569 z = x_divrem(a, b, prem);
2570 if (z == NULL)
2571 return -1;
2572 }
2573 /* Set the signs.
2574 The quotient z has the sign of a*b;
2575 the remainder r has the sign of a,
2576 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002577 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2578 _PyLong_Negate(&z);
2579 if (z == NULL) {
2580 Py_CLEAR(*prem);
2581 return -1;
2582 }
2583 }
2584 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2585 _PyLong_Negate(prem);
2586 if (*prem == NULL) {
2587 Py_DECREF(z);
2588 Py_CLEAR(*prem);
2589 return -1;
2590 }
2591 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 *pdiv = maybe_small_long(z);
2593 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002594}
2595
Serhiy Storchaka95949422013-08-27 19:40:23 +03002596/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002597 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002598
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002599static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002600x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 PyLongObject *v, *w, *a;
2603 Py_ssize_t i, k, size_v, size_w;
2604 int d;
2605 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2606 twodigits vv;
2607 sdigit zhi;
2608 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2611 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2612 handle the special case when the initial estimate q for a quotient
2613 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2614 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002617 size_v = Py_ABS(Py_SIZE(v1));
2618 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2620 v = _PyLong_New(size_v+1);
2621 if (v == NULL) {
2622 *prem = NULL;
2623 return NULL;
2624 }
2625 w = _PyLong_New(size_w);
2626 if (w == NULL) {
2627 Py_DECREF(v);
2628 *prem = NULL;
2629 return NULL;
2630 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2633 shift v1 left by the same amount. Results go into w and v. */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02002634 d = PyLong_SHIFT - bit_length_digit(w1->ob_digit[size_w-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2636 assert(carry == 0);
2637 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2638 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2639 v->ob_digit[size_v] = carry;
2640 size_v++;
2641 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2644 at most (and usually exactly) k = size_v - size_w digits. */
2645 k = size_v - size_w;
2646 assert(k >= 0);
2647 a = _PyLong_New(k);
2648 if (a == NULL) {
2649 Py_DECREF(w);
2650 Py_DECREF(v);
2651 *prem = NULL;
2652 return NULL;
2653 }
2654 v0 = v->ob_digit;
2655 w0 = w->ob_digit;
2656 wm1 = w0[size_w-1];
2657 wm2 = w0[size_w-2];
2658 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2659 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2660 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002663 Py_DECREF(a);
2664 Py_DECREF(w);
2665 Py_DECREF(v);
2666 *prem = NULL;
2667 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002668 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 /* estimate quotient digit q; may overestimate by 1 (rare) */
2671 vtop = vk[size_w];
2672 assert(vtop <= wm1);
2673 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2674 q = (digit)(vv / wm1);
2675 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2676 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2677 | vk[size_w-2])) {
2678 --q;
2679 r += wm1;
2680 if (r >= PyLong_BASE)
2681 break;
2682 }
2683 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2686 zhi = 0;
2687 for (i = 0; i < size_w; ++i) {
2688 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2689 -PyLong_BASE * q <= z < PyLong_BASE */
2690 z = (sdigit)vk[i] + zhi -
2691 (stwodigits)q * (stwodigits)w0[i];
2692 vk[i] = (digit)z & PyLong_MASK;
2693 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002694 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 /* add w back if q was too large (this branch taken rarely) */
2698 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2699 if ((sdigit)vtop + zhi < 0) {
2700 carry = 0;
2701 for (i = 0; i < size_w; ++i) {
2702 carry += vk[i] + w0[i];
2703 vk[i] = carry & PyLong_MASK;
2704 carry >>= PyLong_SHIFT;
2705 }
2706 --q;
2707 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 /* store quotient digit */
2710 assert(q < PyLong_BASE);
2711 *--ak = q;
2712 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 /* unshift remainder; we reuse w to store the result */
2715 carry = v_rshift(w0, v0, size_w, d);
2716 assert(carry==0);
2717 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 *prem = long_normalize(w);
2720 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002721}
2722
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002723/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2724 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2725 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2726 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2727 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2728 -1.0. */
2729
2730/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2731#if DBL_MANT_DIG == 53
2732#define EXP2_DBL_MANT_DIG 9007199254740992.0
2733#else
2734#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2735#endif
2736
2737double
2738_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2741 /* See below for why x_digits is always large enough. */
Dong-hee Nab88cd582020-05-04 22:32:42 +09002742 digit rem;
2743 digit x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT] = {0,};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 double dx;
2745 /* Correction term for round-half-to-even rounding. For a digit x,
2746 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2747 multiple of 4, rounding ties to a multiple of 8. */
2748 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002749
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002750 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 if (a_size == 0) {
2752 /* Special case for 0: significand 0.0, exponent 0. */
2753 *e = 0;
2754 return 0.0;
2755 }
Niklas Fiekas794e7d12020-06-15 14:33:48 +02002756 a_bits = bit_length_digit(a->ob_digit[a_size-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 /* The following is an overflow-free version of the check
2758 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2759 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2760 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2761 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002762 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2766 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 Number of digits needed for result: write // for floor division.
2769 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2778 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2781 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2782 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 in both cases.
2789 */
2790 if (a_bits <= DBL_MANT_DIG + 2) {
2791 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2792 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
Dong-hee Nab88cd582020-05-04 22:32:42 +09002793 x_size = shift_digits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2795 (int)shift_bits);
2796 x_size += a_size;
2797 x_digits[x_size++] = rem;
2798 }
2799 else {
2800 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2801 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2802 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2803 a_size - shift_digits, (int)shift_bits);
2804 x_size = a_size - shift_digits;
2805 /* For correct rounding below, we need the least significant
2806 bit of x to be 'sticky' for this shift: if any of the bits
2807 shifted out was nonzero, we set the least significant bit
2808 of x. */
2809 if (rem)
2810 x_digits[0] |= 1;
2811 else
2812 while (shift_digits > 0)
2813 if (a->ob_digit[--shift_digits]) {
2814 x_digits[0] |= 1;
2815 break;
2816 }
2817 }
Victor Stinner63941882011-09-29 00:42:28 +02002818 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 /* Round, and convert to double. */
2821 x_digits[0] += half_even_correction[x_digits[0] & 7];
2822 dx = x_digits[--x_size];
2823 while (x_size > 0)
2824 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 /* Rescale; make correction if result is 1.0. */
2827 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2828 if (dx == 1.0) {
2829 if (a_bits == PY_SSIZE_T_MAX)
2830 goto overflow;
2831 dx = 0.5;
2832 a_bits += 1;
2833 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 *e = a_bits;
2836 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002837
2838 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 /* exponent > PY_SSIZE_T_MAX */
2840 PyErr_SetString(PyExc_OverflowError,
2841 "huge integer: number of bits overflows a Py_ssize_t");
2842 *e = 0;
2843 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002844}
2845
Serhiy Storchaka95949422013-08-27 19:40:23 +03002846/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002847 using the round-half-to-even rule in the case of a tie. */
2848
2849double
2850PyLong_AsDouble(PyObject *v)
2851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 Py_ssize_t exponent;
2853 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002854
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002855 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 PyErr_BadInternalCall();
2857 return -1.0;
2858 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002859 if (!PyLong_Check(v)) {
2860 PyErr_SetString(PyExc_TypeError, "an integer is required");
2861 return -1.0;
2862 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002863 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002864 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002865 to double. This improves performance of FP/long operations
2866 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002867 */
2868 return (double)MEDIUM_VALUE((PyLongObject *)v);
2869 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2871 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2872 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002873 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 return -1.0;
2875 }
2876 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002877}
2878
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002879/* Methods */
2880
HongWeipeng42acb7b2019-09-18 23:10:15 +08002881/* if a < b, return a negative number
2882 if a == b, return 0
2883 if a > b, return a positive number */
2884
2885static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002886long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002887{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002888 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
2889 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002890 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08002891 sdigit diff = 0;
2892 while (--i >= 0) {
2893 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
2894 if (diff) {
2895 break;
2896 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08002898 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08002900 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002901}
2902
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002903static PyObject *
2904long_richcompare(PyObject *self, PyObject *other, int op)
2905{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002906 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 CHECK_BINOP(self, other);
2908 if (self == other)
2909 result = 0;
2910 else
2911 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01002912 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002913}
2914
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002915static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002916long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002917{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002918 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 Py_ssize_t i;
2920 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 i = Py_SIZE(v);
2923 switch(i) {
2924 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2925 case 0: return 0;
2926 case 1: return v->ob_digit[0];
2927 }
2928 sign = 1;
2929 x = 0;
2930 if (i < 0) {
2931 sign = -1;
2932 i = -(i);
2933 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002935 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2936 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2937 _PyHASH_MODULUS.
2938
2939 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2940 amounts to a rotation of the bits of x. To see this, write
2941
2942 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2943
2944 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2945 PyLong_SHIFT bits of x (those that are shifted out of the
2946 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2947 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2948 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2949 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2950 congruent to y modulo _PyHASH_MODULUS. So
2951
2952 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2953
2954 The right-hand side is just the result of rotating the
2955 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2956 not all _PyHASH_BITS bits of x are 1s, the same is true
2957 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2958 the reduction of x*2**PyLong_SHIFT modulo
2959 _PyHASH_MODULUS. */
2960 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2961 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002963 if (x >= _PyHASH_MODULUS)
2964 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 }
2966 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002967 if (x == (Py_uhash_t)-1)
2968 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002969 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002970}
2971
2972
Serhiy Storchaka95949422013-08-27 19:40:23 +03002973/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002974
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002975static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002976x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002977{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002978 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 PyLongObject *z;
2980 Py_ssize_t i;
2981 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 /* Ensure a is the larger of the two: */
2984 if (size_a < size_b) {
2985 { PyLongObject *temp = a; a = b; b = temp; }
2986 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002987 size_a = size_b;
2988 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 }
2990 z = _PyLong_New(size_a+1);
2991 if (z == NULL)
2992 return NULL;
2993 for (i = 0; i < size_b; ++i) {
2994 carry += a->ob_digit[i] + b->ob_digit[i];
2995 z->ob_digit[i] = carry & PyLong_MASK;
2996 carry >>= PyLong_SHIFT;
2997 }
2998 for (; i < size_a; ++i) {
2999 carry += a->ob_digit[i];
3000 z->ob_digit[i] = carry & PyLong_MASK;
3001 carry >>= PyLong_SHIFT;
3002 }
3003 z->ob_digit[i] = carry;
3004 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003005}
3006
3007/* Subtract the absolute values of two integers. */
3008
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003009static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003010x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003011{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003012 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 PyLongObject *z;
3014 Py_ssize_t i;
3015 int sign = 1;
3016 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 /* Ensure a is the larger of the two: */
3019 if (size_a < size_b) {
3020 sign = -1;
3021 { PyLongObject *temp = a; a = b; b = temp; }
3022 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003023 size_a = size_b;
3024 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 }
3026 else if (size_a == size_b) {
3027 /* Find highest digit where a and b differ: */
3028 i = size_a;
3029 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3030 ;
3031 if (i < 0)
3032 return (PyLongObject *)PyLong_FromLong(0);
3033 if (a->ob_digit[i] < b->ob_digit[i]) {
3034 sign = -1;
3035 { PyLongObject *temp = a; a = b; b = temp; }
3036 }
3037 size_a = size_b = i+1;
3038 }
3039 z = _PyLong_New(size_a);
3040 if (z == NULL)
3041 return NULL;
3042 for (i = 0; i < size_b; ++i) {
3043 /* The following assumes unsigned arithmetic
3044 works module 2**N for some N>PyLong_SHIFT. */
3045 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3046 z->ob_digit[i] = borrow & PyLong_MASK;
3047 borrow >>= PyLong_SHIFT;
3048 borrow &= 1; /* Keep only one sign bit */
3049 }
3050 for (; i < size_a; ++i) {
3051 borrow = a->ob_digit[i] - borrow;
3052 z->ob_digit[i] = borrow & PyLong_MASK;
3053 borrow >>= PyLong_SHIFT;
3054 borrow &= 1; /* Keep only one sign bit */
3055 }
3056 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003057 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003058 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02003059 }
HongWeipeng036fe852019-11-26 15:54:49 +08003060 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003061}
3062
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003063static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003064long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003069
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003070 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003071 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 }
3073 if (Py_SIZE(a) < 0) {
3074 if (Py_SIZE(b) < 0) {
3075 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003076 if (z != NULL) {
3077 /* x_add received at least one multiple-digit int,
3078 and thus z must be a multiple-digit int.
3079 That also means z is not an element of
3080 small_ints, so negating it in-place is safe. */
3081 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003082 Py_SET_SIZE(z, -(Py_SIZE(z)));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003083 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 }
3085 else
3086 z = x_sub(b, a);
3087 }
3088 else {
3089 if (Py_SIZE(b) < 0)
3090 z = x_sub(a, b);
3091 else
3092 z = x_add(a, b);
3093 }
3094 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003095}
3096
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003097static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003098long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003103
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003104 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003105 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 }
3107 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003108 if (Py_SIZE(b) < 0) {
3109 z = x_sub(b, a);
3110 }
3111 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003113 if (z != NULL) {
3114 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003115 Py_SET_SIZE(z, -(Py_SIZE(z)));
HongWeipeng036fe852019-11-26 15:54:49 +08003116 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003117 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 }
3119 else {
3120 if (Py_SIZE(b) < 0)
3121 z = x_add(a, b);
3122 else
3123 z = x_sub(a, b);
3124 }
3125 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003126}
3127
Tim Peters5af4e6c2002-08-12 02:31:19 +00003128/* Grade school multiplication, ignoring the signs.
3129 * Returns the absolute value of the product, or NULL if error.
3130 */
3131static PyLongObject *
3132x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003135 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3136 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 z = _PyLong_New(size_a + size_b);
3140 if (z == NULL)
3141 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3144 if (a == b) {
3145 /* Efficient squaring per HAC, Algorithm 14.16:
3146 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3147 * Gives slightly less than a 2x speedup when a == b,
3148 * via exploiting that each entry in the multiplication
3149 * pyramid appears twice (except for the size_a squares).
3150 */
3151 for (i = 0; i < size_a; ++i) {
3152 twodigits carry;
3153 twodigits f = a->ob_digit[i];
3154 digit *pz = z->ob_digit + (i << 1);
3155 digit *pa = a->ob_digit + i + 1;
3156 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003159 Py_DECREF(z);
3160 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003161 });
Tim Peters0973b992004-08-29 22:16:50 +00003162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 carry = *pz + f * f;
3164 *pz++ = (digit)(carry & PyLong_MASK);
3165 carry >>= PyLong_SHIFT;
3166 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 /* Now f is added in twice in each column of the
3169 * pyramid it appears. Same as adding f<<1 once.
3170 */
3171 f <<= 1;
3172 while (pa < paend) {
3173 carry += *pz + *pa++ * f;
3174 *pz++ = (digit)(carry & PyLong_MASK);
3175 carry >>= PyLong_SHIFT;
3176 assert(carry <= (PyLong_MASK << 1));
3177 }
3178 if (carry) {
3179 carry += *pz;
3180 *pz++ = (digit)(carry & PyLong_MASK);
3181 carry >>= PyLong_SHIFT;
3182 }
3183 if (carry)
3184 *pz += (digit)(carry & PyLong_MASK);
3185 assert((carry >> PyLong_SHIFT) == 0);
3186 }
3187 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003188 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 for (i = 0; i < size_a; ++i) {
3190 twodigits carry = 0;
3191 twodigits f = a->ob_digit[i];
3192 digit *pz = z->ob_digit + i;
3193 digit *pb = b->ob_digit;
3194 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003197 Py_DECREF(z);
3198 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003199 });
Tim Peters0973b992004-08-29 22:16:50 +00003200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 while (pb < pbend) {
3202 carry += *pz + *pb++ * f;
3203 *pz++ = (digit)(carry & PyLong_MASK);
3204 carry >>= PyLong_SHIFT;
3205 assert(carry <= PyLong_MASK);
3206 }
3207 if (carry)
3208 *pz += (digit)(carry & PyLong_MASK);
3209 assert((carry >> PyLong_SHIFT) == 0);
3210 }
3211 }
3212 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003213}
3214
3215/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003216 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003217 split, and sets low and high such that abs(n) == (high << size) + low,
3218 viewing the shift as being by digits. The sign bit is ignored, and
3219 the return values are >= 0.
3220 Returns 0 on success, -1 on failure.
3221*/
3222static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003223kmul_split(PyLongObject *n,
3224 Py_ssize_t size,
3225 PyLongObject **high,
3226 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 PyLongObject *hi, *lo;
3229 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003230 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003231
Victor Stinner640c35c2013-06-04 23:14:37 +02003232 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 if ((hi = _PyLong_New(size_hi)) == NULL)
3236 return -1;
3237 if ((lo = _PyLong_New(size_lo)) == NULL) {
3238 Py_DECREF(hi);
3239 return -1;
3240 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3243 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 *high = long_normalize(hi);
3246 *low = long_normalize(lo);
3247 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003248}
3249
Tim Peters60004642002-08-12 22:01:34 +00003250static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3251
Tim Peters5af4e6c2002-08-12 02:31:19 +00003252/* Karatsuba multiplication. Ignores the input signs, and returns the
3253 * absolute value of the product (or NULL if error).
3254 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3255 */
3256static PyLongObject *
3257k_mul(PyLongObject *a, PyLongObject *b)
3258{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003259 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3260 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 PyLongObject *ah = NULL;
3262 PyLongObject *al = NULL;
3263 PyLongObject *bh = NULL;
3264 PyLongObject *bl = NULL;
3265 PyLongObject *ret = NULL;
3266 PyLongObject *t1, *t2, *t3;
3267 Py_ssize_t shift; /* the number of digits we split off */
3268 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3271 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3272 * Then the original product is
3273 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3274 * By picking X to be a power of 2, "*X" is just shifting, and it's
3275 * been reduced to 3 multiplies on numbers half the size.
3276 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 /* We want to split based on the larger number; fiddle so that b
3279 * is largest.
3280 */
3281 if (asize > bsize) {
3282 t1 = a;
3283 a = b;
3284 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 i = asize;
3287 asize = bsize;
3288 bsize = i;
3289 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 /* Use gradeschool math when either number is too small. */
3292 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3293 if (asize <= i) {
3294 if (asize == 0)
3295 return (PyLongObject *)PyLong_FromLong(0);
3296 else
3297 return x_mul(a, b);
3298 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 /* If a is small compared to b, splitting on b gives a degenerate
3301 * case with ah==0, and Karatsuba may be (even much) less efficient
3302 * than "grade school" then. However, we can still win, by viewing
3303 * b as a string of "big digits", each of width a->ob_size. That
3304 * leads to a sequence of balanced calls to k_mul.
3305 */
3306 if (2 * asize <= bsize)
3307 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 /* Split a & b into hi & lo pieces. */
3310 shift = bsize >> 1;
3311 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3312 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 if (a == b) {
3315 bh = ah;
3316 bl = al;
3317 Py_INCREF(bh);
3318 Py_INCREF(bl);
3319 }
3320 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 /* The plan:
3323 * 1. Allocate result space (asize + bsize digits: that's always
3324 * enough).
3325 * 2. Compute ah*bh, and copy into result at 2*shift.
3326 * 3. Compute al*bl, and copy into result at 0. Note that this
3327 * can't overlap with #2.
3328 * 4. Subtract al*bl from the result, starting at shift. This may
3329 * underflow (borrow out of the high digit), but we don't care:
3330 * we're effectively doing unsigned arithmetic mod
3331 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3332 * borrows and carries out of the high digit can be ignored.
3333 * 5. Subtract ah*bh from the result, starting at shift.
3334 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3335 * at shift.
3336 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 /* 1. Allocate result space. */
3339 ret = _PyLong_New(asize + bsize);
3340 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003341#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 /* Fill with trash, to catch reference to uninitialized digits. */
3343 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003344#endif
Tim Peters44121a62002-08-12 06:17:58 +00003345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3347 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3348 assert(Py_SIZE(t1) >= 0);
3349 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3350 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3351 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 /* Zero-out the digits higher than the ah*bh copy. */
3354 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3355 if (i)
3356 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3357 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 /* 3. t2 <- al*bl, and copy into the low digits. */
3360 if ((t2 = k_mul(al, bl)) == NULL) {
3361 Py_DECREF(t1);
3362 goto fail;
3363 }
3364 assert(Py_SIZE(t2) >= 0);
3365 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3366 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 /* Zero out remaining digits. */
3369 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3370 if (i)
3371 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3374 * because it's fresher in cache.
3375 */
3376 i = Py_SIZE(ret) - shift; /* # digits after shift */
3377 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3378 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3381 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3384 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3385 Py_DECREF(ah);
3386 Py_DECREF(al);
3387 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 if (a == b) {
3390 t2 = t1;
3391 Py_INCREF(t2);
3392 }
3393 else if ((t2 = x_add(bh, bl)) == NULL) {
3394 Py_DECREF(t1);
3395 goto fail;
3396 }
3397 Py_DECREF(bh);
3398 Py_DECREF(bl);
3399 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 t3 = k_mul(t1, t2);
3402 Py_DECREF(t1);
3403 Py_DECREF(t2);
3404 if (t3 == NULL) goto fail;
3405 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 /* Add t3. It's not obvious why we can't run out of room here.
3408 * See the (*) comment after this function.
3409 */
3410 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3411 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003414
Mark Dickinson22b20182010-05-10 21:27:53 +00003415 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 Py_XDECREF(ret);
3417 Py_XDECREF(ah);
3418 Py_XDECREF(al);
3419 Py_XDECREF(bh);
3420 Py_XDECREF(bl);
3421 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003422}
3423
Tim Petersd6974a52002-08-13 20:37:51 +00003424/* (*) Why adding t3 can't "run out of room" above.
3425
Tim Petersab86c2b2002-08-15 20:06:00 +00003426Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3427to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003428
Tim Petersab86c2b2002-08-15 20:06:00 +000034291. For any integer i, i = c(i/2) + f(i/2). In particular,
3430 bsize = c(bsize/2) + f(bsize/2).
34312. shift = f(bsize/2)
34323. asize <= bsize
34334. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3434 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003435
Tim Petersab86c2b2002-08-15 20:06:00 +00003436We allocated asize + bsize result digits, and add t3 into them at an offset
3437of shift. This leaves asize+bsize-shift allocated digit positions for t3
3438to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3439asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003440
Tim Petersab86c2b2002-08-15 20:06:00 +00003441bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3442at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003443
Tim Petersab86c2b2002-08-15 20:06:00 +00003444If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3445digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3446most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003447
Tim Petersab86c2b2002-08-15 20:06:00 +00003448The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003449
Tim Petersab86c2b2002-08-15 20:06:00 +00003450 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003451
Tim Petersab86c2b2002-08-15 20:06:00 +00003452and we have asize + c(bsize/2) available digit positions. We need to show
3453this is always enough. An instance of c(bsize/2) cancels out in both, so
3454the question reduces to whether asize digits is enough to hold
3455(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3456then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3457asize 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 +00003458digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003459asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003460c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3461is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3462bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003463
Tim Peters48d52c02002-08-14 17:07:32 +00003464Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3465clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3466ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003467*/
3468
Tim Peters60004642002-08-12 22:01:34 +00003469/* b has at least twice the digits of a, and a is big enough that Karatsuba
3470 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3471 * of slices, each with a->ob_size digits, and multiply the slices by a,
3472 * one at a time. This gives k_mul balanced inputs to work with, and is
3473 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003474 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003475 * single-width slice overlap between successive partial sums).
3476 */
3477static PyLongObject *
3478k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3479{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003480 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3481 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 Py_ssize_t nbdone; /* # of b digits already multiplied */
3483 PyLongObject *ret;
3484 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 assert(asize > KARATSUBA_CUTOFF);
3487 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 /* Allocate result space, and zero it out. */
3490 ret = _PyLong_New(asize + bsize);
3491 if (ret == NULL)
3492 return NULL;
3493 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 /* Successive slices of b are copied into bslice. */
3496 bslice = _PyLong_New(asize);
3497 if (bslice == NULL)
3498 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 nbdone = 0;
3501 while (bsize > 0) {
3502 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003503 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 /* Multiply the next slice of b by a. */
3506 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3507 nbtouse * sizeof(digit));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003508 Py_SET_SIZE(bslice, nbtouse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 product = k_mul(a, bslice);
3510 if (product == NULL)
3511 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 /* Add into result. */
3514 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3515 product->ob_digit, Py_SIZE(product));
3516 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 bsize -= nbtouse;
3519 nbdone += nbtouse;
3520 }
Tim Peters60004642002-08-12 22:01:34 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 Py_DECREF(bslice);
3523 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003524
Mark Dickinson22b20182010-05-10 21:27:53 +00003525 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 Py_DECREF(ret);
3527 Py_XDECREF(bslice);
3528 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003529}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003530
3531static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003532long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003539 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003541 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 z = k_mul(a, b);
3545 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003546 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3547 _PyLong_Negate(&z);
3548 if (z == NULL)
3549 return NULL;
3550 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003552}
3553
Yury Selivanove0b23092016-02-11 10:26:27 -05003554/* Fast modulo division for single-digit longs. */
3555static PyObject *
3556fast_mod(PyLongObject *a, PyLongObject *b)
3557{
3558 sdigit left = a->ob_digit[0];
3559 sdigit right = b->ob_digit[0];
3560 sdigit mod;
3561
3562 assert(Py_ABS(Py_SIZE(a)) == 1);
3563 assert(Py_ABS(Py_SIZE(b)) == 1);
3564
3565 if (Py_SIZE(a) == Py_SIZE(b)) {
3566 /* 'a' and 'b' have the same sign. */
3567 mod = left % right;
3568 }
3569 else {
3570 /* Either 'a' or 'b' is negative. */
3571 mod = right - 1 - (left - 1) % right;
3572 }
3573
Victor Stinnerf963c132016-03-23 18:36:54 +01003574 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003575}
3576
3577/* Fast floor division for single-digit longs. */
3578static PyObject *
3579fast_floor_div(PyLongObject *a, PyLongObject *b)
3580{
3581 sdigit left = a->ob_digit[0];
3582 sdigit right = b->ob_digit[0];
3583 sdigit div;
3584
3585 assert(Py_ABS(Py_SIZE(a)) == 1);
3586 assert(Py_ABS(Py_SIZE(b)) == 1);
3587
3588 if (Py_SIZE(a) == Py_SIZE(b)) {
3589 /* 'a' and 'b' have the same sign. */
3590 div = left / right;
3591 }
3592 else {
3593 /* Either 'a' or 'b' is negative. */
3594 div = -1 - (left - 1) / right;
3595 }
3596
3597 return PyLong_FromLong(div);
3598}
3599
Guido van Rossume32e0141992-01-19 16:31:05 +00003600/* The / and % operators are now defined in terms of divmod().
3601 The expression a mod b has the value a - b*floor(a/b).
3602 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003603 |a| by |b|, with the sign of a. This is also expressed
3604 as a - b*trunc(a/b), if trunc truncates towards zero.
3605 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 a b a rem b a mod b
3607 13 10 3 3
3608 -13 10 -3 7
3609 13 -10 3 -7
3610 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003611 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003612 have different signs. We then subtract one from the 'div'
3613 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003614
Tim Peters47e52ee2004-08-30 02:44:38 +00003615/* Compute
3616 * *pdiv, *pmod = divmod(v, w)
3617 * NULL can be passed for pdiv or pmod, in which case that part of
3618 * the result is simply thrown away. The caller owns a reference to
3619 * each of these it requests (does not pass NULL for).
3620 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003621static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003622l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003626
Yury Selivanove0b23092016-02-11 10:26:27 -05003627 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3628 /* Fast path for single-digit longs */
3629 div = NULL;
3630 if (pdiv != NULL) {
3631 div = (PyLongObject *)fast_floor_div(v, w);
3632 if (div == NULL) {
3633 return -1;
3634 }
3635 }
3636 if (pmod != NULL) {
3637 mod = (PyLongObject *)fast_mod(v, w);
3638 if (mod == NULL) {
3639 Py_XDECREF(div);
3640 return -1;
3641 }
3642 *pmod = mod;
3643 }
3644 if (pdiv != NULL) {
3645 /* We only want to set `*pdiv` when `*pmod` is
3646 set successfully. */
3647 *pdiv = div;
3648 }
3649 return 0;
3650 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 if (long_divrem(v, w, &div, &mod) < 0)
3652 return -1;
3653 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3654 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3655 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 temp = (PyLongObject *) long_add(mod, w);
3657 Py_DECREF(mod);
3658 mod = temp;
3659 if (mod == NULL) {
3660 Py_DECREF(div);
3661 return -1;
3662 }
Victor Stinner8e3b9f92020-10-27 00:00:03 +01003663 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_GetOne());
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003664 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 Py_DECREF(mod);
3666 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 return -1;
3668 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 Py_DECREF(div);
3670 div = temp;
3671 }
3672 if (pdiv != NULL)
3673 *pdiv = div;
3674 else
3675 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 if (pmod != NULL)
3678 *pmod = mod;
3679 else
3680 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003683}
3684
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003685static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003686long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003691
3692 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3693 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3694 }
3695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3697 div = NULL;
3698 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003699}
3700
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003701/* PyLong/PyLong -> float, with correctly rounded result. */
3702
3703#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3704#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3705
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003706static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003707long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003709 PyLongObject *a, *b, *x;
3710 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3711 digit mask, low;
3712 int inexact, negate, a_is_small, b_is_small;
3713 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003715 CHECK_BINOP(v, w);
3716 a = (PyLongObject *)v;
3717 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 /*
3720 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3723 1. choose a suitable integer 'shift'
3724 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3725 3. adjust x for correct rounding
3726 4. convert x to a double dx with the same value
3727 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3732 returns either 0.0 or -0.0, depending on the sign of b. For a and
3733 b both nonzero, ignore signs of a and b, and add the sign back in
3734 at the end. Now write a_bits and b_bits for the bit lengths of a
3735 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3736 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3741 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3742 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3743 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 1. The integer 'shift' is chosen so that x has the right number of
3748 bits for a double, plus two or three extra bits that will be used
3749 in the rounding decisions. Writing a_bits and b_bits for the
3750 number of significant bits in a and b respectively, a
3751 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 This is fine in the usual case, but if a/b is smaller than the
3756 smallest normal float then it can lead to double rounding on an
3757 IEEE 754 platform, giving incorrectly rounded results. So we
3758 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 2. The quantity x is computed by first shifting a (left -shift bits
3763 if shift <= 0, right shift bits if shift > 0) and then dividing by
3764 b. For both the shift and the division, we keep track of whether
3765 the result is inexact, in a flag 'inexact'; this information is
3766 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 With the choice of shift above, together with our assumption that
3769 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3770 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3773 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 For float representability, we need x/2**extra_bits <
3778 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3779 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 To round, we just modify the bottom digit of x in-place; this can
3784 end up giving a digit with value > PyLONG_MASK, but that's not a
3785 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 With the original choices for shift above, extra_bits will always
3788 be 2 or 3. Then rounding under the round-half-to-even rule, we
3789 round up iff the most significant of the extra bits is 1, and
3790 either: (a) the computation of x in step 2 had an inexact result,
3791 or (b) at least one other of the extra bits is 1, or (c) the least
3792 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 4. Conversion to a double is straightforward; all floating-point
3795 operations involved in the conversion are exact, so there's no
3796 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3799 The result will always be exactly representable as a double, except
3800 in the case that it overflows. To avoid dependence on the exact
3801 behaviour of ldexp on overflow, we check for overflow before
3802 applying ldexp. The result of ldexp is adjusted for sign before
3803 returning.
3804 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003807 a_size = Py_ABS(Py_SIZE(a));
3808 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3810 if (b_size == 0) {
3811 PyErr_SetString(PyExc_ZeroDivisionError,
3812 "division by zero");
3813 goto error;
3814 }
3815 if (a_size == 0)
3816 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 /* Fast path for a and b small (exactly representable in a double).
3819 Relies on floating-point division being correctly rounded; results
3820 may be subject to double rounding on x86 machines that operate with
3821 the x87 FPU set to 64-bit precision. */
3822 a_is_small = a_size <= MANT_DIG_DIGITS ||
3823 (a_size == MANT_DIG_DIGITS+1 &&
3824 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3825 b_is_small = b_size <= MANT_DIG_DIGITS ||
3826 (b_size == MANT_DIG_DIGITS+1 &&
3827 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3828 if (a_is_small && b_is_small) {
3829 double da, db;
3830 da = a->ob_digit[--a_size];
3831 while (a_size > 0)
3832 da = da * PyLong_BASE + a->ob_digit[--a_size];
3833 db = b->ob_digit[--b_size];
3834 while (b_size > 0)
3835 db = db * PyLong_BASE + b->ob_digit[--b_size];
3836 result = da / db;
3837 goto success;
3838 }
Tim Peterse2a60002001-09-04 06:17:36 +00003839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 /* Catch obvious cases of underflow and overflow */
3841 diff = a_size - b_size;
3842 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3843 /* Extreme overflow */
3844 goto overflow;
3845 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3846 /* Extreme underflow */
3847 goto underflow_or_zero;
3848 /* Next line is now safe from overflowing a Py_ssize_t */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02003849 diff = diff * PyLong_SHIFT + bit_length_digit(a->ob_digit[a_size - 1]) -
3850 bit_length_digit(b->ob_digit[b_size - 1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 /* Now diff = a_bits - b_bits. */
3852 if (diff > DBL_MAX_EXP)
3853 goto overflow;
3854 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3855 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003858 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 /* x = abs(a * 2**-shift) */
3863 if (shift <= 0) {
3864 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3865 digit rem;
3866 /* x = a << -shift */
3867 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3868 /* In practice, it's probably impossible to end up
3869 here. Both a and b would have to be enormous,
3870 using close to SIZE_T_MAX bytes of memory each. */
3871 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003872 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 goto error;
3874 }
3875 x = _PyLong_New(a_size + shift_digits + 1);
3876 if (x == NULL)
3877 goto error;
3878 for (i = 0; i < shift_digits; i++)
3879 x->ob_digit[i] = 0;
3880 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3881 a_size, -shift % PyLong_SHIFT);
3882 x->ob_digit[a_size + shift_digits] = rem;
3883 }
3884 else {
3885 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3886 digit rem;
3887 /* x = a >> shift */
3888 assert(a_size >= shift_digits);
3889 x = _PyLong_New(a_size - shift_digits);
3890 if (x == NULL)
3891 goto error;
3892 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3893 a_size - shift_digits, shift % PyLong_SHIFT);
3894 /* set inexact if any of the bits shifted out is nonzero */
3895 if (rem)
3896 inexact = 1;
3897 while (!inexact && shift_digits > 0)
3898 if (a->ob_digit[--shift_digits])
3899 inexact = 1;
3900 }
3901 long_normalize(x);
3902 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3905 reference to x, so it's safe to modify it in-place. */
3906 if (b_size == 1) {
3907 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3908 b->ob_digit[0]);
3909 long_normalize(x);
3910 if (rem)
3911 inexact = 1;
3912 }
3913 else {
3914 PyLongObject *div, *rem;
3915 div = x_divrem(x, b, &rem);
3916 Py_DECREF(x);
3917 x = div;
3918 if (x == NULL)
3919 goto error;
3920 if (Py_SIZE(rem))
3921 inexact = 1;
3922 Py_DECREF(rem);
3923 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003924 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 assert(x_size > 0); /* result of division is never zero */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02003926 x_bits = (x_size-1)*PyLong_SHIFT+bit_length_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003929 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 /* Round by directly modifying the low digit of x. */
3933 mask = (digit)1 << (extra_bits - 1);
3934 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003935 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003937 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 /* Convert x to a double dx; the conversion is exact. */
3940 dx = x->ob_digit[--x_size];
3941 while (x_size > 0)
3942 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3943 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 /* Check whether ldexp result will overflow a double. */
3946 if (shift + x_bits >= DBL_MAX_EXP &&
3947 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3948 goto overflow;
3949 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003950
3951 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003953
3954 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003956
3957 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 PyErr_SetString(PyExc_OverflowError,
3959 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003960 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003962}
3963
3964static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003965long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 CHECK_BINOP(a, b);
3970
Yury Selivanove0b23092016-02-11 10:26:27 -05003971 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3972 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
3973 }
3974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3976 mod = NULL;
3977 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003978}
3979
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003980static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003981long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 PyLongObject *div, *mod;
3984 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3989 return NULL;
3990 }
3991 z = PyTuple_New(2);
3992 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05003993 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
3994 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003995 }
3996 else {
3997 Py_DECREF(div);
3998 Py_DECREF(mod);
3999 }
4000 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004001}
4002
Mark Dickinsonc5299672019-06-02 10:24:06 +01004003
4004/* Compute an inverse to a modulo n, or raise ValueError if a is not
4005 invertible modulo n. Assumes n is positive. The inverse returned
4006 is whatever falls out of the extended Euclidean algorithm: it may
4007 be either positive or negative, but will be smaller than n in
4008 absolute value.
4009
4010 Pure Python equivalent for long_invmod:
4011
4012 def invmod(a, n):
4013 b, c = 1, 0
4014 while n:
4015 q, r = divmod(a, n)
4016 a, b, c, n = n, c, b - q*c, r
4017
4018 # at this point a is the gcd of the original inputs
4019 if a == 1:
4020 return b
4021 raise ValueError("Not invertible")
4022*/
4023
4024static PyLongObject *
4025long_invmod(PyLongObject *a, PyLongObject *n)
4026{
4027 PyLongObject *b, *c;
4028
4029 /* Should only ever be called for positive n */
4030 assert(Py_SIZE(n) > 0);
4031
4032 b = (PyLongObject *)PyLong_FromLong(1L);
4033 if (b == NULL) {
4034 return NULL;
4035 }
4036 c = (PyLongObject *)PyLong_FromLong(0L);
4037 if (c == NULL) {
4038 Py_DECREF(b);
4039 return NULL;
4040 }
4041 Py_INCREF(a);
4042 Py_INCREF(n);
4043
4044 /* references now owned: a, b, c, n */
4045 while (Py_SIZE(n) != 0) {
4046 PyLongObject *q, *r, *s, *t;
4047
4048 if (l_divmod(a, n, &q, &r) == -1) {
4049 goto Error;
4050 }
4051 Py_DECREF(a);
4052 a = n;
4053 n = r;
4054 t = (PyLongObject *)long_mul(q, c);
4055 Py_DECREF(q);
4056 if (t == NULL) {
4057 goto Error;
4058 }
4059 s = (PyLongObject *)long_sub(b, t);
4060 Py_DECREF(t);
4061 if (s == NULL) {
4062 goto Error;
4063 }
4064 Py_DECREF(b);
4065 b = c;
4066 c = s;
4067 }
4068 /* references now owned: a, b, c, n */
4069
4070 Py_DECREF(c);
4071 Py_DECREF(n);
Victor Stinner8e3b9f92020-10-27 00:00:03 +01004072 if (long_compare(a, (PyLongObject *)_PyLong_GetOne())) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004073 /* a != 1; we don't have an inverse. */
4074 Py_DECREF(a);
4075 Py_DECREF(b);
4076 PyErr_SetString(PyExc_ValueError,
4077 "base is not invertible for the given modulus");
4078 return NULL;
4079 }
4080 else {
4081 /* a == 1; b gives an inverse modulo n */
4082 Py_DECREF(a);
4083 return b;
4084 }
4085
4086 Error:
4087 Py_DECREF(a);
4088 Py_DECREF(b);
4089 Py_DECREF(c);
4090 Py_DECREF(n);
4091 return NULL;
4092}
4093
4094
Tim Peters47e52ee2004-08-30 02:44:38 +00004095/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004096static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004097long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4100 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 PyLongObject *z = NULL; /* accumulated result */
4103 Py_ssize_t i, j, k; /* counters */
4104 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 /* 5-ary values. If the exponent is large enough, table is
4107 * precomputed so that table[i] == a**i % c for i in range(32).
4108 */
4109 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4110 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 /* a, b, c = v, w, x */
4113 CHECK_BINOP(v, w);
4114 a = (PyLongObject*)v; Py_INCREF(a);
4115 b = (PyLongObject*)w; Py_INCREF(b);
4116 if (PyLong_Check(x)) {
4117 c = (PyLongObject *)x;
4118 Py_INCREF(x);
4119 }
4120 else if (x == Py_None)
4121 c = NULL;
4122 else {
4123 Py_DECREF(a);
4124 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004125 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 }
Tim Peters4c483c42001-09-05 06:24:58 +00004127
Mark Dickinsonc5299672019-06-02 10:24:06 +01004128 if (Py_SIZE(b) < 0 && c == NULL) {
4129 /* if exponent is negative and there's no modulus:
4130 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 that this calls float_pow() which converts its
4132 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004133 Py_DECREF(a);
4134 Py_DECREF(b);
4135 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 if (c) {
4139 /* if modulus == 0:
4140 raise ValueError() */
4141 if (Py_SIZE(c) == 0) {
4142 PyErr_SetString(PyExc_ValueError,
4143 "pow() 3rd argument cannot be 0");
4144 goto Error;
4145 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 /* if modulus < 0:
4148 negativeOutput = True
4149 modulus = -modulus */
4150 if (Py_SIZE(c) < 0) {
4151 negativeOutput = 1;
4152 temp = (PyLongObject *)_PyLong_Copy(c);
4153 if (temp == NULL)
4154 goto Error;
4155 Py_DECREF(c);
4156 c = temp;
4157 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004158 _PyLong_Negate(&c);
4159 if (c == NULL)
4160 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 /* if modulus == 1:
4164 return 0 */
4165 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4166 z = (PyLongObject *)PyLong_FromLong(0L);
4167 goto Done;
4168 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004169
Mark Dickinsonc5299672019-06-02 10:24:06 +01004170 /* if exponent is negative, negate the exponent and
4171 replace the base with a modular inverse */
4172 if (Py_SIZE(b) < 0) {
4173 temp = (PyLongObject *)_PyLong_Copy(b);
4174 if (temp == NULL)
4175 goto Error;
4176 Py_DECREF(b);
4177 b = temp;
4178 temp = NULL;
4179 _PyLong_Negate(&b);
4180 if (b == NULL)
4181 goto Error;
4182
4183 temp = long_invmod(a, c);
4184 if (temp == NULL)
4185 goto Error;
4186 Py_DECREF(a);
4187 a = temp;
4188 }
4189
Tim Peters81a93152013-10-05 16:53:52 -05004190 /* Reduce base by modulus in some cases:
4191 1. If base < 0. Forcing the base non-negative makes things easier.
4192 2. If base is obviously larger than the modulus. The "small
4193 exponent" case later can multiply directly by base repeatedly,
4194 while the "large exponent" case multiplies directly by base 31
4195 times. It can be unboundedly faster to multiply by
4196 base % modulus instead.
4197 We could _always_ do this reduction, but l_divmod() isn't cheap,
4198 so we only do it when it buys something. */
4199 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 if (l_divmod(a, c, NULL, &temp) < 0)
4201 goto Error;
4202 Py_DECREF(a);
4203 a = temp;
4204 temp = NULL;
4205 }
4206 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 /* At this point a, b, and c are guaranteed non-negative UNLESS
4209 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 z = (PyLongObject *)PyLong_FromLong(1L);
4212 if (z == NULL)
4213 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 /* Perform a modular reduction, X = X % c, but leave X alone if c
4216 * is NULL.
4217 */
4218#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004219 do { \
4220 if (c != NULL) { \
4221 if (l_divmod(X, c, NULL, &temp) < 0) \
4222 goto Error; \
4223 Py_XDECREF(X); \
4224 X = temp; \
4225 temp = NULL; \
4226 } \
4227 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 /* Multiply two values, then reduce the result:
4230 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004231#define MULT(X, Y, result) \
4232 do { \
4233 temp = (PyLongObject *)long_mul(X, Y); \
4234 if (temp == NULL) \
4235 goto Error; \
4236 Py_XDECREF(result); \
4237 result = temp; \
4238 temp = NULL; \
4239 REDUCE(result); \
4240 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4243 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4244 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4245 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4246 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004249 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004251 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 }
4253 }
4254 }
4255 else {
4256 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4257 Py_INCREF(z); /* still holds 1L */
4258 table[0] = z;
4259 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004260 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4263 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4266 const int index = (bi >> j) & 0x1f;
4267 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004268 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004270 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 }
4272 }
4273 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 if (negativeOutput && (Py_SIZE(z) != 0)) {
4276 temp = (PyLongObject *)long_sub(z, c);
4277 if (temp == NULL)
4278 goto Error;
4279 Py_DECREF(z);
4280 z = temp;
4281 temp = NULL;
4282 }
4283 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004284
Mark Dickinson22b20182010-05-10 21:27:53 +00004285 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004286 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004288 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4290 for (i = 0; i < 32; ++i)
4291 Py_XDECREF(table[i]);
4292 }
4293 Py_DECREF(a);
4294 Py_DECREF(b);
4295 Py_XDECREF(c);
4296 Py_XDECREF(temp);
4297 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004298}
4299
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004300static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004301long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 /* Implement ~x as -(x+1) */
4304 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004305 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004306 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Victor Stinner8e3b9f92020-10-27 00:00:03 +01004307 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_GetOne());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004308 if (x == NULL)
4309 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004310 _PyLong_Negate(&x);
4311 /* No need for maybe_small_long here, since any small
4312 longs will have been caught in the Py_SIZE <= 1 fast path. */
4313 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004314}
4315
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004316static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004317long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004320 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 return PyLong_FromLong(-MEDIUM_VALUE(v));
4322 z = (PyLongObject *)_PyLong_Copy(v);
4323 if (z != NULL)
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004324 Py_SET_SIZE(z, -(Py_SIZE(v)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004326}
4327
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004328static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004329long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 if (Py_SIZE(v) < 0)
4332 return long_neg(v);
4333 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004334 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004335}
4336
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004337static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004338long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004341}
4342
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004343/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4344static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004345divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004346{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004347 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004348 assert(Py_SIZE(shiftby) >= 0);
4349 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4350 if (lshiftby >= 0) {
4351 *wordshift = lshiftby / PyLong_SHIFT;
4352 *remshift = lshiftby % PyLong_SHIFT;
4353 return 0;
4354 }
4355 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4356 be that PyLong_AsSsize_t raised an OverflowError. */
4357 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4358 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004359 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004360 if (wordshift_obj == NULL) {
4361 return -1;
4362 }
4363 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4364 Py_DECREF(wordshift_obj);
4365 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4366 return 0;
4367 }
4368 PyErr_Clear();
4369 /* Clip the value. With such large wordshift the right shift
4370 returns 0 and the left shift raises an error in _PyLong_New(). */
4371 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4372 *remshift = 0;
4373 return 0;
4374}
4375
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004376static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004377long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004380 Py_ssize_t newsize, hishift, i, j;
4381 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 if (Py_SIZE(a) < 0) {
4384 /* Right shifting negative numbers is harder */
4385 PyLongObject *a1, *a2;
4386 a1 = (PyLongObject *) long_invert(a);
4387 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004388 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004389 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 Py_DECREF(a1);
4391 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004392 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393 z = (PyLongObject *) long_invert(a2);
4394 Py_DECREF(a2);
4395 }
4396 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004397 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 if (newsize <= 0)
4399 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004400 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 lomask = ((digit)1 << hishift) - 1;
4402 himask = PyLong_MASK ^ lomask;
4403 z = _PyLong_New(newsize);
4404 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004405 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004407 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004409 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004411 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004413 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004414}
4415
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004416static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004417long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004418{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004419 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004420 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004423
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004424 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004426 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004428 if (Py_SIZE(a) == 0) {
4429 return PyLong_FromLong(0);
4430 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004431 if (divmod_shift(b, &wordshift, &remshift) < 0)
4432 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004433 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4434}
4435
4436/* Return a >> shiftby. */
4437PyObject *
4438_PyLong_Rshift(PyObject *a, size_t shiftby)
4439{
4440 Py_ssize_t wordshift;
4441 digit remshift;
4442
4443 assert(PyLong_Check(a));
4444 if (Py_SIZE(a) == 0) {
4445 return PyLong_FromLong(0);
4446 }
4447 wordshift = shiftby / PyLong_SHIFT;
4448 remshift = shiftby % PyLong_SHIFT;
4449 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4450}
4451
4452static PyObject *
4453long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4454{
4455 /* This version due to Tim Peters */
4456 PyLongObject *z = NULL;
4457 Py_ssize_t oldsize, newsize, i, j;
4458 twodigits accum;
4459
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004460 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 newsize = oldsize + wordshift;
4462 if (remshift)
4463 ++newsize;
4464 z = _PyLong_New(newsize);
4465 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004466 return NULL;
4467 if (Py_SIZE(a) < 0) {
4468 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004469 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02004470 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 for (i = 0; i < wordshift; i++)
4472 z->ob_digit[i] = 0;
4473 accum = 0;
4474 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4475 accum |= (twodigits)a->ob_digit[j] << remshift;
4476 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4477 accum >>= PyLong_SHIFT;
4478 }
4479 if (remshift)
4480 z->ob_digit[newsize-1] = (digit)accum;
4481 else
4482 assert(!accum);
4483 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004484 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004485}
4486
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004487static PyObject *
4488long_lshift(PyObject *a, PyObject *b)
4489{
4490 Py_ssize_t wordshift;
4491 digit remshift;
4492
4493 CHECK_BINOP(a, b);
4494
4495 if (Py_SIZE(b) < 0) {
4496 PyErr_SetString(PyExc_ValueError, "negative shift count");
4497 return NULL;
4498 }
4499 if (Py_SIZE(a) == 0) {
4500 return PyLong_FromLong(0);
4501 }
4502 if (divmod_shift(b, &wordshift, &remshift) < 0)
4503 return NULL;
4504 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4505}
4506
4507/* Return a << shiftby. */
4508PyObject *
4509_PyLong_Lshift(PyObject *a, size_t shiftby)
4510{
4511 Py_ssize_t wordshift;
4512 digit remshift;
4513
4514 assert(PyLong_Check(a));
4515 if (Py_SIZE(a) == 0) {
4516 return PyLong_FromLong(0);
4517 }
4518 wordshift = shiftby / PyLong_SHIFT;
4519 remshift = shiftby % PyLong_SHIFT;
4520 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4521}
4522
Mark Dickinson27a87a22009-10-25 20:43:34 +00004523/* Compute two's complement of digit vector a[0:m], writing result to
4524 z[0:m]. The digit vector a need not be normalized, but should not
4525 be entirely zero. a and z may point to the same digit vector. */
4526
4527static void
4528v_complement(digit *z, digit *a, Py_ssize_t m)
4529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 Py_ssize_t i;
4531 digit carry = 1;
4532 for (i = 0; i < m; ++i) {
4533 carry += a[i] ^ PyLong_MASK;
4534 z[i] = carry & PyLong_MASK;
4535 carry >>= PyLong_SHIFT;
4536 }
4537 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004538}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004539
4540/* Bitwise and/xor/or operations */
4541
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004542static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004543long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004544 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004545 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 int nega, negb, negz;
4548 Py_ssize_t size_a, size_b, size_z, i;
4549 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004551 /* Bitwise operations for negative numbers operate as though
4552 on a two's complement representation. So convert arguments
4553 from sign-magnitude to two's complement, and convert the
4554 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004557 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 nega = Py_SIZE(a) < 0;
4559 if (nega) {
4560 z = _PyLong_New(size_a);
4561 if (z == NULL)
4562 return NULL;
4563 v_complement(z->ob_digit, a->ob_digit, size_a);
4564 a = z;
4565 }
4566 else
4567 /* Keep reference count consistent. */
4568 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004571 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004572 negb = Py_SIZE(b) < 0;
4573 if (negb) {
4574 z = _PyLong_New(size_b);
4575 if (z == NULL) {
4576 Py_DECREF(a);
4577 return NULL;
4578 }
4579 v_complement(z->ob_digit, b->ob_digit, size_b);
4580 b = z;
4581 }
4582 else
4583 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 /* Swap a and b if necessary to ensure size_a >= size_b. */
4586 if (size_a < size_b) {
4587 z = a; a = b; b = z;
4588 size_z = size_a; size_a = size_b; size_b = size_z;
4589 negz = nega; nega = negb; negb = negz;
4590 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 /* JRH: The original logic here was to allocate the result value (z)
4593 as the longer of the two operands. However, there are some cases
4594 where the result is guaranteed to be shorter than that: AND of two
4595 positives, OR of two negatives: use the shorter number. AND with
4596 mixed signs: use the positive number. OR with mixed signs: use the
4597 negative number.
4598 */
4599 switch (op) {
4600 case '^':
4601 negz = nega ^ negb;
4602 size_z = size_a;
4603 break;
4604 case '&':
4605 negz = nega & negb;
4606 size_z = negb ? size_a : size_b;
4607 break;
4608 case '|':
4609 negz = nega | negb;
4610 size_z = negb ? size_b : size_a;
4611 break;
4612 default:
stratakisa10d4262019-03-18 18:59:20 +01004613 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 /* We allow an extra digit if z is negative, to make sure that
4617 the final two's complement of z doesn't overflow. */
4618 z = _PyLong_New(size_z + negz);
4619 if (z == NULL) {
4620 Py_DECREF(a);
4621 Py_DECREF(b);
4622 return NULL;
4623 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 /* Compute digits for overlap of a and b. */
4626 switch(op) {
4627 case '&':
4628 for (i = 0; i < size_b; ++i)
4629 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4630 break;
4631 case '|':
4632 for (i = 0; i < size_b; ++i)
4633 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4634 break;
4635 case '^':
4636 for (i = 0; i < size_b; ++i)
4637 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4638 break;
4639 default:
stratakisa10d4262019-03-18 18:59:20 +01004640 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 /* Copy any remaining digits of a, inverting if necessary. */
4644 if (op == '^' && negb)
4645 for (; i < size_z; ++i)
4646 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4647 else if (i < size_z)
4648 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4649 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 /* Complement result if negative. */
4652 if (negz) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004653 Py_SET_SIZE(z, -(Py_SIZE(z)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 z->ob_digit[size_z] = PyLong_MASK;
4655 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4656 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 Py_DECREF(a);
4659 Py_DECREF(b);
4660 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004661}
4662
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004663static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004664long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 PyObject *c;
4667 CHECK_BINOP(a, b);
4668 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4669 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004670}
4671
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004672static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004673long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 PyObject *c;
4676 CHECK_BINOP(a, b);
4677 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4678 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004679}
4680
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004681static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004682long_or(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 Rossum23d6f0e1991-05-14 12:06:49 +00004688}
4689
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004690static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004691long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004693 if (PyLong_CheckExact(v))
4694 Py_INCREF(v);
4695 else
4696 v = _PyLong_Copy((PyLongObject *)v);
4697 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004698}
4699
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004700PyObject *
4701_PyLong_GCD(PyObject *aarg, PyObject *barg)
4702{
4703 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4704 stwodigits x, y, q, s, t, c_carry, d_carry;
4705 stwodigits A, B, C, D, T;
4706 int nbits, k;
4707 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4708 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4709
4710 a = (PyLongObject *)aarg;
4711 b = (PyLongObject *)barg;
4712 size_a = Py_SIZE(a);
4713 size_b = Py_SIZE(b);
4714 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4715 Py_INCREF(a);
4716 Py_INCREF(b);
4717 goto simple;
4718 }
4719
4720 /* Initial reduction: make sure that 0 <= b <= a. */
4721 a = (PyLongObject *)long_abs(a);
4722 if (a == NULL)
4723 return NULL;
4724 b = (PyLongObject *)long_abs(b);
4725 if (b == NULL) {
4726 Py_DECREF(a);
4727 return NULL;
4728 }
4729 if (long_compare(a, b) < 0) {
4730 r = a;
4731 a = b;
4732 b = r;
4733 }
4734 /* We now own references to a and b */
4735
4736 alloc_a = Py_SIZE(a);
4737 alloc_b = Py_SIZE(b);
4738 /* reduce until a fits into 2 digits */
4739 while ((size_a = Py_SIZE(a)) > 2) {
Niklas Fiekas794e7d12020-06-15 14:33:48 +02004740 nbits = bit_length_digit(a->ob_digit[size_a-1]);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004741 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4742 corresponding bits of b into y */
4743 size_b = Py_SIZE(b);
4744 assert(size_b <= size_a);
4745 if (size_b == 0) {
4746 if (size_a < alloc_a) {
4747 r = (PyLongObject *)_PyLong_Copy(a);
4748 Py_DECREF(a);
4749 }
4750 else
4751 r = a;
4752 Py_DECREF(b);
4753 Py_XDECREF(c);
4754 Py_XDECREF(d);
4755 return (PyObject *)r;
4756 }
4757 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4758 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4759 (a->ob_digit[size_a-3] >> nbits));
4760
4761 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4762 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4763 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4764
4765 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4766 larger than PyLong_MASK during the algorithm. */
4767 A = 1; B = 0; C = 0; D = 1;
4768 for (k=0;; k++) {
4769 if (y-C == 0)
4770 break;
4771 q = (x+(A-1))/(y-C);
4772 s = B+q*D;
4773 t = x-q*y;
4774 if (s > t)
4775 break;
4776 x = y; y = t;
4777 t = A+q*C; A = D; B = C; C = s; D = t;
4778 }
4779
4780 if (k == 0) {
4781 /* no progress; do a Euclidean step */
4782 if (l_divmod(a, b, NULL, &r) < 0)
4783 goto error;
4784 Py_DECREF(a);
4785 a = b;
4786 b = r;
4787 alloc_a = alloc_b;
4788 alloc_b = Py_SIZE(b);
4789 continue;
4790 }
4791
4792 /*
4793 a, b = A*b-B*a, D*a-C*b if k is odd
4794 a, b = A*a-B*b, D*b-C*a if k is even
4795 */
4796 if (k&1) {
4797 T = -A; A = -B; B = T;
4798 T = -C; C = -D; D = T;
4799 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004800 if (c != NULL) {
4801 Py_SET_SIZE(c, size_a);
4802 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004803 else if (Py_REFCNT(a) == 1) {
4804 Py_INCREF(a);
4805 c = a;
4806 }
4807 else {
4808 alloc_a = size_a;
4809 c = _PyLong_New(size_a);
4810 if (c == NULL)
4811 goto error;
4812 }
4813
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004814 if (d != NULL) {
4815 Py_SET_SIZE(d, size_a);
4816 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004817 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4818 Py_INCREF(b);
4819 d = b;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004820 Py_SET_SIZE(d, size_a);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004821 }
4822 else {
4823 alloc_b = size_a;
4824 d = _PyLong_New(size_a);
4825 if (d == NULL)
4826 goto error;
4827 }
4828 a_end = a->ob_digit + size_a;
4829 b_end = b->ob_digit + size_b;
4830
4831 /* compute new a and new b in parallel */
4832 a_digit = a->ob_digit;
4833 b_digit = b->ob_digit;
4834 c_digit = c->ob_digit;
4835 d_digit = d->ob_digit;
4836 c_carry = 0;
4837 d_carry = 0;
4838 while (b_digit < b_end) {
4839 c_carry += (A * *a_digit) - (B * *b_digit);
4840 d_carry += (D * *b_digit++) - (C * *a_digit++);
4841 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4842 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4843 c_carry >>= PyLong_SHIFT;
4844 d_carry >>= PyLong_SHIFT;
4845 }
4846 while (a_digit < a_end) {
4847 c_carry += A * *a_digit;
4848 d_carry -= C * *a_digit++;
4849 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4850 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4851 c_carry >>= PyLong_SHIFT;
4852 d_carry >>= PyLong_SHIFT;
4853 }
4854 assert(c_carry == 0);
4855 assert(d_carry == 0);
4856
4857 Py_INCREF(c);
4858 Py_INCREF(d);
4859 Py_DECREF(a);
4860 Py_DECREF(b);
4861 a = long_normalize(c);
4862 b = long_normalize(d);
4863 }
4864 Py_XDECREF(c);
4865 Py_XDECREF(d);
4866
4867simple:
4868 assert(Py_REFCNT(a) > 0);
4869 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004870/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4871 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4872#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004873 /* a fits into a long, so b must too */
4874 x = PyLong_AsLong((PyObject *)a);
4875 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004876#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004877 x = PyLong_AsLongLong((PyObject *)a);
4878 y = PyLong_AsLongLong((PyObject *)b);
4879#else
4880# error "_PyLong_GCD"
4881#endif
4882 x = Py_ABS(x);
4883 y = Py_ABS(y);
4884 Py_DECREF(a);
4885 Py_DECREF(b);
4886
4887 /* usual Euclidean algorithm for longs */
4888 while (y != 0) {
4889 t = y;
4890 y = x % y;
4891 x = t;
4892 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004893#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004894 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004895#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004896 return PyLong_FromLongLong(x);
4897#else
4898# error "_PyLong_GCD"
4899#endif
4900
4901error:
4902 Py_DECREF(a);
4903 Py_DECREF(b);
4904 Py_XDECREF(c);
4905 Py_XDECREF(d);
4906 return NULL;
4907}
4908
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004909static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004910long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004912 double result;
4913 result = PyLong_AsDouble(v);
4914 if (result == -1.0 && PyErr_Occurred())
4915 return NULL;
4916 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004917}
4918
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004919static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004920long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
4921
4922/*[clinic input]
4923@classmethod
4924int.__new__ as long_new
4925 x: object(c_default="NULL") = 0
4926 /
4927 base as obase: object(c_default="NULL") = 10
4928[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004929
Tim Peters6d6c1a32001-08-02 04:15:00 +00004930static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004931long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
4932/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00004933{
Gregory P. Smitha689e522012-12-25 22:38:32 -08004934 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004937 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004938 if (x == NULL) {
4939 if (obase != NULL) {
4940 PyErr_SetString(PyExc_TypeError,
4941 "int() missing string argument");
4942 return NULL;
4943 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004944 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004945 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004946 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004948
Gregory P. Smitha689e522012-12-25 22:38:32 -08004949 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004950 if (base == -1 && PyErr_Occurred())
4951 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004952 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004953 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05304954 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004955 return NULL;
4956 }
4957
4958 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004959 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004961 const char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 if (PyByteArray_Check(x))
4963 string = PyByteArray_AS_STRING(x);
4964 else
4965 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004966 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004967 }
4968 else {
4969 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004970 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 return NULL;
4972 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004973}
4974
Serhiy Storchaka95949422013-08-27 19:40:23 +03004975/* Wimpy, slow approach to tp_new calls for subtypes of int:
4976 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004977 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004978 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004979*/
4980static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004981long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00004982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004983 PyLongObject *tmp, *newobj;
4984 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004987 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004988 if (tmp == NULL)
4989 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02004990 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 n = Py_SIZE(tmp);
4992 if (n < 0)
4993 n = -n;
4994 newobj = (PyLongObject *)type->tp_alloc(type, n);
4995 if (newobj == NULL) {
4996 Py_DECREF(tmp);
4997 return NULL;
4998 }
4999 assert(PyLong_Check(newobj));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005000 Py_SET_SIZE(newobj, Py_SIZE(tmp));
5001 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005002 newobj->ob_digit[i] = tmp->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005003 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005004 Py_DECREF(tmp);
5005 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005006}
5007
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005008/*[clinic input]
5009int.__getnewargs__
5010[clinic start generated code]*/
5011
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005012static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005013int___getnewargs___impl(PyObject *self)
5014/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005015{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005016 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005017}
5018
Guido van Rossumb43daf72007-08-01 18:08:08 +00005019static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005020long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005023}
5024
5025static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005026long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005029}
5030
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005031/*[clinic input]
5032int.__format__
5033
5034 format_spec: unicode
5035 /
5036[clinic start generated code]*/
5037
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005038static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005039int___format___impl(PyObject *self, PyObject *format_spec)
5040/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005041{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005042 _PyUnicodeWriter writer;
5043 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005044
Victor Stinner8f674cc2013-04-17 23:02:17 +02005045 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005046 ret = _PyLong_FormatAdvancedWriter(
5047 &writer,
5048 self,
5049 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5050 if (ret == -1) {
5051 _PyUnicodeWriter_Dealloc(&writer);
5052 return NULL;
5053 }
5054 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005055}
5056
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005057/* Return a pair (q, r) such that a = b * q + r, and
5058 abs(r) <= abs(b)/2, with equality possible only if q is even.
5059 In other words, q == a / b, rounded to the nearest integer using
5060 round-half-to-even. */
5061
5062PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005063_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005064{
5065 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005066 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005067 int quo_is_odd, quo_is_neg;
5068 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005069
5070 /* Equivalent Python code:
5071
5072 def divmod_near(a, b):
5073 q, r = divmod(a, b)
5074 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5075 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5076 # positive, 2 * r < b if b negative.
5077 greater_than_half = 2*r > b if b > 0 else 2*r < b
5078 exactly_half = 2*r == b
5079 if greater_than_half or exactly_half and q % 2 == 1:
5080 q += 1
5081 r -= b
5082 return q, r
5083
5084 */
5085 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5086 PyErr_SetString(PyExc_TypeError,
5087 "non-integer arguments in division");
5088 return NULL;
5089 }
5090
5091 /* Do a and b have different signs? If so, quotient is negative. */
5092 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5093
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005094 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5095 goto error;
5096
5097 /* compare twice the remainder with the divisor, to see
5098 if we need to adjust the quotient and remainder */
Victor Stinner8e3b9f92020-10-27 00:00:03 +01005099 PyObject *one = _PyLong_GetOne(); // borrowed reference
5100 twice_rem = long_lshift((PyObject *)rem, one);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005101 if (twice_rem == NULL)
5102 goto error;
5103 if (quo_is_neg) {
5104 temp = long_neg((PyLongObject*)twice_rem);
5105 Py_DECREF(twice_rem);
5106 twice_rem = temp;
5107 if (twice_rem == NULL)
5108 goto error;
5109 }
5110 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5111 Py_DECREF(twice_rem);
5112
5113 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5114 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5115 /* fix up quotient */
5116 if (quo_is_neg)
Victor Stinner8e3b9f92020-10-27 00:00:03 +01005117 temp = long_sub(quo, (PyLongObject *)one);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005118 else
Victor Stinner8e3b9f92020-10-27 00:00:03 +01005119 temp = long_add(quo, (PyLongObject *)one);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005120 Py_DECREF(quo);
5121 quo = (PyLongObject *)temp;
5122 if (quo == NULL)
5123 goto error;
5124 /* and remainder */
5125 if (quo_is_neg)
5126 temp = long_add(rem, (PyLongObject *)b);
5127 else
5128 temp = long_sub(rem, (PyLongObject *)b);
5129 Py_DECREF(rem);
5130 rem = (PyLongObject *)temp;
5131 if (rem == NULL)
5132 goto error;
5133 }
5134
5135 result = PyTuple_New(2);
5136 if (result == NULL)
5137 goto error;
5138
5139 /* PyTuple_SET_ITEM steals references */
5140 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5141 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005142 return result;
5143
5144 error:
5145 Py_XDECREF(quo);
5146 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005147 return NULL;
5148}
5149
Serhiy Storchaka5a2bac72020-07-20 15:57:37 +03005150/*[clinic input]
5151int.__round__
5152
5153 ndigits as o_ndigits: object = NULL
5154 /
5155
5156Rounding an Integral returns itself.
5157
5158Rounding with an ndigits argument also returns an integer.
5159[clinic start generated code]*/
5160
Eric Smith8c663262007-08-25 02:26:07 +00005161static PyObject *
Serhiy Storchaka5a2bac72020-07-20 15:57:37 +03005162int___round___impl(PyObject *self, PyObject *o_ndigits)
5163/*[clinic end generated code: output=954fda6b18875998 input=1614cf23ec9e18c3]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005164{
Serhiy Storchaka5a2bac72020-07-20 15:57:37 +03005165 PyObject *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005166
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005167 /* To round an integer m to the nearest 10**n (n positive), we make use of
5168 * the divmod_near operation, defined by:
5169 *
5170 * divmod_near(a, b) = (q, r)
5171 *
5172 * where q is the nearest integer to the quotient a / b (the
5173 * nearest even integer in the case of a tie) and r == a - q * b.
5174 * Hence q * b = a - r is the nearest multiple of b to a,
5175 * preferring even multiples in the case of a tie.
5176 *
5177 * So the nearest multiple of 10**n to m is:
5178 *
5179 * m - divmod_near(m, 10**n)[1].
5180 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005181 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005182 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005183
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03005184 ndigits = _PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 if (ndigits == NULL)
5186 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005187
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005188 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005189 if (Py_SIZE(ndigits) >= 0) {
5190 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005191 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005193
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005194 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5195 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005197 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005199 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005200
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005201 result = PyLong_FromLong(10L);
5202 if (result == NULL) {
5203 Py_DECREF(ndigits);
5204 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005206
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005207 temp = long_pow(result, ndigits, Py_None);
5208 Py_DECREF(ndigits);
5209 Py_DECREF(result);
5210 result = temp;
5211 if (result == NULL)
5212 return NULL;
5213
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005214 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005215 Py_DECREF(result);
5216 result = temp;
5217 if (result == NULL)
5218 return NULL;
5219
5220 temp = long_sub((PyLongObject *)self,
5221 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5222 Py_DECREF(result);
5223 result = temp;
5224
5225 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005226}
5227
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005228/*[clinic input]
5229int.__sizeof__ -> Py_ssize_t
5230
5231Returns size in memory, in bytes.
5232[clinic start generated code]*/
5233
5234static Py_ssize_t
5235int___sizeof___impl(PyObject *self)
5236/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005239
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005240 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5241 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005242}
5243
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005244/*[clinic input]
5245int.bit_length
5246
5247Number of bits necessary to represent self in binary.
5248
5249>>> bin(37)
5250'0b100101'
5251>>> (37).bit_length()
52526
5253[clinic start generated code]*/
5254
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005255static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005256int_bit_length_impl(PyObject *self)
5257/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005259 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005260 Py_ssize_t ndigits;
5261 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005263
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005264 assert(self != NULL);
5265 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005266
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005267 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 if (ndigits == 0)
5269 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005270
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005271 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Niklas Fiekas794e7d12020-06-15 14:33:48 +02005272 msd_bits = bit_length_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005274 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5275 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277 /* expression above may overflow; use Python integers instead */
5278 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5279 if (result == NULL)
5280 return NULL;
5281 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5282 if (x == NULL)
5283 goto error;
5284 y = (PyLongObject *)long_mul(result, x);
5285 Py_DECREF(x);
5286 if (y == NULL)
5287 goto error;
5288 Py_DECREF(result);
5289 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5292 if (x == NULL)
5293 goto error;
5294 y = (PyLongObject *)long_add(result, x);
5295 Py_DECREF(x);
5296 if (y == NULL)
5297 goto error;
5298 Py_DECREF(result);
5299 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005302
Mark Dickinson22b20182010-05-10 21:27:53 +00005303 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 Py_DECREF(result);
5305 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005306}
5307
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005308static int
5309popcount_digit(digit d)
5310{
Victor Stinnerc6b292c2020-06-08 16:30:33 +02005311 // digit can be larger than uint32_t, but only PyLong_SHIFT bits
5312 // of it will be ever used.
5313 Py_BUILD_ASSERT(PyLong_SHIFT <= 32);
5314 return _Py_popcount32((uint32_t)d);
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005315}
5316
5317/*[clinic input]
5318int.bit_count
5319
5320Number of ones in the binary representation of the absolute value of self.
5321
5322Also known as the population count.
5323
5324>>> bin(13)
5325'0b1101'
5326>>> (13).bit_count()
53273
5328[clinic start generated code]*/
5329
5330static PyObject *
5331int_bit_count_impl(PyObject *self)
5332/*[clinic end generated code: output=2e571970daf1e5c3 input=7e0adef8e8ccdf2e]*/
5333{
5334 assert(self != NULL);
5335 assert(PyLong_Check(self));
5336
5337 PyLongObject *z = (PyLongObject *)self;
5338 Py_ssize_t ndigits = Py_ABS(Py_SIZE(z));
5339 Py_ssize_t bit_count = 0;
5340
5341 /* Each digit has up to PyLong_SHIFT ones, so the accumulated bit count
5342 from the first PY_SSIZE_T_MAX/PyLong_SHIFT digits can't overflow a
5343 Py_ssize_t. */
5344 Py_ssize_t ndigits_fast = Py_MIN(ndigits, PY_SSIZE_T_MAX/PyLong_SHIFT);
5345 for (Py_ssize_t i = 0; i < ndigits_fast; i++) {
5346 bit_count += popcount_digit(z->ob_digit[i]);
5347 }
5348
5349 PyObject *result = PyLong_FromSsize_t(bit_count);
5350 if (result == NULL) {
5351 return NULL;
5352 }
5353
5354 /* Use Python integers if bit_count would overflow. */
5355 for (Py_ssize_t i = ndigits_fast; i < ndigits; i++) {
5356 PyObject *x = PyLong_FromLong(popcount_digit(z->ob_digit[i]));
5357 if (x == NULL) {
5358 goto error;
5359 }
5360 PyObject *y = long_add((PyLongObject *)result, (PyLongObject *)x);
5361 Py_DECREF(x);
5362 if (y == NULL) {
5363 goto error;
5364 }
5365 Py_DECREF(result);
5366 result = y;
5367 }
5368
5369 return result;
5370
5371 error:
5372 Py_DECREF(result);
5373 return NULL;
5374}
Christian Heimes53876d92008-04-19 00:31:39 +00005375
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005376/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005377int.as_integer_ratio
5378
5379Return integer ratio.
5380
5381Return a pair of integers, whose ratio is exactly equal to the original int
5382and with a positive denominator.
5383
5384>>> (10).as_integer_ratio()
5385(10, 1)
5386>>> (-10).as_integer_ratio()
5387(-10, 1)
5388>>> (0).as_integer_ratio()
5389(0, 1)
5390[clinic start generated code]*/
5391
5392static PyObject *
5393int_as_integer_ratio_impl(PyObject *self)
5394/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5395{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005396 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005397 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005398 if (numerator == NULL) {
5399 return NULL;
5400 }
Victor Stinner8e3b9f92020-10-27 00:00:03 +01005401 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_GetOne());
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005402 Py_DECREF(numerator);
5403 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005404}
5405
5406/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005407int.to_bytes
5408
5409 length: Py_ssize_t
5410 Length of bytes object to use. An OverflowError is raised if the
5411 integer is not representable with the given number of bytes.
5412 byteorder: unicode
5413 The byte order used to represent the integer. If byteorder is 'big',
5414 the most significant byte is at the beginning of the byte array. If
5415 byteorder is 'little', the most significant byte is at the end of the
5416 byte array. To request the native byte order of the host system, use
5417 `sys.byteorder' as the byte order value.
5418 *
5419 signed as is_signed: bool = False
5420 Determines whether two's complement is used to represent the integer.
5421 If signed is False and a negative integer is given, an OverflowError
5422 is raised.
5423
5424Return an array of bytes representing an integer.
5425[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005426
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005427static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005428int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5429 int is_signed)
5430/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005433 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005434
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005435 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005437 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 little_endian = 0;
5439 else {
5440 PyErr_SetString(PyExc_ValueError,
5441 "byteorder must be either 'little' or 'big'");
5442 return NULL;
5443 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 if (length < 0) {
5446 PyErr_SetString(PyExc_ValueError,
5447 "length argument must be non-negative");
5448 return NULL;
5449 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005451 bytes = PyBytes_FromStringAndSize(NULL, length);
5452 if (bytes == NULL)
5453 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005454
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005455 if (_PyLong_AsByteArray((PyLongObject *)self,
5456 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005457 length, little_endian, is_signed) < 0) {
5458 Py_DECREF(bytes);
5459 return NULL;
5460 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005463}
5464
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005465/*[clinic input]
5466@classmethod
5467int.from_bytes
5468
5469 bytes as bytes_obj: object
5470 Holds the array of bytes to convert. The argument must either
5471 support the buffer protocol or be an iterable object producing bytes.
5472 Bytes and bytearray are examples of built-in objects that support the
5473 buffer protocol.
5474 byteorder: unicode
5475 The byte order used to represent the integer. If byteorder is 'big',
5476 the most significant byte is at the beginning of the byte array. If
5477 byteorder is 'little', the most significant byte is at the end of the
5478 byte array. To request the native byte order of the host system, use
5479 `sys.byteorder' as the byte order value.
5480 *
5481 signed as is_signed: bool = False
5482 Indicates whether two's complement is used to represent the integer.
5483
5484Return the integer represented by the given array of bytes.
5485[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005486
5487static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005488int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5489 PyObject *byteorder, int is_signed)
5490/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005493 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005494
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005495 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005496 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005497 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 little_endian = 0;
5499 else {
5500 PyErr_SetString(PyExc_ValueError,
5501 "byteorder must be either 'little' or 'big'");
5502 return NULL;
5503 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005504
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005505 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005506 if (bytes == NULL)
5507 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005509 long_obj = _PyLong_FromByteArray(
5510 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5511 little_endian, is_signed);
5512 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005513
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005514 if (long_obj != NULL && type != &PyLong_Type) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005515 Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005519}
5520
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005521static PyObject *
5522long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5523{
5524 return long_long(self);
5525}
5526
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005527static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005528 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005530 INT_BIT_LENGTH_METHODDEF
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005531 INT_BIT_COUNT_METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005532 INT_TO_BYTES_METHODDEF
5533 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005534 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005535 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005537 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005539 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005540 "Ceiling of an Integral returns itself."},
Serhiy Storchaka5a2bac72020-07-20 15:57:37 +03005541 INT___ROUND___METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005542 INT___GETNEWARGS___METHODDEF
5543 INT___FORMAT___METHODDEF
5544 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005546};
5547
Guido van Rossumb43daf72007-08-01 18:08:08 +00005548static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005549 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005550 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005551 "the real part of a complex number",
5552 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005553 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005554 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005555 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005556 NULL},
5557 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005558 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005559 "the numerator of a rational number in lowest terms",
5560 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005561 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005562 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005563 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005564 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005565 {NULL} /* Sentinel */
5566};
5567
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005568PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005569"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005570int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005571\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005572Convert a number or string to an integer, or return 0 if no arguments\n\
5573are given. If x is a number, return x.__int__(). For floating point\n\
5574numbers, this truncates towards zero.\n\
5575\n\
5576If x is not a number or if base is given, then x must be a string,\n\
5577bytes, or bytearray instance representing an integer literal in the\n\
5578given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5579by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5580Base 0 means to interpret the base from the string as an integer literal.\n\
5581>>> int('0b100', base=0)\n\
55824");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005583
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005584static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005585 (binaryfunc)long_add, /*nb_add*/
5586 (binaryfunc)long_sub, /*nb_subtract*/
5587 (binaryfunc)long_mul, /*nb_multiply*/
5588 long_mod, /*nb_remainder*/
5589 long_divmod, /*nb_divmod*/
5590 long_pow, /*nb_power*/
5591 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005592 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005593 (unaryfunc)long_abs, /*tp_absolute*/
5594 (inquiry)long_bool, /*tp_bool*/
5595 (unaryfunc)long_invert, /*nb_invert*/
5596 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005597 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005598 long_and, /*nb_and*/
5599 long_xor, /*nb_xor*/
5600 long_or, /*nb_or*/
5601 long_long, /*nb_int*/
5602 0, /*nb_reserved*/
5603 long_float, /*nb_float*/
5604 0, /* nb_inplace_add */
5605 0, /* nb_inplace_subtract */
5606 0, /* nb_inplace_multiply */
5607 0, /* nb_inplace_remainder */
5608 0, /* nb_inplace_power */
5609 0, /* nb_inplace_lshift */
5610 0, /* nb_inplace_rshift */
5611 0, /* nb_inplace_and */
5612 0, /* nb_inplace_xor */
5613 0, /* nb_inplace_or */
5614 long_div, /* nb_floor_divide */
5615 long_true_divide, /* nb_true_divide */
5616 0, /* nb_inplace_floor_divide */
5617 0, /* nb_inplace_true_divide */
5618 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005619};
5620
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005621PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5623 "int", /* tp_name */
5624 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5625 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005626 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005627 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005628 0, /* tp_getattr */
5629 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005630 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 long_to_decimal_string, /* tp_repr */
5632 &long_as_number, /* tp_as_number */
5633 0, /* tp_as_sequence */
5634 0, /* tp_as_mapping */
5635 (hashfunc)long_hash, /* tp_hash */
5636 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005637 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005638 PyObject_GenericGetAttr, /* tp_getattro */
5639 0, /* tp_setattro */
5640 0, /* tp_as_buffer */
5641 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Brandt Bucher145bf262021-02-26 14:51:55 -08005642 Py_TPFLAGS_LONG_SUBCLASS |
5643 _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005644 long_doc, /* tp_doc */
5645 0, /* tp_traverse */
5646 0, /* tp_clear */
5647 long_richcompare, /* tp_richcompare */
5648 0, /* tp_weaklistoffset */
5649 0, /* tp_iter */
5650 0, /* tp_iternext */
5651 long_methods, /* tp_methods */
5652 0, /* tp_members */
5653 long_getset, /* tp_getset */
5654 0, /* tp_base */
5655 0, /* tp_dict */
5656 0, /* tp_descr_get */
5657 0, /* tp_descr_set */
5658 0, /* tp_dictoffset */
5659 0, /* tp_init */
5660 0, /* tp_alloc */
5661 long_new, /* tp_new */
5662 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005663};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005664
Mark Dickinsonbd792642009-03-18 20:06:12 +00005665static PyTypeObject Int_InfoType;
5666
5667PyDoc_STRVAR(int_info__doc__,
5668"sys.int_info\n\
5669\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005670A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005671internal representation of integers. The attributes are read only.");
5672
5673static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005675 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005676 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005677};
5678
5679static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 "sys.int_info", /* name */
5681 int_info__doc__, /* doc */
5682 int_info_fields, /* fields */
5683 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005684};
5685
5686PyObject *
5687PyLong_GetInfo(void)
5688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005689 PyObject* int_info;
5690 int field = 0;
5691 int_info = PyStructSequence_New(&Int_InfoType);
5692 if (int_info == NULL)
5693 return NULL;
5694 PyStructSequence_SET_ITEM(int_info, field++,
5695 PyLong_FromLong(PyLong_SHIFT));
5696 PyStructSequence_SET_ITEM(int_info, field++,
5697 PyLong_FromLong(sizeof(digit)));
5698 if (PyErr_Occurred()) {
5699 Py_CLEAR(int_info);
5700 return NULL;
5701 }
5702 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005703}
5704
Guido van Rossumddefaf32007-01-14 03:31:43 +00005705int
Victor Stinnerbcb094b2021-02-19 15:10:45 +01005706_PyLong_Init(PyInterpreterState *interp)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005707{
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005708 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5709 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5710 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005711
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005712 PyLongObject *v = _PyLong_New(1);
5713 if (!v) {
5714 return -1;
5715 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005716
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005717 Py_SET_SIZE(v, size);
Victor Stinner12174a52014-08-15 23:17:38 +02005718 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005719
Victor Stinnerbcb094b2021-02-19 15:10:45 +01005720 interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005721 }
Victor Stinner442ad742021-04-02 15:28:13 +02005722 return 0;
5723}
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005724
Victor Stinner442ad742021-04-02 15:28:13 +02005725
5726int
5727_PyLong_InitTypes(void)
5728{
5729 /* initialize int_info */
5730 if (Int_InfoType.tp_name == NULL) {
5731 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5732 return -1;
Victor Stinner630c8df2019-12-17 13:02:18 +01005733 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005734 }
Victor Stinner442ad742021-04-02 15:28:13 +02005735 return 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005736}
5737
5738void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01005739_PyLong_Fini(PyInterpreterState *interp)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005740{
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005741 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinnerbcb094b2021-02-19 15:10:45 +01005742 Py_CLEAR(interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005743 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005744}