blob: ae63eba134504043f67cfc4bcc7541d8868028a1 [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
Serhiy Storchakaba85d692017-03-30 09:09:41 +030035PyObject *_PyLong_Zero = NULL;
36PyObject *_PyLong_One = NULL;
37
animalize6b519982019-09-06 14:00:56 +080038#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050039#define IS_SMALL_UINT(ival) ((ival) < NSMALLPOSINTS)
Greg Price5e63ab02019-08-24 10:19:37 -070040
Guido van Rossum7eaf8222007-06-18 17:58:50 +000041static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000042get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000043{
animalize6b519982019-09-06 14:00:56 +080044 assert(IS_SMALL_INT(ival));
Victor Stinner8e3b9f92020-10-27 00:00:03 +010045 PyObject *v = __PyLong_GetSmallInt_internal(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048}
Guido van Rossumddefaf32007-01-14 03:31:43 +000049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000051maybe_small_long(PyLongObject *v)
52{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020053 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080055 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 Py_DECREF(v);
57 return (PyLongObject *)get_small_int(ival);
58 }
59 }
60 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000061}
Guido van Rossumddefaf32007-01-14 03:31:43 +000062
Serhiy Storchaka95949422013-08-27 19:40:23 +030063/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000064 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020065Py_LOCAL_INLINE(void)
66_PyLong_Negate(PyLongObject **x_p)
67{
68 PyLongObject *x;
69
70 x = (PyLongObject *)*x_p;
71 if (Py_REFCNT(x) == 1) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +010072 Py_SET_SIZE(x, -Py_SIZE(x));
Victor Stinner8aed6f12013-07-17 22:31:17 +020073 return;
74 }
75
76 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
77 Py_DECREF(x);
78}
79
Serhiy Storchaka95949422013-08-27 19:40:23 +030080/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000081 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030082 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000083 */
Tim Peters0973b992004-08-29 22:16:50 +000084#define KARATSUBA_CUTOFF 70
85#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000086
Tim Peters47e52ee2004-08-30 02:44:38 +000087/* For exponentiation, use the binary left-to-right algorithm
88 * unless the exponent contains more than FIVEARY_CUTOFF digits.
89 * In that case, do 5 bits at a time. The potential drawback is that
90 * a table of 2**5 intermediate results is computed.
91 */
92#define FIVEARY_CUTOFF 8
93
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000094#define SIGCHECK(PyTryBlock) \
95 do { \
96 if (PyErr_CheckSignals()) PyTryBlock \
97 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000098
Serhiy Storchaka95949422013-08-27 19:40:23 +030099/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000100 Doesn't attempt to free the storage--in most cases, due to the nature
101 of the algorithms used, this could save at most be one word anyway. */
102
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000103static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200104long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000105{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200106 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 while (i > 0 && v->ob_digit[i-1] == 0)
110 --i;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100111 if (i != j) {
112 Py_SET_SIZE(v, (Py_SIZE(v) < 0) ? -(i) : i);
113 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000115}
116
Serhiy Storchaka95949422013-08-27 19:40:23 +0300117/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000118 Return NULL and set exception if we run out of memory. */
119
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000120#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000122
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000123PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000124_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 PyLongObject *result;
127 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
128 sizeof(digit)*size. Previous incarnations of this code used
129 sizeof(PyVarObject) instead of the offsetof, but this risks being
130 incorrect in the presence of padding between the PyVarObject header
131 and the digits. */
132 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
133 PyErr_SetString(PyExc_OverflowError,
134 "too many digits in integer");
135 return NULL;
136 }
137 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
138 size*sizeof(digit));
139 if (!result) {
140 PyErr_NoMemory();
141 return NULL;
142 }
Victor Stinner04fc4f22020-06-16 01:28:07 +0200143 _PyObject_InitVar((PyVarObject*)result, &PyLong_Type, size);
144 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000145}
146
Tim Peters64b5ce32001-09-10 20:52:51 +0000147PyObject *
148_PyLong_Copy(PyLongObject *src)
149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 PyLongObject *result;
151 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 assert(src != NULL);
154 i = Py_SIZE(src);
155 if (i < 0)
156 i = -(i);
157 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100158 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800159 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700160 return get_small_int(ival);
161 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 }
163 result = _PyLong_New(i);
164 if (result != NULL) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100165 Py_SET_SIZE(result, Py_SIZE(src));
166 while (--i >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 result->ob_digit[i] = src->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100168 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 }
170 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000171}
172
Serhiy Storchaka95949422013-08-27 19:40:23 +0300173/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000174
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000175PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000176PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 PyLongObject *v;
179 unsigned long abs_ival;
180 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
181 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100182 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000183
animalize6b519982019-09-06 14:00:56 +0800184 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700185 return get_small_int((sdigit)ival);
186 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (ival < 0) {
189 /* negate: can't write this as abs_ival = -ival since that
190 invokes undefined behaviour when ival is LONG_MIN */
191 abs_ival = 0U-(unsigned long)ival;
192 sign = -1;
193 }
194 else {
195 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100196 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 /* Fast path for single-digit ints */
200 if (!(abs_ival >> PyLong_SHIFT)) {
201 v = _PyLong_New(1);
202 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100203 Py_SET_SIZE(v, sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 v->ob_digit[0] = Py_SAFE_DOWNCAST(
205 abs_ival, unsigned long, digit);
206 }
207 return (PyObject*)v;
208 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000209
Mark Dickinson249b8982009-04-27 19:41:00 +0000210#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 /* 2 digits */
212 if (!(abs_ival >> 2*PyLong_SHIFT)) {
213 v = _PyLong_New(2);
214 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100215 Py_SET_SIZE(v, 2 * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 v->ob_digit[0] = Py_SAFE_DOWNCAST(
217 abs_ival & PyLong_MASK, unsigned long, digit);
218 v->ob_digit[1] = Py_SAFE_DOWNCAST(
219 abs_ival >> PyLong_SHIFT, unsigned long, digit);
220 }
221 return (PyObject*)v;
222 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000223#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 /* Larger numbers: loop to determine number of digits */
226 t = abs_ival;
227 while (t) {
228 ++ndigits;
229 t >>= PyLong_SHIFT;
230 }
231 v = _PyLong_New(ndigits);
232 if (v != NULL) {
233 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100234 Py_SET_SIZE(v, ndigits * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 t = abs_ival;
236 while (t) {
237 *p++ = Py_SAFE_DOWNCAST(
238 t & PyLong_MASK, unsigned long, digit);
239 t >>= PyLong_SHIFT;
240 }
241 }
242 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000243}
244
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500245#define PYLONG_FROM_UINT(INT_TYPE, ival) \
246 do { \
247 if (IS_SMALL_UINT(ival)) { \
Victor Stinner6314abc2019-10-01 13:29:53 +0200248 return get_small_int((sdigit)(ival)); \
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500249 } \
250 /* Count the number of Python digits. */ \
251 Py_ssize_t ndigits = 0; \
252 INT_TYPE t = (ival); \
253 while (t) { \
254 ++ndigits; \
255 t >>= PyLong_SHIFT; \
256 } \
257 PyLongObject *v = _PyLong_New(ndigits); \
258 if (v == NULL) { \
259 return NULL; \
260 } \
261 digit *p = v->ob_digit; \
262 while ((ival)) { \
263 *p++ = (digit)((ival) & PyLong_MASK); \
264 (ival) >>= PyLong_SHIFT; \
265 } \
266 return (PyObject *)v; \
267 } while(0)
268
Serhiy Storchaka95949422013-08-27 19:40:23 +0300269/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000270
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000272PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000273{
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500274 PYLONG_FROM_UINT(unsigned long, ival);
275}
Tim Petersce9de2f2001-06-14 04:56:19 +0000276
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500277/* Create a new int object from a C unsigned long long int. */
278
279PyObject *
280PyLong_FromUnsignedLongLong(unsigned long long ival)
281{
282 PYLONG_FROM_UINT(unsigned long long, ival);
283}
284
285/* Create a new int object from a C size_t. */
286
287PyObject *
288PyLong_FromSize_t(size_t ival)
289{
290 PYLONG_FROM_UINT(size_t, ival);
Guido van Rossum53756b11997-01-03 17:14:46 +0000291}
292
Serhiy Storchaka95949422013-08-27 19:40:23 +0300293/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000294
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000295PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000296PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000297{
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500298 /* Try to get out cheap if this fits in a long. When a finite value of real
299 * floating type is converted to an integer type, the value is truncated
300 * toward zero. If the value of the integral part cannot be represented by
301 * the integer type, the behavior is undefined. Thus, we must check that
302 * value is in range (LONG_MIN - 1, LONG_MAX + 1). If a long has more bits
303 * of precision than a double, casting LONG_MIN - 1 to double may yield an
304 * approximation, but LONG_MAX + 1 is a power of two and can be represented
305 * as double exactly (assuming FLT_RADIX is 2 or 16), so for simplicity
306 * check against [-(LONG_MAX + 1), LONG_MAX + 1).
307 */
308 const double int_max = (unsigned long)LONG_MAX + 1;
309 if (-int_max < dval && dval < int_max) {
310 return PyLong_FromLong((long)dval);
311 }
312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 PyLongObject *v;
314 double frac;
315 int i, ndig, expo, neg;
316 neg = 0;
317 if (Py_IS_INFINITY(dval)) {
318 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000319 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 return NULL;
321 }
322 if (Py_IS_NAN(dval)) {
323 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000324 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 return NULL;
326 }
327 if (dval < 0.0) {
328 neg = 1;
329 dval = -dval;
330 }
331 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500332 assert(expo > 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
334 v = _PyLong_New(ndig);
335 if (v == NULL)
336 return NULL;
337 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
338 for (i = ndig; --i >= 0; ) {
339 digit bits = (digit)frac;
340 v->ob_digit[i] = bits;
341 frac = frac - (double)bits;
342 frac = ldexp(frac, PyLong_SHIFT);
343 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100344 if (neg) {
345 Py_SET_SIZE(v, -(Py_SIZE(v)));
346 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000348}
349
Thomas Wouters89f507f2006-12-13 04:49:30 +0000350/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
351 * anything about what happens when a signed integer operation overflows,
352 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700353 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000354 * (unsigned long)LONG_MAX, and for the smallest negative signed long
355 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
356 * However, some other compilers warn about applying unary minus to an
357 * unsigned operand. Hence the weird "0-".
358 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
360#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000361
Mark Dickinson20941de2020-05-27 13:43:17 +0100362/* Get a C long int from an int object or any object that has an __index__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100363 method.
364
365 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
366 the result. Otherwise *overflow is 0.
367
368 For other errors (e.g., TypeError), return -1 and set an error condition.
369 In this case *overflow will be 0.
370*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000371
372long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000373PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200376 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 unsigned long x, prev;
378 long res;
379 Py_ssize_t i;
380 int sign;
Mark Dickinson20941de2020-05-27 13:43:17 +0100381 int do_decref = 0; /* if PyNumber_Index was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 *overflow = 0;
384 if (vv == NULL) {
385 PyErr_BadInternalCall();
386 return -1;
387 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000388
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200389 if (PyLong_Check(vv)) {
390 v = (PyLongObject *)vv;
391 }
392 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300393 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200394 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 return -1;
396 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 switch (i) {
403 case -1:
404 res = -(sdigit)v->ob_digit[0];
405 break;
406 case 0:
407 res = 0;
408 break;
409 case 1:
410 res = v->ob_digit[0];
411 break;
412 default:
413 sign = 1;
414 x = 0;
415 if (i < 0) {
416 sign = -1;
417 i = -(i);
418 }
419 while (--i >= 0) {
420 prev = x;
421 x = (x << PyLong_SHIFT) | v->ob_digit[i];
422 if ((x >> PyLong_SHIFT) != prev) {
423 *overflow = sign;
424 goto exit;
425 }
426 }
427 /* Haven't lost any bits, but casting to long requires extra
428 * care (see comment above).
429 */
430 if (x <= (unsigned long)LONG_MAX) {
431 res = (long)x * sign;
432 }
433 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
434 res = LONG_MIN;
435 }
436 else {
437 *overflow = sign;
438 /* res is already set to -1 */
439 }
440 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000441 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200443 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 }
445 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000446}
447
Mark Dickinson20941de2020-05-27 13:43:17 +0100448/* Get a C long int from an int object or any object that has an __index__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100449 method. Return -1 and set an error if overflow occurs. */
450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000452PyLong_AsLong(PyObject *obj)
453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 int overflow;
455 long result = PyLong_AsLongAndOverflow(obj, &overflow);
456 if (overflow) {
457 /* XXX: could be cute and give a different
458 message for overflow == -1 */
459 PyErr_SetString(PyExc_OverflowError,
460 "Python int too large to convert to C long");
461 }
462 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000463}
464
Mark Dickinson20941de2020-05-27 13:43:17 +0100465/* Get a C int from an int object or any object that has an __index__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200466 method. Return -1 and set an error if overflow occurs. */
467
468int
469_PyLong_AsInt(PyObject *obj)
470{
471 int overflow;
472 long result = PyLong_AsLongAndOverflow(obj, &overflow);
473 if (overflow || result > INT_MAX || result < INT_MIN) {
474 /* XXX: could be cute and give a different
475 message for overflow == -1 */
476 PyErr_SetString(PyExc_OverflowError,
477 "Python int too large to convert to C int");
478 return -1;
479 }
480 return (int)result;
481}
482
Serhiy Storchaka95949422013-08-27 19:40:23 +0300483/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000484 Returns -1 and sets an error condition if overflow occurs. */
485
486Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000487PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200488 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 size_t x, prev;
490 Py_ssize_t i;
491 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (vv == NULL) {
494 PyErr_BadInternalCall();
495 return -1;
496 }
497 if (!PyLong_Check(vv)) {
498 PyErr_SetString(PyExc_TypeError, "an integer is required");
499 return -1;
500 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 v = (PyLongObject *)vv;
503 i = Py_SIZE(v);
504 switch (i) {
505 case -1: return -(sdigit)v->ob_digit[0];
506 case 0: return 0;
507 case 1: return v->ob_digit[0];
508 }
509 sign = 1;
510 x = 0;
511 if (i < 0) {
512 sign = -1;
513 i = -(i);
514 }
515 while (--i >= 0) {
516 prev = x;
517 x = (x << PyLong_SHIFT) | v->ob_digit[i];
518 if ((x >> PyLong_SHIFT) != prev)
519 goto overflow;
520 }
521 /* Haven't lost any bits, but casting to a signed type requires
522 * extra care (see comment above).
523 */
524 if (x <= (size_t)PY_SSIZE_T_MAX) {
525 return (Py_ssize_t)x * sign;
526 }
527 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
528 return PY_SSIZE_T_MIN;
529 }
530 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000531
Mark Dickinson22b20182010-05-10 21:27:53 +0000532 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 PyErr_SetString(PyExc_OverflowError,
534 "Python int too large to convert to C ssize_t");
535 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000536}
537
Serhiy Storchaka95949422013-08-27 19:40:23 +0300538/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000539 Returns -1 and sets an error condition if overflow occurs. */
540
541unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000542PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000543{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200544 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 unsigned long x, prev;
546 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (vv == NULL) {
549 PyErr_BadInternalCall();
550 return (unsigned long)-1;
551 }
552 if (!PyLong_Check(vv)) {
553 PyErr_SetString(PyExc_TypeError, "an integer is required");
554 return (unsigned long)-1;
555 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 v = (PyLongObject *)vv;
558 i = Py_SIZE(v);
559 x = 0;
560 if (i < 0) {
561 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000562 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 return (unsigned long) -1;
564 }
565 switch (i) {
566 case 0: return 0;
567 case 1: return v->ob_digit[0];
568 }
569 while (--i >= 0) {
570 prev = x;
571 x = (x << PyLong_SHIFT) | v->ob_digit[i];
572 if ((x >> PyLong_SHIFT) != prev) {
573 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100574 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000575 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 return (unsigned long) -1;
577 }
578 }
579 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000580}
581
Serhiy Storchaka95949422013-08-27 19:40:23 +0300582/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200583 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000584
585size_t
586PyLong_AsSize_t(PyObject *vv)
587{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200588 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 size_t x, prev;
590 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (vv == NULL) {
593 PyErr_BadInternalCall();
594 return (size_t) -1;
595 }
596 if (!PyLong_Check(vv)) {
597 PyErr_SetString(PyExc_TypeError, "an integer is required");
598 return (size_t)-1;
599 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 v = (PyLongObject *)vv;
602 i = Py_SIZE(v);
603 x = 0;
604 if (i < 0) {
605 PyErr_SetString(PyExc_OverflowError,
606 "can't convert negative value to size_t");
607 return (size_t) -1;
608 }
609 switch (i) {
610 case 0: return 0;
611 case 1: return v->ob_digit[0];
612 }
613 while (--i >= 0) {
614 prev = x;
615 x = (x << PyLong_SHIFT) | v->ob_digit[i];
616 if ((x >> PyLong_SHIFT) != prev) {
617 PyErr_SetString(PyExc_OverflowError,
618 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200619 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 }
621 }
622 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000623}
624
Serhiy Storchaka95949422013-08-27 19:40:23 +0300625/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000626 Returns -1 and sets an error condition if an error occurs. */
627
Guido van Rossumddefaf32007-01-14 03:31:43 +0000628static unsigned long
629_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000630{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200631 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 unsigned long x;
633 Py_ssize_t i;
634 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 if (vv == NULL || !PyLong_Check(vv)) {
637 PyErr_BadInternalCall();
638 return (unsigned long) -1;
639 }
640 v = (PyLongObject *)vv;
641 i = Py_SIZE(v);
642 switch (i) {
643 case 0: return 0;
644 case 1: return v->ob_digit[0];
645 }
646 sign = 1;
647 x = 0;
648 if (i < 0) {
649 sign = -1;
650 i = -i;
651 }
652 while (--i >= 0) {
653 x = (x << PyLong_SHIFT) | v->ob_digit[i];
654 }
655 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000656}
657
Guido van Rossumddefaf32007-01-14 03:31:43 +0000658unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200659PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PyLongObject *lo;
662 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000663
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200664 if (op == NULL) {
665 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 return (unsigned long)-1;
667 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000668
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200669 if (PyLong_Check(op)) {
670 return _PyLong_AsUnsignedLongMask(op);
671 }
672
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300673 lo = (PyLongObject *)_PyNumber_Index(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 if (lo == NULL)
675 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200676
677 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
678 Py_DECREF(lo);
679 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000680}
681
Tim Peters5b8132f2003-01-31 15:52:05 +0000682int
683_PyLong_Sign(PyObject *vv)
684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 assert(v != NULL);
688 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000691}
692
Niklas Fiekas794e7d12020-06-15 14:33:48 +0200693static int
694bit_length_digit(digit x)
695{
696 Py_BUILD_ASSERT(PyLong_SHIFT <= sizeof(unsigned long) * 8);
697 return _Py_bit_length((unsigned long)x);
698}
699
Tim Petersbaefd9e2003-01-28 20:37:45 +0000700size_t
701_PyLong_NumBits(PyObject *vv)
702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 PyLongObject *v = (PyLongObject *)vv;
704 size_t result = 0;
705 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200706 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 assert(v != NULL);
709 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200710 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
712 if (ndigits > 0) {
713 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700714 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100716 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Niklas Fiekas794e7d12020-06-15 14:33:48 +0200717 msd_bits = bit_length_digit(msd);
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200718 if (SIZE_MAX - msd_bits < result)
719 goto Overflow;
720 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 }
722 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000723
Mark Dickinson22b20182010-05-10 21:27:53 +0000724 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
726 "to express in a platform size_t");
727 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000728}
729
Tim Peters2a9b3672001-06-11 21:23:58 +0000730PyObject *
731_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000733{
Mark Dickinson22b20182010-05-10 21:27:53 +0000734 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 int incr; /* direction to move pstartbyte */
736 const unsigned char* pendbyte; /* MSB of bytes */
737 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300738 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 PyLongObject* v; /* result */
740 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 if (n == 0)
743 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 if (little_endian) {
746 pstartbyte = bytes;
747 pendbyte = bytes + n - 1;
748 incr = 1;
749 }
750 else {
751 pstartbyte = bytes + n - 1;
752 pendbyte = bytes;
753 incr = -1;
754 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (is_signed)
757 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200760 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 is positive, and leading 0xff bytes if negative. */
762 {
763 size_t i;
764 const unsigned char* p = pendbyte;
765 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000766 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000769 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 break;
771 }
772 numsignificantbytes = n - i;
773 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
774 actually has 2 significant bytes. OTOH, 0xff0001 ==
775 -0x00ffff, so we wouldn't *need* to bump it there; but we
776 do for 0xffff = -0x0001. To be safe without bothering to
777 check every case, bump it regardless. */
778 if (is_signed && numsignificantbytes < n)
779 ++numsignificantbytes;
780 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000781
Serhiy Storchaka95949422013-08-27 19:40:23 +0300782 /* How many Python int digits do we need? We have
783 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
785 /* catch overflow before it happens */
786 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
787 PyErr_SetString(PyExc_OverflowError,
788 "byte array too long to convert to int");
789 return NULL;
790 }
791 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
792 v = _PyLong_New(ndigits);
793 if (v == NULL)
794 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 /* Copy the bits over. The tricky parts are computing 2's-comp on
797 the fly for signed numbers, and dealing with the mismatch between
798 8-bit bytes and (probably) 15-bit Python digits.*/
799 {
800 size_t i;
801 twodigits carry = 1; /* for 2's-comp calculation */
802 twodigits accum = 0; /* sliding register */
803 unsigned int accumbits = 0; /* number of bits in accum */
804 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
807 twodigits thisbyte = *p;
808 /* Compute correction for 2's comp, if needed. */
809 if (is_signed) {
810 thisbyte = (0xff ^ thisbyte) + carry;
811 carry = thisbyte >> 8;
812 thisbyte &= 0xff;
813 }
814 /* Because we're going LSB to MSB, thisbyte is
815 more significant than what's already in accum,
816 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200817 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 accumbits += 8;
819 if (accumbits >= PyLong_SHIFT) {
820 /* There's enough to fill a Python digit. */
821 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000822 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 ++idigit;
824 accum >>= PyLong_SHIFT;
825 accumbits -= PyLong_SHIFT;
826 assert(accumbits < PyLong_SHIFT);
827 }
828 }
829 assert(accumbits < PyLong_SHIFT);
830 if (accumbits) {
831 assert(idigit < ndigits);
832 v->ob_digit[idigit] = (digit)accum;
833 ++idigit;
834 }
835 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000836
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100837 Py_SET_SIZE(v, is_signed ? -idigit : idigit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000839}
840
841int
842_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 unsigned char* bytes, size_t n,
844 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000847 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000849 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
851 digit carry; /* for computing 2's-comp */
852 size_t j; /* # bytes filled */
853 unsigned char* p; /* pointer to next byte in bytes */
854 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (Py_SIZE(v) < 0) {
859 ndigits = -(Py_SIZE(v));
860 if (!is_signed) {
861 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000862 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 return -1;
864 }
865 do_twos_comp = 1;
866 }
867 else {
868 ndigits = Py_SIZE(v);
869 do_twos_comp = 0;
870 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (little_endian) {
873 p = bytes;
874 pincr = 1;
875 }
876 else {
877 p = bytes + n - 1;
878 pincr = -1;
879 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 /* Copy over all the Python digits.
882 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300883 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 normalized. */
885 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
886 j = 0;
887 accum = 0;
888 accumbits = 0;
889 carry = do_twos_comp ? 1 : 0;
890 for (i = 0; i < ndigits; ++i) {
891 digit thisdigit = v->ob_digit[i];
892 if (do_twos_comp) {
893 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
894 carry = thisdigit >> PyLong_SHIFT;
895 thisdigit &= PyLong_MASK;
896 }
897 /* Because we're going LSB to MSB, thisdigit is more
898 significant than what's already in accum, so needs to be
899 prepended to accum. */
900 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 /* The most-significant digit may be (probably is) at least
903 partly empty. */
904 if (i == ndigits - 1) {
905 /* Count # of sign bits -- they needn't be stored,
906 * although for signed conversion we need later to
907 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000908 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 while (s != 0) {
910 s >>= 1;
911 accumbits++;
912 }
913 }
914 else
915 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* Store as many bytes as possible. */
918 while (accumbits >= 8) {
919 if (j >= n)
920 goto Overflow;
921 ++j;
922 *p = (unsigned char)(accum & 0xff);
923 p += pincr;
924 accumbits -= 8;
925 accum >>= 8;
926 }
927 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Store the straggler (if any). */
930 assert(accumbits < 8);
931 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
932 if (accumbits > 0) {
933 if (j >= n)
934 goto Overflow;
935 ++j;
936 if (do_twos_comp) {
937 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300938 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 infinite supply of sign bits). */
940 accum |= (~(twodigits)0) << accumbits;
941 }
942 *p = (unsigned char)(accum & 0xff);
943 p += pincr;
944 }
945 else if (j == n && n > 0 && is_signed) {
946 /* The main loop filled the byte array exactly, so the code
947 just above didn't get to ensure there's a sign bit, and the
948 loop below wouldn't add one either. Make sure a sign bit
949 exists. */
950 unsigned char msb = *(p - pincr);
951 int sign_bit_set = msb >= 0x80;
952 assert(accumbits == 0);
953 if (sign_bit_set == do_twos_comp)
954 return 0;
955 else
956 goto Overflow;
957 }
Tim Peters05607ad2001-06-13 21:01:27 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 /* Fill remaining bytes with copies of the sign bit. */
960 {
961 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
962 for ( ; j < n; ++j, p += pincr)
963 *p = signbyte;
964 }
Tim Peters05607ad2001-06-13 21:01:27 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000967
Mark Dickinson22b20182010-05-10 21:27:53 +0000968 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
970 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000971
Tim Peters2a9b3672001-06-11 21:23:58 +0000972}
973
Serhiy Storchaka95949422013-08-27 19:40:23 +0300974/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000975
976PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000977PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000978{
Mark Dickinson91044792012-10-18 19:21:43 +0100979#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -0700980 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100981#else
982
Tim Peters70128a12001-06-16 08:48:40 +0000983#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700984# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000985#endif
Benjamin Petersonca470632016-09-06 13:47:26 -0700986 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100987#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000988
Guido van Rossum78694d91998-09-18 14:14:13 +0000989}
990
Serhiy Storchaka95949422013-08-27 19:40:23 +0300991/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000992
993void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000994PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000995{
Tim Peters70128a12001-06-16 08:48:40 +0000996#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1000 x = PyLong_AsLong(vv);
1001 else
1002 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001003#else
Tim Peters70128a12001-06-16 08:48:40 +00001004
Tim Peters70128a12001-06-16 08:48:40 +00001005#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001006# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001007#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001008 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1011 x = PyLong_AsLongLong(vv);
1012 else
1013 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001014
1015#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 if (x == -1 && PyErr_Occurred())
1018 return NULL;
1019 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001020}
1021
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001022/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001023 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001024 */
1025
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001026#define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001027
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001028/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001029
1030PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001031PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001034 unsigned long long abs_ival;
1035 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 int ndigits = 0;
1037 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001038
animalize6b519982019-09-06 14:00:56 +08001039 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001040 return get_small_int((sdigit)ival);
1041 }
1042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (ival < 0) {
1044 /* avoid signed overflow on negation; see comments
1045 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001046 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 negative = 1;
1048 }
1049 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001050 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 /* Count the number of Python digits.
1054 We used to pick 5 ("big enough for anything"), but that's a
1055 waste of time and space given that 5*15 = 75 bits are rarely
1056 needed. */
1057 t = abs_ival;
1058 while (t) {
1059 ++ndigits;
1060 t >>= PyLong_SHIFT;
1061 }
1062 v = _PyLong_New(ndigits);
1063 if (v != NULL) {
1064 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001065 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 t = abs_ival;
1067 while (t) {
1068 *p++ = (digit)(t & PyLong_MASK);
1069 t >>= PyLong_SHIFT;
1070 }
1071 }
1072 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001073}
1074
Serhiy Storchaka95949422013-08-27 19:40:23 +03001075/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001076
1077PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001078PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 PyLongObject *v;
1081 size_t abs_ival;
1082 size_t t; /* unsigned so >> doesn't propagate sign bit */
1083 int ndigits = 0;
1084 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001085
animalize6b519982019-09-06 14:00:56 +08001086 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001087 return get_small_int((sdigit)ival);
1088 }
1089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 if (ival < 0) {
1091 /* avoid signed overflow when ival = SIZE_T_MIN */
1092 abs_ival = (size_t)(-1-ival)+1;
1093 negative = 1;
1094 }
1095 else {
1096 abs_ival = (size_t)ival;
1097 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 /* Count the number of Python digits. */
1100 t = abs_ival;
1101 while (t) {
1102 ++ndigits;
1103 t >>= PyLong_SHIFT;
1104 }
1105 v = _PyLong_New(ndigits);
1106 if (v != NULL) {
1107 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001108 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 t = abs_ival;
1110 while (t) {
1111 *p++ = (digit)(t & PyLong_MASK);
1112 t >>= PyLong_SHIFT;
1113 }
1114 }
1115 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001116}
1117
Serhiy Storchaka95949422013-08-27 19:40:23 +03001118/* Get a C long long int from an int object or any object that has an
Mark Dickinson20941de2020-05-27 13:43:17 +01001119 __index__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001120
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001121long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001122PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001125 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 int res;
Mark Dickinson20941de2020-05-27 13:43:17 +01001127 int do_decref = 0; /* if PyNumber_Index was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 if (vv == NULL) {
1130 PyErr_BadInternalCall();
1131 return -1;
1132 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001133
1134 if (PyLong_Check(vv)) {
1135 v = (PyLongObject *)vv;
1136 }
1137 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001138 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001139 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001141 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001143
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001144 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001146 case -1:
1147 bytes = -(sdigit)v->ob_digit[0];
1148 break;
1149 case 0:
1150 bytes = 0;
1151 break;
1152 case 1:
1153 bytes = v->ob_digit[0];
1154 break;
1155 default:
1156 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001157 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001159 if (do_decref) {
1160 Py_DECREF(v);
1161 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001162
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001163 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001165 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 else
1167 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001168}
1169
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001170/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001171 Return -1 and set an error if overflow occurs. */
1172
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001173unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001174PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001177 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001179
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001180 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001182 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001184 if (!PyLong_Check(vv)) {
1185 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001186 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001187 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 v = (PyLongObject*)vv;
1190 switch(Py_SIZE(v)) {
1191 case 0: return 0;
1192 case 1: return v->ob_digit[0];
1193 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001194
Mark Dickinson22b20182010-05-10 21:27:53 +00001195 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001196 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001197
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001198 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001200 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 else
1202 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001203}
Tim Petersd1a7da62001-06-13 00:35:57 +00001204
Serhiy Storchaka95949422013-08-27 19:40:23 +03001205/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001206 Returns -1 and sets an error condition if an error occurs. */
1207
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001208static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001209_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001210{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001211 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001212 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 Py_ssize_t i;
1214 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 if (vv == NULL || !PyLong_Check(vv)) {
1217 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001218 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 }
1220 v = (PyLongObject *)vv;
1221 switch(Py_SIZE(v)) {
1222 case 0: return 0;
1223 case 1: return v->ob_digit[0];
1224 }
1225 i = Py_SIZE(v);
1226 sign = 1;
1227 x = 0;
1228 if (i < 0) {
1229 sign = -1;
1230 i = -i;
1231 }
1232 while (--i >= 0) {
1233 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1234 }
1235 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001236}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001237
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001238unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001239PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001242 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001243
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001244 if (op == NULL) {
1245 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001246 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001248
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001249 if (PyLong_Check(op)) {
1250 return _PyLong_AsUnsignedLongLongMask(op);
1251 }
1252
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001253 lo = (PyLongObject *)_PyNumber_Index(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001255 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001256
1257 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1258 Py_DECREF(lo);
1259 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001260}
Tim Petersd1a7da62001-06-13 00:35:57 +00001261
Serhiy Storchaka95949422013-08-27 19:40:23 +03001262/* Get a C long long int from an int object or any object that has an
Mark Dickinson20941de2020-05-27 13:43:17 +01001263 __index__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001264
Mark Dickinson8d48b432011-10-23 20:47:14 +01001265 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1266 the result. Otherwise *overflow is 0.
1267
1268 For other errors (e.g., TypeError), return -1 and set an error condition.
1269 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001270*/
1271
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001272long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001273PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001276 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001277 unsigned long long x, prev;
1278 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 Py_ssize_t i;
1280 int sign;
Mark Dickinson20941de2020-05-27 13:43:17 +01001281 int do_decref = 0; /* if PyNumber_Index was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 *overflow = 0;
1284 if (vv == NULL) {
1285 PyErr_BadInternalCall();
1286 return -1;
1287 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001288
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001289 if (PyLong_Check(vv)) {
1290 v = (PyLongObject *)vv;
1291 }
1292 else {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001293 v = (PyLongObject *)_PyNumber_Index(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001294 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 return -1;
1296 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 switch (i) {
1303 case -1:
1304 res = -(sdigit)v->ob_digit[0];
1305 break;
1306 case 0:
1307 res = 0;
1308 break;
1309 case 1:
1310 res = v->ob_digit[0];
1311 break;
1312 default:
1313 sign = 1;
1314 x = 0;
1315 if (i < 0) {
1316 sign = -1;
1317 i = -(i);
1318 }
1319 while (--i >= 0) {
1320 prev = x;
1321 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1322 if ((x >> PyLong_SHIFT) != prev) {
1323 *overflow = sign;
1324 goto exit;
1325 }
1326 }
1327 /* Haven't lost any bits, but casting to long requires extra
1328 * care (see comment above).
1329 */
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001330 if (x <= (unsigned long long)LLONG_MAX) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001331 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 }
1333 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001334 res = LLONG_MIN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 }
1336 else {
1337 *overflow = sign;
1338 /* res is already set to -1 */
1339 }
1340 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001341 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001343 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 }
1345 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001346}
1347
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001348int
1349_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1350{
1351 unsigned long uval;
1352
1353 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1354 PyErr_SetString(PyExc_ValueError, "value must be positive");
1355 return 0;
1356 }
1357 uval = PyLong_AsUnsignedLong(obj);
1358 if (uval == (unsigned long)-1 && PyErr_Occurred())
1359 return 0;
1360 if (uval > USHRT_MAX) {
1361 PyErr_SetString(PyExc_OverflowError,
1362 "Python int too large for C unsigned short");
1363 return 0;
1364 }
1365
1366 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1367 return 1;
1368}
1369
1370int
1371_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1372{
1373 unsigned long uval;
1374
1375 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1376 PyErr_SetString(PyExc_ValueError, "value must be positive");
1377 return 0;
1378 }
1379 uval = PyLong_AsUnsignedLong(obj);
1380 if (uval == (unsigned long)-1 && PyErr_Occurred())
1381 return 0;
1382 if (uval > UINT_MAX) {
1383 PyErr_SetString(PyExc_OverflowError,
1384 "Python int too large for C unsigned int");
1385 return 0;
1386 }
1387
1388 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1389 return 1;
1390}
1391
1392int
1393_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1394{
1395 unsigned long uval;
1396
1397 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1398 PyErr_SetString(PyExc_ValueError, "value must be positive");
1399 return 0;
1400 }
1401 uval = PyLong_AsUnsignedLong(obj);
1402 if (uval == (unsigned long)-1 && PyErr_Occurred())
1403 return 0;
1404
1405 *(unsigned long *)ptr = uval;
1406 return 1;
1407}
1408
1409int
1410_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1411{
1412 unsigned long long uval;
1413
1414 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1415 PyErr_SetString(PyExc_ValueError, "value must be positive");
1416 return 0;
1417 }
1418 uval = PyLong_AsUnsignedLongLong(obj);
1419 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1420 return 0;
1421
1422 *(unsigned long long *)ptr = uval;
1423 return 1;
1424}
1425
1426int
1427_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1428{
1429 size_t uval;
1430
1431 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1432 PyErr_SetString(PyExc_ValueError, "value must be positive");
1433 return 0;
1434 }
1435 uval = PyLong_AsSize_t(obj);
1436 if (uval == (size_t)-1 && PyErr_Occurred())
1437 return 0;
1438
1439 *(size_t *)ptr = uval;
1440 return 1;
1441}
1442
1443
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001444#define CHECK_BINOP(v,w) \
1445 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001446 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1447 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001448 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001449
Tim Peters877a2122002-08-12 05:09:36 +00001450/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1451 * is modified in place, by adding y to it. Carries are propagated as far as
1452 * x[m-1], and the remaining carry (0 or 1) is returned.
1453 */
1454static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001455v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 Py_ssize_t i;
1458 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 assert(m >= n);
1461 for (i = 0; i < n; ++i) {
1462 carry += x[i] + y[i];
1463 x[i] = carry & PyLong_MASK;
1464 carry >>= PyLong_SHIFT;
1465 assert((carry & 1) == carry);
1466 }
1467 for (; carry && i < m; ++i) {
1468 carry += x[i];
1469 x[i] = carry & PyLong_MASK;
1470 carry >>= PyLong_SHIFT;
1471 assert((carry & 1) == carry);
1472 }
1473 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001474}
1475
1476/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1477 * is modified in place, by subtracting y from it. Borrows are propagated as
1478 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1479 */
1480static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001481v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 Py_ssize_t i;
1484 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 assert(m >= n);
1487 for (i = 0; i < n; ++i) {
1488 borrow = x[i] - y[i] - borrow;
1489 x[i] = borrow & PyLong_MASK;
1490 borrow >>= PyLong_SHIFT;
1491 borrow &= 1; /* keep only 1 sign bit */
1492 }
1493 for (; borrow && i < m; ++i) {
1494 borrow = x[i] - borrow;
1495 x[i] = borrow & PyLong_MASK;
1496 borrow >>= PyLong_SHIFT;
1497 borrow &= 1;
1498 }
1499 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001500}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001501
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001502/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1503 * result in z[0:m], and return the d bits shifted out of the top.
1504 */
1505static digit
1506v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 Py_ssize_t i;
1509 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 assert(0 <= d && d < PyLong_SHIFT);
1512 for (i=0; i < m; i++) {
1513 twodigits acc = (twodigits)a[i] << d | carry;
1514 z[i] = (digit)acc & PyLong_MASK;
1515 carry = (digit)(acc >> PyLong_SHIFT);
1516 }
1517 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001518}
1519
1520/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1521 * result in z[0:m], and return the d bits shifted out of the bottom.
1522 */
1523static digit
1524v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 Py_ssize_t i;
1527 digit carry = 0;
1528 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 assert(0 <= d && d < PyLong_SHIFT);
1531 for (i=m; i-- > 0;) {
1532 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1533 carry = (digit)acc & mask;
1534 z[i] = (digit)(acc >> d);
1535 }
1536 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001537}
1538
Tim Peters212e6142001-07-14 12:23:19 +00001539/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1540 in pout, and returning the remainder. pin and pout point at the LSD.
1541 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001542 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001543 immutable. */
1544
1545static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001546inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 assert(n > 0 && n <= PyLong_MASK);
1551 pin += size;
1552 pout += size;
1553 while (--size >= 0) {
1554 digit hi;
1555 rem = (rem << PyLong_SHIFT) | *--pin;
1556 *--pout = hi = (digit)(rem / n);
1557 rem -= (twodigits)hi * n;
1558 }
1559 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001560}
1561
Serhiy Storchaka95949422013-08-27 19:40:23 +03001562/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001563 (as function result) and the remainder (through *prem).
1564 The sign of a is ignored; n should not be zero. */
1565
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001566static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001567divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001568{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001569 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 assert(n > 0 && n <= PyLong_MASK);
1573 z = _PyLong_New(size);
1574 if (z == NULL)
1575 return NULL;
1576 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1577 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001578}
1579
Serhiy Storchaka95949422013-08-27 19:40:23 +03001580/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001581 string. (Return value is non-shared so that callers can modify the
1582 returned value if necessary.) */
1583
Victor Stinnerd3f08822012-05-29 12:57:52 +02001584static int
1585long_to_decimal_string_internal(PyObject *aa,
1586 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001587 _PyUnicodeWriter *writer,
1588 _PyBytesWriter *bytes_writer,
1589 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001592 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 Py_ssize_t size, strlen, size_a, i, j;
1594 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001596 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001597 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 a = (PyLongObject *)aa;
1600 if (a == NULL || !PyLong_Check(a)) {
1601 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001602 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001604 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 /* quick and dirty upper bound for the number of digits
1608 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 But log2(a) < size_a * PyLong_SHIFT, and
1613 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001614 > 3.3 * _PyLong_DECIMAL_SHIFT
1615
1616 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1617 size_a + size_a / d < size_a + size_a / floor(d),
1618 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1619 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001621 d = (33 * _PyLong_DECIMAL_SHIFT) /
1622 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1623 assert(size_a < PY_SSIZE_T_MAX/2);
1624 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 scratch = _PyLong_New(size);
1626 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001627 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 /* convert array of base _PyLong_BASE digits in pin to an array of
1630 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1631 Volume 2 (3rd edn), section 4.4, Method 1b). */
1632 pin = a->ob_digit;
1633 pout = scratch->ob_digit;
1634 size = 0;
1635 for (i = size_a; --i >= 0; ) {
1636 digit hi = pin[i];
1637 for (j = 0; j < size; j++) {
1638 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1639 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1640 pout[j] = (digit)(z - (twodigits)hi *
1641 _PyLong_DECIMAL_BASE);
1642 }
1643 while (hi) {
1644 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1645 hi /= _PyLong_DECIMAL_BASE;
1646 }
1647 /* check for keyboard interrupt */
1648 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001649 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001650 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001651 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 }
1653 /* pout should have at least one digit, so that the case when a = 0
1654 works correctly */
1655 if (size == 0)
1656 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 /* calculate exact length of output string, and allocate */
1659 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1660 tenpow = 10;
1661 rem = pout[size-1];
1662 while (rem >= tenpow) {
1663 tenpow *= 10;
1664 strlen++;
1665 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001666 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001667 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1668 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001669 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001670 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001671 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001673 else if (bytes_writer) {
1674 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1675 if (*bytes_str == NULL) {
1676 Py_DECREF(scratch);
1677 return -1;
1678 }
1679 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001680 else {
1681 str = PyUnicode_New(strlen, '9');
1682 if (str == NULL) {
1683 Py_DECREF(scratch);
1684 return -1;
1685 }
1686 kind = PyUnicode_KIND(str);
1687 }
1688
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001689#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001690 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001691 /* pout[0] through pout[size-2] contribute exactly \
1692 _PyLong_DECIMAL_SHIFT digits each */ \
1693 for (i=0; i < size - 1; i++) { \
1694 rem = pout[i]; \
1695 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1696 *--p = '0' + rem % 10; \
1697 rem /= 10; \
1698 } \
1699 } \
1700 /* pout[size-1]: always produce at least one decimal digit */ \
1701 rem = pout[i]; \
1702 do { \
1703 *--p = '0' + rem % 10; \
1704 rem /= 10; \
1705 } while (rem != 0); \
1706 \
1707 /* and sign */ \
1708 if (negative) \
1709 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001710 } while (0)
1711
1712#define WRITE_UNICODE_DIGITS(TYPE) \
1713 do { \
1714 if (writer) \
1715 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1716 else \
1717 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1718 \
1719 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001720 \
1721 /* check we've counted correctly */ \
1722 if (writer) \
1723 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1724 else \
1725 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1726 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001729 if (bytes_writer) {
1730 char *p = *bytes_str + strlen;
1731 WRITE_DIGITS(p);
1732 assert(p == *bytes_str);
1733 }
1734 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001735 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001736 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001738 else if (kind == PyUnicode_2BYTE_KIND) {
1739 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001740 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001741 }
1742 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001743 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001744 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001745 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001746 }
1747#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001748#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001751 if (writer) {
1752 writer->pos += strlen;
1753 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001754 else if (bytes_writer) {
1755 (*bytes_str) += strlen;
1756 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001757 else {
1758 assert(_PyUnicode_CheckConsistency(str, 1));
1759 *p_output = (PyObject *)str;
1760 }
1761 return 0;
1762}
1763
1764static PyObject *
1765long_to_decimal_string(PyObject *aa)
1766{
1767 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001768 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001769 return NULL;
1770 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001771}
1772
Serhiy Storchaka95949422013-08-27 19:40:23 +03001773/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001774 which should be one of 2, 8 or 16. Return a string object.
1775 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1776 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001777
Victor Stinnerd3f08822012-05-29 12:57:52 +02001778static int
1779long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001780 PyObject **p_output, _PyUnicodeWriter *writer,
1781 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001782{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001783 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001784 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001785 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001787 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001788 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001790
Victor Stinnerd3f08822012-05-29 12:57:52 +02001791 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 if (a == NULL || !PyLong_Check(a)) {
1793 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001794 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001796 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001797 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 /* Compute a rough upper bound for the length of the string */
1800 switch (base) {
1801 case 16:
1802 bits = 4;
1803 break;
1804 case 8:
1805 bits = 3;
1806 break;
1807 case 2:
1808 bits = 1;
1809 break;
1810 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001811 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001813
Mark Dickinsone2846542012-04-20 21:21:24 +01001814 /* Compute exact length 'sz' of output string. */
1815 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001816 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001817 }
1818 else {
1819 Py_ssize_t size_a_in_bits;
1820 /* Ensure overflow doesn't occur during computation of sz. */
1821 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1822 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001823 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001824 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001825 }
1826 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
Niklas Fiekas794e7d12020-06-15 14:33:48 +02001827 bit_length_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001828 /* Allow 1 character for a '-' sign. */
1829 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1830 }
1831 if (alternate) {
1832 /* 2 characters for prefix */
1833 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001834 }
1835
Victor Stinnerd3f08822012-05-29 12:57:52 +02001836 if (writer) {
1837 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1838 return -1;
1839 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001841 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001842 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1843 if (*bytes_str == NULL)
1844 return -1;
1845 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001847 v = PyUnicode_New(sz, 'x');
1848 if (v == NULL)
1849 return -1;
1850 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001852
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001853#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001854 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001855 if (size_a == 0) { \
1856 *--p = '0'; \
1857 } \
1858 else { \
1859 /* JRH: special case for power-of-2 bases */ \
1860 twodigits accum = 0; \
1861 int accumbits = 0; /* # of bits in accum */ \
1862 Py_ssize_t i; \
1863 for (i = 0; i < size_a; ++i) { \
1864 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1865 accumbits += PyLong_SHIFT; \
1866 assert(accumbits >= bits); \
1867 do { \
1868 char cdigit; \
1869 cdigit = (char)(accum & (base - 1)); \
1870 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1871 *--p = cdigit; \
1872 accumbits -= bits; \
1873 accum >>= bits; \
1874 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1875 } \
1876 } \
1877 \
1878 if (alternate) { \
1879 if (base == 16) \
1880 *--p = 'x'; \
1881 else if (base == 8) \
1882 *--p = 'o'; \
1883 else /* (base == 2) */ \
1884 *--p = 'b'; \
1885 *--p = '0'; \
1886 } \
1887 if (negative) \
1888 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001889 } while (0)
1890
1891#define WRITE_UNICODE_DIGITS(TYPE) \
1892 do { \
1893 if (writer) \
1894 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1895 else \
1896 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1897 \
1898 WRITE_DIGITS(p); \
1899 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001900 if (writer) \
1901 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1902 else \
1903 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1904 } while (0)
1905
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001906 if (bytes_writer) {
1907 char *p = *bytes_str + sz;
1908 WRITE_DIGITS(p);
1909 assert(p == *bytes_str);
1910 }
1911 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001912 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001913 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001914 }
1915 else if (kind == PyUnicode_2BYTE_KIND) {
1916 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001917 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001918 }
1919 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001920 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001921 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001922 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001923 }
1924#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001925#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02001926
1927 if (writer) {
1928 writer->pos += sz;
1929 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001930 else if (bytes_writer) {
1931 (*bytes_str) += sz;
1932 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001933 else {
1934 assert(_PyUnicode_CheckConsistency(v, 1));
1935 *p_output = v;
1936 }
1937 return 0;
1938}
1939
1940PyObject *
1941_PyLong_Format(PyObject *obj, int base)
1942{
1943 PyObject *str;
1944 int err;
1945 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001946 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001947 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001948 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001949 if (err == -1)
1950 return NULL;
1951 return str;
1952}
1953
1954int
1955_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1956 PyObject *obj,
1957 int base, int alternate)
1958{
1959 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001960 return long_to_decimal_string_internal(obj, NULL, writer,
1961 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001962 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001963 return long_format_binary(obj, base, alternate, NULL, writer,
1964 NULL, NULL);
1965}
1966
1967char*
1968_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
1969 PyObject *obj,
1970 int base, int alternate)
1971{
1972 char *str2;
1973 int res;
1974 str2 = str;
1975 if (base == 10)
1976 res = long_to_decimal_string_internal(obj, NULL, NULL,
1977 writer, &str2);
1978 else
1979 res = long_format_binary(obj, base, alternate, NULL, NULL,
1980 writer, &str2);
1981 if (res < 0)
1982 return NULL;
1983 assert(str2 != NULL);
1984 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001985}
1986
Thomas Wouters477c8d52006-05-27 19:21:47 +00001987/* Table of digit values for 8-bit string -> integer conversion.
1988 * '0' maps to 0, ..., '9' maps to 9.
1989 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1990 * All other indices map to 37.
1991 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001992 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001993 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001994unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1996 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1997 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1998 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1999 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2000 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2001 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2002 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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,
2008 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2009 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2010 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002011};
2012
2013/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002014 * 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 +03002015 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002016 * The point to this routine is that it takes time linear in the number of
2017 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002018 *
2019 * Return values:
2020 * -1 on syntax error (exception needs to be set, *res is untouched)
2021 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002022 */
Brett Cannona721aba2016-09-09 14:57:09 -07002023static int
2024long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002025{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002026 const char *p = *str;
2027 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002028 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002029 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 int bits_per_char;
2031 Py_ssize_t n;
2032 PyLongObject *z;
2033 twodigits accum;
2034 int bits_in_accum;
2035 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2038 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002039 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002041 }
2042 /* count digits and set p to end-of-string */
2043 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2044 if (*p == '_') {
2045 if (prev == '_') {
2046 *str = p - 1;
2047 return -1;
2048 }
2049 } else {
2050 ++digits;
2051 }
2052 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002054 }
2055 if (prev == '_') {
2056 /* Trailing underscore not allowed. */
2057 *str = p - 1;
2058 return -1;
2059 }
2060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002062 /* n <- the number of Python digits needed,
2063 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2064 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 PyErr_SetString(PyExc_ValueError,
2066 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002067 *res = NULL;
2068 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002070 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002072 if (z == NULL) {
2073 *res = NULL;
2074 return 0;
2075 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002076 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 * from least to most significant in both.
2078 */
2079 accum = 0;
2080 bits_in_accum = 0;
2081 pdigit = z->ob_digit;
2082 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002083 int k;
2084 if (*p == '_') {
2085 continue;
2086 }
2087 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 assert(k >= 0 && k < base);
2089 accum |= (twodigits)k << bits_in_accum;
2090 bits_in_accum += bits_per_char;
2091 if (bits_in_accum >= PyLong_SHIFT) {
2092 *pdigit++ = (digit)(accum & PyLong_MASK);
2093 assert(pdigit - z->ob_digit <= n);
2094 accum >>= PyLong_SHIFT;
2095 bits_in_accum -= PyLong_SHIFT;
2096 assert(bits_in_accum < PyLong_SHIFT);
2097 }
2098 }
2099 if (bits_in_accum) {
2100 assert(bits_in_accum <= PyLong_SHIFT);
2101 *pdigit++ = (digit)accum;
2102 assert(pdigit - z->ob_digit <= n);
2103 }
2104 while (pdigit - z->ob_digit < n)
2105 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002106 *res = long_normalize(z);
2107 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002108}
2109
Serhiy Storchaka95949422013-08-27 19:40:23 +03002110/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002111 * ignored.
2112 *
2113 * If successful, a PyLong object will be returned and 'pend' will be pointing
2114 * to the first unused byte unless it's NULL.
2115 *
2116 * If unsuccessful, NULL will be returned.
2117 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002118PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002119PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002122 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 PyLongObject *z = NULL;
2124 PyObject *strobj;
2125 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if ((base != 0 && base < 2) || base > 36) {
2128 PyErr_SetString(PyExc_ValueError,
2129 "int() arg 2 must be >= 2 and <= 36");
2130 return NULL;
2131 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002132 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002134 }
2135 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002137 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 else if (*str == '-') {
2139 ++str;
2140 sign = -1;
2141 }
2142 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002143 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002145 }
2146 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002148 }
2149 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002151 }
2152 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002154 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 else {
2156 /* "old" (C-style) octal literal, now invalid.
2157 it might still be zero though */
2158 error_if_nonzero = 1;
2159 base = 10;
2160 }
2161 }
2162 if (str[0] == '0' &&
2163 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2164 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002165 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002167 /* One underscore allowed here. */
2168 if (*str == '_') {
2169 ++str;
2170 }
2171 }
2172 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002173 /* May not start with underscores. */
2174 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002175 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002178 if ((base & (base - 1)) == 0) {
2179 int res = long_from_binary_base(&str, base, &z);
2180 if (res < 0) {
2181 /* Syntax error. */
2182 goto onError;
2183 }
2184 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002186/***
2187Binary bases can be converted in time linear in the number of digits, because
2188Python's representation base is binary. Other bases (including decimal!) use
2189the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002190
Thomas Wouters477c8d52006-05-27 19:21:47 +00002191First some math: the largest integer that can be expressed in N base-B digits
2192is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2193case number of Python digits needed to hold it is the smallest integer n s.t.
2194
2195 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2196 BASE**n >= B**N [taking logs to base BASE]
2197 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2198
2199The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002200this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002201and the result is computed into it.
2202
2203The input string is actually treated as being in base base**i (i.e., i digits
2204are processed at a time), where two more static arrays hold:
2205
2206 convwidth_base[base] = the largest integer i such that base**i <= BASE
2207 convmultmax_base[base] = base ** convwidth_base[base]
2208
2209The first of these is the largest i such that i consecutive input digits
2210must fit in a single Python digit. The second is effectively the input
2211base we're really using.
2212
2213Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2214convmultmax_base[base], the result is "simply"
2215
2216 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2217
2218where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002219
2220Error analysis: as above, the number of Python digits `n` needed is worst-
2221case
2222
2223 n >= N * log(B)/log(BASE)
2224
2225where `N` is the number of input digits in base `B`. This is computed via
2226
2227 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2228
2229below. Two numeric concerns are how much space this can waste, and whether
2230the computed result can be too small. To be concrete, assume BASE = 2**15,
2231which is the default (and it's unlikely anyone changes that).
2232
2233Waste isn't a problem: provided the first input digit isn't 0, the difference
2234between the worst-case input with N digits and the smallest input with N
2235digits is about a factor of B, but B is small compared to BASE so at most
2236one allocated Python digit can remain unused on that count. If
2237N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2238and adding 1 returns a result 1 larger than necessary. However, that can't
2239happen: whenever B is a power of 2, long_from_binary_base() is called
2240instead, and it's impossible for B**i to be an integer power of 2**15 when
2241B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2242an exact integer when B is not a power of 2, since B**i has a prime factor
2243other than 2 in that case, but (2**15)**j's only prime factor is 2).
2244
2245The computed result can be too small if the true value of N*log(B)/log(BASE)
2246is a little bit larger than an exact integer, but due to roundoff errors (in
2247computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2248yields a numeric result a little less than that integer. Unfortunately, "how
2249close can a transcendental function get to an integer over some range?"
2250questions are generally theoretically intractable. Computer analysis via
2251continued fractions is practical: expand log(B)/log(BASE) via continued
2252fractions, giving a sequence i/j of "the best" rational approximations. Then
2253j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2254we can get very close to being in trouble, but very rarely. For example,
225576573 is a denominator in one of the continued-fraction approximations to
2256log(10)/log(2**15), and indeed:
2257
2258 >>> log(10)/log(2**15)*76573
2259 16958.000000654003
2260
2261is very close to an integer. If we were working with IEEE single-precision,
2262rounding errors could kill us. Finding worst cases in IEEE double-precision
2263requires better-than-double-precision log() functions, and Tim didn't bother.
2264Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002265new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002266This should happen extremely rarely, and in fact I don't have a test case
2267that triggers it(!). Instead the code was tested by artificially allocating
2268just 1 digit at the start, so that the copying code was exercised for every
2269digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002270***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002271 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002273 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 int i;
2275 int convwidth;
2276 twodigits convmultmax, convmult;
2277 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002278 const char *scan, *lastdigit;
2279 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 static double log_base_BASE[37] = {0.0e0,};
2282 static int convwidth_base[37] = {0,};
2283 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 if (log_base_BASE[base] == 0.0) {
2286 twodigits convmax = base;
2287 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002288
Mark Dickinson22b20182010-05-10 21:27:53 +00002289 log_base_BASE[base] = (log((double)base) /
2290 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 for (;;) {
2292 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002293 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002295 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 convmax = next;
2297 ++i;
2298 }
2299 convmultmax_base[base] = convmax;
2300 assert(i > 0);
2301 convwidth_base[base] = i;
2302 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 /* Find length of the string of numeric characters. */
2305 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002306 lastdigit = str;
2307
2308 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2309 if (*scan == '_') {
2310 if (prev == '_') {
2311 /* Only one underscore allowed. */
2312 str = lastdigit + 1;
2313 goto onError;
2314 }
2315 }
2316 else {
2317 ++digits;
2318 lastdigit = scan;
2319 }
2320 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002322 }
2323 if (prev == '_') {
2324 /* Trailing underscore not allowed. */
2325 /* Set error pointer to first underscore. */
2326 str = lastdigit + 1;
2327 goto onError;
2328 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002329
Serhiy Storchaka95949422013-08-27 19:40:23 +03002330 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 * integer with this base and length. Note that there's no
2332 * need to initialize z->ob_digit -- no slot is read up before
2333 * being stored into.
2334 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002335 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2336 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002337 /* The same exception as in _PyLong_New(). */
2338 PyErr_SetString(PyExc_OverflowError,
2339 "too many digits in integer");
2340 return NULL;
2341 }
2342 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 /* Uncomment next line to test exceedingly rare copy code */
2344 /* size_z = 1; */
2345 assert(size_z > 0);
2346 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002347 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002349 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002350 Py_SET_SIZE(z, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 /* `convwidth` consecutive input digits are treated as a single
2353 * digit in base `convmultmax`.
2354 */
2355 convwidth = convwidth_base[base];
2356 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 /* Work ;-) */
2359 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002360 if (*str == '_') {
2361 str++;
2362 continue;
2363 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 /* grab up to convwidth digits from the input string */
2365 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002366 for (i = 1; i < convwidth && str != scan; ++str) {
2367 if (*str == '_') {
2368 continue;
2369 }
2370 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002372 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 assert(c < PyLong_BASE);
2374 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 convmult = convmultmax;
2377 /* Calculate the shift only if we couldn't get
2378 * convwidth digits.
2379 */
2380 if (i != convwidth) {
2381 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002382 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002384 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 /* Multiply z by convmult, and add c. */
2388 pz = z->ob_digit;
2389 pzstop = pz + Py_SIZE(z);
2390 for (; pz < pzstop; ++pz) {
2391 c += (twodigits)*pz * convmult;
2392 *pz = (digit)(c & PyLong_MASK);
2393 c >>= PyLong_SHIFT;
2394 }
2395 /* carry off the current end? */
2396 if (c) {
2397 assert(c < PyLong_BASE);
2398 if (Py_SIZE(z) < size_z) {
2399 *pz = (digit)c;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002400 Py_SET_SIZE(z, Py_SIZE(z) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 }
2402 else {
2403 PyLongObject *tmp;
2404 /* Extremely rare. Get more space. */
2405 assert(Py_SIZE(z) == size_z);
2406 tmp = _PyLong_New(size_z + 1);
2407 if (tmp == NULL) {
2408 Py_DECREF(z);
2409 return NULL;
2410 }
2411 memcpy(tmp->ob_digit,
2412 z->ob_digit,
2413 sizeof(digit) * size_z);
2414 Py_DECREF(z);
2415 z = tmp;
2416 z->ob_digit[size_z] = (digit)c;
2417 ++size_z;
2418 }
2419 }
2420 }
2421 }
Brett Cannona721aba2016-09-09 14:57:09 -07002422 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002424 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 if (error_if_nonzero) {
2426 /* reset the base to 0, else the exception message
2427 doesn't make too much sense */
2428 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002429 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 /* there might still be other problems, therefore base
2433 remains zero here for the same reason */
2434 }
Brett Cannona721aba2016-09-09 14:57:09 -07002435 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002437 }
2438 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002439 Py_SET_SIZE(z, -(Py_SIZE(z)));
Brett Cannona721aba2016-09-09 14:57:09 -07002440 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002441 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002443 }
2444 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002448 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002449 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002450 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002451 }
2452 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002453 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002454 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002455 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002456
Mark Dickinson22b20182010-05-10 21:27:53 +00002457 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002458 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002459 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002460 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 Py_XDECREF(z);
2462 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2463 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002464 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002466 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002468 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 base, strobj);
2470 Py_DECREF(strobj);
2471 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002472}
2473
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002474/* Since PyLong_FromString doesn't have a length parameter,
2475 * check here for possible NULs in the string.
2476 *
2477 * Reports an invalid literal as a bytes object.
2478 */
2479PyObject *
2480_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2481{
2482 PyObject *result, *strobj;
2483 char *end = NULL;
2484
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002485 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002486 if (end == NULL || (result != NULL && end == s + len))
2487 return result;
2488 Py_XDECREF(result);
2489 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2490 if (strobj != NULL) {
2491 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002492 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002493 base, strobj);
2494 Py_DECREF(strobj);
2495 }
2496 return NULL;
2497}
2498
Guido van Rossum9e896b32000-04-05 20:11:21 +00002499PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500PyLong_FromUnicodeObject(PyObject *u, int base)
2501{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002502 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002503 const char *buffer;
2504 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002505 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002506
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002507 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002508 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002510 assert(PyUnicode_IS_ASCII(asciidig));
2511 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002512 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002513 assert(buffer != NULL);
2514
2515 result = PyLong_FromString(buffer, &end, base);
2516 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002517 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002518 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002520 Py_DECREF(asciidig);
2521 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002522 PyErr_Format(PyExc_ValueError,
2523 "invalid literal for int() with base %d: %.200R",
2524 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002525 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002526}
2527
Tim Peters9f688bf2000-07-07 15:53:28 +00002528/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002529static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002531static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002532
Serhiy Storchaka95949422013-08-27 19:40:23 +03002533/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002534
Guido van Rossume32e0141992-01-19 16:31:05 +00002535static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002536long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002538{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002539 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 if (size_b == 0) {
2543 PyErr_SetString(PyExc_ZeroDivisionError,
2544 "integer division or modulo by zero");
2545 return -1;
2546 }
2547 if (size_a < size_b ||
2548 (size_a == size_b &&
2549 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2550 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002551 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002552 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002553 return -1;
2554 }
Victor Stinner8e3b9f92020-10-27 00:00:03 +01002555 PyObject *zero = _PyLong_GetZero();
2556 Py_INCREF(zero);
2557 *pdiv = (PyLongObject*)zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 return 0;
2559 }
2560 if (size_b == 1) {
2561 digit rem = 0;
2562 z = divrem1(a, b->ob_digit[0], &rem);
2563 if (z == NULL)
2564 return -1;
2565 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2566 if (*prem == NULL) {
2567 Py_DECREF(z);
2568 return -1;
2569 }
2570 }
2571 else {
2572 z = x_divrem(a, b, prem);
2573 if (z == NULL)
2574 return -1;
2575 }
2576 /* Set the signs.
2577 The quotient z has the sign of a*b;
2578 the remainder r has the sign of a,
2579 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002580 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2581 _PyLong_Negate(&z);
2582 if (z == NULL) {
2583 Py_CLEAR(*prem);
2584 return -1;
2585 }
2586 }
2587 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2588 _PyLong_Negate(prem);
2589 if (*prem == NULL) {
2590 Py_DECREF(z);
2591 Py_CLEAR(*prem);
2592 return -1;
2593 }
2594 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 *pdiv = maybe_small_long(z);
2596 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002597}
2598
Serhiy Storchaka95949422013-08-27 19:40:23 +03002599/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002600 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002601
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002602static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002603x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 PyLongObject *v, *w, *a;
2606 Py_ssize_t i, k, size_v, size_w;
2607 int d;
2608 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2609 twodigits vv;
2610 sdigit zhi;
2611 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2614 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2615 handle the special case when the initial estimate q for a quotient
2616 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2617 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002620 size_v = Py_ABS(Py_SIZE(v1));
2621 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2623 v = _PyLong_New(size_v+1);
2624 if (v == NULL) {
2625 *prem = NULL;
2626 return NULL;
2627 }
2628 w = _PyLong_New(size_w);
2629 if (w == NULL) {
2630 Py_DECREF(v);
2631 *prem = NULL;
2632 return NULL;
2633 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2636 shift v1 left by the same amount. Results go into w and v. */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02002637 d = PyLong_SHIFT - bit_length_digit(w1->ob_digit[size_w-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2639 assert(carry == 0);
2640 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2641 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2642 v->ob_digit[size_v] = carry;
2643 size_v++;
2644 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2647 at most (and usually exactly) k = size_v - size_w digits. */
2648 k = size_v - size_w;
2649 assert(k >= 0);
2650 a = _PyLong_New(k);
2651 if (a == NULL) {
2652 Py_DECREF(w);
2653 Py_DECREF(v);
2654 *prem = NULL;
2655 return NULL;
2656 }
2657 v0 = v->ob_digit;
2658 w0 = w->ob_digit;
2659 wm1 = w0[size_w-1];
2660 wm2 = w0[size_w-2];
2661 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2662 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2663 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002666 Py_DECREF(a);
2667 Py_DECREF(w);
2668 Py_DECREF(v);
2669 *prem = NULL;
2670 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002671 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 /* estimate quotient digit q; may overestimate by 1 (rare) */
2674 vtop = vk[size_w];
2675 assert(vtop <= wm1);
2676 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2677 q = (digit)(vv / wm1);
2678 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2679 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2680 | vk[size_w-2])) {
2681 --q;
2682 r += wm1;
2683 if (r >= PyLong_BASE)
2684 break;
2685 }
2686 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2689 zhi = 0;
2690 for (i = 0; i < size_w; ++i) {
2691 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2692 -PyLong_BASE * q <= z < PyLong_BASE */
2693 z = (sdigit)vk[i] + zhi -
2694 (stwodigits)q * (stwodigits)w0[i];
2695 vk[i] = (digit)z & PyLong_MASK;
2696 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002697 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 /* add w back if q was too large (this branch taken rarely) */
2701 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2702 if ((sdigit)vtop + zhi < 0) {
2703 carry = 0;
2704 for (i = 0; i < size_w; ++i) {
2705 carry += vk[i] + w0[i];
2706 vk[i] = carry & PyLong_MASK;
2707 carry >>= PyLong_SHIFT;
2708 }
2709 --q;
2710 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 /* store quotient digit */
2713 assert(q < PyLong_BASE);
2714 *--ak = q;
2715 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 /* unshift remainder; we reuse w to store the result */
2718 carry = v_rshift(w0, v0, size_w, d);
2719 assert(carry==0);
2720 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 *prem = long_normalize(w);
2723 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002724}
2725
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002726/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2727 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2728 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2729 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2730 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2731 -1.0. */
2732
2733/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2734#if DBL_MANT_DIG == 53
2735#define EXP2_DBL_MANT_DIG 9007199254740992.0
2736#else
2737#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2738#endif
2739
2740double
2741_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2744 /* See below for why x_digits is always large enough. */
Dong-hee Nab88cd582020-05-04 22:32:42 +09002745 digit rem;
2746 digit x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT] = {0,};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 double dx;
2748 /* Correction term for round-half-to-even rounding. For a digit x,
2749 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2750 multiple of 4, rounding ties to a multiple of 8. */
2751 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002752
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002753 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 if (a_size == 0) {
2755 /* Special case for 0: significand 0.0, exponent 0. */
2756 *e = 0;
2757 return 0.0;
2758 }
Niklas Fiekas794e7d12020-06-15 14:33:48 +02002759 a_bits = bit_length_digit(a->ob_digit[a_size-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 /* The following is an overflow-free version of the check
2761 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2762 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2763 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2764 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002765 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2769 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 Number of digits needed for result: write // for floor division.
2772 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2781 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2784 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2785 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 in both cases.
2792 */
2793 if (a_bits <= DBL_MANT_DIG + 2) {
2794 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2795 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
Dong-hee Nab88cd582020-05-04 22:32:42 +09002796 x_size = shift_digits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2798 (int)shift_bits);
2799 x_size += a_size;
2800 x_digits[x_size++] = rem;
2801 }
2802 else {
2803 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2804 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2805 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2806 a_size - shift_digits, (int)shift_bits);
2807 x_size = a_size - shift_digits;
2808 /* For correct rounding below, we need the least significant
2809 bit of x to be 'sticky' for this shift: if any of the bits
2810 shifted out was nonzero, we set the least significant bit
2811 of x. */
2812 if (rem)
2813 x_digits[0] |= 1;
2814 else
2815 while (shift_digits > 0)
2816 if (a->ob_digit[--shift_digits]) {
2817 x_digits[0] |= 1;
2818 break;
2819 }
2820 }
Victor Stinner63941882011-09-29 00:42:28 +02002821 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 /* Round, and convert to double. */
2824 x_digits[0] += half_even_correction[x_digits[0] & 7];
2825 dx = x_digits[--x_size];
2826 while (x_size > 0)
2827 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 /* Rescale; make correction if result is 1.0. */
2830 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2831 if (dx == 1.0) {
2832 if (a_bits == PY_SSIZE_T_MAX)
2833 goto overflow;
2834 dx = 0.5;
2835 a_bits += 1;
2836 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 *e = a_bits;
2839 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002840
2841 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 /* exponent > PY_SSIZE_T_MAX */
2843 PyErr_SetString(PyExc_OverflowError,
2844 "huge integer: number of bits overflows a Py_ssize_t");
2845 *e = 0;
2846 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002847}
2848
Serhiy Storchaka95949422013-08-27 19:40:23 +03002849/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002850 using the round-half-to-even rule in the case of a tie. */
2851
2852double
2853PyLong_AsDouble(PyObject *v)
2854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 Py_ssize_t exponent;
2856 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002857
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002858 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 PyErr_BadInternalCall();
2860 return -1.0;
2861 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002862 if (!PyLong_Check(v)) {
2863 PyErr_SetString(PyExc_TypeError, "an integer is required");
2864 return -1.0;
2865 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002866 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002867 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002868 to double. This improves performance of FP/long operations
2869 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002870 */
2871 return (double)MEDIUM_VALUE((PyLongObject *)v);
2872 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2874 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2875 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002876 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 return -1.0;
2878 }
2879 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002880}
2881
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002882/* Methods */
2883
HongWeipeng42acb7b2019-09-18 23:10:15 +08002884/* if a < b, return a negative number
2885 if a == b, return 0
2886 if a > b, return a positive number */
2887
2888static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002889long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002890{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002891 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
2892 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002893 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08002894 sdigit diff = 0;
2895 while (--i >= 0) {
2896 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
2897 if (diff) {
2898 break;
2899 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08002901 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08002903 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002904}
2905
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002906static PyObject *
2907long_richcompare(PyObject *self, PyObject *other, int op)
2908{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002909 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 CHECK_BINOP(self, other);
2911 if (self == other)
2912 result = 0;
2913 else
2914 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01002915 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002916}
2917
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002918static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002919long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002920{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002921 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 Py_ssize_t i;
2923 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 i = Py_SIZE(v);
2926 switch(i) {
2927 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2928 case 0: return 0;
2929 case 1: return v->ob_digit[0];
2930 }
2931 sign = 1;
2932 x = 0;
2933 if (i < 0) {
2934 sign = -1;
2935 i = -(i);
2936 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002938 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2939 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2940 _PyHASH_MODULUS.
2941
2942 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2943 amounts to a rotation of the bits of x. To see this, write
2944
2945 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2946
2947 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2948 PyLong_SHIFT bits of x (those that are shifted out of the
2949 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2950 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2951 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2952 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2953 congruent to y modulo _PyHASH_MODULUS. So
2954
2955 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2956
2957 The right-hand side is just the result of rotating the
2958 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2959 not all _PyHASH_BITS bits of x are 1s, the same is true
2960 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2961 the reduction of x*2**PyLong_SHIFT modulo
2962 _PyHASH_MODULUS. */
2963 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2964 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002966 if (x >= _PyHASH_MODULUS)
2967 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 }
2969 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002970 if (x == (Py_uhash_t)-1)
2971 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002972 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002973}
2974
2975
Serhiy Storchaka95949422013-08-27 19:40:23 +03002976/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002977
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002978static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002979x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002980{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002981 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 PyLongObject *z;
2983 Py_ssize_t i;
2984 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 /* Ensure a is the larger of the two: */
2987 if (size_a < size_b) {
2988 { PyLongObject *temp = a; a = b; b = temp; }
2989 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002990 size_a = size_b;
2991 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 }
2993 z = _PyLong_New(size_a+1);
2994 if (z == NULL)
2995 return NULL;
2996 for (i = 0; i < size_b; ++i) {
2997 carry += a->ob_digit[i] + b->ob_digit[i];
2998 z->ob_digit[i] = carry & PyLong_MASK;
2999 carry >>= PyLong_SHIFT;
3000 }
3001 for (; i < size_a; ++i) {
3002 carry += a->ob_digit[i];
3003 z->ob_digit[i] = carry & PyLong_MASK;
3004 carry >>= PyLong_SHIFT;
3005 }
3006 z->ob_digit[i] = carry;
3007 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003008}
3009
3010/* Subtract the absolute values of two integers. */
3011
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003012static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003013x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003014{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003015 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 PyLongObject *z;
3017 Py_ssize_t i;
3018 int sign = 1;
3019 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 /* Ensure a is the larger of the two: */
3022 if (size_a < size_b) {
3023 sign = -1;
3024 { PyLongObject *temp = a; a = b; b = temp; }
3025 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003026 size_a = size_b;
3027 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 }
3029 else if (size_a == size_b) {
3030 /* Find highest digit where a and b differ: */
3031 i = size_a;
3032 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3033 ;
3034 if (i < 0)
3035 return (PyLongObject *)PyLong_FromLong(0);
3036 if (a->ob_digit[i] < b->ob_digit[i]) {
3037 sign = -1;
3038 { PyLongObject *temp = a; a = b; b = temp; }
3039 }
3040 size_a = size_b = i+1;
3041 }
3042 z = _PyLong_New(size_a);
3043 if (z == NULL)
3044 return NULL;
3045 for (i = 0; i < size_b; ++i) {
3046 /* The following assumes unsigned arithmetic
3047 works module 2**N for some N>PyLong_SHIFT. */
3048 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3049 z->ob_digit[i] = borrow & PyLong_MASK;
3050 borrow >>= PyLong_SHIFT;
3051 borrow &= 1; /* Keep only one sign bit */
3052 }
3053 for (; i < size_a; ++i) {
3054 borrow = a->ob_digit[i] - borrow;
3055 z->ob_digit[i] = borrow & PyLong_MASK;
3056 borrow >>= PyLong_SHIFT;
3057 borrow &= 1; /* Keep only one sign bit */
3058 }
3059 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003060 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003061 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02003062 }
HongWeipeng036fe852019-11-26 15:54:49 +08003063 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003064}
3065
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003066static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003067long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003072
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003073 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003074 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 }
3076 if (Py_SIZE(a) < 0) {
3077 if (Py_SIZE(b) < 0) {
3078 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003079 if (z != NULL) {
3080 /* x_add received at least one multiple-digit int,
3081 and thus z must be a multiple-digit int.
3082 That also means z is not an element of
3083 small_ints, so negating it in-place is safe. */
3084 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003085 Py_SET_SIZE(z, -(Py_SIZE(z)));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003086 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 }
3088 else
3089 z = x_sub(b, a);
3090 }
3091 else {
3092 if (Py_SIZE(b) < 0)
3093 z = x_sub(a, b);
3094 else
3095 z = x_add(a, b);
3096 }
3097 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003098}
3099
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003100static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003101long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003106
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003107 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003108 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 }
3110 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003111 if (Py_SIZE(b) < 0) {
3112 z = x_sub(b, a);
3113 }
3114 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003116 if (z != NULL) {
3117 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003118 Py_SET_SIZE(z, -(Py_SIZE(z)));
HongWeipeng036fe852019-11-26 15:54:49 +08003119 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003120 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 }
3122 else {
3123 if (Py_SIZE(b) < 0)
3124 z = x_add(a, b);
3125 else
3126 z = x_sub(a, b);
3127 }
3128 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003129}
3130
Tim Peters5af4e6c2002-08-12 02:31:19 +00003131/* Grade school multiplication, ignoring the signs.
3132 * Returns the absolute value of the product, or NULL if error.
3133 */
3134static PyLongObject *
3135x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003138 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3139 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 z = _PyLong_New(size_a + size_b);
3143 if (z == NULL)
3144 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3147 if (a == b) {
3148 /* Efficient squaring per HAC, Algorithm 14.16:
3149 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3150 * Gives slightly less than a 2x speedup when a == b,
3151 * via exploiting that each entry in the multiplication
3152 * pyramid appears twice (except for the size_a squares).
3153 */
3154 for (i = 0; i < size_a; ++i) {
3155 twodigits carry;
3156 twodigits f = a->ob_digit[i];
3157 digit *pz = z->ob_digit + (i << 1);
3158 digit *pa = a->ob_digit + i + 1;
3159 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003162 Py_DECREF(z);
3163 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003164 });
Tim Peters0973b992004-08-29 22:16:50 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 carry = *pz + f * f;
3167 *pz++ = (digit)(carry & PyLong_MASK);
3168 carry >>= PyLong_SHIFT;
3169 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 /* Now f is added in twice in each column of the
3172 * pyramid it appears. Same as adding f<<1 once.
3173 */
3174 f <<= 1;
3175 while (pa < paend) {
3176 carry += *pz + *pa++ * f;
3177 *pz++ = (digit)(carry & PyLong_MASK);
3178 carry >>= PyLong_SHIFT;
3179 assert(carry <= (PyLong_MASK << 1));
3180 }
3181 if (carry) {
3182 carry += *pz;
3183 *pz++ = (digit)(carry & PyLong_MASK);
3184 carry >>= PyLong_SHIFT;
3185 }
3186 if (carry)
3187 *pz += (digit)(carry & PyLong_MASK);
3188 assert((carry >> PyLong_SHIFT) == 0);
3189 }
3190 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003191 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 for (i = 0; i < size_a; ++i) {
3193 twodigits carry = 0;
3194 twodigits f = a->ob_digit[i];
3195 digit *pz = z->ob_digit + i;
3196 digit *pb = b->ob_digit;
3197 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003200 Py_DECREF(z);
3201 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003202 });
Tim Peters0973b992004-08-29 22:16:50 +00003203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 while (pb < pbend) {
3205 carry += *pz + *pb++ * f;
3206 *pz++ = (digit)(carry & PyLong_MASK);
3207 carry >>= PyLong_SHIFT;
3208 assert(carry <= PyLong_MASK);
3209 }
3210 if (carry)
3211 *pz += (digit)(carry & PyLong_MASK);
3212 assert((carry >> PyLong_SHIFT) == 0);
3213 }
3214 }
3215 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003216}
3217
3218/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003219 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003220 split, and sets low and high such that abs(n) == (high << size) + low,
3221 viewing the shift as being by digits. The sign bit is ignored, and
3222 the return values are >= 0.
3223 Returns 0 on success, -1 on failure.
3224*/
3225static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003226kmul_split(PyLongObject *n,
3227 Py_ssize_t size,
3228 PyLongObject **high,
3229 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 PyLongObject *hi, *lo;
3232 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003233 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003234
Victor Stinner640c35c2013-06-04 23:14:37 +02003235 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 if ((hi = _PyLong_New(size_hi)) == NULL)
3239 return -1;
3240 if ((lo = _PyLong_New(size_lo)) == NULL) {
3241 Py_DECREF(hi);
3242 return -1;
3243 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3246 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 *high = long_normalize(hi);
3249 *low = long_normalize(lo);
3250 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003251}
3252
Tim Peters60004642002-08-12 22:01:34 +00003253static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3254
Tim Peters5af4e6c2002-08-12 02:31:19 +00003255/* Karatsuba multiplication. Ignores the input signs, and returns the
3256 * absolute value of the product (or NULL if error).
3257 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3258 */
3259static PyLongObject *
3260k_mul(PyLongObject *a, PyLongObject *b)
3261{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003262 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3263 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 PyLongObject *ah = NULL;
3265 PyLongObject *al = NULL;
3266 PyLongObject *bh = NULL;
3267 PyLongObject *bl = NULL;
3268 PyLongObject *ret = NULL;
3269 PyLongObject *t1, *t2, *t3;
3270 Py_ssize_t shift; /* the number of digits we split off */
3271 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3274 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3275 * Then the original product is
3276 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3277 * By picking X to be a power of 2, "*X" is just shifting, and it's
3278 * been reduced to 3 multiplies on numbers half the size.
3279 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 /* We want to split based on the larger number; fiddle so that b
3282 * is largest.
3283 */
3284 if (asize > bsize) {
3285 t1 = a;
3286 a = b;
3287 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 i = asize;
3290 asize = bsize;
3291 bsize = i;
3292 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 /* Use gradeschool math when either number is too small. */
3295 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3296 if (asize <= i) {
3297 if (asize == 0)
3298 return (PyLongObject *)PyLong_FromLong(0);
3299 else
3300 return x_mul(a, b);
3301 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 /* If a is small compared to b, splitting on b gives a degenerate
3304 * case with ah==0, and Karatsuba may be (even much) less efficient
3305 * than "grade school" then. However, we can still win, by viewing
3306 * b as a string of "big digits", each of width a->ob_size. That
3307 * leads to a sequence of balanced calls to k_mul.
3308 */
3309 if (2 * asize <= bsize)
3310 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 /* Split a & b into hi & lo pieces. */
3313 shift = bsize >> 1;
3314 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3315 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 if (a == b) {
3318 bh = ah;
3319 bl = al;
3320 Py_INCREF(bh);
3321 Py_INCREF(bl);
3322 }
3323 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 /* The plan:
3326 * 1. Allocate result space (asize + bsize digits: that's always
3327 * enough).
3328 * 2. Compute ah*bh, and copy into result at 2*shift.
3329 * 3. Compute al*bl, and copy into result at 0. Note that this
3330 * can't overlap with #2.
3331 * 4. Subtract al*bl from the result, starting at shift. This may
3332 * underflow (borrow out of the high digit), but we don't care:
3333 * we're effectively doing unsigned arithmetic mod
3334 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3335 * borrows and carries out of the high digit can be ignored.
3336 * 5. Subtract ah*bh from the result, starting at shift.
3337 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3338 * at shift.
3339 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 /* 1. Allocate result space. */
3342 ret = _PyLong_New(asize + bsize);
3343 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003344#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 /* Fill with trash, to catch reference to uninitialized digits. */
3346 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003347#endif
Tim Peters44121a62002-08-12 06:17:58 +00003348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3350 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3351 assert(Py_SIZE(t1) >= 0);
3352 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3353 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3354 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 /* Zero-out the digits higher than the ah*bh copy. */
3357 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3358 if (i)
3359 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3360 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 /* 3. t2 <- al*bl, and copy into the low digits. */
3363 if ((t2 = k_mul(al, bl)) == NULL) {
3364 Py_DECREF(t1);
3365 goto fail;
3366 }
3367 assert(Py_SIZE(t2) >= 0);
3368 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3369 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 /* Zero out remaining digits. */
3372 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3373 if (i)
3374 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3377 * because it's fresher in cache.
3378 */
3379 i = Py_SIZE(ret) - shift; /* # digits after shift */
3380 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3381 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3384 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3387 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3388 Py_DECREF(ah);
3389 Py_DECREF(al);
3390 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 if (a == b) {
3393 t2 = t1;
3394 Py_INCREF(t2);
3395 }
3396 else if ((t2 = x_add(bh, bl)) == NULL) {
3397 Py_DECREF(t1);
3398 goto fail;
3399 }
3400 Py_DECREF(bh);
3401 Py_DECREF(bl);
3402 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 t3 = k_mul(t1, t2);
3405 Py_DECREF(t1);
3406 Py_DECREF(t2);
3407 if (t3 == NULL) goto fail;
3408 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 /* Add t3. It's not obvious why we can't run out of room here.
3411 * See the (*) comment after this function.
3412 */
3413 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3414 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003417
Mark Dickinson22b20182010-05-10 21:27:53 +00003418 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 Py_XDECREF(ret);
3420 Py_XDECREF(ah);
3421 Py_XDECREF(al);
3422 Py_XDECREF(bh);
3423 Py_XDECREF(bl);
3424 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003425}
3426
Tim Petersd6974a52002-08-13 20:37:51 +00003427/* (*) Why adding t3 can't "run out of room" above.
3428
Tim Petersab86c2b2002-08-15 20:06:00 +00003429Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3430to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003431
Tim Petersab86c2b2002-08-15 20:06:00 +000034321. For any integer i, i = c(i/2) + f(i/2). In particular,
3433 bsize = c(bsize/2) + f(bsize/2).
34342. shift = f(bsize/2)
34353. asize <= bsize
34364. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3437 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003438
Tim Petersab86c2b2002-08-15 20:06:00 +00003439We allocated asize + bsize result digits, and add t3 into them at an offset
3440of shift. This leaves asize+bsize-shift allocated digit positions for t3
3441to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3442asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003443
Tim Petersab86c2b2002-08-15 20:06:00 +00003444bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3445at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003446
Tim Petersab86c2b2002-08-15 20:06:00 +00003447If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3448digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3449most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003450
Tim Petersab86c2b2002-08-15 20:06:00 +00003451The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003452
Tim Petersab86c2b2002-08-15 20:06:00 +00003453 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003454
Tim Petersab86c2b2002-08-15 20:06:00 +00003455and we have asize + c(bsize/2) available digit positions. We need to show
3456this is always enough. An instance of c(bsize/2) cancels out in both, so
3457the question reduces to whether asize digits is enough to hold
3458(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3459then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3460asize 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 +00003461digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003462asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003463c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3464is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3465bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003466
Tim Peters48d52c02002-08-14 17:07:32 +00003467Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3468clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3469ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003470*/
3471
Tim Peters60004642002-08-12 22:01:34 +00003472/* b has at least twice the digits of a, and a is big enough that Karatsuba
3473 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3474 * of slices, each with a->ob_size digits, and multiply the slices by a,
3475 * one at a time. This gives k_mul balanced inputs to work with, and is
3476 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003477 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003478 * single-width slice overlap between successive partial sums).
3479 */
3480static PyLongObject *
3481k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3482{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003483 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3484 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 Py_ssize_t nbdone; /* # of b digits already multiplied */
3486 PyLongObject *ret;
3487 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 assert(asize > KARATSUBA_CUTOFF);
3490 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 /* Allocate result space, and zero it out. */
3493 ret = _PyLong_New(asize + bsize);
3494 if (ret == NULL)
3495 return NULL;
3496 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 /* Successive slices of b are copied into bslice. */
3499 bslice = _PyLong_New(asize);
3500 if (bslice == NULL)
3501 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 nbdone = 0;
3504 while (bsize > 0) {
3505 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003506 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 /* Multiply the next slice of b by a. */
3509 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3510 nbtouse * sizeof(digit));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003511 Py_SET_SIZE(bslice, nbtouse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 product = k_mul(a, bslice);
3513 if (product == NULL)
3514 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 /* Add into result. */
3517 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3518 product->ob_digit, Py_SIZE(product));
3519 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 bsize -= nbtouse;
3522 nbdone += nbtouse;
3523 }
Tim Peters60004642002-08-12 22:01:34 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 Py_DECREF(bslice);
3526 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003527
Mark Dickinson22b20182010-05-10 21:27:53 +00003528 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 Py_DECREF(ret);
3530 Py_XDECREF(bslice);
3531 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003532}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003533
3534static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003535long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003542 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003544 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 z = k_mul(a, b);
3548 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003549 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3550 _PyLong_Negate(&z);
3551 if (z == NULL)
3552 return NULL;
3553 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003555}
3556
Yury Selivanove0b23092016-02-11 10:26:27 -05003557/* Fast modulo division for single-digit longs. */
3558static PyObject *
3559fast_mod(PyLongObject *a, PyLongObject *b)
3560{
3561 sdigit left = a->ob_digit[0];
3562 sdigit right = b->ob_digit[0];
3563 sdigit mod;
3564
3565 assert(Py_ABS(Py_SIZE(a)) == 1);
3566 assert(Py_ABS(Py_SIZE(b)) == 1);
3567
3568 if (Py_SIZE(a) == Py_SIZE(b)) {
3569 /* 'a' and 'b' have the same sign. */
3570 mod = left % right;
3571 }
3572 else {
3573 /* Either 'a' or 'b' is negative. */
3574 mod = right - 1 - (left - 1) % right;
3575 }
3576
Victor Stinnerf963c132016-03-23 18:36:54 +01003577 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003578}
3579
3580/* Fast floor division for single-digit longs. */
3581static PyObject *
3582fast_floor_div(PyLongObject *a, PyLongObject *b)
3583{
3584 sdigit left = a->ob_digit[0];
3585 sdigit right = b->ob_digit[0];
3586 sdigit div;
3587
3588 assert(Py_ABS(Py_SIZE(a)) == 1);
3589 assert(Py_ABS(Py_SIZE(b)) == 1);
3590
3591 if (Py_SIZE(a) == Py_SIZE(b)) {
3592 /* 'a' and 'b' have the same sign. */
3593 div = left / right;
3594 }
3595 else {
3596 /* Either 'a' or 'b' is negative. */
3597 div = -1 - (left - 1) / right;
3598 }
3599
3600 return PyLong_FromLong(div);
3601}
3602
Guido van Rossume32e0141992-01-19 16:31:05 +00003603/* The / and % operators are now defined in terms of divmod().
3604 The expression a mod b has the value a - b*floor(a/b).
3605 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003606 |a| by |b|, with the sign of a. This is also expressed
3607 as a - b*trunc(a/b), if trunc truncates towards zero.
3608 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 a b a rem b a mod b
3610 13 10 3 3
3611 -13 10 -3 7
3612 13 -10 3 -7
3613 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003614 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003615 have different signs. We then subtract one from the 'div'
3616 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003617
Tim Peters47e52ee2004-08-30 02:44:38 +00003618/* Compute
3619 * *pdiv, *pmod = divmod(v, w)
3620 * NULL can be passed for pdiv or pmod, in which case that part of
3621 * the result is simply thrown away. The caller owns a reference to
3622 * each of these it requests (does not pass NULL for).
3623 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003624static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003625l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003629
Yury Selivanove0b23092016-02-11 10:26:27 -05003630 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3631 /* Fast path for single-digit longs */
3632 div = NULL;
3633 if (pdiv != NULL) {
3634 div = (PyLongObject *)fast_floor_div(v, w);
3635 if (div == NULL) {
3636 return -1;
3637 }
3638 }
3639 if (pmod != NULL) {
3640 mod = (PyLongObject *)fast_mod(v, w);
3641 if (mod == NULL) {
3642 Py_XDECREF(div);
3643 return -1;
3644 }
3645 *pmod = mod;
3646 }
3647 if (pdiv != NULL) {
3648 /* We only want to set `*pdiv` when `*pmod` is
3649 set successfully. */
3650 *pdiv = div;
3651 }
3652 return 0;
3653 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 if (long_divrem(v, w, &div, &mod) < 0)
3655 return -1;
3656 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3657 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3658 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 temp = (PyLongObject *) long_add(mod, w);
3660 Py_DECREF(mod);
3661 mod = temp;
3662 if (mod == NULL) {
3663 Py_DECREF(div);
3664 return -1;
3665 }
Victor Stinner8e3b9f92020-10-27 00:00:03 +01003666 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_GetOne());
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003667 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 Py_DECREF(mod);
3669 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 return -1;
3671 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 Py_DECREF(div);
3673 div = temp;
3674 }
3675 if (pdiv != NULL)
3676 *pdiv = div;
3677 else
3678 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 if (pmod != NULL)
3681 *pmod = mod;
3682 else
3683 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003686}
3687
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003688static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003689long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003694
3695 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3696 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3697 }
3698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3700 div = NULL;
3701 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003702}
3703
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003704/* PyLong/PyLong -> float, with correctly rounded result. */
3705
3706#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3707#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3708
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003709static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003710long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003712 PyLongObject *a, *b, *x;
3713 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3714 digit mask, low;
3715 int inexact, negate, a_is_small, b_is_small;
3716 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 CHECK_BINOP(v, w);
3719 a = (PyLongObject *)v;
3720 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 /*
3723 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3726 1. choose a suitable integer 'shift'
3727 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3728 3. adjust x for correct rounding
3729 4. convert x to a double dx with the same value
3730 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3735 returns either 0.0 or -0.0, depending on the sign of b. For a and
3736 b both nonzero, ignore signs of a and b, and add the sign back in
3737 at the end. Now write a_bits and b_bits for the bit lengths of a
3738 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3739 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3744 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3745 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3746 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 1. The integer 'shift' is chosen so that x has the right number of
3751 bits for a double, plus two or three extra bits that will be used
3752 in the rounding decisions. Writing a_bits and b_bits for the
3753 number of significant bits in a and b respectively, a
3754 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 This is fine in the usual case, but if a/b is smaller than the
3759 smallest normal float then it can lead to double rounding on an
3760 IEEE 754 platform, giving incorrectly rounded results. So we
3761 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 2. The quantity x is computed by first shifting a (left -shift bits
3766 if shift <= 0, right shift bits if shift > 0) and then dividing by
3767 b. For both the shift and the division, we keep track of whether
3768 the result is inexact, in a flag 'inexact'; this information is
3769 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 With the choice of shift above, together with our assumption that
3772 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3773 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3776 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 For float representability, we need x/2**extra_bits <
3781 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3782 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 To round, we just modify the bottom digit of x in-place; this can
3787 end up giving a digit with value > PyLONG_MASK, but that's not a
3788 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 With the original choices for shift above, extra_bits will always
3791 be 2 or 3. Then rounding under the round-half-to-even rule, we
3792 round up iff the most significant of the extra bits is 1, and
3793 either: (a) the computation of x in step 2 had an inexact result,
3794 or (b) at least one other of the extra bits is 1, or (c) the least
3795 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 4. Conversion to a double is straightforward; all floating-point
3798 operations involved in the conversion are exact, so there's no
3799 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3802 The result will always be exactly representable as a double, except
3803 in the case that it overflows. To avoid dependence on the exact
3804 behaviour of ldexp on overflow, we check for overflow before
3805 applying ldexp. The result of ldexp is adjusted for sign before
3806 returning.
3807 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003810 a_size = Py_ABS(Py_SIZE(a));
3811 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3813 if (b_size == 0) {
3814 PyErr_SetString(PyExc_ZeroDivisionError,
3815 "division by zero");
3816 goto error;
3817 }
3818 if (a_size == 0)
3819 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 /* Fast path for a and b small (exactly representable in a double).
3822 Relies on floating-point division being correctly rounded; results
3823 may be subject to double rounding on x86 machines that operate with
3824 the x87 FPU set to 64-bit precision. */
3825 a_is_small = a_size <= MANT_DIG_DIGITS ||
3826 (a_size == MANT_DIG_DIGITS+1 &&
3827 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3828 b_is_small = b_size <= MANT_DIG_DIGITS ||
3829 (b_size == MANT_DIG_DIGITS+1 &&
3830 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3831 if (a_is_small && b_is_small) {
3832 double da, db;
3833 da = a->ob_digit[--a_size];
3834 while (a_size > 0)
3835 da = da * PyLong_BASE + a->ob_digit[--a_size];
3836 db = b->ob_digit[--b_size];
3837 while (b_size > 0)
3838 db = db * PyLong_BASE + b->ob_digit[--b_size];
3839 result = da / db;
3840 goto success;
3841 }
Tim Peterse2a60002001-09-04 06:17:36 +00003842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 /* Catch obvious cases of underflow and overflow */
3844 diff = a_size - b_size;
3845 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3846 /* Extreme overflow */
3847 goto overflow;
3848 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3849 /* Extreme underflow */
3850 goto underflow_or_zero;
3851 /* Next line is now safe from overflowing a Py_ssize_t */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02003852 diff = diff * PyLong_SHIFT + bit_length_digit(a->ob_digit[a_size - 1]) -
3853 bit_length_digit(b->ob_digit[b_size - 1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854 /* Now diff = a_bits - b_bits. */
3855 if (diff > DBL_MAX_EXP)
3856 goto overflow;
3857 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3858 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003861 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 /* x = abs(a * 2**-shift) */
3866 if (shift <= 0) {
3867 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3868 digit rem;
3869 /* x = a << -shift */
3870 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3871 /* In practice, it's probably impossible to end up
3872 here. Both a and b would have to be enormous,
3873 using close to SIZE_T_MAX bytes of memory each. */
3874 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003875 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 goto error;
3877 }
3878 x = _PyLong_New(a_size + shift_digits + 1);
3879 if (x == NULL)
3880 goto error;
3881 for (i = 0; i < shift_digits; i++)
3882 x->ob_digit[i] = 0;
3883 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3884 a_size, -shift % PyLong_SHIFT);
3885 x->ob_digit[a_size + shift_digits] = rem;
3886 }
3887 else {
3888 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3889 digit rem;
3890 /* x = a >> shift */
3891 assert(a_size >= shift_digits);
3892 x = _PyLong_New(a_size - shift_digits);
3893 if (x == NULL)
3894 goto error;
3895 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3896 a_size - shift_digits, shift % PyLong_SHIFT);
3897 /* set inexact if any of the bits shifted out is nonzero */
3898 if (rem)
3899 inexact = 1;
3900 while (!inexact && shift_digits > 0)
3901 if (a->ob_digit[--shift_digits])
3902 inexact = 1;
3903 }
3904 long_normalize(x);
3905 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3908 reference to x, so it's safe to modify it in-place. */
3909 if (b_size == 1) {
3910 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3911 b->ob_digit[0]);
3912 long_normalize(x);
3913 if (rem)
3914 inexact = 1;
3915 }
3916 else {
3917 PyLongObject *div, *rem;
3918 div = x_divrem(x, b, &rem);
3919 Py_DECREF(x);
3920 x = div;
3921 if (x == NULL)
3922 goto error;
3923 if (Py_SIZE(rem))
3924 inexact = 1;
3925 Py_DECREF(rem);
3926 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003927 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 assert(x_size > 0); /* result of division is never zero */
Niklas Fiekas794e7d12020-06-15 14:33:48 +02003929 x_bits = (x_size-1)*PyLong_SHIFT+bit_length_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003932 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 /* Round by directly modifying the low digit of x. */
3936 mask = (digit)1 << (extra_bits - 1);
3937 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003938 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003940 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 /* Convert x to a double dx; the conversion is exact. */
3943 dx = x->ob_digit[--x_size];
3944 while (x_size > 0)
3945 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3946 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 /* Check whether ldexp result will overflow a double. */
3949 if (shift + x_bits >= DBL_MAX_EXP &&
3950 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3951 goto overflow;
3952 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003953
3954 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003956
3957 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003959
3960 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 PyErr_SetString(PyExc_OverflowError,
3962 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003963 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003965}
3966
3967static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003968long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 CHECK_BINOP(a, b);
3973
Yury Selivanove0b23092016-02-11 10:26:27 -05003974 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3975 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
3976 }
3977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3979 mod = NULL;
3980 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003981}
3982
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003983static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003984long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 PyLongObject *div, *mod;
3987 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3992 return NULL;
3993 }
3994 z = PyTuple_New(2);
3995 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05003996 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
3997 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 }
3999 else {
4000 Py_DECREF(div);
4001 Py_DECREF(mod);
4002 }
4003 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004004}
4005
Mark Dickinsonc5299672019-06-02 10:24:06 +01004006
4007/* Compute an inverse to a modulo n, or raise ValueError if a is not
4008 invertible modulo n. Assumes n is positive. The inverse returned
4009 is whatever falls out of the extended Euclidean algorithm: it may
4010 be either positive or negative, but will be smaller than n in
4011 absolute value.
4012
4013 Pure Python equivalent for long_invmod:
4014
4015 def invmod(a, n):
4016 b, c = 1, 0
4017 while n:
4018 q, r = divmod(a, n)
4019 a, b, c, n = n, c, b - q*c, r
4020
4021 # at this point a is the gcd of the original inputs
4022 if a == 1:
4023 return b
4024 raise ValueError("Not invertible")
4025*/
4026
4027static PyLongObject *
4028long_invmod(PyLongObject *a, PyLongObject *n)
4029{
4030 PyLongObject *b, *c;
4031
4032 /* Should only ever be called for positive n */
4033 assert(Py_SIZE(n) > 0);
4034
4035 b = (PyLongObject *)PyLong_FromLong(1L);
4036 if (b == NULL) {
4037 return NULL;
4038 }
4039 c = (PyLongObject *)PyLong_FromLong(0L);
4040 if (c == NULL) {
4041 Py_DECREF(b);
4042 return NULL;
4043 }
4044 Py_INCREF(a);
4045 Py_INCREF(n);
4046
4047 /* references now owned: a, b, c, n */
4048 while (Py_SIZE(n) != 0) {
4049 PyLongObject *q, *r, *s, *t;
4050
4051 if (l_divmod(a, n, &q, &r) == -1) {
4052 goto Error;
4053 }
4054 Py_DECREF(a);
4055 a = n;
4056 n = r;
4057 t = (PyLongObject *)long_mul(q, c);
4058 Py_DECREF(q);
4059 if (t == NULL) {
4060 goto Error;
4061 }
4062 s = (PyLongObject *)long_sub(b, t);
4063 Py_DECREF(t);
4064 if (s == NULL) {
4065 goto Error;
4066 }
4067 Py_DECREF(b);
4068 b = c;
4069 c = s;
4070 }
4071 /* references now owned: a, b, c, n */
4072
4073 Py_DECREF(c);
4074 Py_DECREF(n);
Victor Stinner8e3b9f92020-10-27 00:00:03 +01004075 if (long_compare(a, (PyLongObject *)_PyLong_GetOne())) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004076 /* a != 1; we don't have an inverse. */
4077 Py_DECREF(a);
4078 Py_DECREF(b);
4079 PyErr_SetString(PyExc_ValueError,
4080 "base is not invertible for the given modulus");
4081 return NULL;
4082 }
4083 else {
4084 /* a == 1; b gives an inverse modulo n */
4085 Py_DECREF(a);
4086 return b;
4087 }
4088
4089 Error:
4090 Py_DECREF(a);
4091 Py_DECREF(b);
4092 Py_DECREF(c);
4093 Py_DECREF(n);
4094 return NULL;
4095}
4096
4097
Tim Peters47e52ee2004-08-30 02:44:38 +00004098/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004099static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004100long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4103 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 PyLongObject *z = NULL; /* accumulated result */
4106 Py_ssize_t i, j, k; /* counters */
4107 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 /* 5-ary values. If the exponent is large enough, table is
4110 * precomputed so that table[i] == a**i % c for i in range(32).
4111 */
4112 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4113 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 /* a, b, c = v, w, x */
4116 CHECK_BINOP(v, w);
4117 a = (PyLongObject*)v; Py_INCREF(a);
4118 b = (PyLongObject*)w; Py_INCREF(b);
4119 if (PyLong_Check(x)) {
4120 c = (PyLongObject *)x;
4121 Py_INCREF(x);
4122 }
4123 else if (x == Py_None)
4124 c = NULL;
4125 else {
4126 Py_DECREF(a);
4127 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004128 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 }
Tim Peters4c483c42001-09-05 06:24:58 +00004130
Mark Dickinsonc5299672019-06-02 10:24:06 +01004131 if (Py_SIZE(b) < 0 && c == NULL) {
4132 /* if exponent is negative and there's no modulus:
4133 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 that this calls float_pow() which converts its
4135 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004136 Py_DECREF(a);
4137 Py_DECREF(b);
4138 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004139 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 if (c) {
4142 /* if modulus == 0:
4143 raise ValueError() */
4144 if (Py_SIZE(c) == 0) {
4145 PyErr_SetString(PyExc_ValueError,
4146 "pow() 3rd argument cannot be 0");
4147 goto Error;
4148 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 /* if modulus < 0:
4151 negativeOutput = True
4152 modulus = -modulus */
4153 if (Py_SIZE(c) < 0) {
4154 negativeOutput = 1;
4155 temp = (PyLongObject *)_PyLong_Copy(c);
4156 if (temp == NULL)
4157 goto Error;
4158 Py_DECREF(c);
4159 c = temp;
4160 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004161 _PyLong_Negate(&c);
4162 if (c == NULL)
4163 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 /* if modulus == 1:
4167 return 0 */
4168 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4169 z = (PyLongObject *)PyLong_FromLong(0L);
4170 goto Done;
4171 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004172
Mark Dickinsonc5299672019-06-02 10:24:06 +01004173 /* if exponent is negative, negate the exponent and
4174 replace the base with a modular inverse */
4175 if (Py_SIZE(b) < 0) {
4176 temp = (PyLongObject *)_PyLong_Copy(b);
4177 if (temp == NULL)
4178 goto Error;
4179 Py_DECREF(b);
4180 b = temp;
4181 temp = NULL;
4182 _PyLong_Negate(&b);
4183 if (b == NULL)
4184 goto Error;
4185
4186 temp = long_invmod(a, c);
4187 if (temp == NULL)
4188 goto Error;
4189 Py_DECREF(a);
4190 a = temp;
4191 }
4192
Tim Peters81a93152013-10-05 16:53:52 -05004193 /* Reduce base by modulus in some cases:
4194 1. If base < 0. Forcing the base non-negative makes things easier.
4195 2. If base is obviously larger than the modulus. The "small
4196 exponent" case later can multiply directly by base repeatedly,
4197 while the "large exponent" case multiplies directly by base 31
4198 times. It can be unboundedly faster to multiply by
4199 base % modulus instead.
4200 We could _always_ do this reduction, but l_divmod() isn't cheap,
4201 so we only do it when it buys something. */
4202 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 if (l_divmod(a, c, NULL, &temp) < 0)
4204 goto Error;
4205 Py_DECREF(a);
4206 a = temp;
4207 temp = NULL;
4208 }
4209 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 /* At this point a, b, and c are guaranteed non-negative UNLESS
4212 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 z = (PyLongObject *)PyLong_FromLong(1L);
4215 if (z == NULL)
4216 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 /* Perform a modular reduction, X = X % c, but leave X alone if c
4219 * is NULL.
4220 */
4221#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004222 do { \
4223 if (c != NULL) { \
4224 if (l_divmod(X, c, NULL, &temp) < 0) \
4225 goto Error; \
4226 Py_XDECREF(X); \
4227 X = temp; \
4228 temp = NULL; \
4229 } \
4230 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 /* Multiply two values, then reduce the result:
4233 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004234#define MULT(X, Y, result) \
4235 do { \
4236 temp = (PyLongObject *)long_mul(X, Y); \
4237 if (temp == NULL) \
4238 goto Error; \
4239 Py_XDECREF(result); \
4240 result = temp; \
4241 temp = NULL; \
4242 REDUCE(result); \
4243 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4246 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4247 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4248 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4249 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004252 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004254 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 }
4256 }
4257 }
4258 else {
4259 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4260 Py_INCREF(z); /* still holds 1L */
4261 table[0] = z;
4262 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004263 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4266 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4269 const int index = (bi >> j) & 0x1f;
4270 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004271 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004273 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 }
4275 }
4276 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 if (negativeOutput && (Py_SIZE(z) != 0)) {
4279 temp = (PyLongObject *)long_sub(z, c);
4280 if (temp == NULL)
4281 goto Error;
4282 Py_DECREF(z);
4283 z = temp;
4284 temp = NULL;
4285 }
4286 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004287
Mark Dickinson22b20182010-05-10 21:27:53 +00004288 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004289 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004291 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4293 for (i = 0; i < 32; ++i)
4294 Py_XDECREF(table[i]);
4295 }
4296 Py_DECREF(a);
4297 Py_DECREF(b);
4298 Py_XDECREF(c);
4299 Py_XDECREF(temp);
4300 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004301}
4302
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004303static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004304long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004306 /* Implement ~x as -(x+1) */
4307 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004308 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Victor Stinner8e3b9f92020-10-27 00:00:03 +01004310 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_GetOne());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 if (x == NULL)
4312 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004313 _PyLong_Negate(&x);
4314 /* No need for maybe_small_long here, since any small
4315 longs will have been caught in the Py_SIZE <= 1 fast path. */
4316 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004317}
4318
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004319static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004320long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004323 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 return PyLong_FromLong(-MEDIUM_VALUE(v));
4325 z = (PyLongObject *)_PyLong_Copy(v);
4326 if (z != NULL)
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004327 Py_SET_SIZE(z, -(Py_SIZE(v)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004329}
4330
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004331static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004332long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 if (Py_SIZE(v) < 0)
4335 return long_neg(v);
4336 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004337 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004338}
4339
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004340static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004341long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004344}
4345
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004346/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4347static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004348divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004349{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004350 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004351 assert(Py_SIZE(shiftby) >= 0);
4352 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4353 if (lshiftby >= 0) {
4354 *wordshift = lshiftby / PyLong_SHIFT;
4355 *remshift = lshiftby % PyLong_SHIFT;
4356 return 0;
4357 }
4358 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4359 be that PyLong_AsSsize_t raised an OverflowError. */
4360 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4361 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004362 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004363 if (wordshift_obj == NULL) {
4364 return -1;
4365 }
4366 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4367 Py_DECREF(wordshift_obj);
4368 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4369 return 0;
4370 }
4371 PyErr_Clear();
4372 /* Clip the value. With such large wordshift the right shift
4373 returns 0 and the left shift raises an error in _PyLong_New(). */
4374 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4375 *remshift = 0;
4376 return 0;
4377}
4378
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004379static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004380long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004383 Py_ssize_t newsize, hishift, i, j;
4384 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 if (Py_SIZE(a) < 0) {
4387 /* Right shifting negative numbers is harder */
4388 PyLongObject *a1, *a2;
4389 a1 = (PyLongObject *) long_invert(a);
4390 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004391 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004392 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393 Py_DECREF(a1);
4394 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004395 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 z = (PyLongObject *) long_invert(a2);
4397 Py_DECREF(a2);
4398 }
4399 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004400 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 if (newsize <= 0)
4402 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004403 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 lomask = ((digit)1 << hishift) - 1;
4405 himask = PyLong_MASK ^ lomask;
4406 z = _PyLong_New(newsize);
4407 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004408 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004409 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004410 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004412 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004414 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004416 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004417}
4418
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004419static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004420long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004421{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004422 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004423 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004426
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004427 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004429 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004431 if (Py_SIZE(a) == 0) {
4432 return PyLong_FromLong(0);
4433 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004434 if (divmod_shift(b, &wordshift, &remshift) < 0)
4435 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004436 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4437}
4438
4439/* Return a >> shiftby. */
4440PyObject *
4441_PyLong_Rshift(PyObject *a, size_t shiftby)
4442{
4443 Py_ssize_t wordshift;
4444 digit remshift;
4445
4446 assert(PyLong_Check(a));
4447 if (Py_SIZE(a) == 0) {
4448 return PyLong_FromLong(0);
4449 }
4450 wordshift = shiftby / PyLong_SHIFT;
4451 remshift = shiftby % PyLong_SHIFT;
4452 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4453}
4454
4455static PyObject *
4456long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4457{
4458 /* This version due to Tim Peters */
4459 PyLongObject *z = NULL;
4460 Py_ssize_t oldsize, newsize, i, j;
4461 twodigits accum;
4462
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004463 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 newsize = oldsize + wordshift;
4465 if (remshift)
4466 ++newsize;
4467 z = _PyLong_New(newsize);
4468 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004469 return NULL;
4470 if (Py_SIZE(a) < 0) {
4471 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004472 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02004473 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 for (i = 0; i < wordshift; i++)
4475 z->ob_digit[i] = 0;
4476 accum = 0;
4477 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4478 accum |= (twodigits)a->ob_digit[j] << remshift;
4479 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4480 accum >>= PyLong_SHIFT;
4481 }
4482 if (remshift)
4483 z->ob_digit[newsize-1] = (digit)accum;
4484 else
4485 assert(!accum);
4486 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004488}
4489
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004490static PyObject *
4491long_lshift(PyObject *a, PyObject *b)
4492{
4493 Py_ssize_t wordshift;
4494 digit remshift;
4495
4496 CHECK_BINOP(a, b);
4497
4498 if (Py_SIZE(b) < 0) {
4499 PyErr_SetString(PyExc_ValueError, "negative shift count");
4500 return NULL;
4501 }
4502 if (Py_SIZE(a) == 0) {
4503 return PyLong_FromLong(0);
4504 }
4505 if (divmod_shift(b, &wordshift, &remshift) < 0)
4506 return NULL;
4507 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4508}
4509
4510/* Return a << shiftby. */
4511PyObject *
4512_PyLong_Lshift(PyObject *a, size_t shiftby)
4513{
4514 Py_ssize_t wordshift;
4515 digit remshift;
4516
4517 assert(PyLong_Check(a));
4518 if (Py_SIZE(a) == 0) {
4519 return PyLong_FromLong(0);
4520 }
4521 wordshift = shiftby / PyLong_SHIFT;
4522 remshift = shiftby % PyLong_SHIFT;
4523 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4524}
4525
Mark Dickinson27a87a22009-10-25 20:43:34 +00004526/* Compute two's complement of digit vector a[0:m], writing result to
4527 z[0:m]. The digit vector a need not be normalized, but should not
4528 be entirely zero. a and z may point to the same digit vector. */
4529
4530static void
4531v_complement(digit *z, digit *a, Py_ssize_t m)
4532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004533 Py_ssize_t i;
4534 digit carry = 1;
4535 for (i = 0; i < m; ++i) {
4536 carry += a[i] ^ PyLong_MASK;
4537 z[i] = carry & PyLong_MASK;
4538 carry >>= PyLong_SHIFT;
4539 }
4540 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004541}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004542
4543/* Bitwise and/xor/or operations */
4544
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004545static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004546long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004547 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004548 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 int nega, negb, negz;
4551 Py_ssize_t size_a, size_b, size_z, i;
4552 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004554 /* Bitwise operations for negative numbers operate as though
4555 on a two's complement representation. So convert arguments
4556 from sign-magnitude to two's complement, and convert the
4557 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004560 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 nega = Py_SIZE(a) < 0;
4562 if (nega) {
4563 z = _PyLong_New(size_a);
4564 if (z == NULL)
4565 return NULL;
4566 v_complement(z->ob_digit, a->ob_digit, size_a);
4567 a = z;
4568 }
4569 else
4570 /* Keep reference count consistent. */
4571 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004574 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 negb = Py_SIZE(b) < 0;
4576 if (negb) {
4577 z = _PyLong_New(size_b);
4578 if (z == NULL) {
4579 Py_DECREF(a);
4580 return NULL;
4581 }
4582 v_complement(z->ob_digit, b->ob_digit, size_b);
4583 b = z;
4584 }
4585 else
4586 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 /* Swap a and b if necessary to ensure size_a >= size_b. */
4589 if (size_a < size_b) {
4590 z = a; a = b; b = z;
4591 size_z = size_a; size_a = size_b; size_b = size_z;
4592 negz = nega; nega = negb; negb = negz;
4593 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004595 /* JRH: The original logic here was to allocate the result value (z)
4596 as the longer of the two operands. However, there are some cases
4597 where the result is guaranteed to be shorter than that: AND of two
4598 positives, OR of two negatives: use the shorter number. AND with
4599 mixed signs: use the positive number. OR with mixed signs: use the
4600 negative number.
4601 */
4602 switch (op) {
4603 case '^':
4604 negz = nega ^ negb;
4605 size_z = size_a;
4606 break;
4607 case '&':
4608 negz = nega & negb;
4609 size_z = negb ? size_a : size_b;
4610 break;
4611 case '|':
4612 negz = nega | negb;
4613 size_z = negb ? size_b : size_a;
4614 break;
4615 default:
stratakisa10d4262019-03-18 18:59:20 +01004616 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004617 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 /* We allow an extra digit if z is negative, to make sure that
4620 the final two's complement of z doesn't overflow. */
4621 z = _PyLong_New(size_z + negz);
4622 if (z == NULL) {
4623 Py_DECREF(a);
4624 Py_DECREF(b);
4625 return NULL;
4626 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 /* Compute digits for overlap of a and b. */
4629 switch(op) {
4630 case '&':
4631 for (i = 0; i < size_b; ++i)
4632 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4633 break;
4634 case '|':
4635 for (i = 0; i < size_b; ++i)
4636 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4637 break;
4638 case '^':
4639 for (i = 0; i < size_b; ++i)
4640 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4641 break;
4642 default:
stratakisa10d4262019-03-18 18:59:20 +01004643 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 /* Copy any remaining digits of a, inverting if necessary. */
4647 if (op == '^' && negb)
4648 for (; i < size_z; ++i)
4649 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4650 else if (i < size_z)
4651 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4652 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 /* Complement result if negative. */
4655 if (negz) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004656 Py_SET_SIZE(z, -(Py_SIZE(z)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 z->ob_digit[size_z] = PyLong_MASK;
4658 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4659 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 Py_DECREF(a);
4662 Py_DECREF(b);
4663 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004664}
4665
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004666static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004667long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 PyObject *c;
4670 CHECK_BINOP(a, b);
4671 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4672 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004673}
4674
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004675static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004676long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 PyObject *c;
4679 CHECK_BINOP(a, b);
4680 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4681 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004682}
4683
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004684static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004685long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687 PyObject *c;
4688 CHECK_BINOP(a, b);
4689 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4690 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004691}
4692
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004693static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004694long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 if (PyLong_CheckExact(v))
4697 Py_INCREF(v);
4698 else
4699 v = _PyLong_Copy((PyLongObject *)v);
4700 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004701}
4702
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004703PyObject *
4704_PyLong_GCD(PyObject *aarg, PyObject *barg)
4705{
4706 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4707 stwodigits x, y, q, s, t, c_carry, d_carry;
4708 stwodigits A, B, C, D, T;
4709 int nbits, k;
4710 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4711 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4712
4713 a = (PyLongObject *)aarg;
4714 b = (PyLongObject *)barg;
4715 size_a = Py_SIZE(a);
4716 size_b = Py_SIZE(b);
4717 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4718 Py_INCREF(a);
4719 Py_INCREF(b);
4720 goto simple;
4721 }
4722
4723 /* Initial reduction: make sure that 0 <= b <= a. */
4724 a = (PyLongObject *)long_abs(a);
4725 if (a == NULL)
4726 return NULL;
4727 b = (PyLongObject *)long_abs(b);
4728 if (b == NULL) {
4729 Py_DECREF(a);
4730 return NULL;
4731 }
4732 if (long_compare(a, b) < 0) {
4733 r = a;
4734 a = b;
4735 b = r;
4736 }
4737 /* We now own references to a and b */
4738
4739 alloc_a = Py_SIZE(a);
4740 alloc_b = Py_SIZE(b);
4741 /* reduce until a fits into 2 digits */
4742 while ((size_a = Py_SIZE(a)) > 2) {
Niklas Fiekas794e7d12020-06-15 14:33:48 +02004743 nbits = bit_length_digit(a->ob_digit[size_a-1]);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004744 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4745 corresponding bits of b into y */
4746 size_b = Py_SIZE(b);
4747 assert(size_b <= size_a);
4748 if (size_b == 0) {
4749 if (size_a < alloc_a) {
4750 r = (PyLongObject *)_PyLong_Copy(a);
4751 Py_DECREF(a);
4752 }
4753 else
4754 r = a;
4755 Py_DECREF(b);
4756 Py_XDECREF(c);
4757 Py_XDECREF(d);
4758 return (PyObject *)r;
4759 }
4760 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4761 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4762 (a->ob_digit[size_a-3] >> nbits));
4763
4764 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4765 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4766 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4767
4768 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4769 larger than PyLong_MASK during the algorithm. */
4770 A = 1; B = 0; C = 0; D = 1;
4771 for (k=0;; k++) {
4772 if (y-C == 0)
4773 break;
4774 q = (x+(A-1))/(y-C);
4775 s = B+q*D;
4776 t = x-q*y;
4777 if (s > t)
4778 break;
4779 x = y; y = t;
4780 t = A+q*C; A = D; B = C; C = s; D = t;
4781 }
4782
4783 if (k == 0) {
4784 /* no progress; do a Euclidean step */
4785 if (l_divmod(a, b, NULL, &r) < 0)
4786 goto error;
4787 Py_DECREF(a);
4788 a = b;
4789 b = r;
4790 alloc_a = alloc_b;
4791 alloc_b = Py_SIZE(b);
4792 continue;
4793 }
4794
4795 /*
4796 a, b = A*b-B*a, D*a-C*b if k is odd
4797 a, b = A*a-B*b, D*b-C*a if k is even
4798 */
4799 if (k&1) {
4800 T = -A; A = -B; B = T;
4801 T = -C; C = -D; D = T;
4802 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004803 if (c != NULL) {
4804 Py_SET_SIZE(c, size_a);
4805 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004806 else if (Py_REFCNT(a) == 1) {
4807 Py_INCREF(a);
4808 c = a;
4809 }
4810 else {
4811 alloc_a = size_a;
4812 c = _PyLong_New(size_a);
4813 if (c == NULL)
4814 goto error;
4815 }
4816
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004817 if (d != NULL) {
4818 Py_SET_SIZE(d, size_a);
4819 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004820 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4821 Py_INCREF(b);
4822 d = b;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004823 Py_SET_SIZE(d, size_a);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004824 }
4825 else {
4826 alloc_b = size_a;
4827 d = _PyLong_New(size_a);
4828 if (d == NULL)
4829 goto error;
4830 }
4831 a_end = a->ob_digit + size_a;
4832 b_end = b->ob_digit + size_b;
4833
4834 /* compute new a and new b in parallel */
4835 a_digit = a->ob_digit;
4836 b_digit = b->ob_digit;
4837 c_digit = c->ob_digit;
4838 d_digit = d->ob_digit;
4839 c_carry = 0;
4840 d_carry = 0;
4841 while (b_digit < b_end) {
4842 c_carry += (A * *a_digit) - (B * *b_digit);
4843 d_carry += (D * *b_digit++) - (C * *a_digit++);
4844 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4845 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4846 c_carry >>= PyLong_SHIFT;
4847 d_carry >>= PyLong_SHIFT;
4848 }
4849 while (a_digit < a_end) {
4850 c_carry += A * *a_digit;
4851 d_carry -= C * *a_digit++;
4852 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4853 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4854 c_carry >>= PyLong_SHIFT;
4855 d_carry >>= PyLong_SHIFT;
4856 }
4857 assert(c_carry == 0);
4858 assert(d_carry == 0);
4859
4860 Py_INCREF(c);
4861 Py_INCREF(d);
4862 Py_DECREF(a);
4863 Py_DECREF(b);
4864 a = long_normalize(c);
4865 b = long_normalize(d);
4866 }
4867 Py_XDECREF(c);
4868 Py_XDECREF(d);
4869
4870simple:
4871 assert(Py_REFCNT(a) > 0);
4872 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004873/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4874 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4875#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004876 /* a fits into a long, so b must too */
4877 x = PyLong_AsLong((PyObject *)a);
4878 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004879#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004880 x = PyLong_AsLongLong((PyObject *)a);
4881 y = PyLong_AsLongLong((PyObject *)b);
4882#else
4883# error "_PyLong_GCD"
4884#endif
4885 x = Py_ABS(x);
4886 y = Py_ABS(y);
4887 Py_DECREF(a);
4888 Py_DECREF(b);
4889
4890 /* usual Euclidean algorithm for longs */
4891 while (y != 0) {
4892 t = y;
4893 y = x % y;
4894 x = t;
4895 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004896#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004897 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004898#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004899 return PyLong_FromLongLong(x);
4900#else
4901# error "_PyLong_GCD"
4902#endif
4903
4904error:
4905 Py_DECREF(a);
4906 Py_DECREF(b);
4907 Py_XDECREF(c);
4908 Py_XDECREF(d);
4909 return NULL;
4910}
4911
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004912static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004913long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004915 double result;
4916 result = PyLong_AsDouble(v);
4917 if (result == -1.0 && PyErr_Occurred())
4918 return NULL;
4919 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004920}
4921
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004922static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004923long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
4924
4925/*[clinic input]
4926@classmethod
4927int.__new__ as long_new
4928 x: object(c_default="NULL") = 0
4929 /
4930 base as obase: object(c_default="NULL") = 10
4931[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004932
Tim Peters6d6c1a32001-08-02 04:15:00 +00004933static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004934long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
4935/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00004936{
Gregory P. Smitha689e522012-12-25 22:38:32 -08004937 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004939 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004940 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004941 if (x == NULL) {
4942 if (obase != NULL) {
4943 PyErr_SetString(PyExc_TypeError,
4944 "int() missing string argument");
4945 return NULL;
4946 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004948 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004949 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004950 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004951
Gregory P. Smitha689e522012-12-25 22:38:32 -08004952 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004953 if (base == -1 && PyErr_Occurred())
4954 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004955 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004956 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05304957 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004958 return NULL;
4959 }
4960
4961 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004962 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004963 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004964 const char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 if (PyByteArray_Check(x))
4966 string = PyByteArray_AS_STRING(x);
4967 else
4968 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004969 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004970 }
4971 else {
4972 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004973 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004974 return NULL;
4975 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004976}
4977
Serhiy Storchaka95949422013-08-27 19:40:23 +03004978/* Wimpy, slow approach to tp_new calls for subtypes of int:
4979 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004980 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004981 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004982*/
4983static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004984long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00004985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 PyLongObject *tmp, *newobj;
4987 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004990 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 if (tmp == NULL)
4992 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02004993 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004994 n = Py_SIZE(tmp);
4995 if (n < 0)
4996 n = -n;
4997 newobj = (PyLongObject *)type->tp_alloc(type, n);
4998 if (newobj == NULL) {
4999 Py_DECREF(tmp);
5000 return NULL;
5001 }
5002 assert(PyLong_Check(newobj));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005003 Py_SET_SIZE(newobj, Py_SIZE(tmp));
5004 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005005 newobj->ob_digit[i] = tmp->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005006 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005007 Py_DECREF(tmp);
5008 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005009}
5010
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005011/*[clinic input]
5012int.__getnewargs__
5013[clinic start generated code]*/
5014
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005015static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005016int___getnewargs___impl(PyObject *self)
5017/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005018{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005019 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005020}
5021
Guido van Rossumb43daf72007-08-01 18:08:08 +00005022static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005023long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005026}
5027
5028static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005029long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005031 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005032}
5033
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005034/*[clinic input]
5035int.__format__
5036
5037 format_spec: unicode
5038 /
5039[clinic start generated code]*/
5040
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005041static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005042int___format___impl(PyObject *self, PyObject *format_spec)
5043/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005044{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005045 _PyUnicodeWriter writer;
5046 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005047
Victor Stinner8f674cc2013-04-17 23:02:17 +02005048 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005049 ret = _PyLong_FormatAdvancedWriter(
5050 &writer,
5051 self,
5052 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5053 if (ret == -1) {
5054 _PyUnicodeWriter_Dealloc(&writer);
5055 return NULL;
5056 }
5057 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005058}
5059
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005060/* Return a pair (q, r) such that a = b * q + r, and
5061 abs(r) <= abs(b)/2, with equality possible only if q is even.
5062 In other words, q == a / b, rounded to the nearest integer using
5063 round-half-to-even. */
5064
5065PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005066_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005067{
5068 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005069 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005070 int quo_is_odd, quo_is_neg;
5071 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005072
5073 /* Equivalent Python code:
5074
5075 def divmod_near(a, b):
5076 q, r = divmod(a, b)
5077 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5078 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5079 # positive, 2 * r < b if b negative.
5080 greater_than_half = 2*r > b if b > 0 else 2*r < b
5081 exactly_half = 2*r == b
5082 if greater_than_half or exactly_half and q % 2 == 1:
5083 q += 1
5084 r -= b
5085 return q, r
5086
5087 */
5088 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5089 PyErr_SetString(PyExc_TypeError,
5090 "non-integer arguments in division");
5091 return NULL;
5092 }
5093
5094 /* Do a and b have different signs? If so, quotient is negative. */
5095 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5096
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005097 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5098 goto error;
5099
5100 /* compare twice the remainder with the divisor, to see
5101 if we need to adjust the quotient and remainder */
Victor Stinner8e3b9f92020-10-27 00:00:03 +01005102 PyObject *one = _PyLong_GetOne(); // borrowed reference
5103 twice_rem = long_lshift((PyObject *)rem, one);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005104 if (twice_rem == NULL)
5105 goto error;
5106 if (quo_is_neg) {
5107 temp = long_neg((PyLongObject*)twice_rem);
5108 Py_DECREF(twice_rem);
5109 twice_rem = temp;
5110 if (twice_rem == NULL)
5111 goto error;
5112 }
5113 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5114 Py_DECREF(twice_rem);
5115
5116 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5117 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5118 /* fix up quotient */
5119 if (quo_is_neg)
Victor Stinner8e3b9f92020-10-27 00:00:03 +01005120 temp = long_sub(quo, (PyLongObject *)one);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005121 else
Victor Stinner8e3b9f92020-10-27 00:00:03 +01005122 temp = long_add(quo, (PyLongObject *)one);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005123 Py_DECREF(quo);
5124 quo = (PyLongObject *)temp;
5125 if (quo == NULL)
5126 goto error;
5127 /* and remainder */
5128 if (quo_is_neg)
5129 temp = long_add(rem, (PyLongObject *)b);
5130 else
5131 temp = long_sub(rem, (PyLongObject *)b);
5132 Py_DECREF(rem);
5133 rem = (PyLongObject *)temp;
5134 if (rem == NULL)
5135 goto error;
5136 }
5137
5138 result = PyTuple_New(2);
5139 if (result == NULL)
5140 goto error;
5141
5142 /* PyTuple_SET_ITEM steals references */
5143 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5144 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005145 return result;
5146
5147 error:
5148 Py_XDECREF(quo);
5149 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005150 return NULL;
5151}
5152
Serhiy Storchaka5a2bac72020-07-20 15:57:37 +03005153/*[clinic input]
5154int.__round__
5155
5156 ndigits as o_ndigits: object = NULL
5157 /
5158
5159Rounding an Integral returns itself.
5160
5161Rounding with an ndigits argument also returns an integer.
5162[clinic start generated code]*/
5163
Eric Smith8c663262007-08-25 02:26:07 +00005164static PyObject *
Serhiy Storchaka5a2bac72020-07-20 15:57:37 +03005165int___round___impl(PyObject *self, PyObject *o_ndigits)
5166/*[clinic end generated code: output=954fda6b18875998 input=1614cf23ec9e18c3]*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005167{
Serhiy Storchaka5a2bac72020-07-20 15:57:37 +03005168 PyObject *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005169
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005170 /* To round an integer m to the nearest 10**n (n positive), we make use of
5171 * the divmod_near operation, defined by:
5172 *
5173 * divmod_near(a, b) = (q, r)
5174 *
5175 * where q is the nearest integer to the quotient a / b (the
5176 * nearest even integer in the case of a tie) and r == a - q * b.
5177 * Hence q * b = a - r is the nearest multiple of b to a,
5178 * preferring even multiples in the case of a tie.
5179 *
5180 * So the nearest multiple of 10**n to m is:
5181 *
5182 * m - divmod_near(m, 10**n)[1].
5183 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005185 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005186
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03005187 ndigits = _PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005188 if (ndigits == NULL)
5189 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005190
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005191 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 if (Py_SIZE(ndigits) >= 0) {
5193 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005194 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005196
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005197 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5198 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005199 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005200 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005202 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005203
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005204 result = PyLong_FromLong(10L);
5205 if (result == NULL) {
5206 Py_DECREF(ndigits);
5207 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005209
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005210 temp = long_pow(result, ndigits, Py_None);
5211 Py_DECREF(ndigits);
5212 Py_DECREF(result);
5213 result = temp;
5214 if (result == NULL)
5215 return NULL;
5216
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005217 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005218 Py_DECREF(result);
5219 result = temp;
5220 if (result == NULL)
5221 return NULL;
5222
5223 temp = long_sub((PyLongObject *)self,
5224 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5225 Py_DECREF(result);
5226 result = temp;
5227
5228 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005229}
5230
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005231/*[clinic input]
5232int.__sizeof__ -> Py_ssize_t
5233
5234Returns size in memory, in bytes.
5235[clinic start generated code]*/
5236
5237static Py_ssize_t
5238int___sizeof___impl(PyObject *self)
5239/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005241 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005242
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005243 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5244 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005245}
5246
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005247/*[clinic input]
5248int.bit_length
5249
5250Number of bits necessary to represent self in binary.
5251
5252>>> bin(37)
5253'0b100101'
5254>>> (37).bit_length()
52556
5256[clinic start generated code]*/
5257
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005258static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005259int_bit_length_impl(PyObject *self)
5260/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005263 Py_ssize_t ndigits;
5264 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005266
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005267 assert(self != NULL);
5268 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005269
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005270 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 if (ndigits == 0)
5272 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005273
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005274 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Niklas Fiekas794e7d12020-06-15 14:33:48 +02005275 msd_bits = bit_length_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5278 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 /* expression above may overflow; use Python integers instead */
5281 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5282 if (result == NULL)
5283 return NULL;
5284 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5285 if (x == NULL)
5286 goto error;
5287 y = (PyLongObject *)long_mul(result, x);
5288 Py_DECREF(x);
5289 if (y == NULL)
5290 goto error;
5291 Py_DECREF(result);
5292 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5295 if (x == NULL)
5296 goto error;
5297 y = (PyLongObject *)long_add(result, x);
5298 Py_DECREF(x);
5299 if (y == NULL)
5300 goto error;
5301 Py_DECREF(result);
5302 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005305
Mark Dickinson22b20182010-05-10 21:27:53 +00005306 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 Py_DECREF(result);
5308 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005309}
5310
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005311static int
5312popcount_digit(digit d)
5313{
Victor Stinnerc6b292c2020-06-08 16:30:33 +02005314 // digit can be larger than uint32_t, but only PyLong_SHIFT bits
5315 // of it will be ever used.
5316 Py_BUILD_ASSERT(PyLong_SHIFT <= 32);
5317 return _Py_popcount32((uint32_t)d);
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005318}
5319
5320/*[clinic input]
5321int.bit_count
5322
5323Number of ones in the binary representation of the absolute value of self.
5324
5325Also known as the population count.
5326
5327>>> bin(13)
5328'0b1101'
5329>>> (13).bit_count()
53303
5331[clinic start generated code]*/
5332
5333static PyObject *
5334int_bit_count_impl(PyObject *self)
5335/*[clinic end generated code: output=2e571970daf1e5c3 input=7e0adef8e8ccdf2e]*/
5336{
5337 assert(self != NULL);
5338 assert(PyLong_Check(self));
5339
5340 PyLongObject *z = (PyLongObject *)self;
5341 Py_ssize_t ndigits = Py_ABS(Py_SIZE(z));
5342 Py_ssize_t bit_count = 0;
5343
5344 /* Each digit has up to PyLong_SHIFT ones, so the accumulated bit count
5345 from the first PY_SSIZE_T_MAX/PyLong_SHIFT digits can't overflow a
5346 Py_ssize_t. */
5347 Py_ssize_t ndigits_fast = Py_MIN(ndigits, PY_SSIZE_T_MAX/PyLong_SHIFT);
5348 for (Py_ssize_t i = 0; i < ndigits_fast; i++) {
5349 bit_count += popcount_digit(z->ob_digit[i]);
5350 }
5351
5352 PyObject *result = PyLong_FromSsize_t(bit_count);
5353 if (result == NULL) {
5354 return NULL;
5355 }
5356
5357 /* Use Python integers if bit_count would overflow. */
5358 for (Py_ssize_t i = ndigits_fast; i < ndigits; i++) {
5359 PyObject *x = PyLong_FromLong(popcount_digit(z->ob_digit[i]));
5360 if (x == NULL) {
5361 goto error;
5362 }
5363 PyObject *y = long_add((PyLongObject *)result, (PyLongObject *)x);
5364 Py_DECREF(x);
5365 if (y == NULL) {
5366 goto error;
5367 }
5368 Py_DECREF(result);
5369 result = y;
5370 }
5371
5372 return result;
5373
5374 error:
5375 Py_DECREF(result);
5376 return NULL;
5377}
Christian Heimes53876d92008-04-19 00:31:39 +00005378
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005379/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005380int.as_integer_ratio
5381
5382Return integer ratio.
5383
5384Return a pair of integers, whose ratio is exactly equal to the original int
5385and with a positive denominator.
5386
5387>>> (10).as_integer_ratio()
5388(10, 1)
5389>>> (-10).as_integer_ratio()
5390(-10, 1)
5391>>> (0).as_integer_ratio()
5392(0, 1)
5393[clinic start generated code]*/
5394
5395static PyObject *
5396int_as_integer_ratio_impl(PyObject *self)
5397/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5398{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005399 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005400 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005401 if (numerator == NULL) {
5402 return NULL;
5403 }
Victor Stinner8e3b9f92020-10-27 00:00:03 +01005404 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_GetOne());
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005405 Py_DECREF(numerator);
5406 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005407}
5408
5409/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005410int.to_bytes
5411
5412 length: Py_ssize_t
5413 Length of bytes object to use. An OverflowError is raised if the
5414 integer is not representable with the given number of bytes.
5415 byteorder: unicode
5416 The byte order used to represent the integer. If byteorder is 'big',
5417 the most significant byte is at the beginning of the byte array. If
5418 byteorder is 'little', the most significant byte is at the end of the
5419 byte array. To request the native byte order of the host system, use
5420 `sys.byteorder' as the byte order value.
5421 *
5422 signed as is_signed: bool = False
5423 Determines whether two's complement is used to represent the integer.
5424 If signed is False and a negative integer is given, an OverflowError
5425 is raised.
5426
5427Return an array of bytes representing an integer.
5428[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005429
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005430static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005431int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5432 int is_signed)
5433/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005435 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005437
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005438 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005440 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 little_endian = 0;
5442 else {
5443 PyErr_SetString(PyExc_ValueError,
5444 "byteorder must be either 'little' or 'big'");
5445 return NULL;
5446 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 if (length < 0) {
5449 PyErr_SetString(PyExc_ValueError,
5450 "length argument must be non-negative");
5451 return NULL;
5452 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005454 bytes = PyBytes_FromStringAndSize(NULL, length);
5455 if (bytes == NULL)
5456 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005457
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005458 if (_PyLong_AsByteArray((PyLongObject *)self,
5459 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 length, little_endian, is_signed) < 0) {
5461 Py_DECREF(bytes);
5462 return NULL;
5463 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005466}
5467
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005468/*[clinic input]
5469@classmethod
5470int.from_bytes
5471
5472 bytes as bytes_obj: object
5473 Holds the array of bytes to convert. The argument must either
5474 support the buffer protocol or be an iterable object producing bytes.
5475 Bytes and bytearray are examples of built-in objects that support the
5476 buffer protocol.
5477 byteorder: unicode
5478 The byte order used to represent the integer. If byteorder is 'big',
5479 the most significant byte is at the beginning of the byte array. If
5480 byteorder is 'little', the most significant byte is at the end of the
5481 byte array. To request the native byte order of the host system, use
5482 `sys.byteorder' as the byte order value.
5483 *
5484 signed as is_signed: bool = False
5485 Indicates whether two's complement is used to represent the integer.
5486
5487Return the integer represented by the given array of bytes.
5488[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005489
5490static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005491int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5492 PyObject *byteorder, int is_signed)
5493/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005495 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005496 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005497
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005498 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005500 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 little_endian = 0;
5502 else {
5503 PyErr_SetString(PyExc_ValueError,
5504 "byteorder must be either 'little' or 'big'");
5505 return NULL;
5506 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005507
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005508 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005509 if (bytes == NULL)
5510 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005512 long_obj = _PyLong_FromByteArray(
5513 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5514 little_endian, is_signed);
5515 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005516
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005517 if (long_obj != NULL && type != &PyLong_Type) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005518 Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005522}
5523
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005524static PyObject *
5525long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5526{
5527 return long_long(self);
5528}
5529
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005530static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005531 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005532 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005533 INT_BIT_LENGTH_METHODDEF
Niklas Fiekas8bd216d2020-05-29 18:28:02 +02005534 INT_BIT_COUNT_METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005535 INT_TO_BYTES_METHODDEF
5536 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005537 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005538 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005540 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005542 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 "Ceiling of an Integral returns itself."},
Serhiy Storchaka5a2bac72020-07-20 15:57:37 +03005544 INT___ROUND___METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005545 INT___GETNEWARGS___METHODDEF
5546 INT___FORMAT___METHODDEF
5547 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005548 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005549};
5550
Guido van Rossumb43daf72007-08-01 18:08:08 +00005551static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005552 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005553 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005554 "the real part of a complex number",
5555 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005556 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005557 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005558 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005559 NULL},
5560 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005561 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005562 "the numerator of a rational number in lowest terms",
5563 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005564 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005565 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005566 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005567 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005568 {NULL} /* Sentinel */
5569};
5570
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005571PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005572"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005573int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005574\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005575Convert a number or string to an integer, or return 0 if no arguments\n\
5576are given. If x is a number, return x.__int__(). For floating point\n\
5577numbers, this truncates towards zero.\n\
5578\n\
5579If x is not a number or if base is given, then x must be a string,\n\
5580bytes, or bytearray instance representing an integer literal in the\n\
5581given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5582by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5583Base 0 means to interpret the base from the string as an integer literal.\n\
5584>>> int('0b100', base=0)\n\
55854");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005586
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005587static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005588 (binaryfunc)long_add, /*nb_add*/
5589 (binaryfunc)long_sub, /*nb_subtract*/
5590 (binaryfunc)long_mul, /*nb_multiply*/
5591 long_mod, /*nb_remainder*/
5592 long_divmod, /*nb_divmod*/
5593 long_pow, /*nb_power*/
5594 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005595 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005596 (unaryfunc)long_abs, /*tp_absolute*/
5597 (inquiry)long_bool, /*tp_bool*/
5598 (unaryfunc)long_invert, /*nb_invert*/
5599 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005600 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005601 long_and, /*nb_and*/
5602 long_xor, /*nb_xor*/
5603 long_or, /*nb_or*/
5604 long_long, /*nb_int*/
5605 0, /*nb_reserved*/
5606 long_float, /*nb_float*/
5607 0, /* nb_inplace_add */
5608 0, /* nb_inplace_subtract */
5609 0, /* nb_inplace_multiply */
5610 0, /* nb_inplace_remainder */
5611 0, /* nb_inplace_power */
5612 0, /* nb_inplace_lshift */
5613 0, /* nb_inplace_rshift */
5614 0, /* nb_inplace_and */
5615 0, /* nb_inplace_xor */
5616 0, /* nb_inplace_or */
5617 long_div, /* nb_floor_divide */
5618 long_true_divide, /* nb_true_divide */
5619 0, /* nb_inplace_floor_divide */
5620 0, /* nb_inplace_true_divide */
5621 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005622};
5623
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005624PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5626 "int", /* tp_name */
5627 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5628 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005629 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005630 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 0, /* tp_getattr */
5632 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005633 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 long_to_decimal_string, /* tp_repr */
5635 &long_as_number, /* tp_as_number */
5636 0, /* tp_as_sequence */
5637 0, /* tp_as_mapping */
5638 (hashfunc)long_hash, /* tp_hash */
5639 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005640 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005641 PyObject_GenericGetAttr, /* tp_getattro */
5642 0, /* tp_setattro */
5643 0, /* tp_as_buffer */
5644 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5645 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5646 long_doc, /* tp_doc */
5647 0, /* tp_traverse */
5648 0, /* tp_clear */
5649 long_richcompare, /* tp_richcompare */
5650 0, /* tp_weaklistoffset */
5651 0, /* tp_iter */
5652 0, /* tp_iternext */
5653 long_methods, /* tp_methods */
5654 0, /* tp_members */
5655 long_getset, /* tp_getset */
5656 0, /* tp_base */
5657 0, /* tp_dict */
5658 0, /* tp_descr_get */
5659 0, /* tp_descr_set */
5660 0, /* tp_dictoffset */
5661 0, /* tp_init */
5662 0, /* tp_alloc */
5663 long_new, /* tp_new */
5664 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005665};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005666
Mark Dickinsonbd792642009-03-18 20:06:12 +00005667static PyTypeObject Int_InfoType;
5668
5669PyDoc_STRVAR(int_info__doc__,
5670"sys.int_info\n\
5671\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005672A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005673internal representation of integers. The attributes are read only.");
5674
5675static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005676 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005677 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005678 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005679};
5680
5681static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 "sys.int_info", /* name */
5683 int_info__doc__, /* doc */
5684 int_info_fields, /* fields */
5685 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005686};
5687
5688PyObject *
5689PyLong_GetInfo(void)
5690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005691 PyObject* int_info;
5692 int field = 0;
5693 int_info = PyStructSequence_New(&Int_InfoType);
5694 if (int_info == NULL)
5695 return NULL;
5696 PyStructSequence_SET_ITEM(int_info, field++,
5697 PyLong_FromLong(PyLong_SHIFT));
5698 PyStructSequence_SET_ITEM(int_info, field++,
5699 PyLong_FromLong(sizeof(digit)));
5700 if (PyErr_Occurred()) {
5701 Py_CLEAR(int_info);
5702 return NULL;
5703 }
5704 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005705}
5706
Guido van Rossumddefaf32007-01-14 03:31:43 +00005707int
Victor Stinner630c8df2019-12-17 13:02:18 +01005708_PyLong_Init(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005709{
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005710 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5711 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5712 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005713
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005714 PyLongObject *v = _PyLong_New(1);
5715 if (!v) {
5716 return -1;
5717 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005718
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005719 Py_SET_SIZE(v, size);
Victor Stinner12174a52014-08-15 23:17:38 +02005720 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005721
Victor Stinner630c8df2019-12-17 13:02:18 +01005722 tstate->interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005723 }
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005724
Victor Stinner630c8df2019-12-17 13:02:18 +01005725 if (_Py_IsMainInterpreter(tstate)) {
5726 _PyLong_Zero = PyLong_FromLong(0);
5727 if (_PyLong_Zero == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005728 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005729 }
Victor Stinner630c8df2019-12-17 13:02:18 +01005730
5731 _PyLong_One = PyLong_FromLong(1);
5732 if (_PyLong_One == NULL) {
5733 return 0;
5734 }
5735
5736 /* initialize int_info */
5737 if (Int_InfoType.tp_name == NULL) {
5738 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5739 return 0;
5740 }
5741 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005742 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005744 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005745}
5746
5747void
Victor Stinner630c8df2019-12-17 13:02:18 +01005748_PyLong_Fini(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005749{
Victor Stinner630c8df2019-12-17 13:02:18 +01005750 if (_Py_IsMainInterpreter(tstate)) {
5751 Py_CLEAR(_PyLong_One);
5752 Py_CLEAR(_PyLong_Zero);
5753 }
5754
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005755 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinner630c8df2019-12-17 13:02:18 +01005756 Py_CLEAR(tstate->interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005757 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005758}