blob: cfb4a3e7c0d3b3ce87aec194ab50c5893954fc4a [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"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Serhiy Storchaka495e8802017-02-01 23:12:20 +020012#include "clinic/longobject.c.h"
13/*[clinic input]
14class int "PyObject *" "&PyLong_Type"
15[clinic start generated code]*/
16/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
17
Guido van Rossumddefaf32007-01-14 03:31:43 +000018#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000019#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000020#endif
21#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000023#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020025_Py_IDENTIFIER(little);
26_Py_IDENTIFIER(big);
27
Mark Dickinsone4416742009-02-15 15:14:57 +000028/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020029#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
30 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 (Py_SIZE(x) == 0 ? (sdigit)0 : \
32 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000033
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#if NSMALLNEGINTS + NSMALLPOSINTS > 0
35/* Small integers are preallocated in this array so that they
36 can be shared.
37 The integers that are preallocated are those in the range
38 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
39*/
40static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
41#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010042Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000043#endif
44
Guido van Rossum7eaf8222007-06-18 17:58:50 +000045static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000046get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000047{
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050048 PyObject *v;
Benjamin Peterson041c38a2014-03-14 21:47:23 -050049 assert(-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS);
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050050 v = (PyObject *)&small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000052#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 if (ival >= 0)
54 quick_int_allocs++;
55 else
56 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000057#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000059}
60#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
62 return get_small_int((sdigit)ival); \
63 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000066maybe_small_long(PyLongObject *v)
67{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020068 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 sdigit ival = MEDIUM_VALUE(v);
70 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
71 Py_DECREF(v);
72 return (PyLongObject *)get_small_int(ival);
73 }
74 }
75 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000076}
Guido van Rossumddefaf32007-01-14 03:31:43 +000077#else
78#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000079#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000080#endif
81
Serhiy Storchaka95949422013-08-27 19:40:23 +030082/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000083 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020084Py_LOCAL_INLINE(void)
85_PyLong_Negate(PyLongObject **x_p)
86{
87 PyLongObject *x;
88
89 x = (PyLongObject *)*x_p;
90 if (Py_REFCNT(x) == 1) {
91 Py_SIZE(x) = -Py_SIZE(x);
92 return;
93 }
94
95 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
96 Py_DECREF(x);
97}
98
Serhiy Storchaka95949422013-08-27 19:40:23 +030099/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +0000100 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +0300101 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +0000102 */
Tim Peters0973b992004-08-29 22:16:50 +0000103#define KARATSUBA_CUTOFF 70
104#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +0000105
Tim Peters47e52ee2004-08-30 02:44:38 +0000106/* For exponentiation, use the binary left-to-right algorithm
107 * unless the exponent contains more than FIVEARY_CUTOFF digits.
108 * In that case, do 5 bits at a time. The potential drawback is that
109 * a table of 2**5 intermediate results is computed.
110 */
111#define FIVEARY_CUTOFF 8
112
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000113#define SIGCHECK(PyTryBlock) \
114 do { \
115 if (PyErr_CheckSignals()) PyTryBlock \
116 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000117
Serhiy Storchaka95949422013-08-27 19:40:23 +0300118/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000119 Doesn't attempt to free the storage--in most cases, due to the nature
120 of the algorithms used, this could save at most be one word anyway. */
121
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000122static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200123long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000124{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200125 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 while (i > 0 && v->ob_digit[i-1] == 0)
129 --i;
130 if (i != j)
131 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
132 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000133}
134
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200135/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
136 using the nb_int slot, if available. Raise TypeError if either the
137 nb_int slot is not available or the result of the call to nb_int
138 returns something not of type int.
139*/
140PyLongObject *
141_PyLong_FromNbInt(PyObject *integral)
142{
143 PyNumberMethods *nb;
144 PyObject *result;
145
146 /* Fast path for the case that we already have an int. */
147 if (PyLong_CheckExact(integral)) {
148 Py_INCREF(integral);
149 return (PyLongObject *)integral;
150 }
151
152 nb = Py_TYPE(integral)->tp_as_number;
153 if (nb == NULL || nb->nb_int == NULL) {
154 PyErr_Format(PyExc_TypeError,
155 "an integer is required (got type %.200s)",
156 Py_TYPE(integral)->tp_name);
157 return NULL;
158 }
159
160 /* Convert using the nb_int slot, which should return something
161 of exact type int. */
162 result = nb->nb_int(integral);
163 if (!result || PyLong_CheckExact(result))
164 return (PyLongObject *)result;
165 if (!PyLong_Check(result)) {
166 PyErr_Format(PyExc_TypeError,
167 "__int__ returned non-int (type %.200s)",
168 result->ob_type->tp_name);
169 Py_DECREF(result);
170 return NULL;
171 }
172 /* Issue #17576: warn if 'result' not of exact type int. */
173 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
174 "__int__ returned non-int (type %.200s). "
175 "The ability to return an instance of a strict subclass of int "
176 "is deprecated, and may be removed in a future version of Python.",
177 result->ob_type->tp_name)) {
178 Py_DECREF(result);
179 return NULL;
180 }
181 return (PyLongObject *)result;
182}
183
184
Serhiy Storchaka95949422013-08-27 19:40:23 +0300185/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000186 Return NULL and set exception if we run out of memory. */
187
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000188#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000190
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000191PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000192_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 PyLongObject *result;
195 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
196 sizeof(digit)*size. Previous incarnations of this code used
197 sizeof(PyVarObject) instead of the offsetof, but this risks being
198 incorrect in the presence of padding between the PyVarObject header
199 and the digits. */
200 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
201 PyErr_SetString(PyExc_OverflowError,
202 "too many digits in integer");
203 return NULL;
204 }
205 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
206 size*sizeof(digit));
207 if (!result) {
208 PyErr_NoMemory();
209 return NULL;
210 }
211 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000212}
213
Tim Peters64b5ce32001-09-10 20:52:51 +0000214PyObject *
215_PyLong_Copy(PyLongObject *src)
216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 PyLongObject *result;
218 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 assert(src != NULL);
221 i = Py_SIZE(src);
222 if (i < 0)
223 i = -(i);
224 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100225 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 CHECK_SMALL_INT(ival);
227 }
228 result = _PyLong_New(i);
229 if (result != NULL) {
230 Py_SIZE(result) = Py_SIZE(src);
231 while (--i >= 0)
232 result->ob_digit[i] = src->ob_digit[i];
233 }
234 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000235}
236
Serhiy Storchaka95949422013-08-27 19:40:23 +0300237/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000239PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000240PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 PyLongObject *v;
243 unsigned long abs_ival;
244 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
245 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100246 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (ival < 0) {
251 /* negate: can't write this as abs_ival = -ival since that
252 invokes undefined behaviour when ival is LONG_MIN */
253 abs_ival = 0U-(unsigned long)ival;
254 sign = -1;
255 }
256 else {
257 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100258 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 /* Fast path for single-digit ints */
262 if (!(abs_ival >> PyLong_SHIFT)) {
263 v = _PyLong_New(1);
264 if (v) {
265 Py_SIZE(v) = sign;
266 v->ob_digit[0] = Py_SAFE_DOWNCAST(
267 abs_ival, unsigned long, digit);
268 }
269 return (PyObject*)v;
270 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000271
Mark Dickinson249b8982009-04-27 19:41:00 +0000272#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 /* 2 digits */
274 if (!(abs_ival >> 2*PyLong_SHIFT)) {
275 v = _PyLong_New(2);
276 if (v) {
277 Py_SIZE(v) = 2*sign;
278 v->ob_digit[0] = Py_SAFE_DOWNCAST(
279 abs_ival & PyLong_MASK, unsigned long, digit);
280 v->ob_digit[1] = Py_SAFE_DOWNCAST(
281 abs_ival >> PyLong_SHIFT, unsigned long, digit);
282 }
283 return (PyObject*)v;
284 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000285#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 /* Larger numbers: loop to determine number of digits */
288 t = abs_ival;
289 while (t) {
290 ++ndigits;
291 t >>= PyLong_SHIFT;
292 }
293 v = _PyLong_New(ndigits);
294 if (v != NULL) {
295 digit *p = v->ob_digit;
296 Py_SIZE(v) = ndigits*sign;
297 t = abs_ival;
298 while (t) {
299 *p++ = Py_SAFE_DOWNCAST(
300 t & PyLong_MASK, unsigned long, digit);
301 t >>= PyLong_SHIFT;
302 }
303 }
304 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000305}
306
Serhiy Storchaka95949422013-08-27 19:40:23 +0300307/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000308
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000309PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000310PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 PyLongObject *v;
313 unsigned long t;
314 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (ival < PyLong_BASE)
317 return PyLong_FromLong(ival);
318 /* Count the number of Python digits. */
orenmn86aa2692017-03-06 10:42:47 +0200319 t = ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 while (t) {
321 ++ndigits;
322 t >>= PyLong_SHIFT;
323 }
324 v = _PyLong_New(ndigits);
325 if (v != NULL) {
326 digit *p = v->ob_digit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 while (ival) {
328 *p++ = (digit)(ival & PyLong_MASK);
329 ival >>= PyLong_SHIFT;
330 }
331 }
332 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000333}
334
Serhiy Storchaka95949422013-08-27 19:40:23 +0300335/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000336
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000337PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 PyLongObject *v;
341 double frac;
342 int i, ndig, expo, neg;
343 neg = 0;
344 if (Py_IS_INFINITY(dval)) {
345 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000346 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return NULL;
348 }
349 if (Py_IS_NAN(dval)) {
350 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000351 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 return NULL;
353 }
354 if (dval < 0.0) {
355 neg = 1;
356 dval = -dval;
357 }
358 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
359 if (expo <= 0)
360 return PyLong_FromLong(0L);
361 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
362 v = _PyLong_New(ndig);
363 if (v == NULL)
364 return NULL;
365 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
366 for (i = ndig; --i >= 0; ) {
367 digit bits = (digit)frac;
368 v->ob_digit[i] = bits;
369 frac = frac - (double)bits;
370 frac = ldexp(frac, PyLong_SHIFT);
371 }
372 if (neg)
373 Py_SIZE(v) = -(Py_SIZE(v));
374 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000375}
376
Thomas Wouters89f507f2006-12-13 04:49:30 +0000377/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
378 * anything about what happens when a signed integer operation overflows,
379 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700380 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000381 * (unsigned long)LONG_MAX, and for the smallest negative signed long
382 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
383 * However, some other compilers warn about applying unary minus to an
384 * unsigned operand. Hence the weird "0-".
385 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
387#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000388
Serhiy Storchaka95949422013-08-27 19:40:23 +0300389/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100390 method.
391
392 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
393 the result. Otherwise *overflow is 0.
394
395 For other errors (e.g., TypeError), return -1 and set an error condition.
396 In this case *overflow will be 0.
397*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000398
399long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000400PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200403 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 unsigned long x, prev;
405 long res;
406 Py_ssize_t i;
407 int sign;
408 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 *overflow = 0;
411 if (vv == NULL) {
412 PyErr_BadInternalCall();
413 return -1;
414 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000415
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200416 if (PyLong_Check(vv)) {
417 v = (PyLongObject *)vv;
418 }
419 else {
420 v = _PyLong_FromNbInt(vv);
421 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 return -1;
423 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 switch (i) {
430 case -1:
431 res = -(sdigit)v->ob_digit[0];
432 break;
433 case 0:
434 res = 0;
435 break;
436 case 1:
437 res = v->ob_digit[0];
438 break;
439 default:
440 sign = 1;
441 x = 0;
442 if (i < 0) {
443 sign = -1;
444 i = -(i);
445 }
446 while (--i >= 0) {
447 prev = x;
448 x = (x << PyLong_SHIFT) | v->ob_digit[i];
449 if ((x >> PyLong_SHIFT) != prev) {
450 *overflow = sign;
451 goto exit;
452 }
453 }
454 /* Haven't lost any bits, but casting to long requires extra
455 * care (see comment above).
456 */
457 if (x <= (unsigned long)LONG_MAX) {
458 res = (long)x * sign;
459 }
460 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
461 res = LONG_MIN;
462 }
463 else {
464 *overflow = sign;
465 /* res is already set to -1 */
466 }
467 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000468 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200470 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 }
472 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000473}
474
Serhiy Storchaka95949422013-08-27 19:40:23 +0300475/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100476 method. Return -1 and set an error if overflow occurs. */
477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000479PyLong_AsLong(PyObject *obj)
480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 int overflow;
482 long result = PyLong_AsLongAndOverflow(obj, &overflow);
483 if (overflow) {
484 /* XXX: could be cute and give a different
485 message for overflow == -1 */
486 PyErr_SetString(PyExc_OverflowError,
487 "Python int too large to convert to C long");
488 }
489 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000490}
491
Serhiy Storchaka95949422013-08-27 19:40:23 +0300492/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200493 method. Return -1 and set an error if overflow occurs. */
494
495int
496_PyLong_AsInt(PyObject *obj)
497{
498 int overflow;
499 long result = PyLong_AsLongAndOverflow(obj, &overflow);
500 if (overflow || result > INT_MAX || result < INT_MIN) {
501 /* XXX: could be cute and give a different
502 message for overflow == -1 */
503 PyErr_SetString(PyExc_OverflowError,
504 "Python int too large to convert to C int");
505 return -1;
506 }
507 return (int)result;
508}
509
Serhiy Storchaka95949422013-08-27 19:40:23 +0300510/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000511 Returns -1 and sets an error condition if overflow occurs. */
512
513Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000514PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200515 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 size_t x, prev;
517 Py_ssize_t i;
518 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (vv == NULL) {
521 PyErr_BadInternalCall();
522 return -1;
523 }
524 if (!PyLong_Check(vv)) {
525 PyErr_SetString(PyExc_TypeError, "an integer is required");
526 return -1;
527 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 v = (PyLongObject *)vv;
530 i = Py_SIZE(v);
531 switch (i) {
532 case -1: return -(sdigit)v->ob_digit[0];
533 case 0: return 0;
534 case 1: return v->ob_digit[0];
535 }
536 sign = 1;
537 x = 0;
538 if (i < 0) {
539 sign = -1;
540 i = -(i);
541 }
542 while (--i >= 0) {
543 prev = x;
544 x = (x << PyLong_SHIFT) | v->ob_digit[i];
545 if ((x >> PyLong_SHIFT) != prev)
546 goto overflow;
547 }
548 /* Haven't lost any bits, but casting to a signed type requires
549 * extra care (see comment above).
550 */
551 if (x <= (size_t)PY_SSIZE_T_MAX) {
552 return (Py_ssize_t)x * sign;
553 }
554 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
555 return PY_SSIZE_T_MIN;
556 }
557 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000558
Mark Dickinson22b20182010-05-10 21:27:53 +0000559 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 PyErr_SetString(PyExc_OverflowError,
561 "Python int too large to convert to C ssize_t");
562 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000563}
564
Serhiy Storchaka95949422013-08-27 19:40:23 +0300565/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000566 Returns -1 and sets an error condition if overflow occurs. */
567
568unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000569PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000570{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200571 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 unsigned long x, prev;
573 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 if (vv == NULL) {
576 PyErr_BadInternalCall();
577 return (unsigned long)-1;
578 }
579 if (!PyLong_Check(vv)) {
580 PyErr_SetString(PyExc_TypeError, "an integer is required");
581 return (unsigned long)-1;
582 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 v = (PyLongObject *)vv;
585 i = Py_SIZE(v);
586 x = 0;
587 if (i < 0) {
588 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000589 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 return (unsigned long) -1;
591 }
592 switch (i) {
593 case 0: return 0;
594 case 1: return v->ob_digit[0];
595 }
596 while (--i >= 0) {
597 prev = x;
598 x = (x << PyLong_SHIFT) | v->ob_digit[i];
599 if ((x >> PyLong_SHIFT) != prev) {
600 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100601 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000602 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 return (unsigned long) -1;
604 }
605 }
606 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000607}
608
Serhiy Storchaka95949422013-08-27 19:40:23 +0300609/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200610 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000611
612size_t
613PyLong_AsSize_t(PyObject *vv)
614{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200615 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 size_t x, prev;
617 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (vv == NULL) {
620 PyErr_BadInternalCall();
621 return (size_t) -1;
622 }
623 if (!PyLong_Check(vv)) {
624 PyErr_SetString(PyExc_TypeError, "an integer is required");
625 return (size_t)-1;
626 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 v = (PyLongObject *)vv;
629 i = Py_SIZE(v);
630 x = 0;
631 if (i < 0) {
632 PyErr_SetString(PyExc_OverflowError,
633 "can't convert negative value to size_t");
634 return (size_t) -1;
635 }
636 switch (i) {
637 case 0: return 0;
638 case 1: return v->ob_digit[0];
639 }
640 while (--i >= 0) {
641 prev = x;
642 x = (x << PyLong_SHIFT) | v->ob_digit[i];
643 if ((x >> PyLong_SHIFT) != prev) {
644 PyErr_SetString(PyExc_OverflowError,
645 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200646 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 }
648 }
649 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000650}
651
Serhiy Storchaka95949422013-08-27 19:40:23 +0300652/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000653 Returns -1 and sets an error condition if an error occurs. */
654
Guido van Rossumddefaf32007-01-14 03:31:43 +0000655static unsigned long
656_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000657{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200658 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 unsigned long x;
660 Py_ssize_t i;
661 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 if (vv == NULL || !PyLong_Check(vv)) {
664 PyErr_BadInternalCall();
665 return (unsigned long) -1;
666 }
667 v = (PyLongObject *)vv;
668 i = Py_SIZE(v);
669 switch (i) {
670 case 0: return 0;
671 case 1: return v->ob_digit[0];
672 }
673 sign = 1;
674 x = 0;
675 if (i < 0) {
676 sign = -1;
677 i = -i;
678 }
679 while (--i >= 0) {
680 x = (x << PyLong_SHIFT) | v->ob_digit[i];
681 }
682 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000683}
684
Guido van Rossumddefaf32007-01-14 03:31:43 +0000685unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200686PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 PyLongObject *lo;
689 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000690
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200691 if (op == NULL) {
692 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 return (unsigned long)-1;
694 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000695
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200696 if (PyLong_Check(op)) {
697 return _PyLong_AsUnsignedLongMask(op);
698 }
699
700 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (lo == NULL)
702 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200703
704 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
705 Py_DECREF(lo);
706 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000707}
708
Tim Peters5b8132f2003-01-31 15:52:05 +0000709int
710_PyLong_Sign(PyObject *vv)
711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 assert(v != NULL);
715 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000718}
719
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200720/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
721 2**k if d is nonzero, else 0. */
722
723static const unsigned char BitLengthTable[32] = {
724 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
725 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
726};
727
728static int
729bits_in_digit(digit d)
730{
731 int d_bits = 0;
732 while (d >= 32) {
733 d_bits += 6;
734 d >>= 6;
735 }
736 d_bits += (int)BitLengthTable[d];
737 return d_bits;
738}
739
Tim Petersbaefd9e2003-01-28 20:37:45 +0000740size_t
741_PyLong_NumBits(PyObject *vv)
742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 PyLongObject *v = (PyLongObject *)vv;
744 size_t result = 0;
745 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200746 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 assert(v != NULL);
749 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200750 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
752 if (ndigits > 0) {
753 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700754 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100756 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200757 msd_bits = bits_in_digit(msd);
758 if (SIZE_MAX - msd_bits < result)
759 goto Overflow;
760 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 }
762 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000763
Mark Dickinson22b20182010-05-10 21:27:53 +0000764 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
766 "to express in a platform size_t");
767 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000768}
769
Tim Peters2a9b3672001-06-11 21:23:58 +0000770PyObject *
771_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000773{
Mark Dickinson22b20182010-05-10 21:27:53 +0000774 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 int incr; /* direction to move pstartbyte */
776 const unsigned char* pendbyte; /* MSB of bytes */
777 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300778 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 PyLongObject* v; /* result */
780 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (n == 0)
783 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (little_endian) {
786 pstartbyte = bytes;
787 pendbyte = bytes + n - 1;
788 incr = 1;
789 }
790 else {
791 pstartbyte = bytes + n - 1;
792 pendbyte = bytes;
793 incr = -1;
794 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (is_signed)
797 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200800 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 is positive, and leading 0xff bytes if negative. */
802 {
803 size_t i;
804 const unsigned char* p = pendbyte;
805 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000806 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000809 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 break;
811 }
812 numsignificantbytes = n - i;
813 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
814 actually has 2 significant bytes. OTOH, 0xff0001 ==
815 -0x00ffff, so we wouldn't *need* to bump it there; but we
816 do for 0xffff = -0x0001. To be safe without bothering to
817 check every case, bump it regardless. */
818 if (is_signed && numsignificantbytes < n)
819 ++numsignificantbytes;
820 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000821
Serhiy Storchaka95949422013-08-27 19:40:23 +0300822 /* How many Python int digits do we need? We have
823 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
825 /* catch overflow before it happens */
826 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
827 PyErr_SetString(PyExc_OverflowError,
828 "byte array too long to convert to int");
829 return NULL;
830 }
831 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
832 v = _PyLong_New(ndigits);
833 if (v == NULL)
834 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 /* Copy the bits over. The tricky parts are computing 2's-comp on
837 the fly for signed numbers, and dealing with the mismatch between
838 8-bit bytes and (probably) 15-bit Python digits.*/
839 {
840 size_t i;
841 twodigits carry = 1; /* for 2's-comp calculation */
842 twodigits accum = 0; /* sliding register */
843 unsigned int accumbits = 0; /* number of bits in accum */
844 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
847 twodigits thisbyte = *p;
848 /* Compute correction for 2's comp, if needed. */
849 if (is_signed) {
850 thisbyte = (0xff ^ thisbyte) + carry;
851 carry = thisbyte >> 8;
852 thisbyte &= 0xff;
853 }
854 /* Because we're going LSB to MSB, thisbyte is
855 more significant than what's already in accum,
856 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200857 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 accumbits += 8;
859 if (accumbits >= PyLong_SHIFT) {
860 /* There's enough to fill a Python digit. */
861 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000862 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 ++idigit;
864 accum >>= PyLong_SHIFT;
865 accumbits -= PyLong_SHIFT;
866 assert(accumbits < PyLong_SHIFT);
867 }
868 }
869 assert(accumbits < PyLong_SHIFT);
870 if (accumbits) {
871 assert(idigit < ndigits);
872 v->ob_digit[idigit] = (digit)accum;
873 ++idigit;
874 }
875 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 Py_SIZE(v) = is_signed ? -idigit : idigit;
878 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000879}
880
881int
882_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 unsigned char* bytes, size_t n,
884 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000887 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000889 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
891 digit carry; /* for computing 2's-comp */
892 size_t j; /* # bytes filled */
893 unsigned char* p; /* pointer to next byte in bytes */
894 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 if (Py_SIZE(v) < 0) {
899 ndigits = -(Py_SIZE(v));
900 if (!is_signed) {
901 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000902 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 return -1;
904 }
905 do_twos_comp = 1;
906 }
907 else {
908 ndigits = Py_SIZE(v);
909 do_twos_comp = 0;
910 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (little_endian) {
913 p = bytes;
914 pincr = 1;
915 }
916 else {
917 p = bytes + n - 1;
918 pincr = -1;
919 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* Copy over all the Python digits.
922 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300923 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 normalized. */
925 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
926 j = 0;
927 accum = 0;
928 accumbits = 0;
929 carry = do_twos_comp ? 1 : 0;
930 for (i = 0; i < ndigits; ++i) {
931 digit thisdigit = v->ob_digit[i];
932 if (do_twos_comp) {
933 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
934 carry = thisdigit >> PyLong_SHIFT;
935 thisdigit &= PyLong_MASK;
936 }
937 /* Because we're going LSB to MSB, thisdigit is more
938 significant than what's already in accum, so needs to be
939 prepended to accum. */
940 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* The most-significant digit may be (probably is) at least
943 partly empty. */
944 if (i == ndigits - 1) {
945 /* Count # of sign bits -- they needn't be stored,
946 * although for signed conversion we need later to
947 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000948 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 while (s != 0) {
950 s >>= 1;
951 accumbits++;
952 }
953 }
954 else
955 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 /* Store as many bytes as possible. */
958 while (accumbits >= 8) {
959 if (j >= n)
960 goto Overflow;
961 ++j;
962 *p = (unsigned char)(accum & 0xff);
963 p += pincr;
964 accumbits -= 8;
965 accum >>= 8;
966 }
967 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 /* Store the straggler (if any). */
970 assert(accumbits < 8);
971 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
972 if (accumbits > 0) {
973 if (j >= n)
974 goto Overflow;
975 ++j;
976 if (do_twos_comp) {
977 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300978 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 infinite supply of sign bits). */
980 accum |= (~(twodigits)0) << accumbits;
981 }
982 *p = (unsigned char)(accum & 0xff);
983 p += pincr;
984 }
985 else if (j == n && n > 0 && is_signed) {
986 /* The main loop filled the byte array exactly, so the code
987 just above didn't get to ensure there's a sign bit, and the
988 loop below wouldn't add one either. Make sure a sign bit
989 exists. */
990 unsigned char msb = *(p - pincr);
991 int sign_bit_set = msb >= 0x80;
992 assert(accumbits == 0);
993 if (sign_bit_set == do_twos_comp)
994 return 0;
995 else
996 goto Overflow;
997 }
Tim Peters05607ad2001-06-13 21:01:27 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 /* Fill remaining bytes with copies of the sign bit. */
1000 {
1001 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1002 for ( ; j < n; ++j, p += pincr)
1003 *p = signbyte;
1004 }
Tim Peters05607ad2001-06-13 21:01:27 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001007
Mark Dickinson22b20182010-05-10 21:27:53 +00001008 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1010 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001011
Tim Peters2a9b3672001-06-11 21:23:58 +00001012}
1013
Serhiy Storchaka95949422013-08-27 19:40:23 +03001014/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001015
1016PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001017PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001018{
Mark Dickinson91044792012-10-18 19:21:43 +01001019#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001020 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001021#else
1022
Tim Peters70128a12001-06-16 08:48:40 +00001023#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001024# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001025#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001026 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001027#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001028
Guido van Rossum78694d91998-09-18 14:14:13 +00001029}
1030
Serhiy Storchaka95949422013-08-27 19:40:23 +03001031/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001032
1033void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001034PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001035{
Tim Peters70128a12001-06-16 08:48:40 +00001036#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1040 x = PyLong_AsLong(vv);
1041 else
1042 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001043#else
Tim Peters70128a12001-06-16 08:48:40 +00001044
Tim Peters70128a12001-06-16 08:48:40 +00001045#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001046# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001047#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001048 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1051 x = PyLong_AsLongLong(vv);
1052 else
1053 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001054
1055#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 if (x == -1 && PyErr_Occurred())
1058 return NULL;
1059 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001060}
1061
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001062/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001063 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001064 */
1065
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001066#define PY_ABS_LLONG_MIN (0-(unsigned long long)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001067
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001068/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001069
1070PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001071PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001074 unsigned long long abs_ival;
1075 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 int ndigits = 0;
1077 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 CHECK_SMALL_INT(ival);
1080 if (ival < 0) {
1081 /* avoid signed overflow on negation; see comments
1082 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001083 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 negative = 1;
1085 }
1086 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001087 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 /* Count the number of Python digits.
1091 We used to pick 5 ("big enough for anything"), but that's a
1092 waste of time and space given that 5*15 = 75 bits are rarely
1093 needed. */
1094 t = abs_ival;
1095 while (t) {
1096 ++ndigits;
1097 t >>= PyLong_SHIFT;
1098 }
1099 v = _PyLong_New(ndigits);
1100 if (v != NULL) {
1101 digit *p = v->ob_digit;
1102 Py_SIZE(v) = negative ? -ndigits : ndigits;
1103 t = abs_ival;
1104 while (t) {
1105 *p++ = (digit)(t & PyLong_MASK);
1106 t >>= PyLong_SHIFT;
1107 }
1108 }
1109 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001110}
1111
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001112/* Create a new int object from a C unsigned long long int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001113
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001114PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001115PyLong_FromUnsignedLongLong(unsigned long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001118 unsigned long long t;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (ival < PyLong_BASE)
1122 return PyLong_FromLong((long)ival);
1123 /* Count the number of Python digits. */
orenmn86aa2692017-03-06 10:42:47 +02001124 t = ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 while (t) {
1126 ++ndigits;
1127 t >>= PyLong_SHIFT;
1128 }
1129 v = _PyLong_New(ndigits);
1130 if (v != NULL) {
1131 digit *p = v->ob_digit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 while (ival) {
1133 *p++ = (digit)(ival & PyLong_MASK);
1134 ival >>= PyLong_SHIFT;
1135 }
1136 }
1137 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001138}
1139
Serhiy Storchaka95949422013-08-27 19:40:23 +03001140/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001141
1142PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001143PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyLongObject *v;
1146 size_t abs_ival;
1147 size_t t; /* unsigned so >> doesn't propagate sign bit */
1148 int ndigits = 0;
1149 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 CHECK_SMALL_INT(ival);
1152 if (ival < 0) {
1153 /* avoid signed overflow when ival = SIZE_T_MIN */
1154 abs_ival = (size_t)(-1-ival)+1;
1155 negative = 1;
1156 }
1157 else {
1158 abs_ival = (size_t)ival;
1159 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 /* Count the number of Python digits. */
1162 t = abs_ival;
1163 while (t) {
1164 ++ndigits;
1165 t >>= PyLong_SHIFT;
1166 }
1167 v = _PyLong_New(ndigits);
1168 if (v != NULL) {
1169 digit *p = v->ob_digit;
1170 Py_SIZE(v) = negative ? -ndigits : ndigits;
1171 t = abs_ival;
1172 while (t) {
1173 *p++ = (digit)(t & PyLong_MASK);
1174 t >>= PyLong_SHIFT;
1175 }
1176 }
1177 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001178}
1179
Serhiy Storchaka95949422013-08-27 19:40:23 +03001180/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001181
1182PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001183PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 PyLongObject *v;
1186 size_t t;
1187 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 if (ival < PyLong_BASE)
1190 return PyLong_FromLong((long)ival);
1191 /* Count the number of Python digits. */
1192 t = ival;
1193 while (t) {
1194 ++ndigits;
1195 t >>= PyLong_SHIFT;
1196 }
1197 v = _PyLong_New(ndigits);
1198 if (v != NULL) {
1199 digit *p = v->ob_digit;
1200 Py_SIZE(v) = ndigits;
1201 while (ival) {
1202 *p++ = (digit)(ival & PyLong_MASK);
1203 ival >>= PyLong_SHIFT;
1204 }
1205 }
1206 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001207}
1208
Serhiy Storchaka95949422013-08-27 19:40:23 +03001209/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001210 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001211
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001212long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001213PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001216 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001218 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (vv == NULL) {
1221 PyErr_BadInternalCall();
1222 return -1;
1223 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001224
1225 if (PyLong_Check(vv)) {
1226 v = (PyLongObject *)vv;
1227 }
1228 else {
1229 v = _PyLong_FromNbInt(vv);
1230 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001232 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001234
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001235 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001237 case -1:
1238 bytes = -(sdigit)v->ob_digit[0];
1239 break;
1240 case 0:
1241 bytes = 0;
1242 break;
1243 case 1:
1244 bytes = v->ob_digit[0];
1245 break;
1246 default:
1247 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001248 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001250 if (do_decref) {
1251 Py_DECREF(v);
1252 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001253
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001254 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001256 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 else
1258 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001259}
1260
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001261/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001262 Return -1 and set an error if overflow occurs. */
1263
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001264unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001265PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001268 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001270
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001271 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001273 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001275 if (!PyLong_Check(vv)) {
1276 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001277 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001278 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 v = (PyLongObject*)vv;
1281 switch(Py_SIZE(v)) {
1282 case 0: return 0;
1283 case 1: return v->ob_digit[0];
1284 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001285
Mark Dickinson22b20182010-05-10 21:27:53 +00001286 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001287 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001288
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001289 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001291 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 else
1293 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001294}
Tim Petersd1a7da62001-06-13 00:35:57 +00001295
Serhiy Storchaka95949422013-08-27 19:40:23 +03001296/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001297 Returns -1 and sets an error condition if an error occurs. */
1298
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001299static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001300_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001301{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001302 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001303 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 Py_ssize_t i;
1305 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 if (vv == NULL || !PyLong_Check(vv)) {
1308 PyErr_BadInternalCall();
1309 return (unsigned long) -1;
1310 }
1311 v = (PyLongObject *)vv;
1312 switch(Py_SIZE(v)) {
1313 case 0: return 0;
1314 case 1: return v->ob_digit[0];
1315 }
1316 i = Py_SIZE(v);
1317 sign = 1;
1318 x = 0;
1319 if (i < 0) {
1320 sign = -1;
1321 i = -i;
1322 }
1323 while (--i >= 0) {
1324 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1325 }
1326 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001327}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001328
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001329unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001330PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001333 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001334
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001335 if (op == NULL) {
1336 PyErr_BadInternalCall();
1337 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001339
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001340 if (PyLong_Check(op)) {
1341 return _PyLong_AsUnsignedLongLongMask(op);
1342 }
1343
1344 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001346 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001347
1348 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1349 Py_DECREF(lo);
1350 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001351}
Tim Petersd1a7da62001-06-13 00:35:57 +00001352
Serhiy Storchaka95949422013-08-27 19:40:23 +03001353/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001354 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001355
Mark Dickinson8d48b432011-10-23 20:47:14 +01001356 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1357 the result. Otherwise *overflow is 0.
1358
1359 For other errors (e.g., TypeError), return -1 and set an error condition.
1360 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001361*/
1362
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001363long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001364PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001367 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001368 unsigned long long x, prev;
1369 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 Py_ssize_t i;
1371 int sign;
1372 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 *overflow = 0;
1375 if (vv == NULL) {
1376 PyErr_BadInternalCall();
1377 return -1;
1378 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001379
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001380 if (PyLong_Check(vv)) {
1381 v = (PyLongObject *)vv;
1382 }
1383 else {
1384 v = _PyLong_FromNbInt(vv);
1385 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 return -1;
1387 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 switch (i) {
1394 case -1:
1395 res = -(sdigit)v->ob_digit[0];
1396 break;
1397 case 0:
1398 res = 0;
1399 break;
1400 case 1:
1401 res = v->ob_digit[0];
1402 break;
1403 default:
1404 sign = 1;
1405 x = 0;
1406 if (i < 0) {
1407 sign = -1;
1408 i = -(i);
1409 }
1410 while (--i >= 0) {
1411 prev = x;
1412 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1413 if ((x >> PyLong_SHIFT) != prev) {
1414 *overflow = sign;
1415 goto exit;
1416 }
1417 }
1418 /* Haven't lost any bits, but casting to long requires extra
1419 * care (see comment above).
1420 */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001421 if (x <= (unsigned long long)PY_LLONG_MAX) {
1422 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 }
1424 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1425 res = PY_LLONG_MIN;
1426 }
1427 else {
1428 *overflow = sign;
1429 /* res is already set to -1 */
1430 }
1431 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001432 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001434 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 }
1436 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001437}
1438
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001439#define CHECK_BINOP(v,w) \
1440 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001441 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1442 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001443 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001444
Tim Peters877a2122002-08-12 05:09:36 +00001445/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1446 * is modified in place, by adding y to it. Carries are propagated as far as
1447 * x[m-1], and the remaining carry (0 or 1) is returned.
1448 */
1449static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001450v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 Py_ssize_t i;
1453 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 assert(m >= n);
1456 for (i = 0; i < n; ++i) {
1457 carry += x[i] + y[i];
1458 x[i] = carry & PyLong_MASK;
1459 carry >>= PyLong_SHIFT;
1460 assert((carry & 1) == carry);
1461 }
1462 for (; carry && i < m; ++i) {
1463 carry += x[i];
1464 x[i] = carry & PyLong_MASK;
1465 carry >>= PyLong_SHIFT;
1466 assert((carry & 1) == carry);
1467 }
1468 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001469}
1470
1471/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1472 * is modified in place, by subtracting y from it. Borrows are propagated as
1473 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1474 */
1475static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001476v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 Py_ssize_t i;
1479 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 assert(m >= n);
1482 for (i = 0; i < n; ++i) {
1483 borrow = x[i] - y[i] - borrow;
1484 x[i] = borrow & PyLong_MASK;
1485 borrow >>= PyLong_SHIFT;
1486 borrow &= 1; /* keep only 1 sign bit */
1487 }
1488 for (; borrow && i < m; ++i) {
1489 borrow = x[i] - borrow;
1490 x[i] = borrow & PyLong_MASK;
1491 borrow >>= PyLong_SHIFT;
1492 borrow &= 1;
1493 }
1494 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001495}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001496
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001497/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1498 * result in z[0:m], and return the d bits shifted out of the top.
1499 */
1500static digit
1501v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 Py_ssize_t i;
1504 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 assert(0 <= d && d < PyLong_SHIFT);
1507 for (i=0; i < m; i++) {
1508 twodigits acc = (twodigits)a[i] << d | carry;
1509 z[i] = (digit)acc & PyLong_MASK;
1510 carry = (digit)(acc >> PyLong_SHIFT);
1511 }
1512 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001513}
1514
1515/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1516 * result in z[0:m], and return the d bits shifted out of the bottom.
1517 */
1518static digit
1519v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 Py_ssize_t i;
1522 digit carry = 0;
1523 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 assert(0 <= d && d < PyLong_SHIFT);
1526 for (i=m; i-- > 0;) {
1527 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1528 carry = (digit)acc & mask;
1529 z[i] = (digit)(acc >> d);
1530 }
1531 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001532}
1533
Tim Peters212e6142001-07-14 12:23:19 +00001534/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1535 in pout, and returning the remainder. pin and pout point at the LSD.
1536 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001537 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001538 immutable. */
1539
1540static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001541inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 assert(n > 0 && n <= PyLong_MASK);
1546 pin += size;
1547 pout += size;
1548 while (--size >= 0) {
1549 digit hi;
1550 rem = (rem << PyLong_SHIFT) | *--pin;
1551 *--pout = hi = (digit)(rem / n);
1552 rem -= (twodigits)hi * n;
1553 }
1554 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001555}
1556
Serhiy Storchaka95949422013-08-27 19:40:23 +03001557/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001558 (as function result) and the remainder (through *prem).
1559 The sign of a is ignored; n should not be zero. */
1560
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001561static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001562divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001563{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001564 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 assert(n > 0 && n <= PyLong_MASK);
1568 z = _PyLong_New(size);
1569 if (z == NULL)
1570 return NULL;
1571 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1572 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001573}
1574
Serhiy Storchaka95949422013-08-27 19:40:23 +03001575/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001576 string. (Return value is non-shared so that callers can modify the
1577 returned value if necessary.) */
1578
Victor Stinnerd3f08822012-05-29 12:57:52 +02001579static int
1580long_to_decimal_string_internal(PyObject *aa,
1581 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001582 _PyUnicodeWriter *writer,
1583 _PyBytesWriter *bytes_writer,
1584 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001587 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 Py_ssize_t size, strlen, size_a, i, j;
1589 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001591 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001592 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 a = (PyLongObject *)aa;
1595 if (a == NULL || !PyLong_Check(a)) {
1596 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001597 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001599 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 /* quick and dirty upper bound for the number of digits
1603 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 But log2(a) < size_a * PyLong_SHIFT, and
1608 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001609 > 3.3 * _PyLong_DECIMAL_SHIFT
1610
1611 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1612 size_a + size_a / d < size_a + size_a / floor(d),
1613 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1614 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001616 d = (33 * _PyLong_DECIMAL_SHIFT) /
1617 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1618 assert(size_a < PY_SSIZE_T_MAX/2);
1619 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 scratch = _PyLong_New(size);
1621 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001622 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 /* convert array of base _PyLong_BASE digits in pin to an array of
1625 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1626 Volume 2 (3rd edn), section 4.4, Method 1b). */
1627 pin = a->ob_digit;
1628 pout = scratch->ob_digit;
1629 size = 0;
1630 for (i = size_a; --i >= 0; ) {
1631 digit hi = pin[i];
1632 for (j = 0; j < size; j++) {
1633 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1634 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1635 pout[j] = (digit)(z - (twodigits)hi *
1636 _PyLong_DECIMAL_BASE);
1637 }
1638 while (hi) {
1639 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1640 hi /= _PyLong_DECIMAL_BASE;
1641 }
1642 /* check for keyboard interrupt */
1643 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001644 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001645 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001646 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 }
1648 /* pout should have at least one digit, so that the case when a = 0
1649 works correctly */
1650 if (size == 0)
1651 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 /* calculate exact length of output string, and allocate */
1654 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1655 tenpow = 10;
1656 rem = pout[size-1];
1657 while (rem >= tenpow) {
1658 tenpow *= 10;
1659 strlen++;
1660 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001661 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001662 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1663 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001664 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001665 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001666 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001668 else if (bytes_writer) {
1669 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1670 if (*bytes_str == NULL) {
1671 Py_DECREF(scratch);
1672 return -1;
1673 }
1674 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001675 else {
1676 str = PyUnicode_New(strlen, '9');
1677 if (str == NULL) {
1678 Py_DECREF(scratch);
1679 return -1;
1680 }
1681 kind = PyUnicode_KIND(str);
1682 }
1683
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001684#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001685 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001686 /* pout[0] through pout[size-2] contribute exactly \
1687 _PyLong_DECIMAL_SHIFT digits each */ \
1688 for (i=0; i < size - 1; i++) { \
1689 rem = pout[i]; \
1690 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1691 *--p = '0' + rem % 10; \
1692 rem /= 10; \
1693 } \
1694 } \
1695 /* pout[size-1]: always produce at least one decimal digit */ \
1696 rem = pout[i]; \
1697 do { \
1698 *--p = '0' + rem % 10; \
1699 rem /= 10; \
1700 } while (rem != 0); \
1701 \
1702 /* and sign */ \
1703 if (negative) \
1704 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001705 } while (0)
1706
1707#define WRITE_UNICODE_DIGITS(TYPE) \
1708 do { \
1709 if (writer) \
1710 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1711 else \
1712 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1713 \
1714 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001715 \
1716 /* check we've counted correctly */ \
1717 if (writer) \
1718 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1719 else \
1720 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1721 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001724 if (bytes_writer) {
1725 char *p = *bytes_str + strlen;
1726 WRITE_DIGITS(p);
1727 assert(p == *bytes_str);
1728 }
1729 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001730 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001731 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001733 else if (kind == PyUnicode_2BYTE_KIND) {
1734 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001735 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001736 }
1737 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001738 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001739 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001740 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001741 }
1742#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001743#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001746 if (writer) {
1747 writer->pos += strlen;
1748 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001749 else if (bytes_writer) {
1750 (*bytes_str) += strlen;
1751 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001752 else {
1753 assert(_PyUnicode_CheckConsistency(str, 1));
1754 *p_output = (PyObject *)str;
1755 }
1756 return 0;
1757}
1758
1759static PyObject *
1760long_to_decimal_string(PyObject *aa)
1761{
1762 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001763 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001764 return NULL;
1765 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001766}
1767
Serhiy Storchaka95949422013-08-27 19:40:23 +03001768/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001769 which should be one of 2, 8 or 16. Return a string object.
1770 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1771 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001772
Victor Stinnerd3f08822012-05-29 12:57:52 +02001773static int
1774long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001775 PyObject **p_output, _PyUnicodeWriter *writer,
1776 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001777{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001778 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001779 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001780 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001782 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001783 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001785
Victor Stinnerd3f08822012-05-29 12:57:52 +02001786 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 if (a == NULL || !PyLong_Check(a)) {
1788 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001789 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001791 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001792 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 /* Compute a rough upper bound for the length of the string */
1795 switch (base) {
1796 case 16:
1797 bits = 4;
1798 break;
1799 case 8:
1800 bits = 3;
1801 break;
1802 case 2:
1803 bits = 1;
1804 break;
1805 default:
1806 assert(0); /* shouldn't ever get here */
1807 bits = 0; /* to silence gcc warning */
1808 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001809
Mark Dickinsone2846542012-04-20 21:21:24 +01001810 /* Compute exact length 'sz' of output string. */
1811 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001812 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001813 }
1814 else {
1815 Py_ssize_t size_a_in_bits;
1816 /* Ensure overflow doesn't occur during computation of sz. */
1817 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1818 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001819 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001820 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001821 }
1822 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1823 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001824 /* Allow 1 character for a '-' sign. */
1825 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1826 }
1827 if (alternate) {
1828 /* 2 characters for prefix */
1829 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001830 }
1831
Victor Stinnerd3f08822012-05-29 12:57:52 +02001832 if (writer) {
1833 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1834 return -1;
1835 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001837 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001838 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1839 if (*bytes_str == NULL)
1840 return -1;
1841 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001843 v = PyUnicode_New(sz, 'x');
1844 if (v == NULL)
1845 return -1;
1846 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001848
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001849#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001850 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001851 if (size_a == 0) { \
1852 *--p = '0'; \
1853 } \
1854 else { \
1855 /* JRH: special case for power-of-2 bases */ \
1856 twodigits accum = 0; \
1857 int accumbits = 0; /* # of bits in accum */ \
1858 Py_ssize_t i; \
1859 for (i = 0; i < size_a; ++i) { \
1860 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1861 accumbits += PyLong_SHIFT; \
1862 assert(accumbits >= bits); \
1863 do { \
1864 char cdigit; \
1865 cdigit = (char)(accum & (base - 1)); \
1866 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1867 *--p = cdigit; \
1868 accumbits -= bits; \
1869 accum >>= bits; \
1870 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1871 } \
1872 } \
1873 \
1874 if (alternate) { \
1875 if (base == 16) \
1876 *--p = 'x'; \
1877 else if (base == 8) \
1878 *--p = 'o'; \
1879 else /* (base == 2) */ \
1880 *--p = 'b'; \
1881 *--p = '0'; \
1882 } \
1883 if (negative) \
1884 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001885 } while (0)
1886
1887#define WRITE_UNICODE_DIGITS(TYPE) \
1888 do { \
1889 if (writer) \
1890 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1891 else \
1892 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1893 \
1894 WRITE_DIGITS(p); \
1895 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001896 if (writer) \
1897 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1898 else \
1899 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1900 } while (0)
1901
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001902 if (bytes_writer) {
1903 char *p = *bytes_str + sz;
1904 WRITE_DIGITS(p);
1905 assert(p == *bytes_str);
1906 }
1907 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001908 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001909 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001910 }
1911 else if (kind == PyUnicode_2BYTE_KIND) {
1912 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001913 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001914 }
1915 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001916 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001917 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001918 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001919 }
1920#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001921#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02001922
1923 if (writer) {
1924 writer->pos += sz;
1925 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001926 else if (bytes_writer) {
1927 (*bytes_str) += sz;
1928 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001929 else {
1930 assert(_PyUnicode_CheckConsistency(v, 1));
1931 *p_output = v;
1932 }
1933 return 0;
1934}
1935
1936PyObject *
1937_PyLong_Format(PyObject *obj, int base)
1938{
1939 PyObject *str;
1940 int err;
1941 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001942 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001943 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001944 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001945 if (err == -1)
1946 return NULL;
1947 return str;
1948}
1949
1950int
1951_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1952 PyObject *obj,
1953 int base, int alternate)
1954{
1955 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001956 return long_to_decimal_string_internal(obj, NULL, writer,
1957 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001958 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001959 return long_format_binary(obj, base, alternate, NULL, writer,
1960 NULL, NULL);
1961}
1962
1963char*
1964_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
1965 PyObject *obj,
1966 int base, int alternate)
1967{
1968 char *str2;
1969 int res;
1970 str2 = str;
1971 if (base == 10)
1972 res = long_to_decimal_string_internal(obj, NULL, NULL,
1973 writer, &str2);
1974 else
1975 res = long_format_binary(obj, base, alternate, NULL, NULL,
1976 writer, &str2);
1977 if (res < 0)
1978 return NULL;
1979 assert(str2 != NULL);
1980 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001981}
1982
Thomas Wouters477c8d52006-05-27 19:21:47 +00001983/* Table of digit values for 8-bit string -> integer conversion.
1984 * '0' maps to 0, ..., '9' maps to 9.
1985 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1986 * All other indices map to 37.
1987 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001988 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001989 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001990unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1992 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1993 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1994 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1995 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1996 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1997 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1998 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1999 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2000 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2001 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2002 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2003 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2004 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2005 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2006 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002007};
2008
2009/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002010 * 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 +03002011 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002012 * The point to this routine is that it takes time linear in the number of
2013 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002014 *
2015 * Return values:
2016 * -1 on syntax error (exception needs to be set, *res is untouched)
2017 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002018 */
Brett Cannona721aba2016-09-09 14:57:09 -07002019static int
2020long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002021{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002022 const char *p = *str;
2023 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002024 char prev = 0;
2025 int digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 int bits_per_char;
2027 Py_ssize_t n;
2028 PyLongObject *z;
2029 twodigits accum;
2030 int bits_in_accum;
2031 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2034 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002035 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002037 }
2038 /* count digits and set p to end-of-string */
2039 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2040 if (*p == '_') {
2041 if (prev == '_') {
2042 *str = p - 1;
2043 return -1;
2044 }
2045 } else {
2046 ++digits;
2047 }
2048 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002050 }
2051 if (prev == '_') {
2052 /* Trailing underscore not allowed. */
2053 *str = p - 1;
2054 return -1;
2055 }
2056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 *str = p;
2058 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
Brett Cannona721aba2016-09-09 14:57:09 -07002059 n = digits * bits_per_char + PyLong_SHIFT - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 if (n / bits_per_char < p - start) {
2061 PyErr_SetString(PyExc_ValueError,
2062 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002063 *res = NULL;
2064 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 }
2066 n = n / PyLong_SHIFT;
2067 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002068 if (z == NULL) {
2069 *res = NULL;
2070 return 0;
2071 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002072 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 * from least to most significant in both.
2074 */
2075 accum = 0;
2076 bits_in_accum = 0;
2077 pdigit = z->ob_digit;
2078 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002079 int k;
2080 if (*p == '_') {
2081 continue;
2082 }
2083 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 assert(k >= 0 && k < base);
2085 accum |= (twodigits)k << bits_in_accum;
2086 bits_in_accum += bits_per_char;
2087 if (bits_in_accum >= PyLong_SHIFT) {
2088 *pdigit++ = (digit)(accum & PyLong_MASK);
2089 assert(pdigit - z->ob_digit <= n);
2090 accum >>= PyLong_SHIFT;
2091 bits_in_accum -= PyLong_SHIFT;
2092 assert(bits_in_accum < PyLong_SHIFT);
2093 }
2094 }
2095 if (bits_in_accum) {
2096 assert(bits_in_accum <= PyLong_SHIFT);
2097 *pdigit++ = (digit)accum;
2098 assert(pdigit - z->ob_digit <= n);
2099 }
2100 while (pdigit - z->ob_digit < n)
2101 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002102 *res = long_normalize(z);
2103 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002104}
2105
Serhiy Storchaka95949422013-08-27 19:40:23 +03002106/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002107 * ignored.
2108 *
2109 * If successful, a PyLong object will be returned and 'pend' will be pointing
2110 * to the first unused byte unless it's NULL.
2111 *
2112 * If unsuccessful, NULL will be returned.
2113 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002114PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002115PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002118 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 PyLongObject *z = NULL;
2120 PyObject *strobj;
2121 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 if ((base != 0 && base < 2) || base > 36) {
2124 PyErr_SetString(PyExc_ValueError,
2125 "int() arg 2 must be >= 2 and <= 36");
2126 return NULL;
2127 }
Brett Cannona721aba2016-09-09 14:57:09 -07002128 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002130 }
2131 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002133 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 else if (*str == '-') {
2135 ++str;
2136 sign = -1;
2137 }
2138 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002139 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002141 }
2142 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002144 }
2145 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002147 }
2148 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002150 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 else {
2152 /* "old" (C-style) octal literal, now invalid.
2153 it might still be zero though */
2154 error_if_nonzero = 1;
2155 base = 10;
2156 }
2157 }
2158 if (str[0] == '0' &&
2159 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2160 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002161 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002163 /* One underscore allowed here. */
2164 if (*str == '_') {
2165 ++str;
2166 }
2167 }
2168 if (str[0] == '_') {
2169 /* May not start with underscores. */
2170 goto onError;
2171 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002174 if ((base & (base - 1)) == 0) {
2175 int res = long_from_binary_base(&str, base, &z);
2176 if (res < 0) {
2177 /* Syntax error. */
2178 goto onError;
2179 }
2180 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002182/***
2183Binary bases can be converted in time linear in the number of digits, because
2184Python's representation base is binary. Other bases (including decimal!) use
2185the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002186
Thomas Wouters477c8d52006-05-27 19:21:47 +00002187First some math: the largest integer that can be expressed in N base-B digits
2188is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2189case number of Python digits needed to hold it is the smallest integer n s.t.
2190
2191 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2192 BASE**n >= B**N [taking logs to base BASE]
2193 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2194
2195The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002196this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002197and the result is computed into it.
2198
2199The input string is actually treated as being in base base**i (i.e., i digits
2200are processed at a time), where two more static arrays hold:
2201
2202 convwidth_base[base] = the largest integer i such that base**i <= BASE
2203 convmultmax_base[base] = base ** convwidth_base[base]
2204
2205The first of these is the largest i such that i consecutive input digits
2206must fit in a single Python digit. The second is effectively the input
2207base we're really using.
2208
2209Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2210convmultmax_base[base], the result is "simply"
2211
2212 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2213
2214where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002215
2216Error analysis: as above, the number of Python digits `n` needed is worst-
2217case
2218
2219 n >= N * log(B)/log(BASE)
2220
2221where `N` is the number of input digits in base `B`. This is computed via
2222
2223 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2224
2225below. Two numeric concerns are how much space this can waste, and whether
2226the computed result can be too small. To be concrete, assume BASE = 2**15,
2227which is the default (and it's unlikely anyone changes that).
2228
2229Waste isn't a problem: provided the first input digit isn't 0, the difference
2230between the worst-case input with N digits and the smallest input with N
2231digits is about a factor of B, but B is small compared to BASE so at most
2232one allocated Python digit can remain unused on that count. If
2233N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2234and adding 1 returns a result 1 larger than necessary. However, that can't
2235happen: whenever B is a power of 2, long_from_binary_base() is called
2236instead, and it's impossible for B**i to be an integer power of 2**15 when
2237B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2238an exact integer when B is not a power of 2, since B**i has a prime factor
2239other than 2 in that case, but (2**15)**j's only prime factor is 2).
2240
2241The computed result can be too small if the true value of N*log(B)/log(BASE)
2242is a little bit larger than an exact integer, but due to roundoff errors (in
2243computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2244yields a numeric result a little less than that integer. Unfortunately, "how
2245close can a transcendental function get to an integer over some range?"
2246questions are generally theoretically intractable. Computer analysis via
2247continued fractions is practical: expand log(B)/log(BASE) via continued
2248fractions, giving a sequence i/j of "the best" rational approximations. Then
2249j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2250we can get very close to being in trouble, but very rarely. For example,
225176573 is a denominator in one of the continued-fraction approximations to
2252log(10)/log(2**15), and indeed:
2253
2254 >>> log(10)/log(2**15)*76573
2255 16958.000000654003
2256
2257is very close to an integer. If we were working with IEEE single-precision,
2258rounding errors could kill us. Finding worst cases in IEEE double-precision
2259requires better-than-double-precision log() functions, and Tim didn't bother.
2260Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002261new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002262This should happen extremely rarely, and in fact I don't have a test case
2263that triggers it(!). Instead the code was tested by artificially allocating
2264just 1 digit at the start, so that the copying code was exercised for every
2265digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002266***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002267 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 Py_ssize_t size_z;
Brett Cannona721aba2016-09-09 14:57:09 -07002269 int digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 int i;
2271 int convwidth;
2272 twodigits convmultmax, convmult;
2273 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002274 const char *scan, *lastdigit;
2275 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 static double log_base_BASE[37] = {0.0e0,};
2278 static int convwidth_base[37] = {0,};
2279 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 if (log_base_BASE[base] == 0.0) {
2282 twodigits convmax = base;
2283 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002284
Mark Dickinson22b20182010-05-10 21:27:53 +00002285 log_base_BASE[base] = (log((double)base) /
2286 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 for (;;) {
2288 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002289 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002291 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 convmax = next;
2293 ++i;
2294 }
2295 convmultmax_base[base] = convmax;
2296 assert(i > 0);
2297 convwidth_base[base] = i;
2298 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 /* Find length of the string of numeric characters. */
2301 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002302 lastdigit = str;
2303
2304 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2305 if (*scan == '_') {
2306 if (prev == '_') {
2307 /* Only one underscore allowed. */
2308 str = lastdigit + 1;
2309 goto onError;
2310 }
2311 }
2312 else {
2313 ++digits;
2314 lastdigit = scan;
2315 }
2316 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002318 }
2319 if (prev == '_') {
2320 /* Trailing underscore not allowed. */
2321 /* Set error pointer to first underscore. */
2322 str = lastdigit + 1;
2323 goto onError;
2324 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002325
Serhiy Storchaka95949422013-08-27 19:40:23 +03002326 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 * integer with this base and length. Note that there's no
2328 * need to initialize z->ob_digit -- no slot is read up before
2329 * being stored into.
2330 */
Brett Cannona721aba2016-09-09 14:57:09 -07002331 size_z = (Py_ssize_t)(digits * log_base_BASE[base]) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* Uncomment next line to test exceedingly rare copy code */
2333 /* size_z = 1; */
2334 assert(size_z > 0);
2335 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002336 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002338 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* `convwidth` consecutive input digits are treated as a single
2342 * digit in base `convmultmax`.
2343 */
2344 convwidth = convwidth_base[base];
2345 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 /* Work ;-) */
2348 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002349 if (*str == '_') {
2350 str++;
2351 continue;
2352 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 /* grab up to convwidth digits from the input string */
2354 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002355 for (i = 1; i < convwidth && str != scan; ++str) {
2356 if (*str == '_') {
2357 continue;
2358 }
2359 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002361 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 assert(c < PyLong_BASE);
2363 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 convmult = convmultmax;
2366 /* Calculate the shift only if we couldn't get
2367 * convwidth digits.
2368 */
2369 if (i != convwidth) {
2370 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002371 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002373 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 /* Multiply z by convmult, and add c. */
2377 pz = z->ob_digit;
2378 pzstop = pz + Py_SIZE(z);
2379 for (; pz < pzstop; ++pz) {
2380 c += (twodigits)*pz * convmult;
2381 *pz = (digit)(c & PyLong_MASK);
2382 c >>= PyLong_SHIFT;
2383 }
2384 /* carry off the current end? */
2385 if (c) {
2386 assert(c < PyLong_BASE);
2387 if (Py_SIZE(z) < size_z) {
2388 *pz = (digit)c;
2389 ++Py_SIZE(z);
2390 }
2391 else {
2392 PyLongObject *tmp;
2393 /* Extremely rare. Get more space. */
2394 assert(Py_SIZE(z) == size_z);
2395 tmp = _PyLong_New(size_z + 1);
2396 if (tmp == NULL) {
2397 Py_DECREF(z);
2398 return NULL;
2399 }
2400 memcpy(tmp->ob_digit,
2401 z->ob_digit,
2402 sizeof(digit) * size_z);
2403 Py_DECREF(z);
2404 z = tmp;
2405 z->ob_digit[size_z] = (digit)c;
2406 ++size_z;
2407 }
2408 }
2409 }
2410 }
Brett Cannona721aba2016-09-09 14:57:09 -07002411 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002413 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 if (error_if_nonzero) {
2415 /* reset the base to 0, else the exception message
2416 doesn't make too much sense */
2417 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002418 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002420 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 /* there might still be other problems, therefore base
2422 remains zero here for the same reason */
2423 }
Brett Cannona721aba2016-09-09 14:57:09 -07002424 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002426 }
2427 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002429 }
2430 while (*str && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002432 }
2433 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002437 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002438 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002439 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002440 }
2441 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002442 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002443 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002444 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002445
Mark Dickinson22b20182010-05-10 21:27:53 +00002446 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002447 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002448 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 Py_XDECREF(z);
2451 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2452 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002453 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002455 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002457 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 base, strobj);
2459 Py_DECREF(strobj);
2460 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002461}
2462
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002463/* Since PyLong_FromString doesn't have a length parameter,
2464 * check here for possible NULs in the string.
2465 *
2466 * Reports an invalid literal as a bytes object.
2467 */
2468PyObject *
2469_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2470{
2471 PyObject *result, *strobj;
2472 char *end = NULL;
2473
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002474 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002475 if (end == NULL || (result != NULL && end == s + len))
2476 return result;
2477 Py_XDECREF(result);
2478 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2479 if (strobj != NULL) {
2480 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002481 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002482 base, strobj);
2483 Py_DECREF(strobj);
2484 }
2485 return NULL;
2486}
2487
Guido van Rossum9e896b32000-04-05 20:11:21 +00002488PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002489PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002490{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002491 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002492 if (unicode == NULL)
2493 return NULL;
2494 v = PyLong_FromUnicodeObject(unicode, base);
2495 Py_DECREF(unicode);
2496 return v;
2497}
2498
2499PyObject *
2500PyLong_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;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002510 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002511 if (buffer == NULL) {
2512 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002513 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2514 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002516 else {
2517 result = PyLong_FromString(buffer, &end, base);
2518 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2519 Py_DECREF(asciidig);
2520 return result;
2521 }
2522 Py_DECREF(asciidig);
2523 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002524 }
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002525 PyErr_Format(PyExc_ValueError,
2526 "invalid literal for int() with base %d: %.200R",
2527 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002528 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002529}
2530
Tim Peters9f688bf2000-07-07 15:53:28 +00002531/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002532static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002534static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002535
Serhiy Storchaka95949422013-08-27 19:40:23 +03002536/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002537
Guido van Rossume32e0141992-01-19 16:31:05 +00002538static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002539long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002541{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002542 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 if (size_b == 0) {
2546 PyErr_SetString(PyExc_ZeroDivisionError,
2547 "integer division or modulo by zero");
2548 return -1;
2549 }
2550 if (size_a < size_b ||
2551 (size_a == size_b &&
2552 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2553 /* |a| < |b|. */
2554 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2555 if (*pdiv == NULL)
2556 return -1;
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002557 *prem = (PyLongObject *)long_long((PyObject *)a);
2558 if (*prem == NULL) {
2559 Py_CLEAR(*pdiv);
2560 return -1;
2561 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 return 0;
2563 }
2564 if (size_b == 1) {
2565 digit rem = 0;
2566 z = divrem1(a, b->ob_digit[0], &rem);
2567 if (z == NULL)
2568 return -1;
2569 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2570 if (*prem == NULL) {
2571 Py_DECREF(z);
2572 return -1;
2573 }
2574 }
2575 else {
2576 z = x_divrem(a, b, prem);
2577 if (z == NULL)
2578 return -1;
2579 }
2580 /* Set the signs.
2581 The quotient z has the sign of a*b;
2582 the remainder r has the sign of a,
2583 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002584 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2585 _PyLong_Negate(&z);
2586 if (z == NULL) {
2587 Py_CLEAR(*prem);
2588 return -1;
2589 }
2590 }
2591 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2592 _PyLong_Negate(prem);
2593 if (*prem == NULL) {
2594 Py_DECREF(z);
2595 Py_CLEAR(*prem);
2596 return -1;
2597 }
2598 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 *pdiv = maybe_small_long(z);
2600 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002601}
2602
Serhiy Storchaka95949422013-08-27 19:40:23 +03002603/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002604 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002605
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002606static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002607x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 PyLongObject *v, *w, *a;
2610 Py_ssize_t i, k, size_v, size_w;
2611 int d;
2612 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2613 twodigits vv;
2614 sdigit zhi;
2615 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2618 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2619 handle the special case when the initial estimate q for a quotient
2620 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2621 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002624 size_v = Py_ABS(Py_SIZE(v1));
2625 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2627 v = _PyLong_New(size_v+1);
2628 if (v == NULL) {
2629 *prem = NULL;
2630 return NULL;
2631 }
2632 w = _PyLong_New(size_w);
2633 if (w == NULL) {
2634 Py_DECREF(v);
2635 *prem = NULL;
2636 return NULL;
2637 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2640 shift v1 left by the same amount. Results go into w and v. */
2641 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2642 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2643 assert(carry == 0);
2644 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2645 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2646 v->ob_digit[size_v] = carry;
2647 size_v++;
2648 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2651 at most (and usually exactly) k = size_v - size_w digits. */
2652 k = size_v - size_w;
2653 assert(k >= 0);
2654 a = _PyLong_New(k);
2655 if (a == NULL) {
2656 Py_DECREF(w);
2657 Py_DECREF(v);
2658 *prem = NULL;
2659 return NULL;
2660 }
2661 v0 = v->ob_digit;
2662 w0 = w->ob_digit;
2663 wm1 = w0[size_w-1];
2664 wm2 = w0[size_w-2];
2665 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2666 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2667 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002670 Py_DECREF(a);
2671 Py_DECREF(w);
2672 Py_DECREF(v);
2673 *prem = NULL;
2674 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002675 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 /* estimate quotient digit q; may overestimate by 1 (rare) */
2678 vtop = vk[size_w];
2679 assert(vtop <= wm1);
2680 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2681 q = (digit)(vv / wm1);
2682 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2683 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2684 | vk[size_w-2])) {
2685 --q;
2686 r += wm1;
2687 if (r >= PyLong_BASE)
2688 break;
2689 }
2690 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2693 zhi = 0;
2694 for (i = 0; i < size_w; ++i) {
2695 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2696 -PyLong_BASE * q <= z < PyLong_BASE */
2697 z = (sdigit)vk[i] + zhi -
2698 (stwodigits)q * (stwodigits)w0[i];
2699 vk[i] = (digit)z & PyLong_MASK;
2700 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002701 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 /* add w back if q was too large (this branch taken rarely) */
2705 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2706 if ((sdigit)vtop + zhi < 0) {
2707 carry = 0;
2708 for (i = 0; i < size_w; ++i) {
2709 carry += vk[i] + w0[i];
2710 vk[i] = carry & PyLong_MASK;
2711 carry >>= PyLong_SHIFT;
2712 }
2713 --q;
2714 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 /* store quotient digit */
2717 assert(q < PyLong_BASE);
2718 *--ak = q;
2719 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 /* unshift remainder; we reuse w to store the result */
2722 carry = v_rshift(w0, v0, size_w, d);
2723 assert(carry==0);
2724 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 *prem = long_normalize(w);
2727 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002728}
2729
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002730/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2731 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2732 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2733 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2734 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2735 -1.0. */
2736
2737/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2738#if DBL_MANT_DIG == 53
2739#define EXP2_DBL_MANT_DIG 9007199254740992.0
2740#else
2741#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2742#endif
2743
2744double
2745_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2748 /* See below for why x_digits is always large enough. */
2749 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2750 double dx;
2751 /* Correction term for round-half-to-even rounding. For a digit x,
2752 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2753 multiple of 4, rounding ties to a multiple of 8. */
2754 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002755
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002756 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 if (a_size == 0) {
2758 /* Special case for 0: significand 0.0, exponent 0. */
2759 *e = 0;
2760 return 0.0;
2761 }
2762 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2763 /* The following is an overflow-free version of the check
2764 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2765 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2766 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2767 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002768 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2772 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 Number of digits needed for result: write // for floor division.
2775 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2784 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2787 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2788 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 in both cases.
2795 */
2796 if (a_bits <= DBL_MANT_DIG + 2) {
2797 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2798 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2799 x_size = 0;
2800 while (x_size < shift_digits)
2801 x_digits[x_size++] = 0;
2802 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2803 (int)shift_bits);
2804 x_size += a_size;
2805 x_digits[x_size++] = rem;
2806 }
2807 else {
2808 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2809 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2810 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2811 a_size - shift_digits, (int)shift_bits);
2812 x_size = a_size - shift_digits;
2813 /* For correct rounding below, we need the least significant
2814 bit of x to be 'sticky' for this shift: if any of the bits
2815 shifted out was nonzero, we set the least significant bit
2816 of x. */
2817 if (rem)
2818 x_digits[0] |= 1;
2819 else
2820 while (shift_digits > 0)
2821 if (a->ob_digit[--shift_digits]) {
2822 x_digits[0] |= 1;
2823 break;
2824 }
2825 }
Victor Stinner63941882011-09-29 00:42:28 +02002826 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 /* Round, and convert to double. */
2829 x_digits[0] += half_even_correction[x_digits[0] & 7];
2830 dx = x_digits[--x_size];
2831 while (x_size > 0)
2832 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 /* Rescale; make correction if result is 1.0. */
2835 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2836 if (dx == 1.0) {
2837 if (a_bits == PY_SSIZE_T_MAX)
2838 goto overflow;
2839 dx = 0.5;
2840 a_bits += 1;
2841 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 *e = a_bits;
2844 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002845
2846 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 /* exponent > PY_SSIZE_T_MAX */
2848 PyErr_SetString(PyExc_OverflowError,
2849 "huge integer: number of bits overflows a Py_ssize_t");
2850 *e = 0;
2851 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002852}
2853
Serhiy Storchaka95949422013-08-27 19:40:23 +03002854/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002855 using the round-half-to-even rule in the case of a tie. */
2856
2857double
2858PyLong_AsDouble(PyObject *v)
2859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 Py_ssize_t exponent;
2861 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002862
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002863 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 PyErr_BadInternalCall();
2865 return -1.0;
2866 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002867 if (!PyLong_Check(v)) {
2868 PyErr_SetString(PyExc_TypeError, "an integer is required");
2869 return -1.0;
2870 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002871 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002872 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002873 to double. This improves performance of FP/long operations
2874 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002875 */
2876 return (double)MEDIUM_VALUE((PyLongObject *)v);
2877 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2879 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2880 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002881 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 return -1.0;
2883 }
2884 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002885}
2886
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002887/* Methods */
2888
2889static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002890long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002893}
2894
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002895static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002896long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 if (Py_SIZE(a) != Py_SIZE(b)) {
2901 sign = Py_SIZE(a) - Py_SIZE(b);
2902 }
2903 else {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002904 Py_ssize_t i = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2906 ;
2907 if (i < 0)
2908 sign = 0;
2909 else {
2910 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2911 if (Py_SIZE(a) < 0)
2912 sign = -sign;
2913 }
2914 }
2915 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002916}
2917
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002918#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002920
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002921static PyObject *
2922long_richcompare(PyObject *self, PyObject *other, int op)
2923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 int result;
2925 PyObject *v;
2926 CHECK_BINOP(self, other);
2927 if (self == other)
2928 result = 0;
2929 else
2930 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2931 /* Convert the return value to a Boolean */
2932 switch (op) {
2933 case Py_EQ:
2934 v = TEST_COND(result == 0);
2935 break;
2936 case Py_NE:
2937 v = TEST_COND(result != 0);
2938 break;
2939 case Py_LE:
2940 v = TEST_COND(result <= 0);
2941 break;
2942 case Py_GE:
2943 v = TEST_COND(result >= 0);
2944 break;
2945 case Py_LT:
2946 v = TEST_COND(result == -1);
2947 break;
2948 case Py_GT:
2949 v = TEST_COND(result == 1);
2950 break;
2951 default:
2952 PyErr_BadArgument();
2953 return NULL;
2954 }
2955 Py_INCREF(v);
2956 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002957}
2958
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002959static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002960long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002961{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002962 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 Py_ssize_t i;
2964 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 i = Py_SIZE(v);
2967 switch(i) {
2968 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2969 case 0: return 0;
2970 case 1: return v->ob_digit[0];
2971 }
2972 sign = 1;
2973 x = 0;
2974 if (i < 0) {
2975 sign = -1;
2976 i = -(i);
2977 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002979 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2980 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2981 _PyHASH_MODULUS.
2982
2983 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2984 amounts to a rotation of the bits of x. To see this, write
2985
2986 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2987
2988 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2989 PyLong_SHIFT bits of x (those that are shifted out of the
2990 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2991 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2992 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2993 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2994 congruent to y modulo _PyHASH_MODULUS. So
2995
2996 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2997
2998 The right-hand side is just the result of rotating the
2999 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3000 not all _PyHASH_BITS bits of x are 1s, the same is true
3001 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3002 the reduction of x*2**PyLong_SHIFT modulo
3003 _PyHASH_MODULUS. */
3004 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3005 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003007 if (x >= _PyHASH_MODULUS)
3008 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 }
3010 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003011 if (x == (Py_uhash_t)-1)
3012 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003013 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003014}
3015
3016
Serhiy Storchaka95949422013-08-27 19:40:23 +03003017/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003018
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003019static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003020x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003021{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003022 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 PyLongObject *z;
3024 Py_ssize_t i;
3025 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 /* Ensure a is the larger of the two: */
3028 if (size_a < size_b) {
3029 { PyLongObject *temp = a; a = b; b = temp; }
3030 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003031 size_a = size_b;
3032 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 }
3034 z = _PyLong_New(size_a+1);
3035 if (z == NULL)
3036 return NULL;
3037 for (i = 0; i < size_b; ++i) {
3038 carry += a->ob_digit[i] + b->ob_digit[i];
3039 z->ob_digit[i] = carry & PyLong_MASK;
3040 carry >>= PyLong_SHIFT;
3041 }
3042 for (; i < size_a; ++i) {
3043 carry += a->ob_digit[i];
3044 z->ob_digit[i] = carry & PyLong_MASK;
3045 carry >>= PyLong_SHIFT;
3046 }
3047 z->ob_digit[i] = carry;
3048 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003049}
3050
3051/* Subtract the absolute values of two integers. */
3052
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003053static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003054x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003055{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003056 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 PyLongObject *z;
3058 Py_ssize_t i;
3059 int sign = 1;
3060 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 /* Ensure a is the larger of the two: */
3063 if (size_a < size_b) {
3064 sign = -1;
3065 { PyLongObject *temp = a; a = b; b = temp; }
3066 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003067 size_a = size_b;
3068 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 }
3070 else if (size_a == size_b) {
3071 /* Find highest digit where a and b differ: */
3072 i = size_a;
3073 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3074 ;
3075 if (i < 0)
3076 return (PyLongObject *)PyLong_FromLong(0);
3077 if (a->ob_digit[i] < b->ob_digit[i]) {
3078 sign = -1;
3079 { PyLongObject *temp = a; a = b; b = temp; }
3080 }
3081 size_a = size_b = i+1;
3082 }
3083 z = _PyLong_New(size_a);
3084 if (z == NULL)
3085 return NULL;
3086 for (i = 0; i < size_b; ++i) {
3087 /* The following assumes unsigned arithmetic
3088 works module 2**N for some N>PyLong_SHIFT. */
3089 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3090 z->ob_digit[i] = borrow & PyLong_MASK;
3091 borrow >>= PyLong_SHIFT;
3092 borrow &= 1; /* Keep only one sign bit */
3093 }
3094 for (; i < size_a; ++i) {
3095 borrow = a->ob_digit[i] - borrow;
3096 z->ob_digit[i] = borrow & PyLong_MASK;
3097 borrow >>= PyLong_SHIFT;
3098 borrow &= 1; /* Keep only one sign bit */
3099 }
3100 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003101 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003102 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003103 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003105}
3106
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003107static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003108long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003113
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003114 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003115 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 }
3117 if (Py_SIZE(a) < 0) {
3118 if (Py_SIZE(b) < 0) {
3119 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003120 if (z != NULL) {
3121 /* x_add received at least one multiple-digit int,
3122 and thus z must be a multiple-digit int.
3123 That also means z is not an element of
3124 small_ints, so negating it in-place is safe. */
3125 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003127 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 }
3129 else
3130 z = x_sub(b, a);
3131 }
3132 else {
3133 if (Py_SIZE(b) < 0)
3134 z = x_sub(a, b);
3135 else
3136 z = x_add(a, b);
3137 }
3138 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003139}
3140
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003141static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003142long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003147
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003148 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003149 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 }
3151 if (Py_SIZE(a) < 0) {
3152 if (Py_SIZE(b) < 0)
3153 z = x_sub(a, b);
3154 else
3155 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003156 if (z != NULL) {
3157 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003159 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 }
3161 else {
3162 if (Py_SIZE(b) < 0)
3163 z = x_add(a, b);
3164 else
3165 z = x_sub(a, b);
3166 }
3167 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003168}
3169
Tim Peters5af4e6c2002-08-12 02:31:19 +00003170/* Grade school multiplication, ignoring the signs.
3171 * Returns the absolute value of the product, or NULL if error.
3172 */
3173static PyLongObject *
3174x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003177 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3178 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 z = _PyLong_New(size_a + size_b);
3182 if (z == NULL)
3183 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3186 if (a == b) {
3187 /* Efficient squaring per HAC, Algorithm 14.16:
3188 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3189 * Gives slightly less than a 2x speedup when a == b,
3190 * via exploiting that each entry in the multiplication
3191 * pyramid appears twice (except for the size_a squares).
3192 */
3193 for (i = 0; i < size_a; ++i) {
3194 twodigits carry;
3195 twodigits f = a->ob_digit[i];
3196 digit *pz = z->ob_digit + (i << 1);
3197 digit *pa = a->ob_digit + i + 1;
3198 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003201 Py_DECREF(z);
3202 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003203 });
Tim Peters0973b992004-08-29 22:16:50 +00003204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 carry = *pz + f * f;
3206 *pz++ = (digit)(carry & PyLong_MASK);
3207 carry >>= PyLong_SHIFT;
3208 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 /* Now f is added in twice in each column of the
3211 * pyramid it appears. Same as adding f<<1 once.
3212 */
3213 f <<= 1;
3214 while (pa < paend) {
3215 carry += *pz + *pa++ * f;
3216 *pz++ = (digit)(carry & PyLong_MASK);
3217 carry >>= PyLong_SHIFT;
3218 assert(carry <= (PyLong_MASK << 1));
3219 }
3220 if (carry) {
3221 carry += *pz;
3222 *pz++ = (digit)(carry & PyLong_MASK);
3223 carry >>= PyLong_SHIFT;
3224 }
3225 if (carry)
3226 *pz += (digit)(carry & PyLong_MASK);
3227 assert((carry >> PyLong_SHIFT) == 0);
3228 }
3229 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003230 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 for (i = 0; i < size_a; ++i) {
3232 twodigits carry = 0;
3233 twodigits f = a->ob_digit[i];
3234 digit *pz = z->ob_digit + i;
3235 digit *pb = b->ob_digit;
3236 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003239 Py_DECREF(z);
3240 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003241 });
Tim Peters0973b992004-08-29 22:16:50 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 while (pb < pbend) {
3244 carry += *pz + *pb++ * f;
3245 *pz++ = (digit)(carry & PyLong_MASK);
3246 carry >>= PyLong_SHIFT;
3247 assert(carry <= PyLong_MASK);
3248 }
3249 if (carry)
3250 *pz += (digit)(carry & PyLong_MASK);
3251 assert((carry >> PyLong_SHIFT) == 0);
3252 }
3253 }
3254 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003255}
3256
3257/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003258 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003259 split, and sets low and high such that abs(n) == (high << size) + low,
3260 viewing the shift as being by digits. The sign bit is ignored, and
3261 the return values are >= 0.
3262 Returns 0 on success, -1 on failure.
3263*/
3264static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003265kmul_split(PyLongObject *n,
3266 Py_ssize_t size,
3267 PyLongObject **high,
3268 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 PyLongObject *hi, *lo;
3271 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003272 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003273
Victor Stinner640c35c2013-06-04 23:14:37 +02003274 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 if ((hi = _PyLong_New(size_hi)) == NULL)
3278 return -1;
3279 if ((lo = _PyLong_New(size_lo)) == NULL) {
3280 Py_DECREF(hi);
3281 return -1;
3282 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3285 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 *high = long_normalize(hi);
3288 *low = long_normalize(lo);
3289 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003290}
3291
Tim Peters60004642002-08-12 22:01:34 +00003292static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3293
Tim Peters5af4e6c2002-08-12 02:31:19 +00003294/* Karatsuba multiplication. Ignores the input signs, and returns the
3295 * absolute value of the product (or NULL if error).
3296 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3297 */
3298static PyLongObject *
3299k_mul(PyLongObject *a, PyLongObject *b)
3300{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003301 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3302 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 PyLongObject *ah = NULL;
3304 PyLongObject *al = NULL;
3305 PyLongObject *bh = NULL;
3306 PyLongObject *bl = NULL;
3307 PyLongObject *ret = NULL;
3308 PyLongObject *t1, *t2, *t3;
3309 Py_ssize_t shift; /* the number of digits we split off */
3310 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3313 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3314 * Then the original product is
3315 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3316 * By picking X to be a power of 2, "*X" is just shifting, and it's
3317 * been reduced to 3 multiplies on numbers half the size.
3318 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 /* We want to split based on the larger number; fiddle so that b
3321 * is largest.
3322 */
3323 if (asize > bsize) {
3324 t1 = a;
3325 a = b;
3326 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 i = asize;
3329 asize = bsize;
3330 bsize = i;
3331 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 /* Use gradeschool math when either number is too small. */
3334 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3335 if (asize <= i) {
3336 if (asize == 0)
3337 return (PyLongObject *)PyLong_FromLong(0);
3338 else
3339 return x_mul(a, b);
3340 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 /* If a is small compared to b, splitting on b gives a degenerate
3343 * case with ah==0, and Karatsuba may be (even much) less efficient
3344 * than "grade school" then. However, we can still win, by viewing
3345 * b as a string of "big digits", each of width a->ob_size. That
3346 * leads to a sequence of balanced calls to k_mul.
3347 */
3348 if (2 * asize <= bsize)
3349 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 /* Split a & b into hi & lo pieces. */
3352 shift = bsize >> 1;
3353 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3354 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 if (a == b) {
3357 bh = ah;
3358 bl = al;
3359 Py_INCREF(bh);
3360 Py_INCREF(bl);
3361 }
3362 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 /* The plan:
3365 * 1. Allocate result space (asize + bsize digits: that's always
3366 * enough).
3367 * 2. Compute ah*bh, and copy into result at 2*shift.
3368 * 3. Compute al*bl, and copy into result at 0. Note that this
3369 * can't overlap with #2.
3370 * 4. Subtract al*bl from the result, starting at shift. This may
3371 * underflow (borrow out of the high digit), but we don't care:
3372 * we're effectively doing unsigned arithmetic mod
3373 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3374 * borrows and carries out of the high digit can be ignored.
3375 * 5. Subtract ah*bh from the result, starting at shift.
3376 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3377 * at shift.
3378 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 /* 1. Allocate result space. */
3381 ret = _PyLong_New(asize + bsize);
3382 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003383#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 /* Fill with trash, to catch reference to uninitialized digits. */
3385 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003386#endif
Tim Peters44121a62002-08-12 06:17:58 +00003387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3389 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3390 assert(Py_SIZE(t1) >= 0);
3391 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3392 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3393 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 /* Zero-out the digits higher than the ah*bh copy. */
3396 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3397 if (i)
3398 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3399 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 /* 3. t2 <- al*bl, and copy into the low digits. */
3402 if ((t2 = k_mul(al, bl)) == NULL) {
3403 Py_DECREF(t1);
3404 goto fail;
3405 }
3406 assert(Py_SIZE(t2) >= 0);
3407 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3408 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 /* Zero out remaining digits. */
3411 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3412 if (i)
3413 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3416 * because it's fresher in cache.
3417 */
3418 i = Py_SIZE(ret) - shift; /* # digits after shift */
3419 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3420 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3423 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3426 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3427 Py_DECREF(ah);
3428 Py_DECREF(al);
3429 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 if (a == b) {
3432 t2 = t1;
3433 Py_INCREF(t2);
3434 }
3435 else if ((t2 = x_add(bh, bl)) == NULL) {
3436 Py_DECREF(t1);
3437 goto fail;
3438 }
3439 Py_DECREF(bh);
3440 Py_DECREF(bl);
3441 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 t3 = k_mul(t1, t2);
3444 Py_DECREF(t1);
3445 Py_DECREF(t2);
3446 if (t3 == NULL) goto fail;
3447 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 /* Add t3. It's not obvious why we can't run out of room here.
3450 * See the (*) comment after this function.
3451 */
3452 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3453 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003456
Mark Dickinson22b20182010-05-10 21:27:53 +00003457 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 Py_XDECREF(ret);
3459 Py_XDECREF(ah);
3460 Py_XDECREF(al);
3461 Py_XDECREF(bh);
3462 Py_XDECREF(bl);
3463 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003464}
3465
Tim Petersd6974a52002-08-13 20:37:51 +00003466/* (*) Why adding t3 can't "run out of room" above.
3467
Tim Petersab86c2b2002-08-15 20:06:00 +00003468Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3469to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003470
Tim Petersab86c2b2002-08-15 20:06:00 +000034711. For any integer i, i = c(i/2) + f(i/2). In particular,
3472 bsize = c(bsize/2) + f(bsize/2).
34732. shift = f(bsize/2)
34743. asize <= bsize
34754. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3476 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003477
Tim Petersab86c2b2002-08-15 20:06:00 +00003478We allocated asize + bsize result digits, and add t3 into them at an offset
3479of shift. This leaves asize+bsize-shift allocated digit positions for t3
3480to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3481asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003482
Tim Petersab86c2b2002-08-15 20:06:00 +00003483bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3484at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003485
Tim Petersab86c2b2002-08-15 20:06:00 +00003486If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3487digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3488most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003489
Tim Petersab86c2b2002-08-15 20:06:00 +00003490The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003491
Tim Petersab86c2b2002-08-15 20:06:00 +00003492 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003493
Tim Petersab86c2b2002-08-15 20:06:00 +00003494and we have asize + c(bsize/2) available digit positions. We need to show
3495this is always enough. An instance of c(bsize/2) cancels out in both, so
3496the question reduces to whether asize digits is enough to hold
3497(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3498then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3499asize 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 +00003500digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003501asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003502c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3503is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3504bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003505
Tim Peters48d52c02002-08-14 17:07:32 +00003506Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3507clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3508ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003509*/
3510
Tim Peters60004642002-08-12 22:01:34 +00003511/* b has at least twice the digits of a, and a is big enough that Karatsuba
3512 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3513 * of slices, each with a->ob_size digits, and multiply the slices by a,
3514 * one at a time. This gives k_mul balanced inputs to work with, and is
3515 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003516 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003517 * single-width slice overlap between successive partial sums).
3518 */
3519static PyLongObject *
3520k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3521{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003522 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3523 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 Py_ssize_t nbdone; /* # of b digits already multiplied */
3525 PyLongObject *ret;
3526 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 assert(asize > KARATSUBA_CUTOFF);
3529 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 /* Allocate result space, and zero it out. */
3532 ret = _PyLong_New(asize + bsize);
3533 if (ret == NULL)
3534 return NULL;
3535 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 /* Successive slices of b are copied into bslice. */
3538 bslice = _PyLong_New(asize);
3539 if (bslice == NULL)
3540 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 nbdone = 0;
3543 while (bsize > 0) {
3544 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003545 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 /* Multiply the next slice of b by a. */
3548 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3549 nbtouse * sizeof(digit));
3550 Py_SIZE(bslice) = nbtouse;
3551 product = k_mul(a, bslice);
3552 if (product == NULL)
3553 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 /* Add into result. */
3556 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3557 product->ob_digit, Py_SIZE(product));
3558 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 bsize -= nbtouse;
3561 nbdone += nbtouse;
3562 }
Tim Peters60004642002-08-12 22:01:34 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 Py_DECREF(bslice);
3565 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003566
Mark Dickinson22b20182010-05-10 21:27:53 +00003567 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 Py_DECREF(ret);
3569 Py_XDECREF(bslice);
3570 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003571}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003572
3573static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003574long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003581 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003583 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 z = k_mul(a, b);
3587 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003588 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3589 _PyLong_Negate(&z);
3590 if (z == NULL)
3591 return NULL;
3592 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003594}
3595
Yury Selivanove0b23092016-02-11 10:26:27 -05003596/* Fast modulo division for single-digit longs. */
3597static PyObject *
3598fast_mod(PyLongObject *a, PyLongObject *b)
3599{
3600 sdigit left = a->ob_digit[0];
3601 sdigit right = b->ob_digit[0];
3602 sdigit mod;
3603
3604 assert(Py_ABS(Py_SIZE(a)) == 1);
3605 assert(Py_ABS(Py_SIZE(b)) == 1);
3606
3607 if (Py_SIZE(a) == Py_SIZE(b)) {
3608 /* 'a' and 'b' have the same sign. */
3609 mod = left % right;
3610 }
3611 else {
3612 /* Either 'a' or 'b' is negative. */
3613 mod = right - 1 - (left - 1) % right;
3614 }
3615
Victor Stinnerf963c132016-03-23 18:36:54 +01003616 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003617}
3618
3619/* Fast floor division for single-digit longs. */
3620static PyObject *
3621fast_floor_div(PyLongObject *a, PyLongObject *b)
3622{
3623 sdigit left = a->ob_digit[0];
3624 sdigit right = b->ob_digit[0];
3625 sdigit div;
3626
3627 assert(Py_ABS(Py_SIZE(a)) == 1);
3628 assert(Py_ABS(Py_SIZE(b)) == 1);
3629
3630 if (Py_SIZE(a) == Py_SIZE(b)) {
3631 /* 'a' and 'b' have the same sign. */
3632 div = left / right;
3633 }
3634 else {
3635 /* Either 'a' or 'b' is negative. */
3636 div = -1 - (left - 1) / right;
3637 }
3638
3639 return PyLong_FromLong(div);
3640}
3641
Guido van Rossume32e0141992-01-19 16:31:05 +00003642/* The / and % operators are now defined in terms of divmod().
3643 The expression a mod b has the value a - b*floor(a/b).
3644 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003645 |a| by |b|, with the sign of a. This is also expressed
3646 as a - b*trunc(a/b), if trunc truncates towards zero.
3647 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 a b a rem b a mod b
3649 13 10 3 3
3650 -13 10 -3 7
3651 13 -10 3 -7
3652 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003653 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003654 have different signs. We then subtract one from the 'div'
3655 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003656
Tim Peters47e52ee2004-08-30 02:44:38 +00003657/* Compute
3658 * *pdiv, *pmod = divmod(v, w)
3659 * NULL can be passed for pdiv or pmod, in which case that part of
3660 * the result is simply thrown away. The caller owns a reference to
3661 * each of these it requests (does not pass NULL for).
3662 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003663static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003664l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003668
Yury Selivanove0b23092016-02-11 10:26:27 -05003669 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3670 /* Fast path for single-digit longs */
3671 div = NULL;
3672 if (pdiv != NULL) {
3673 div = (PyLongObject *)fast_floor_div(v, w);
3674 if (div == NULL) {
3675 return -1;
3676 }
3677 }
3678 if (pmod != NULL) {
3679 mod = (PyLongObject *)fast_mod(v, w);
3680 if (mod == NULL) {
3681 Py_XDECREF(div);
3682 return -1;
3683 }
3684 *pmod = mod;
3685 }
3686 if (pdiv != NULL) {
3687 /* We only want to set `*pdiv` when `*pmod` is
3688 set successfully. */
3689 *pdiv = div;
3690 }
3691 return 0;
3692 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 if (long_divrem(v, w, &div, &mod) < 0)
3694 return -1;
3695 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3696 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3697 PyLongObject *temp;
3698 PyLongObject *one;
3699 temp = (PyLongObject *) long_add(mod, w);
3700 Py_DECREF(mod);
3701 mod = temp;
3702 if (mod == NULL) {
3703 Py_DECREF(div);
3704 return -1;
3705 }
3706 one = (PyLongObject *) PyLong_FromLong(1L);
3707 if (one == NULL ||
3708 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3709 Py_DECREF(mod);
3710 Py_DECREF(div);
3711 Py_XDECREF(one);
3712 return -1;
3713 }
3714 Py_DECREF(one);
3715 Py_DECREF(div);
3716 div = temp;
3717 }
3718 if (pdiv != NULL)
3719 *pdiv = div;
3720 else
3721 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 if (pmod != NULL)
3724 *pmod = mod;
3725 else
3726 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003729}
3730
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003731static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003732long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003737
3738 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3739 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3740 }
3741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3743 div = NULL;
3744 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003745}
3746
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003747/* PyLong/PyLong -> float, with correctly rounded result. */
3748
3749#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3750#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3751
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003752static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003753long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 PyLongObject *a, *b, *x;
3756 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3757 digit mask, low;
3758 int inexact, negate, a_is_small, b_is_small;
3759 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 CHECK_BINOP(v, w);
3762 a = (PyLongObject *)v;
3763 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 /*
3766 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3769 1. choose a suitable integer 'shift'
3770 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3771 3. adjust x for correct rounding
3772 4. convert x to a double dx with the same value
3773 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3778 returns either 0.0 or -0.0, depending on the sign of b. For a and
3779 b both nonzero, ignore signs of a and b, and add the sign back in
3780 at the end. Now write a_bits and b_bits for the bit lengths of a
3781 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3782 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3787 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3788 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3789 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 1. The integer 'shift' is chosen so that x has the right number of
3794 bits for a double, plus two or three extra bits that will be used
3795 in the rounding decisions. Writing a_bits and b_bits for the
3796 number of significant bits in a and b respectively, a
3797 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 This is fine in the usual case, but if a/b is smaller than the
3802 smallest normal float then it can lead to double rounding on an
3803 IEEE 754 platform, giving incorrectly rounded results. So we
3804 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 2. The quantity x is computed by first shifting a (left -shift bits
3809 if shift <= 0, right shift bits if shift > 0) and then dividing by
3810 b. For both the shift and the division, we keep track of whether
3811 the result is inexact, in a flag 'inexact'; this information is
3812 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 With the choice of shift above, together with our assumption that
3815 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3816 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3819 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 For float representability, we need x/2**extra_bits <
3824 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3825 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 To round, we just modify the bottom digit of x in-place; this can
3830 end up giving a digit with value > PyLONG_MASK, but that's not a
3831 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 With the original choices for shift above, extra_bits will always
3834 be 2 or 3. Then rounding under the round-half-to-even rule, we
3835 round up iff the most significant of the extra bits is 1, and
3836 either: (a) the computation of x in step 2 had an inexact result,
3837 or (b) at least one other of the extra bits is 1, or (c) the least
3838 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 4. Conversion to a double is straightforward; all floating-point
3841 operations involved in the conversion are exact, so there's no
3842 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3845 The result will always be exactly representable as a double, except
3846 in the case that it overflows. To avoid dependence on the exact
3847 behaviour of ldexp on overflow, we check for overflow before
3848 applying ldexp. The result of ldexp is adjusted for sign before
3849 returning.
3850 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003853 a_size = Py_ABS(Py_SIZE(a));
3854 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3856 if (b_size == 0) {
3857 PyErr_SetString(PyExc_ZeroDivisionError,
3858 "division by zero");
3859 goto error;
3860 }
3861 if (a_size == 0)
3862 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 /* Fast path for a and b small (exactly representable in a double).
3865 Relies on floating-point division being correctly rounded; results
3866 may be subject to double rounding on x86 machines that operate with
3867 the x87 FPU set to 64-bit precision. */
3868 a_is_small = a_size <= MANT_DIG_DIGITS ||
3869 (a_size == MANT_DIG_DIGITS+1 &&
3870 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3871 b_is_small = b_size <= MANT_DIG_DIGITS ||
3872 (b_size == MANT_DIG_DIGITS+1 &&
3873 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3874 if (a_is_small && b_is_small) {
3875 double da, db;
3876 da = a->ob_digit[--a_size];
3877 while (a_size > 0)
3878 da = da * PyLong_BASE + a->ob_digit[--a_size];
3879 db = b->ob_digit[--b_size];
3880 while (b_size > 0)
3881 db = db * PyLong_BASE + b->ob_digit[--b_size];
3882 result = da / db;
3883 goto success;
3884 }
Tim Peterse2a60002001-09-04 06:17:36 +00003885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 /* Catch obvious cases of underflow and overflow */
3887 diff = a_size - b_size;
3888 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3889 /* Extreme overflow */
3890 goto overflow;
3891 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3892 /* Extreme underflow */
3893 goto underflow_or_zero;
3894 /* Next line is now safe from overflowing a Py_ssize_t */
3895 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3896 bits_in_digit(b->ob_digit[b_size - 1]);
3897 /* Now diff = a_bits - b_bits. */
3898 if (diff > DBL_MAX_EXP)
3899 goto overflow;
3900 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3901 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003904 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003906 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 /* x = abs(a * 2**-shift) */
3909 if (shift <= 0) {
3910 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3911 digit rem;
3912 /* x = a << -shift */
3913 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3914 /* In practice, it's probably impossible to end up
3915 here. Both a and b would have to be enormous,
3916 using close to SIZE_T_MAX bytes of memory each. */
3917 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003918 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 goto error;
3920 }
3921 x = _PyLong_New(a_size + shift_digits + 1);
3922 if (x == NULL)
3923 goto error;
3924 for (i = 0; i < shift_digits; i++)
3925 x->ob_digit[i] = 0;
3926 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3927 a_size, -shift % PyLong_SHIFT);
3928 x->ob_digit[a_size + shift_digits] = rem;
3929 }
3930 else {
3931 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3932 digit rem;
3933 /* x = a >> shift */
3934 assert(a_size >= shift_digits);
3935 x = _PyLong_New(a_size - shift_digits);
3936 if (x == NULL)
3937 goto error;
3938 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3939 a_size - shift_digits, shift % PyLong_SHIFT);
3940 /* set inexact if any of the bits shifted out is nonzero */
3941 if (rem)
3942 inexact = 1;
3943 while (!inexact && shift_digits > 0)
3944 if (a->ob_digit[--shift_digits])
3945 inexact = 1;
3946 }
3947 long_normalize(x);
3948 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3951 reference to x, so it's safe to modify it in-place. */
3952 if (b_size == 1) {
3953 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3954 b->ob_digit[0]);
3955 long_normalize(x);
3956 if (rem)
3957 inexact = 1;
3958 }
3959 else {
3960 PyLongObject *div, *rem;
3961 div = x_divrem(x, b, &rem);
3962 Py_DECREF(x);
3963 x = div;
3964 if (x == NULL)
3965 goto error;
3966 if (Py_SIZE(rem))
3967 inexact = 1;
3968 Py_DECREF(rem);
3969 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003970 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 assert(x_size > 0); /* result of division is never zero */
3972 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003975 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 /* Round by directly modifying the low digit of x. */
3979 mask = (digit)1 << (extra_bits - 1);
3980 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003981 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003983 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 /* Convert x to a double dx; the conversion is exact. */
3986 dx = x->ob_digit[--x_size];
3987 while (x_size > 0)
3988 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3989 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 /* Check whether ldexp result will overflow a double. */
3992 if (shift + x_bits >= DBL_MAX_EXP &&
3993 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3994 goto overflow;
3995 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003996
3997 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003999
4000 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004002
4003 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 PyErr_SetString(PyExc_OverflowError,
4005 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004006 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004008}
4009
4010static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004011long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 CHECK_BINOP(a, b);
4016
Yury Selivanove0b23092016-02-11 10:26:27 -05004017 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4018 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4019 }
4020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4022 mod = NULL;
4023 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004024}
4025
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004026static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004027long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 PyLongObject *div, *mod;
4030 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4035 return NULL;
4036 }
4037 z = PyTuple_New(2);
4038 if (z != NULL) {
4039 PyTuple_SetItem(z, 0, (PyObject *) div);
4040 PyTuple_SetItem(z, 1, (PyObject *) mod);
4041 }
4042 else {
4043 Py_DECREF(div);
4044 Py_DECREF(mod);
4045 }
4046 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004047}
4048
Tim Peters47e52ee2004-08-30 02:44:38 +00004049/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004050static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004051long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4054 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 PyLongObject *z = NULL; /* accumulated result */
4057 Py_ssize_t i, j, k; /* counters */
4058 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004060 /* 5-ary values. If the exponent is large enough, table is
4061 * precomputed so that table[i] == a**i % c for i in range(32).
4062 */
4063 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4064 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004066 /* a, b, c = v, w, x */
4067 CHECK_BINOP(v, w);
4068 a = (PyLongObject*)v; Py_INCREF(a);
4069 b = (PyLongObject*)w; Py_INCREF(b);
4070 if (PyLong_Check(x)) {
4071 c = (PyLongObject *)x;
4072 Py_INCREF(x);
4073 }
4074 else if (x == Py_None)
4075 c = NULL;
4076 else {
4077 Py_DECREF(a);
4078 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004079 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 }
Tim Peters4c483c42001-09-05 06:24:58 +00004081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 if (Py_SIZE(b) < 0) { /* if exponent is negative */
4083 if (c) {
Mark Dickinson0c346d82014-04-11 14:34:40 -04004084 PyErr_SetString(PyExc_ValueError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00004085 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 goto Error;
4087 }
4088 else {
4089 /* else return a float. This works because we know
4090 that this calls float_pow() which converts its
4091 arguments to double. */
4092 Py_DECREF(a);
4093 Py_DECREF(b);
4094 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
4095 }
4096 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 if (c) {
4099 /* if modulus == 0:
4100 raise ValueError() */
4101 if (Py_SIZE(c) == 0) {
4102 PyErr_SetString(PyExc_ValueError,
4103 "pow() 3rd argument cannot be 0");
4104 goto Error;
4105 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 /* if modulus < 0:
4108 negativeOutput = True
4109 modulus = -modulus */
4110 if (Py_SIZE(c) < 0) {
4111 negativeOutput = 1;
4112 temp = (PyLongObject *)_PyLong_Copy(c);
4113 if (temp == NULL)
4114 goto Error;
4115 Py_DECREF(c);
4116 c = temp;
4117 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004118 _PyLong_Negate(&c);
4119 if (c == NULL)
4120 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 /* if modulus == 1:
4124 return 0 */
4125 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4126 z = (PyLongObject *)PyLong_FromLong(0L);
4127 goto Done;
4128 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004129
Tim Peters81a93152013-10-05 16:53:52 -05004130 /* Reduce base by modulus in some cases:
4131 1. If base < 0. Forcing the base non-negative makes things easier.
4132 2. If base is obviously larger than the modulus. The "small
4133 exponent" case later can multiply directly by base repeatedly,
4134 while the "large exponent" case multiplies directly by base 31
4135 times. It can be unboundedly faster to multiply by
4136 base % modulus instead.
4137 We could _always_ do this reduction, but l_divmod() isn't cheap,
4138 so we only do it when it buys something. */
4139 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 if (l_divmod(a, c, NULL, &temp) < 0)
4141 goto Error;
4142 Py_DECREF(a);
4143 a = temp;
4144 temp = NULL;
4145 }
4146 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 /* At this point a, b, and c are guaranteed non-negative UNLESS
4149 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 z = (PyLongObject *)PyLong_FromLong(1L);
4152 if (z == NULL)
4153 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 /* Perform a modular reduction, X = X % c, but leave X alone if c
4156 * is NULL.
4157 */
4158#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004159 do { \
4160 if (c != NULL) { \
4161 if (l_divmod(X, c, NULL, &temp) < 0) \
4162 goto Error; \
4163 Py_XDECREF(X); \
4164 X = temp; \
4165 temp = NULL; \
4166 } \
4167 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 /* Multiply two values, then reduce the result:
4170 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004171#define MULT(X, Y, result) \
4172 do { \
4173 temp = (PyLongObject *)long_mul(X, Y); \
4174 if (temp == NULL) \
4175 goto Error; \
4176 Py_XDECREF(result); \
4177 result = temp; \
4178 temp = NULL; \
4179 REDUCE(result); \
4180 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4183 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4184 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4185 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4186 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004189 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004191 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 }
4193 }
4194 }
4195 else {
4196 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4197 Py_INCREF(z); /* still holds 1L */
4198 table[0] = z;
4199 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004200 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4203 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4206 const int index = (bi >> j) & 0x1f;
4207 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004208 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004210 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 }
4212 }
4213 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 if (negativeOutput && (Py_SIZE(z) != 0)) {
4216 temp = (PyLongObject *)long_sub(z, c);
4217 if (temp == NULL)
4218 goto Error;
4219 Py_DECREF(z);
4220 z = temp;
4221 temp = NULL;
4222 }
4223 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004224
Mark Dickinson22b20182010-05-10 21:27:53 +00004225 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004226 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004227 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004228 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4230 for (i = 0; i < 32; ++i)
4231 Py_XDECREF(table[i]);
4232 }
4233 Py_DECREF(a);
4234 Py_DECREF(b);
4235 Py_XDECREF(c);
4236 Py_XDECREF(temp);
4237 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004238}
4239
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004240static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004241long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 /* Implement ~x as -(x+1) */
4244 PyLongObject *x;
4245 PyLongObject *w;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004246 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
4248 w = (PyLongObject *)PyLong_FromLong(1L);
4249 if (w == NULL)
4250 return NULL;
4251 x = (PyLongObject *) long_add(v, w);
4252 Py_DECREF(w);
4253 if (x == NULL)
4254 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004255 _PyLong_Negate(&x);
4256 /* No need for maybe_small_long here, since any small
4257 longs will have been caught in the Py_SIZE <= 1 fast path. */
4258 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004259}
4260
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004261static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004262long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004265 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 return PyLong_FromLong(-MEDIUM_VALUE(v));
4267 z = (PyLongObject *)_PyLong_Copy(v);
4268 if (z != NULL)
4269 Py_SIZE(z) = -(Py_SIZE(v));
4270 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004271}
4272
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004273static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004274long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 if (Py_SIZE(v) < 0)
4277 return long_neg(v);
4278 else
4279 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004280}
4281
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004282static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004283long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004286}
4287
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004288static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004289long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004291 PyLongObject *z = NULL;
4292 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4293 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004295 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 if (Py_SIZE(a) < 0) {
4298 /* Right shifting negative numbers is harder */
4299 PyLongObject *a1, *a2;
4300 a1 = (PyLongObject *) long_invert(a);
4301 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004302 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 a2 = (PyLongObject *) long_rshift(a1, b);
4304 Py_DECREF(a1);
4305 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004306 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 z = (PyLongObject *) long_invert(a2);
4308 Py_DECREF(a2);
4309 }
4310 else {
4311 shiftby = PyLong_AsSsize_t((PyObject *)b);
4312 if (shiftby == -1L && PyErr_Occurred())
Mark Dickinson92ca5352016-09-17 17:50:50 +01004313 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 if (shiftby < 0) {
4315 PyErr_SetString(PyExc_ValueError,
4316 "negative shift count");
Mark Dickinson92ca5352016-09-17 17:50:50 +01004317 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318 }
4319 wordshift = shiftby / PyLong_SHIFT;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004320 newsize = Py_ABS(Py_SIZE(a)) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 if (newsize <= 0)
4322 return PyLong_FromLong(0);
4323 loshift = shiftby % PyLong_SHIFT;
4324 hishift = PyLong_SHIFT - loshift;
4325 lomask = ((digit)1 << hishift) - 1;
4326 himask = PyLong_MASK ^ lomask;
4327 z = _PyLong_New(newsize);
4328 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004329 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4331 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4332 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004333 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004335 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004337 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004338}
4339
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004340static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004341long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 /* This version due to Tim Peters */
4344 PyLongObject *a = (PyLongObject*)v;
4345 PyLongObject *b = (PyLongObject*)w;
4346 PyLongObject *z = NULL;
4347 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4348 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 shiftby = PyLong_AsSsize_t((PyObject *)b);
4353 if (shiftby == -1L && PyErr_Occurred())
Victor Stinner8aed6f12013-07-17 22:31:17 +02004354 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 if (shiftby < 0) {
4356 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004357 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004359
4360 if (Py_SIZE(a) == 0) {
4361 return PyLong_FromLong(0);
4362 }
4363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4365 wordshift = shiftby / PyLong_SHIFT;
4366 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004367
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004368 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 newsize = oldsize + wordshift;
4370 if (remshift)
4371 ++newsize;
4372 z = _PyLong_New(newsize);
4373 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004374 return NULL;
4375 if (Py_SIZE(a) < 0) {
4376 assert(Py_REFCNT(z) == 1);
4377 Py_SIZE(z) = -Py_SIZE(z);
4378 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 for (i = 0; i < wordshift; i++)
4380 z->ob_digit[i] = 0;
4381 accum = 0;
4382 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4383 accum |= (twodigits)a->ob_digit[j] << remshift;
4384 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4385 accum >>= PyLong_SHIFT;
4386 }
4387 if (remshift)
4388 z->ob_digit[newsize-1] = (digit)accum;
4389 else
4390 assert(!accum);
4391 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004393}
4394
Mark Dickinson27a87a22009-10-25 20:43:34 +00004395/* Compute two's complement of digit vector a[0:m], writing result to
4396 z[0:m]. The digit vector a need not be normalized, but should not
4397 be entirely zero. a and z may point to the same digit vector. */
4398
4399static void
4400v_complement(digit *z, digit *a, Py_ssize_t m)
4401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 Py_ssize_t i;
4403 digit carry = 1;
4404 for (i = 0; i < m; ++i) {
4405 carry += a[i] ^ PyLong_MASK;
4406 z[i] = carry & PyLong_MASK;
4407 carry >>= PyLong_SHIFT;
4408 }
4409 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004410}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004411
4412/* Bitwise and/xor/or operations */
4413
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004414static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004415long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004416 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004417 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 int nega, negb, negz;
4420 Py_ssize_t size_a, size_b, size_z, i;
4421 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 /* Bitwise operations for negative numbers operate as though
4424 on a two's complement representation. So convert arguments
4425 from sign-magnitude to two's complement, and convert the
4426 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004429 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 nega = Py_SIZE(a) < 0;
4431 if (nega) {
4432 z = _PyLong_New(size_a);
4433 if (z == NULL)
4434 return NULL;
4435 v_complement(z->ob_digit, a->ob_digit, size_a);
4436 a = z;
4437 }
4438 else
4439 /* Keep reference count consistent. */
4440 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004443 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 negb = Py_SIZE(b) < 0;
4445 if (negb) {
4446 z = _PyLong_New(size_b);
4447 if (z == NULL) {
4448 Py_DECREF(a);
4449 return NULL;
4450 }
4451 v_complement(z->ob_digit, b->ob_digit, size_b);
4452 b = z;
4453 }
4454 else
4455 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 /* Swap a and b if necessary to ensure size_a >= size_b. */
4458 if (size_a < size_b) {
4459 z = a; a = b; b = z;
4460 size_z = size_a; size_a = size_b; size_b = size_z;
4461 negz = nega; nega = negb; negb = negz;
4462 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 /* JRH: The original logic here was to allocate the result value (z)
4465 as the longer of the two operands. However, there are some cases
4466 where the result is guaranteed to be shorter than that: AND of two
4467 positives, OR of two negatives: use the shorter number. AND with
4468 mixed signs: use the positive number. OR with mixed signs: use the
4469 negative number.
4470 */
4471 switch (op) {
4472 case '^':
4473 negz = nega ^ negb;
4474 size_z = size_a;
4475 break;
4476 case '&':
4477 negz = nega & negb;
4478 size_z = negb ? size_a : size_b;
4479 break;
4480 case '|':
4481 negz = nega | negb;
4482 size_z = negb ? size_b : size_a;
4483 break;
4484 default:
4485 PyErr_BadArgument();
4486 return NULL;
4487 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 /* We allow an extra digit if z is negative, to make sure that
4490 the final two's complement of z doesn't overflow. */
4491 z = _PyLong_New(size_z + negz);
4492 if (z == NULL) {
4493 Py_DECREF(a);
4494 Py_DECREF(b);
4495 return NULL;
4496 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 /* Compute digits for overlap of a and b. */
4499 switch(op) {
4500 case '&':
4501 for (i = 0; i < size_b; ++i)
4502 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4503 break;
4504 case '|':
4505 for (i = 0; i < size_b; ++i)
4506 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4507 break;
4508 case '^':
4509 for (i = 0; i < size_b; ++i)
4510 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4511 break;
4512 default:
4513 PyErr_BadArgument();
4514 return NULL;
4515 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 /* Copy any remaining digits of a, inverting if necessary. */
4518 if (op == '^' && negb)
4519 for (; i < size_z; ++i)
4520 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4521 else if (i < size_z)
4522 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4523 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 /* Complement result if negative. */
4526 if (negz) {
4527 Py_SIZE(z) = -(Py_SIZE(z));
4528 z->ob_digit[size_z] = PyLong_MASK;
4529 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4530 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 Py_DECREF(a);
4533 Py_DECREF(b);
4534 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004535}
4536
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004537static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004538long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 PyObject *c;
4541 CHECK_BINOP(a, b);
4542 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4543 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004544}
4545
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004546static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004547long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 PyObject *c;
4550 CHECK_BINOP(a, b);
4551 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4552 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004553}
4554
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004555static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004556long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 PyObject *c;
4559 CHECK_BINOP(a, b);
4560 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4561 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004562}
4563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004564static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004565long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 if (PyLong_CheckExact(v))
4568 Py_INCREF(v);
4569 else
4570 v = _PyLong_Copy((PyLongObject *)v);
4571 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004572}
4573
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004574PyObject *
4575_PyLong_GCD(PyObject *aarg, PyObject *barg)
4576{
4577 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4578 stwodigits x, y, q, s, t, c_carry, d_carry;
4579 stwodigits A, B, C, D, T;
4580 int nbits, k;
4581 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4582 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4583
4584 a = (PyLongObject *)aarg;
4585 b = (PyLongObject *)barg;
4586 size_a = Py_SIZE(a);
4587 size_b = Py_SIZE(b);
4588 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4589 Py_INCREF(a);
4590 Py_INCREF(b);
4591 goto simple;
4592 }
4593
4594 /* Initial reduction: make sure that 0 <= b <= a. */
4595 a = (PyLongObject *)long_abs(a);
4596 if (a == NULL)
4597 return NULL;
4598 b = (PyLongObject *)long_abs(b);
4599 if (b == NULL) {
4600 Py_DECREF(a);
4601 return NULL;
4602 }
4603 if (long_compare(a, b) < 0) {
4604 r = a;
4605 a = b;
4606 b = r;
4607 }
4608 /* We now own references to a and b */
4609
4610 alloc_a = Py_SIZE(a);
4611 alloc_b = Py_SIZE(b);
4612 /* reduce until a fits into 2 digits */
4613 while ((size_a = Py_SIZE(a)) > 2) {
4614 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4615 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4616 corresponding bits of b into y */
4617 size_b = Py_SIZE(b);
4618 assert(size_b <= size_a);
4619 if (size_b == 0) {
4620 if (size_a < alloc_a) {
4621 r = (PyLongObject *)_PyLong_Copy(a);
4622 Py_DECREF(a);
4623 }
4624 else
4625 r = a;
4626 Py_DECREF(b);
4627 Py_XDECREF(c);
4628 Py_XDECREF(d);
4629 return (PyObject *)r;
4630 }
4631 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4632 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4633 (a->ob_digit[size_a-3] >> nbits));
4634
4635 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4636 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4637 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4638
4639 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4640 larger than PyLong_MASK during the algorithm. */
4641 A = 1; B = 0; C = 0; D = 1;
4642 for (k=0;; k++) {
4643 if (y-C == 0)
4644 break;
4645 q = (x+(A-1))/(y-C);
4646 s = B+q*D;
4647 t = x-q*y;
4648 if (s > t)
4649 break;
4650 x = y; y = t;
4651 t = A+q*C; A = D; B = C; C = s; D = t;
4652 }
4653
4654 if (k == 0) {
4655 /* no progress; do a Euclidean step */
4656 if (l_divmod(a, b, NULL, &r) < 0)
4657 goto error;
4658 Py_DECREF(a);
4659 a = b;
4660 b = r;
4661 alloc_a = alloc_b;
4662 alloc_b = Py_SIZE(b);
4663 continue;
4664 }
4665
4666 /*
4667 a, b = A*b-B*a, D*a-C*b if k is odd
4668 a, b = A*a-B*b, D*b-C*a if k is even
4669 */
4670 if (k&1) {
4671 T = -A; A = -B; B = T;
4672 T = -C; C = -D; D = T;
4673 }
4674 if (c != NULL)
4675 Py_SIZE(c) = size_a;
4676 else if (Py_REFCNT(a) == 1) {
4677 Py_INCREF(a);
4678 c = a;
4679 }
4680 else {
4681 alloc_a = size_a;
4682 c = _PyLong_New(size_a);
4683 if (c == NULL)
4684 goto error;
4685 }
4686
4687 if (d != NULL)
4688 Py_SIZE(d) = size_a;
4689 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4690 Py_INCREF(b);
4691 d = b;
4692 Py_SIZE(d) = size_a;
4693 }
4694 else {
4695 alloc_b = size_a;
4696 d = _PyLong_New(size_a);
4697 if (d == NULL)
4698 goto error;
4699 }
4700 a_end = a->ob_digit + size_a;
4701 b_end = b->ob_digit + size_b;
4702
4703 /* compute new a and new b in parallel */
4704 a_digit = a->ob_digit;
4705 b_digit = b->ob_digit;
4706 c_digit = c->ob_digit;
4707 d_digit = d->ob_digit;
4708 c_carry = 0;
4709 d_carry = 0;
4710 while (b_digit < b_end) {
4711 c_carry += (A * *a_digit) - (B * *b_digit);
4712 d_carry += (D * *b_digit++) - (C * *a_digit++);
4713 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4714 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4715 c_carry >>= PyLong_SHIFT;
4716 d_carry >>= PyLong_SHIFT;
4717 }
4718 while (a_digit < a_end) {
4719 c_carry += A * *a_digit;
4720 d_carry -= C * *a_digit++;
4721 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4722 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4723 c_carry >>= PyLong_SHIFT;
4724 d_carry >>= PyLong_SHIFT;
4725 }
4726 assert(c_carry == 0);
4727 assert(d_carry == 0);
4728
4729 Py_INCREF(c);
4730 Py_INCREF(d);
4731 Py_DECREF(a);
4732 Py_DECREF(b);
4733 a = long_normalize(c);
4734 b = long_normalize(d);
4735 }
4736 Py_XDECREF(c);
4737 Py_XDECREF(d);
4738
4739simple:
4740 assert(Py_REFCNT(a) > 0);
4741 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004742/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4743 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4744#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004745 /* a fits into a long, so b must too */
4746 x = PyLong_AsLong((PyObject *)a);
4747 y = PyLong_AsLong((PyObject *)b);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004748#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004749 x = PyLong_AsLongLong((PyObject *)a);
4750 y = PyLong_AsLongLong((PyObject *)b);
4751#else
4752# error "_PyLong_GCD"
4753#endif
4754 x = Py_ABS(x);
4755 y = Py_ABS(y);
4756 Py_DECREF(a);
4757 Py_DECREF(b);
4758
4759 /* usual Euclidean algorithm for longs */
4760 while (y != 0) {
4761 t = y;
4762 y = x % y;
4763 x = t;
4764 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004765#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004766 return PyLong_FromLong(x);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004767#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004768 return PyLong_FromLongLong(x);
4769#else
4770# error "_PyLong_GCD"
4771#endif
4772
4773error:
4774 Py_DECREF(a);
4775 Py_DECREF(b);
4776 Py_XDECREF(c);
4777 Py_XDECREF(d);
4778 return NULL;
4779}
4780
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004781static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004782long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004784 double result;
4785 result = PyLong_AsDouble(v);
4786 if (result == -1.0 && PyErr_Occurred())
4787 return NULL;
4788 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004789}
4790
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004791static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004792long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004793
Tim Peters6d6c1a32001-08-02 04:15:00 +00004794static PyObject *
4795long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4796{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004797 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004798 Py_ssize_t base;
Serhiy Storchaka2e564242017-03-06 17:01:06 +02004799 static char *kwlist[] = {"", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 if (type != &PyLong_Type)
4802 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004803 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4804 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004806 if (x == NULL) {
4807 if (obase != NULL) {
4808 PyErr_SetString(PyExc_TypeError,
4809 "int() missing string argument");
4810 return NULL;
4811 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004813 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004814 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004815 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004816
Gregory P. Smitha689e522012-12-25 22:38:32 -08004817 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004818 if (base == -1 && PyErr_Occurred())
4819 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004820 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004821 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004822 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004823 return NULL;
4824 }
4825
4826 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004827 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004828 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 if (PyByteArray_Check(x))
4831 string = PyByteArray_AS_STRING(x);
4832 else
4833 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004834 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004835 }
4836 else {
4837 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004838 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 return NULL;
4840 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004841}
4842
Serhiy Storchaka95949422013-08-27 19:40:23 +03004843/* Wimpy, slow approach to tp_new calls for subtypes of int:
4844 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004845 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004846 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004847*/
4848static PyObject *
4849long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 PyLongObject *tmp, *newobj;
4852 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004854 assert(PyType_IsSubtype(type, &PyLong_Type));
4855 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4856 if (tmp == NULL)
4857 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02004858 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004859 n = Py_SIZE(tmp);
4860 if (n < 0)
4861 n = -n;
4862 newobj = (PyLongObject *)type->tp_alloc(type, n);
4863 if (newobj == NULL) {
4864 Py_DECREF(tmp);
4865 return NULL;
4866 }
4867 assert(PyLong_Check(newobj));
4868 Py_SIZE(newobj) = Py_SIZE(tmp);
4869 for (i = 0; i < n; i++)
4870 newobj->ob_digit[i] = tmp->ob_digit[i];
4871 Py_DECREF(tmp);
4872 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004873}
4874
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004875/*[clinic input]
4876int.__getnewargs__
4877[clinic start generated code]*/
4878
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004879static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004880int___getnewargs___impl(PyObject *self)
4881/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004882{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004883 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004884}
4885
Guido van Rossumb43daf72007-08-01 18:08:08 +00004886static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004887long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004889}
4890
4891static PyObject *
4892long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004894}
4895
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004896/*[clinic input]
4897int.__format__
4898
4899 format_spec: unicode
4900 /
4901[clinic start generated code]*/
4902
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004903static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004904int___format___impl(PyObject *self, PyObject *format_spec)
4905/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00004906{
Victor Stinnerd3f08822012-05-29 12:57:52 +02004907 _PyUnicodeWriter writer;
4908 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004909
Victor Stinner8f674cc2013-04-17 23:02:17 +02004910 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004911 ret = _PyLong_FormatAdvancedWriter(
4912 &writer,
4913 self,
4914 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4915 if (ret == -1) {
4916 _PyUnicodeWriter_Dealloc(&writer);
4917 return NULL;
4918 }
4919 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004920}
4921
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004922/* Return a pair (q, r) such that a = b * q + r, and
4923 abs(r) <= abs(b)/2, with equality possible only if q is even.
4924 In other words, q == a / b, rounded to the nearest integer using
4925 round-half-to-even. */
4926
4927PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004928_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004929{
4930 PyLongObject *quo = NULL, *rem = NULL;
4931 PyObject *one = NULL, *twice_rem, *result, *temp;
4932 int cmp, quo_is_odd, quo_is_neg;
4933
4934 /* Equivalent Python code:
4935
4936 def divmod_near(a, b):
4937 q, r = divmod(a, b)
4938 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4939 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4940 # positive, 2 * r < b if b negative.
4941 greater_than_half = 2*r > b if b > 0 else 2*r < b
4942 exactly_half = 2*r == b
4943 if greater_than_half or exactly_half and q % 2 == 1:
4944 q += 1
4945 r -= b
4946 return q, r
4947
4948 */
4949 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4950 PyErr_SetString(PyExc_TypeError,
4951 "non-integer arguments in division");
4952 return NULL;
4953 }
4954
4955 /* Do a and b have different signs? If so, quotient is negative. */
4956 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4957
4958 one = PyLong_FromLong(1L);
4959 if (one == NULL)
4960 return NULL;
4961
4962 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4963 goto error;
4964
4965 /* compare twice the remainder with the divisor, to see
4966 if we need to adjust the quotient and remainder */
4967 twice_rem = long_lshift((PyObject *)rem, one);
4968 if (twice_rem == NULL)
4969 goto error;
4970 if (quo_is_neg) {
4971 temp = long_neg((PyLongObject*)twice_rem);
4972 Py_DECREF(twice_rem);
4973 twice_rem = temp;
4974 if (twice_rem == NULL)
4975 goto error;
4976 }
4977 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4978 Py_DECREF(twice_rem);
4979
4980 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4981 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4982 /* fix up quotient */
4983 if (quo_is_neg)
4984 temp = long_sub(quo, (PyLongObject *)one);
4985 else
4986 temp = long_add(quo, (PyLongObject *)one);
4987 Py_DECREF(quo);
4988 quo = (PyLongObject *)temp;
4989 if (quo == NULL)
4990 goto error;
4991 /* and remainder */
4992 if (quo_is_neg)
4993 temp = long_add(rem, (PyLongObject *)b);
4994 else
4995 temp = long_sub(rem, (PyLongObject *)b);
4996 Py_DECREF(rem);
4997 rem = (PyLongObject *)temp;
4998 if (rem == NULL)
4999 goto error;
5000 }
5001
5002 result = PyTuple_New(2);
5003 if (result == NULL)
5004 goto error;
5005
5006 /* PyTuple_SET_ITEM steals references */
5007 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5008 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
5009 Py_DECREF(one);
5010 return result;
5011
5012 error:
5013 Py_XDECREF(quo);
5014 Py_XDECREF(rem);
5015 Py_XDECREF(one);
5016 return NULL;
5017}
5018
Eric Smith8c663262007-08-25 02:26:07 +00005019static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005020long_round(PyObject *self, PyObject *args)
5021{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005022 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005023
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005024 /* To round an integer m to the nearest 10**n (n positive), we make use of
5025 * the divmod_near operation, defined by:
5026 *
5027 * divmod_near(a, b) = (q, r)
5028 *
5029 * where q is the nearest integer to the quotient a / b (the
5030 * nearest even integer in the case of a tie) and r == a - q * b.
5031 * Hence q * b = a - r is the nearest multiple of b to a,
5032 * preferring even multiples in the case of a tie.
5033 *
5034 * So the nearest multiple of 10**n to m is:
5035 *
5036 * m - divmod_near(m, 10**n)[1].
5037 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5039 return NULL;
5040 if (o_ndigits == NULL)
5041 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005042
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005043 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 if (ndigits == NULL)
5045 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005046
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005047 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 if (Py_SIZE(ndigits) >= 0) {
5049 Py_DECREF(ndigits);
5050 return long_long(self);
5051 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005052
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005053 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5054 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005056 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005058 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005059
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005060 result = PyLong_FromLong(10L);
5061 if (result == NULL) {
5062 Py_DECREF(ndigits);
5063 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005065
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005066 temp = long_pow(result, ndigits, Py_None);
5067 Py_DECREF(ndigits);
5068 Py_DECREF(result);
5069 result = temp;
5070 if (result == NULL)
5071 return NULL;
5072
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005073 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005074 Py_DECREF(result);
5075 result = temp;
5076 if (result == NULL)
5077 return NULL;
5078
5079 temp = long_sub((PyLongObject *)self,
5080 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5081 Py_DECREF(result);
5082 result = temp;
5083
5084 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005085}
5086
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005087/*[clinic input]
5088int.__sizeof__ -> Py_ssize_t
5089
5090Returns size in memory, in bytes.
5091[clinic start generated code]*/
5092
5093static Py_ssize_t
5094int___sizeof___impl(PyObject *self)
5095/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005097 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005098
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005099 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5100 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005101}
5102
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005103/*[clinic input]
5104int.bit_length
5105
5106Number of bits necessary to represent self in binary.
5107
5108>>> bin(37)
5109'0b100101'
5110>>> (37).bit_length()
51116
5112[clinic start generated code]*/
5113
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005114static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005115int_bit_length_impl(PyObject *self)
5116/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005119 Py_ssize_t ndigits;
5120 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005121 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005122
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005123 assert(self != NULL);
5124 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005125
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005126 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005127 if (ndigits == 0)
5128 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005129
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005130 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005131 msd_bits = bits_in_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005133 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5134 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 /* expression above may overflow; use Python integers instead */
5137 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5138 if (result == NULL)
5139 return NULL;
5140 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5141 if (x == NULL)
5142 goto error;
5143 y = (PyLongObject *)long_mul(result, x);
5144 Py_DECREF(x);
5145 if (y == NULL)
5146 goto error;
5147 Py_DECREF(result);
5148 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005150 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5151 if (x == NULL)
5152 goto error;
5153 y = (PyLongObject *)long_add(result, x);
5154 Py_DECREF(x);
5155 if (y == NULL)
5156 goto error;
5157 Py_DECREF(result);
5158 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005160 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005161
Mark Dickinson22b20182010-05-10 21:27:53 +00005162 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005163 Py_DECREF(result);
5164 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005165}
5166
Christian Heimes53876d92008-04-19 00:31:39 +00005167#if 0
5168static PyObject *
5169long_is_finite(PyObject *v)
5170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005172}
5173#endif
5174
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005175/*[clinic input]
5176int.to_bytes
5177
5178 length: Py_ssize_t
5179 Length of bytes object to use. An OverflowError is raised if the
5180 integer is not representable with the given number of bytes.
5181 byteorder: unicode
5182 The byte order used to represent the integer. If byteorder is 'big',
5183 the most significant byte is at the beginning of the byte array. If
5184 byteorder is 'little', the most significant byte is at the end of the
5185 byte array. To request the native byte order of the host system, use
5186 `sys.byteorder' as the byte order value.
5187 *
5188 signed as is_signed: bool = False
5189 Determines whether two's complement is used to represent the integer.
5190 If signed is False and a negative integer is given, an OverflowError
5191 is raised.
5192
5193Return an array of bytes representing an integer.
5194[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005195
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005196static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005197int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5198 int is_signed)
5199/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005203
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005204 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005206 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 little_endian = 0;
5208 else {
5209 PyErr_SetString(PyExc_ValueError,
5210 "byteorder must be either 'little' or 'big'");
5211 return NULL;
5212 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 if (length < 0) {
5215 PyErr_SetString(PyExc_ValueError,
5216 "length argument must be non-negative");
5217 return NULL;
5218 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220 bytes = PyBytes_FromStringAndSize(NULL, length);
5221 if (bytes == NULL)
5222 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005223
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005224 if (_PyLong_AsByteArray((PyLongObject *)self,
5225 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005226 length, little_endian, is_signed) < 0) {
5227 Py_DECREF(bytes);
5228 return NULL;
5229 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005231 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005232}
5233
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005234/*[clinic input]
5235@classmethod
5236int.from_bytes
5237
5238 bytes as bytes_obj: object
5239 Holds the array of bytes to convert. The argument must either
5240 support the buffer protocol or be an iterable object producing bytes.
5241 Bytes and bytearray are examples of built-in objects that support the
5242 buffer protocol.
5243 byteorder: unicode
5244 The byte order used to represent the integer. If byteorder is 'big',
5245 the most significant byte is at the beginning of the byte array. If
5246 byteorder is 'little', the most significant byte is at the end of the
5247 byte array. To request the native byte order of the host system, use
5248 `sys.byteorder' as the byte order value.
5249 *
5250 signed as is_signed: bool = False
5251 Indicates whether two's complement is used to represent the integer.
5252
5253Return the integer represented by the given array of bytes.
5254[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005255
5256static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005257int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5258 PyObject *byteorder, int is_signed)
5259/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005262 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005263
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005264 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005266 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 little_endian = 0;
5268 else {
5269 PyErr_SetString(PyExc_ValueError,
5270 "byteorder must be either 'little' or 'big'");
5271 return NULL;
5272 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005273
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005274 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 if (bytes == NULL)
5276 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005278 long_obj = _PyLong_FromByteArray(
5279 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5280 little_endian, is_signed);
5281 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005282
Serhiy Storchakaea36c942016-05-12 10:37:58 +03005283 if (type != &PyLong_Type) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01005284 Py_SETREF(long_obj, PyObject_CallFunctionObjArgs((PyObject *)type,
5285 long_obj, NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005286 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005289}
5290
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005291static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
5293 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005294 INT_BIT_LENGTH_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00005295#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5297 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005298#endif
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005299 INT_TO_BYTES_METHODDEF
5300 INT_FROM_BYTES_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
5302 "Truncating an Integral returns itself."},
5303 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
5304 "Flooring an Integral returns itself."},
5305 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
5306 "Ceiling of an Integral returns itself."},
5307 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5308 "Rounding an Integral returns itself.\n"
5309 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005310 INT___GETNEWARGS___METHODDEF
5311 INT___FORMAT___METHODDEF
5312 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005314};
5315
Guido van Rossumb43daf72007-08-01 18:08:08 +00005316static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005317 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005318 (getter)long_long, (setter)NULL,
5319 "the real part of a complex number",
5320 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005321 {"imag",
5322 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005323 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005324 NULL},
5325 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005326 (getter)long_long, (setter)NULL,
5327 "the numerator of a rational number in lowest terms",
5328 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005329 {"denominator",
5330 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005331 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005332 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005333 {NULL} /* Sentinel */
5334};
5335
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005336PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005337"int(x=0) -> integer\n\
5338int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005339\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005340Convert a number or string to an integer, or return 0 if no arguments\n\
5341are given. If x is a number, return x.__int__(). For floating point\n\
5342numbers, this truncates towards zero.\n\
5343\n\
5344If x is not a number or if base is given, then x must be a string,\n\
5345bytes, or bytearray instance representing an integer literal in the\n\
5346given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5347by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5348Base 0 means to interpret the base from the string as an integer literal.\n\
5349>>> int('0b100', base=0)\n\
53504");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005351
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005352static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005353 (binaryfunc)long_add, /*nb_add*/
5354 (binaryfunc)long_sub, /*nb_subtract*/
5355 (binaryfunc)long_mul, /*nb_multiply*/
5356 long_mod, /*nb_remainder*/
5357 long_divmod, /*nb_divmod*/
5358 long_pow, /*nb_power*/
5359 (unaryfunc)long_neg, /*nb_negative*/
5360 (unaryfunc)long_long, /*tp_positive*/
5361 (unaryfunc)long_abs, /*tp_absolute*/
5362 (inquiry)long_bool, /*tp_bool*/
5363 (unaryfunc)long_invert, /*nb_invert*/
5364 long_lshift, /*nb_lshift*/
5365 (binaryfunc)long_rshift, /*nb_rshift*/
5366 long_and, /*nb_and*/
5367 long_xor, /*nb_xor*/
5368 long_or, /*nb_or*/
5369 long_long, /*nb_int*/
5370 0, /*nb_reserved*/
5371 long_float, /*nb_float*/
5372 0, /* nb_inplace_add */
5373 0, /* nb_inplace_subtract */
5374 0, /* nb_inplace_multiply */
5375 0, /* nb_inplace_remainder */
5376 0, /* nb_inplace_power */
5377 0, /* nb_inplace_lshift */
5378 0, /* nb_inplace_rshift */
5379 0, /* nb_inplace_and */
5380 0, /* nb_inplace_xor */
5381 0, /* nb_inplace_or */
5382 long_div, /* nb_floor_divide */
5383 long_true_divide, /* nb_true_divide */
5384 0, /* nb_inplace_floor_divide */
5385 0, /* nb_inplace_true_divide */
5386 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005387};
5388
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005389PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005390 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5391 "int", /* tp_name */
5392 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5393 sizeof(digit), /* tp_itemsize */
5394 long_dealloc, /* tp_dealloc */
5395 0, /* tp_print */
5396 0, /* tp_getattr */
5397 0, /* tp_setattr */
5398 0, /* tp_reserved */
5399 long_to_decimal_string, /* tp_repr */
5400 &long_as_number, /* tp_as_number */
5401 0, /* tp_as_sequence */
5402 0, /* tp_as_mapping */
5403 (hashfunc)long_hash, /* tp_hash */
5404 0, /* tp_call */
5405 long_to_decimal_string, /* tp_str */
5406 PyObject_GenericGetAttr, /* tp_getattro */
5407 0, /* tp_setattro */
5408 0, /* tp_as_buffer */
5409 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5410 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5411 long_doc, /* tp_doc */
5412 0, /* tp_traverse */
5413 0, /* tp_clear */
5414 long_richcompare, /* tp_richcompare */
5415 0, /* tp_weaklistoffset */
5416 0, /* tp_iter */
5417 0, /* tp_iternext */
5418 long_methods, /* tp_methods */
5419 0, /* tp_members */
5420 long_getset, /* tp_getset */
5421 0, /* tp_base */
5422 0, /* tp_dict */
5423 0, /* tp_descr_get */
5424 0, /* tp_descr_set */
5425 0, /* tp_dictoffset */
5426 0, /* tp_init */
5427 0, /* tp_alloc */
5428 long_new, /* tp_new */
5429 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005430};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005431
Mark Dickinsonbd792642009-03-18 20:06:12 +00005432static PyTypeObject Int_InfoType;
5433
5434PyDoc_STRVAR(int_info__doc__,
5435"sys.int_info\n\
5436\n\
5437A struct sequence that holds information about Python's\n\
5438internal representation of integers. The attributes are read only.");
5439
5440static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005442 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005444};
5445
5446static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 "sys.int_info", /* name */
5448 int_info__doc__, /* doc */
5449 int_info_fields, /* fields */
5450 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005451};
5452
5453PyObject *
5454PyLong_GetInfo(void)
5455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 PyObject* int_info;
5457 int field = 0;
5458 int_info = PyStructSequence_New(&Int_InfoType);
5459 if (int_info == NULL)
5460 return NULL;
5461 PyStructSequence_SET_ITEM(int_info, field++,
5462 PyLong_FromLong(PyLong_SHIFT));
5463 PyStructSequence_SET_ITEM(int_info, field++,
5464 PyLong_FromLong(sizeof(digit)));
5465 if (PyErr_Occurred()) {
5466 Py_CLEAR(int_info);
5467 return NULL;
5468 }
5469 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005470}
5471
Guido van Rossumddefaf32007-01-14 03:31:43 +00005472int
5473_PyLong_Init(void)
5474{
5475#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 int ival, size;
5477 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5480 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5481 if (Py_TYPE(v) == &PyLong_Type) {
5482 /* The element is already initialized, most likely
5483 * the Python interpreter was initialized before.
5484 */
5485 Py_ssize_t refcnt;
5486 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005488 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5489 _Py_NewReference(op);
5490 /* _Py_NewReference sets the ref count to 1 but
5491 * the ref count might be larger. Set the refcnt
5492 * to the original refcnt + 1 */
5493 Py_REFCNT(op) = refcnt + 1;
5494 assert(Py_SIZE(op) == size);
Victor Stinner12174a52014-08-15 23:17:38 +02005495 assert(v->ob_digit[0] == (digit)abs(ival));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005496 }
5497 else {
Christian Heimesd3afe782013-12-04 09:27:47 +01005498 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 }
5500 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005501 v->ob_digit[0] = (digit)abs(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005502 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005503#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005504 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005505 if (Int_InfoType.tp_name == NULL) {
5506 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5507 return 0;
5508 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005511}
5512
5513void
5514PyLong_Fini(void)
5515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 /* Integers are currently statically allocated. Py_DECREF is not
5517 needed, but Python must forget about the reference or multiple
5518 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005519#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 int i;
5521 PyLongObject *v = small_ints;
5522 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5523 _Py_DEC_REFTOTAL;
5524 _Py_ForgetReference((PyObject*)v);
5525 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005526#endif
5527}