blob: ba23599535934cc0d7a70b02708cf21d0a63a002 [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
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000014#endif
15#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000017#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020020#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
21 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 (Py_SIZE(x) == 0 ? (sdigit)0 : \
23 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010033Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050039 PyObject *v;
Benjamin Peterson041c38a2014-03-14 21:47:23 -050040 assert(-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS);
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050041 v = (PyObject *)&small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000043#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 if (ival >= 0)
45 quick_int_allocs++;
46 else
47 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000050}
51#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
53 return get_small_int((sdigit)ival); \
54 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000057maybe_small_long(PyLongObject *v)
58{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020059 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 sdigit ival = MEDIUM_VALUE(v);
61 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
62 Py_DECREF(v);
63 return (PyLongObject *)get_small_int(ival);
64 }
65 }
66 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000067}
Guido van Rossumddefaf32007-01-14 03:31:43 +000068#else
69#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000070#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000071#endif
72
Serhiy Storchaka95949422013-08-27 19:40:23 +030073/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000074 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020075Py_LOCAL_INLINE(void)
76_PyLong_Negate(PyLongObject **x_p)
77{
78 PyLongObject *x;
79
80 x = (PyLongObject *)*x_p;
81 if (Py_REFCNT(x) == 1) {
82 Py_SIZE(x) = -Py_SIZE(x);
83 return;
84 }
85
86 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
87 Py_DECREF(x);
88}
89
Serhiy Storchaka95949422013-08-27 19:40:23 +030090/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000091 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030092 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000093 */
Tim Peters0973b992004-08-29 22:16:50 +000094#define KARATSUBA_CUTOFF 70
95#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000096
Tim Peters47e52ee2004-08-30 02:44:38 +000097/* For exponentiation, use the binary left-to-right algorithm
98 * unless the exponent contains more than FIVEARY_CUTOFF digits.
99 * In that case, do 5 bits at a time. The potential drawback is that
100 * a table of 2**5 intermediate results is computed.
101 */
102#define FIVEARY_CUTOFF 8
103
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000104#define SIGCHECK(PyTryBlock) \
105 do { \
106 if (PyErr_CheckSignals()) PyTryBlock \
107 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000108
Serhiy Storchaka95949422013-08-27 19:40:23 +0300109/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000110 Doesn't attempt to free the storage--in most cases, due to the nature
111 of the algorithms used, this could save at most be one word anyway. */
112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200114long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000115{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200116 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 while (i > 0 && v->ob_digit[i-1] == 0)
120 --i;
121 if (i != j)
122 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
123 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000124}
125
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200126/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
127 using the nb_int slot, if available. Raise TypeError if either the
128 nb_int slot is not available or the result of the call to nb_int
129 returns something not of type int.
130*/
131PyLongObject *
132_PyLong_FromNbInt(PyObject *integral)
133{
134 PyNumberMethods *nb;
135 PyObject *result;
136
137 /* Fast path for the case that we already have an int. */
138 if (PyLong_CheckExact(integral)) {
139 Py_INCREF(integral);
140 return (PyLongObject *)integral;
141 }
142
143 nb = Py_TYPE(integral)->tp_as_number;
144 if (nb == NULL || nb->nb_int == NULL) {
145 PyErr_Format(PyExc_TypeError,
146 "an integer is required (got type %.200s)",
147 Py_TYPE(integral)->tp_name);
148 return NULL;
149 }
150
151 /* Convert using the nb_int slot, which should return something
152 of exact type int. */
153 result = nb->nb_int(integral);
154 if (!result || PyLong_CheckExact(result))
155 return (PyLongObject *)result;
156 if (!PyLong_Check(result)) {
157 PyErr_Format(PyExc_TypeError,
158 "__int__ returned non-int (type %.200s)",
159 result->ob_type->tp_name);
160 Py_DECREF(result);
161 return NULL;
162 }
163 /* Issue #17576: warn if 'result' not of exact type int. */
164 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
165 "__int__ returned non-int (type %.200s). "
166 "The ability to return an instance of a strict subclass of int "
167 "is deprecated, and may be removed in a future version of Python.",
168 result->ob_type->tp_name)) {
169 Py_DECREF(result);
170 return NULL;
171 }
172 return (PyLongObject *)result;
173}
174
175
Serhiy Storchaka95949422013-08-27 19:40:23 +0300176/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000177 Return NULL and set exception if we run out of memory. */
178
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000179#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000181
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000182PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000183_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyLongObject *result;
186 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
187 sizeof(digit)*size. Previous incarnations of this code used
188 sizeof(PyVarObject) instead of the offsetof, but this risks being
189 incorrect in the presence of padding between the PyVarObject header
190 and the digits. */
191 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
192 PyErr_SetString(PyExc_OverflowError,
193 "too many digits in integer");
194 return NULL;
195 }
196 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
197 size*sizeof(digit));
198 if (!result) {
199 PyErr_NoMemory();
200 return NULL;
201 }
202 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000203}
204
Tim Peters64b5ce32001-09-10 20:52:51 +0000205PyObject *
206_PyLong_Copy(PyLongObject *src)
207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 PyLongObject *result;
209 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 assert(src != NULL);
212 i = Py_SIZE(src);
213 if (i < 0)
214 i = -(i);
215 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100216 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 CHECK_SMALL_INT(ival);
218 }
219 result = _PyLong_New(i);
220 if (result != NULL) {
221 Py_SIZE(result) = Py_SIZE(src);
222 while (--i >= 0)
223 result->ob_digit[i] = src->ob_digit[i];
224 }
225 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000226}
227
Serhiy Storchaka95949422013-08-27 19:40:23 +0300228/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000229
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000230PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000231PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 PyLongObject *v;
234 unsigned long abs_ival;
235 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
236 int ndigits = 0;
237 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 if (ival < 0) {
242 /* negate: can't write this as abs_ival = -ival since that
243 invokes undefined behaviour when ival is LONG_MIN */
244 abs_ival = 0U-(unsigned long)ival;
245 sign = -1;
246 }
247 else {
248 abs_ival = (unsigned long)ival;
249 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 /* Fast path for single-digit ints */
252 if (!(abs_ival >> PyLong_SHIFT)) {
253 v = _PyLong_New(1);
254 if (v) {
255 Py_SIZE(v) = sign;
256 v->ob_digit[0] = Py_SAFE_DOWNCAST(
257 abs_ival, unsigned long, digit);
258 }
259 return (PyObject*)v;
260 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000261
Mark Dickinson249b8982009-04-27 19:41:00 +0000262#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 /* 2 digits */
264 if (!(abs_ival >> 2*PyLong_SHIFT)) {
265 v = _PyLong_New(2);
266 if (v) {
267 Py_SIZE(v) = 2*sign;
268 v->ob_digit[0] = Py_SAFE_DOWNCAST(
269 abs_ival & PyLong_MASK, unsigned long, digit);
270 v->ob_digit[1] = Py_SAFE_DOWNCAST(
271 abs_ival >> PyLong_SHIFT, unsigned long, digit);
272 }
273 return (PyObject*)v;
274 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000275#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 /* Larger numbers: loop to determine number of digits */
278 t = abs_ival;
279 while (t) {
280 ++ndigits;
281 t >>= PyLong_SHIFT;
282 }
283 v = _PyLong_New(ndigits);
284 if (v != NULL) {
285 digit *p = v->ob_digit;
286 Py_SIZE(v) = ndigits*sign;
287 t = abs_ival;
288 while (t) {
289 *p++ = Py_SAFE_DOWNCAST(
290 t & PyLong_MASK, unsigned long, digit);
291 t >>= PyLong_SHIFT;
292 }
293 }
294 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000295}
296
Serhiy Storchaka95949422013-08-27 19:40:23 +0300297/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000298
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000300PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 PyLongObject *v;
303 unsigned long t;
304 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (ival < PyLong_BASE)
307 return PyLong_FromLong(ival);
308 /* Count the number of Python digits. */
309 t = (unsigned long)ival;
310 while (t) {
311 ++ndigits;
312 t >>= PyLong_SHIFT;
313 }
314 v = _PyLong_New(ndigits);
315 if (v != NULL) {
316 digit *p = v->ob_digit;
317 Py_SIZE(v) = ndigits;
318 while (ival) {
319 *p++ = (digit)(ival & PyLong_MASK);
320 ival >>= PyLong_SHIFT;
321 }
322 }
323 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000324}
325
Serhiy Storchaka95949422013-08-27 19:40:23 +0300326/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000327
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyLongObject *v;
332 double frac;
333 int i, ndig, expo, neg;
334 neg = 0;
335 if (Py_IS_INFINITY(dval)) {
336 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000337 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 return NULL;
339 }
340 if (Py_IS_NAN(dval)) {
341 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000342 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 return NULL;
344 }
345 if (dval < 0.0) {
346 neg = 1;
347 dval = -dval;
348 }
349 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
350 if (expo <= 0)
351 return PyLong_FromLong(0L);
352 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
353 v = _PyLong_New(ndig);
354 if (v == NULL)
355 return NULL;
356 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
357 for (i = ndig; --i >= 0; ) {
358 digit bits = (digit)frac;
359 v->ob_digit[i] = bits;
360 frac = frac - (double)bits;
361 frac = ldexp(frac, PyLong_SHIFT);
362 }
363 if (neg)
364 Py_SIZE(v) = -(Py_SIZE(v));
365 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000366}
367
Thomas Wouters89f507f2006-12-13 04:49:30 +0000368/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
369 * anything about what happens when a signed integer operation overflows,
370 * and some compilers think they're doing you a favor by being "clever"
371 * then. The bit pattern for the largest postive signed long is
372 * (unsigned long)LONG_MAX, and for the smallest negative signed long
373 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
374 * However, some other compilers warn about applying unary minus to an
375 * unsigned operand. Hence the weird "0-".
376 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
378#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000379
Serhiy Storchaka95949422013-08-27 19:40:23 +0300380/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100381 method.
382
383 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
384 the result. Otherwise *overflow is 0.
385
386 For other errors (e.g., TypeError), return -1 and set an error condition.
387 In this case *overflow will be 0.
388*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000389
390long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000391PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200394 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 unsigned long x, prev;
396 long res;
397 Py_ssize_t i;
398 int sign;
399 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 *overflow = 0;
402 if (vv == NULL) {
403 PyErr_BadInternalCall();
404 return -1;
405 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000406
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200407 if (PyLong_Check(vv)) {
408 v = (PyLongObject *)vv;
409 }
410 else {
411 v = _PyLong_FromNbInt(vv);
412 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 return -1;
414 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 switch (i) {
421 case -1:
422 res = -(sdigit)v->ob_digit[0];
423 break;
424 case 0:
425 res = 0;
426 break;
427 case 1:
428 res = v->ob_digit[0];
429 break;
430 default:
431 sign = 1;
432 x = 0;
433 if (i < 0) {
434 sign = -1;
435 i = -(i);
436 }
437 while (--i >= 0) {
438 prev = x;
439 x = (x << PyLong_SHIFT) | v->ob_digit[i];
440 if ((x >> PyLong_SHIFT) != prev) {
441 *overflow = sign;
442 goto exit;
443 }
444 }
445 /* Haven't lost any bits, but casting to long requires extra
446 * care (see comment above).
447 */
448 if (x <= (unsigned long)LONG_MAX) {
449 res = (long)x * sign;
450 }
451 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
452 res = LONG_MIN;
453 }
454 else {
455 *overflow = sign;
456 /* res is already set to -1 */
457 }
458 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000459 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200461 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 }
463 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000464}
465
Serhiy Storchaka95949422013-08-27 19:40:23 +0300466/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100467 method. Return -1 and set an error if overflow occurs. */
468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000470PyLong_AsLong(PyObject *obj)
471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 int overflow;
473 long result = PyLong_AsLongAndOverflow(obj, &overflow);
474 if (overflow) {
475 /* XXX: could be cute and give a different
476 message for overflow == -1 */
477 PyErr_SetString(PyExc_OverflowError,
478 "Python int too large to convert to C long");
479 }
480 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000481}
482
Serhiy Storchaka95949422013-08-27 19:40:23 +0300483/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200484 method. Return -1 and set an error if overflow occurs. */
485
486int
487_PyLong_AsInt(PyObject *obj)
488{
489 int overflow;
490 long result = PyLong_AsLongAndOverflow(obj, &overflow);
491 if (overflow || result > INT_MAX || result < INT_MIN) {
492 /* XXX: could be cute and give a different
493 message for overflow == -1 */
494 PyErr_SetString(PyExc_OverflowError,
495 "Python int too large to convert to C int");
496 return -1;
497 }
498 return (int)result;
499}
500
Serhiy Storchaka95949422013-08-27 19:40:23 +0300501/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000502 Returns -1 and sets an error condition if overflow occurs. */
503
504Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000505PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200506 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 size_t x, prev;
508 Py_ssize_t i;
509 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (vv == NULL) {
512 PyErr_BadInternalCall();
513 return -1;
514 }
515 if (!PyLong_Check(vv)) {
516 PyErr_SetString(PyExc_TypeError, "an integer is required");
517 return -1;
518 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 v = (PyLongObject *)vv;
521 i = Py_SIZE(v);
522 switch (i) {
523 case -1: return -(sdigit)v->ob_digit[0];
524 case 0: return 0;
525 case 1: return v->ob_digit[0];
526 }
527 sign = 1;
528 x = 0;
529 if (i < 0) {
530 sign = -1;
531 i = -(i);
532 }
533 while (--i >= 0) {
534 prev = x;
535 x = (x << PyLong_SHIFT) | v->ob_digit[i];
536 if ((x >> PyLong_SHIFT) != prev)
537 goto overflow;
538 }
539 /* Haven't lost any bits, but casting to a signed type requires
540 * extra care (see comment above).
541 */
542 if (x <= (size_t)PY_SSIZE_T_MAX) {
543 return (Py_ssize_t)x * sign;
544 }
545 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
546 return PY_SSIZE_T_MIN;
547 }
548 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000549
Mark Dickinson22b20182010-05-10 21:27:53 +0000550 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 PyErr_SetString(PyExc_OverflowError,
552 "Python int too large to convert to C ssize_t");
553 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000554}
555
Serhiy Storchaka95949422013-08-27 19:40:23 +0300556/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000557 Returns -1 and sets an error condition if overflow occurs. */
558
559unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000560PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000561{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200562 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 unsigned long x, prev;
564 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 if (vv == NULL) {
567 PyErr_BadInternalCall();
568 return (unsigned long)-1;
569 }
570 if (!PyLong_Check(vv)) {
571 PyErr_SetString(PyExc_TypeError, "an integer is required");
572 return (unsigned long)-1;
573 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 v = (PyLongObject *)vv;
576 i = Py_SIZE(v);
577 x = 0;
578 if (i < 0) {
579 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000580 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return (unsigned long) -1;
582 }
583 switch (i) {
584 case 0: return 0;
585 case 1: return v->ob_digit[0];
586 }
587 while (--i >= 0) {
588 prev = x;
589 x = (x << PyLong_SHIFT) | v->ob_digit[i];
590 if ((x >> PyLong_SHIFT) != prev) {
591 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100592 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000593 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 return (unsigned long) -1;
595 }
596 }
597 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000598}
599
Serhiy Storchaka95949422013-08-27 19:40:23 +0300600/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200601 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000602
603size_t
604PyLong_AsSize_t(PyObject *vv)
605{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200606 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 size_t x, prev;
608 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (vv == NULL) {
611 PyErr_BadInternalCall();
612 return (size_t) -1;
613 }
614 if (!PyLong_Check(vv)) {
615 PyErr_SetString(PyExc_TypeError, "an integer is required");
616 return (size_t)-1;
617 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 v = (PyLongObject *)vv;
620 i = Py_SIZE(v);
621 x = 0;
622 if (i < 0) {
623 PyErr_SetString(PyExc_OverflowError,
624 "can't convert negative value to size_t");
625 return (size_t) -1;
626 }
627 switch (i) {
628 case 0: return 0;
629 case 1: return v->ob_digit[0];
630 }
631 while (--i >= 0) {
632 prev = x;
633 x = (x << PyLong_SHIFT) | v->ob_digit[i];
634 if ((x >> PyLong_SHIFT) != prev) {
635 PyErr_SetString(PyExc_OverflowError,
636 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200637 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 }
639 }
640 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000641}
642
Serhiy Storchaka95949422013-08-27 19:40:23 +0300643/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000644 Returns -1 and sets an error condition if an error occurs. */
645
Guido van Rossumddefaf32007-01-14 03:31:43 +0000646static unsigned long
647_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000648{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200649 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 unsigned long x;
651 Py_ssize_t i;
652 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (vv == NULL || !PyLong_Check(vv)) {
655 PyErr_BadInternalCall();
656 return (unsigned long) -1;
657 }
658 v = (PyLongObject *)vv;
659 i = Py_SIZE(v);
660 switch (i) {
661 case 0: return 0;
662 case 1: return v->ob_digit[0];
663 }
664 sign = 1;
665 x = 0;
666 if (i < 0) {
667 sign = -1;
668 i = -i;
669 }
670 while (--i >= 0) {
671 x = (x << PyLong_SHIFT) | v->ob_digit[i];
672 }
673 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000674}
675
Guido van Rossumddefaf32007-01-14 03:31:43 +0000676unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200677PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyLongObject *lo;
680 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000681
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200682 if (op == NULL) {
683 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 return (unsigned long)-1;
685 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000686
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200687 if (PyLong_Check(op)) {
688 return _PyLong_AsUnsignedLongMask(op);
689 }
690
691 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (lo == NULL)
693 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200694
695 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
696 Py_DECREF(lo);
697 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000698}
699
Tim Peters5b8132f2003-01-31 15:52:05 +0000700int
701_PyLong_Sign(PyObject *vv)
702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 assert(v != NULL);
706 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000709}
710
Tim Petersbaefd9e2003-01-28 20:37:45 +0000711size_t
712_PyLong_NumBits(PyObject *vv)
713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyLongObject *v = (PyLongObject *)vv;
715 size_t result = 0;
716 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 assert(v != NULL);
719 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200720 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
722 if (ndigits > 0) {
723 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100724 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100726 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 do {
728 ++result;
729 if (result == 0)
730 goto Overflow;
731 msd >>= 1;
732 } while (msd);
733 }
734 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000735
Mark Dickinson22b20182010-05-10 21:27:53 +0000736 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
738 "to express in a platform size_t");
739 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000740}
741
Tim Peters2a9b3672001-06-11 21:23:58 +0000742PyObject *
743_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000745{
Mark Dickinson22b20182010-05-10 21:27:53 +0000746 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 int incr; /* direction to move pstartbyte */
748 const unsigned char* pendbyte; /* MSB of bytes */
749 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300750 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 PyLongObject* v; /* result */
752 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (n == 0)
755 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (little_endian) {
758 pstartbyte = bytes;
759 pendbyte = bytes + n - 1;
760 incr = 1;
761 }
762 else {
763 pstartbyte = bytes + n - 1;
764 pendbyte = bytes;
765 incr = -1;
766 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 if (is_signed)
769 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200772 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 is positive, and leading 0xff bytes if negative. */
774 {
775 size_t i;
776 const unsigned char* p = pendbyte;
777 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000778 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000781 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 break;
783 }
784 numsignificantbytes = n - i;
785 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
786 actually has 2 significant bytes. OTOH, 0xff0001 ==
787 -0x00ffff, so we wouldn't *need* to bump it there; but we
788 do for 0xffff = -0x0001. To be safe without bothering to
789 check every case, bump it regardless. */
790 if (is_signed && numsignificantbytes < n)
791 ++numsignificantbytes;
792 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000793
Serhiy Storchaka95949422013-08-27 19:40:23 +0300794 /* How many Python int digits do we need? We have
795 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
797 /* catch overflow before it happens */
798 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
799 PyErr_SetString(PyExc_OverflowError,
800 "byte array too long to convert to int");
801 return NULL;
802 }
803 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
804 v = _PyLong_New(ndigits);
805 if (v == NULL)
806 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 /* Copy the bits over. The tricky parts are computing 2's-comp on
809 the fly for signed numbers, and dealing with the mismatch between
810 8-bit bytes and (probably) 15-bit Python digits.*/
811 {
812 size_t i;
813 twodigits carry = 1; /* for 2's-comp calculation */
814 twodigits accum = 0; /* sliding register */
815 unsigned int accumbits = 0; /* number of bits in accum */
816 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
819 twodigits thisbyte = *p;
820 /* Compute correction for 2's comp, if needed. */
821 if (is_signed) {
822 thisbyte = (0xff ^ thisbyte) + carry;
823 carry = thisbyte >> 8;
824 thisbyte &= 0xff;
825 }
826 /* Because we're going LSB to MSB, thisbyte is
827 more significant than what's already in accum,
828 so needs to be prepended to accum. */
829 accum |= (twodigits)thisbyte << accumbits;
830 accumbits += 8;
831 if (accumbits >= PyLong_SHIFT) {
832 /* There's enough to fill a Python digit. */
833 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000834 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 ++idigit;
836 accum >>= PyLong_SHIFT;
837 accumbits -= PyLong_SHIFT;
838 assert(accumbits < PyLong_SHIFT);
839 }
840 }
841 assert(accumbits < PyLong_SHIFT);
842 if (accumbits) {
843 assert(idigit < ndigits);
844 v->ob_digit[idigit] = (digit)accum;
845 ++idigit;
846 }
847 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 Py_SIZE(v) = is_signed ? -idigit : idigit;
850 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000851}
852
853int
854_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 unsigned char* bytes, size_t n,
856 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000859 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000861 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
863 digit carry; /* for computing 2's-comp */
864 size_t j; /* # bytes filled */
865 unsigned char* p; /* pointer to next byte in bytes */
866 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if (Py_SIZE(v) < 0) {
871 ndigits = -(Py_SIZE(v));
872 if (!is_signed) {
873 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000874 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 return -1;
876 }
877 do_twos_comp = 1;
878 }
879 else {
880 ndigits = Py_SIZE(v);
881 do_twos_comp = 0;
882 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (little_endian) {
885 p = bytes;
886 pincr = 1;
887 }
888 else {
889 p = bytes + n - 1;
890 pincr = -1;
891 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 /* Copy over all the Python digits.
894 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300895 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 normalized. */
897 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
898 j = 0;
899 accum = 0;
900 accumbits = 0;
901 carry = do_twos_comp ? 1 : 0;
902 for (i = 0; i < ndigits; ++i) {
903 digit thisdigit = v->ob_digit[i];
904 if (do_twos_comp) {
905 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
906 carry = thisdigit >> PyLong_SHIFT;
907 thisdigit &= PyLong_MASK;
908 }
909 /* Because we're going LSB to MSB, thisdigit is more
910 significant than what's already in accum, so needs to be
911 prepended to accum. */
912 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* The most-significant digit may be (probably is) at least
915 partly empty. */
916 if (i == ndigits - 1) {
917 /* Count # of sign bits -- they needn't be stored,
918 * although for signed conversion we need later to
919 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000920 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 while (s != 0) {
922 s >>= 1;
923 accumbits++;
924 }
925 }
926 else
927 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Store as many bytes as possible. */
930 while (accumbits >= 8) {
931 if (j >= n)
932 goto Overflow;
933 ++j;
934 *p = (unsigned char)(accum & 0xff);
935 p += pincr;
936 accumbits -= 8;
937 accum >>= 8;
938 }
939 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Store the straggler (if any). */
942 assert(accumbits < 8);
943 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
944 if (accumbits > 0) {
945 if (j >= n)
946 goto Overflow;
947 ++j;
948 if (do_twos_comp) {
949 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300950 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 infinite supply of sign bits). */
952 accum |= (~(twodigits)0) << accumbits;
953 }
954 *p = (unsigned char)(accum & 0xff);
955 p += pincr;
956 }
957 else if (j == n && n > 0 && is_signed) {
958 /* The main loop filled the byte array exactly, so the code
959 just above didn't get to ensure there's a sign bit, and the
960 loop below wouldn't add one either. Make sure a sign bit
961 exists. */
962 unsigned char msb = *(p - pincr);
963 int sign_bit_set = msb >= 0x80;
964 assert(accumbits == 0);
965 if (sign_bit_set == do_twos_comp)
966 return 0;
967 else
968 goto Overflow;
969 }
Tim Peters05607ad2001-06-13 21:01:27 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* Fill remaining bytes with copies of the sign bit. */
972 {
973 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
974 for ( ; j < n; ++j, p += pincr)
975 *p = signbyte;
976 }
Tim Peters05607ad2001-06-13 21:01:27 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000979
Mark Dickinson22b20182010-05-10 21:27:53 +0000980 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
982 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000983
Tim Peters2a9b3672001-06-11 21:23:58 +0000984}
985
Serhiy Storchaka95949422013-08-27 19:40:23 +0300986/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000987
988PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000989PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000990{
Mark Dickinson91044792012-10-18 19:21:43 +0100991#if SIZEOF_VOID_P <= SIZEOF_LONG
Mark Dickinson91044792012-10-18 19:21:43 +0100992 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
993#else
994
Tim Peters70128a12001-06-16 08:48:40 +0000995#ifndef HAVE_LONG_LONG
996# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
997#endif
998#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000999# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001000#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001002#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001003
Guido van Rossum78694d91998-09-18 14:14:13 +00001004}
1005
Serhiy Storchaka95949422013-08-27 19:40:23 +03001006/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001007
1008void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001009PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001010{
Tim Peters70128a12001-06-16 08:48:40 +00001011#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1015 x = PyLong_AsLong(vv);
1016 else
1017 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001018#else
Tim Peters70128a12001-06-16 08:48:40 +00001019
1020#ifndef HAVE_LONG_LONG
1021# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1022#endif
1023#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001024# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001025#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1029 x = PyLong_AsLongLong(vv);
1030 else
1031 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001032
1033#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 if (x == -1 && PyErr_Occurred())
1036 return NULL;
1037 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001038}
1039
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001040#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001041
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001042/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001043 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001044 */
1045
Mark Dickinson22b20182010-05-10 21:27:53 +00001046#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001047
Serhiy Storchaka95949422013-08-27 19:40:23 +03001048/* Create a new int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001049
1050PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001051PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyLongObject *v;
1054 unsigned PY_LONG_LONG abs_ival;
1055 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1056 int ndigits = 0;
1057 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 CHECK_SMALL_INT(ival);
1060 if (ival < 0) {
1061 /* avoid signed overflow on negation; see comments
1062 in PyLong_FromLong above. */
1063 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1064 negative = 1;
1065 }
1066 else {
1067 abs_ival = (unsigned PY_LONG_LONG)ival;
1068 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 /* Count the number of Python digits.
1071 We used to pick 5 ("big enough for anything"), but that's a
1072 waste of time and space given that 5*15 = 75 bits are rarely
1073 needed. */
1074 t = abs_ival;
1075 while (t) {
1076 ++ndigits;
1077 t >>= PyLong_SHIFT;
1078 }
1079 v = _PyLong_New(ndigits);
1080 if (v != NULL) {
1081 digit *p = v->ob_digit;
1082 Py_SIZE(v) = negative ? -ndigits : ndigits;
1083 t = abs_ival;
1084 while (t) {
1085 *p++ = (digit)(t & PyLong_MASK);
1086 t >>= PyLong_SHIFT;
1087 }
1088 }
1089 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001090}
1091
Serhiy Storchaka95949422013-08-27 19:40:23 +03001092/* Create a new int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001093
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001094PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001095PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyLongObject *v;
1098 unsigned PY_LONG_LONG t;
1099 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (ival < PyLong_BASE)
1102 return PyLong_FromLong((long)ival);
1103 /* Count the number of Python digits. */
1104 t = (unsigned PY_LONG_LONG)ival;
1105 while (t) {
1106 ++ndigits;
1107 t >>= PyLong_SHIFT;
1108 }
1109 v = _PyLong_New(ndigits);
1110 if (v != NULL) {
1111 digit *p = v->ob_digit;
1112 Py_SIZE(v) = ndigits;
1113 while (ival) {
1114 *p++ = (digit)(ival & PyLong_MASK);
1115 ival >>= PyLong_SHIFT;
1116 }
1117 }
1118 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001119}
1120
Serhiy Storchaka95949422013-08-27 19:40:23 +03001121/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001122
1123PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001124PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 PyLongObject *v;
1127 size_t abs_ival;
1128 size_t t; /* unsigned so >> doesn't propagate sign bit */
1129 int ndigits = 0;
1130 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 CHECK_SMALL_INT(ival);
1133 if (ival < 0) {
1134 /* avoid signed overflow when ival = SIZE_T_MIN */
1135 abs_ival = (size_t)(-1-ival)+1;
1136 negative = 1;
1137 }
1138 else {
1139 abs_ival = (size_t)ival;
1140 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 /* Count the number of Python digits. */
1143 t = abs_ival;
1144 while (t) {
1145 ++ndigits;
1146 t >>= PyLong_SHIFT;
1147 }
1148 v = _PyLong_New(ndigits);
1149 if (v != NULL) {
1150 digit *p = v->ob_digit;
1151 Py_SIZE(v) = negative ? -ndigits : ndigits;
1152 t = abs_ival;
1153 while (t) {
1154 *p++ = (digit)(t & PyLong_MASK);
1155 t >>= PyLong_SHIFT;
1156 }
1157 }
1158 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001159}
1160
Serhiy Storchaka95949422013-08-27 19:40:23 +03001161/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001162
1163PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001164PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 PyLongObject *v;
1167 size_t t;
1168 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 if (ival < PyLong_BASE)
1171 return PyLong_FromLong((long)ival);
1172 /* Count the number of Python digits. */
1173 t = ival;
1174 while (t) {
1175 ++ndigits;
1176 t >>= PyLong_SHIFT;
1177 }
1178 v = _PyLong_New(ndigits);
1179 if (v != NULL) {
1180 digit *p = v->ob_digit;
1181 Py_SIZE(v) = ndigits;
1182 while (ival) {
1183 *p++ = (digit)(ival & PyLong_MASK);
1184 ival >>= PyLong_SHIFT;
1185 }
1186 }
1187 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001188}
1189
Serhiy Storchaka95949422013-08-27 19:40:23 +03001190/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001191 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001192
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001193PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001194PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 PyLongObject *v;
1197 PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001199 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 if (vv == NULL) {
1202 PyErr_BadInternalCall();
1203 return -1;
1204 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001205
1206 if (PyLong_Check(vv)) {
1207 v = (PyLongObject *)vv;
1208 }
1209 else {
1210 v = _PyLong_FromNbInt(vv);
1211 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001213 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001215
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001216 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001218 case -1:
1219 bytes = -(sdigit)v->ob_digit[0];
1220 break;
1221 case 0:
1222 bytes = 0;
1223 break;
1224 case 1:
1225 bytes = v->ob_digit[0];
1226 break;
1227 default:
1228 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001229 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001231 if (do_decref) {
1232 Py_DECREF(v);
1233 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1236 if (res < 0)
1237 return (PY_LONG_LONG)-1;
1238 else
1239 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001240}
1241
Serhiy Storchaka95949422013-08-27 19:40:23 +03001242/* Get a C unsigned PY_LONG_LONG int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001243 Return -1 and set an error if overflow occurs. */
1244
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001245unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001246PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 PyLongObject *v;
1249 unsigned PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001251
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001252 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 PyErr_BadInternalCall();
1254 return (unsigned PY_LONG_LONG)-1;
1255 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001256 if (!PyLong_Check(vv)) {
1257 PyErr_SetString(PyExc_TypeError, "an integer is required");
1258 return (unsigned PY_LONG_LONG)-1;
1259 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 v = (PyLongObject*)vv;
1262 switch(Py_SIZE(v)) {
1263 case 0: return 0;
1264 case 1: return v->ob_digit[0];
1265 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001266
Mark Dickinson22b20182010-05-10 21:27:53 +00001267 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001268 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1271 if (res < 0)
1272 return (unsigned PY_LONG_LONG)res;
1273 else
1274 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001275}
Tim Petersd1a7da62001-06-13 00:35:57 +00001276
Serhiy Storchaka95949422013-08-27 19:40:23 +03001277/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001278 Returns -1 and sets an error condition if an error occurs. */
1279
Guido van Rossumddefaf32007-01-14 03:31:43 +00001280static unsigned PY_LONG_LONG
1281_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001282{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001283 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 unsigned PY_LONG_LONG x;
1285 Py_ssize_t i;
1286 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (vv == NULL || !PyLong_Check(vv)) {
1289 PyErr_BadInternalCall();
1290 return (unsigned long) -1;
1291 }
1292 v = (PyLongObject *)vv;
1293 switch(Py_SIZE(v)) {
1294 case 0: return 0;
1295 case 1: return v->ob_digit[0];
1296 }
1297 i = Py_SIZE(v);
1298 sign = 1;
1299 x = 0;
1300 if (i < 0) {
1301 sign = -1;
1302 i = -i;
1303 }
1304 while (--i >= 0) {
1305 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1306 }
1307 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001308}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001309
1310unsigned PY_LONG_LONG
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001311PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 PyLongObject *lo;
1314 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001315
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001316 if (op == NULL) {
1317 PyErr_BadInternalCall();
1318 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001320
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001321 if (PyLong_Check(op)) {
1322 return _PyLong_AsUnsignedLongLongMask(op);
1323 }
1324
1325 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (lo == NULL)
1327 return (unsigned PY_LONG_LONG)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001328
1329 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1330 Py_DECREF(lo);
1331 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001332}
Tim Petersd1a7da62001-06-13 00:35:57 +00001333
Serhiy Storchaka95949422013-08-27 19:40:23 +03001334/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001335 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001336
Mark Dickinson8d48b432011-10-23 20:47:14 +01001337 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1338 the result. Otherwise *overflow is 0.
1339
1340 For other errors (e.g., TypeError), return -1 and set an error condition.
1341 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001342*/
1343
1344PY_LONG_LONG
1345PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001348 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 unsigned PY_LONG_LONG x, prev;
1350 PY_LONG_LONG res;
1351 Py_ssize_t i;
1352 int sign;
1353 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 *overflow = 0;
1356 if (vv == NULL) {
1357 PyErr_BadInternalCall();
1358 return -1;
1359 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001360
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001361 if (PyLong_Check(vv)) {
1362 v = (PyLongObject *)vv;
1363 }
1364 else {
1365 v = _PyLong_FromNbInt(vv);
1366 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 return -1;
1368 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 switch (i) {
1375 case -1:
1376 res = -(sdigit)v->ob_digit[0];
1377 break;
1378 case 0:
1379 res = 0;
1380 break;
1381 case 1:
1382 res = v->ob_digit[0];
1383 break;
1384 default:
1385 sign = 1;
1386 x = 0;
1387 if (i < 0) {
1388 sign = -1;
1389 i = -(i);
1390 }
1391 while (--i >= 0) {
1392 prev = x;
1393 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1394 if ((x >> PyLong_SHIFT) != prev) {
1395 *overflow = sign;
1396 goto exit;
1397 }
1398 }
1399 /* Haven't lost any bits, but casting to long requires extra
1400 * care (see comment above).
1401 */
1402 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1403 res = (PY_LONG_LONG)x * sign;
1404 }
1405 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1406 res = PY_LLONG_MIN;
1407 }
1408 else {
1409 *overflow = sign;
1410 /* res is already set to -1 */
1411 }
1412 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001413 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001415 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 }
1417 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001418}
1419
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001420#endif /* HAVE_LONG_LONG */
1421
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001422#define CHECK_BINOP(v,w) \
1423 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001424 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1425 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001426 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001427
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001428/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1429 2**k if d is nonzero, else 0. */
1430
1431static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1433 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001434};
1435
1436static int
1437bits_in_digit(digit d)
1438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 int d_bits = 0;
1440 while (d >= 32) {
1441 d_bits += 6;
1442 d >>= 6;
1443 }
1444 d_bits += (int)BitLengthTable[d];
1445 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001446}
1447
Tim Peters877a2122002-08-12 05:09:36 +00001448/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1449 * is modified in place, by adding y to it. Carries are propagated as far as
1450 * x[m-1], and the remaining carry (0 or 1) is returned.
1451 */
1452static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001453v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 Py_ssize_t i;
1456 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 assert(m >= n);
1459 for (i = 0; i < n; ++i) {
1460 carry += x[i] + y[i];
1461 x[i] = carry & PyLong_MASK;
1462 carry >>= PyLong_SHIFT;
1463 assert((carry & 1) == carry);
1464 }
1465 for (; carry && i < m; ++i) {
1466 carry += x[i];
1467 x[i] = carry & PyLong_MASK;
1468 carry >>= PyLong_SHIFT;
1469 assert((carry & 1) == carry);
1470 }
1471 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001472}
1473
1474/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1475 * is modified in place, by subtracting y from it. Borrows are propagated as
1476 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1477 */
1478static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001479v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 Py_ssize_t i;
1482 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 assert(m >= n);
1485 for (i = 0; i < n; ++i) {
1486 borrow = x[i] - y[i] - borrow;
1487 x[i] = borrow & PyLong_MASK;
1488 borrow >>= PyLong_SHIFT;
1489 borrow &= 1; /* keep only 1 sign bit */
1490 }
1491 for (; borrow && i < m; ++i) {
1492 borrow = x[i] - borrow;
1493 x[i] = borrow & PyLong_MASK;
1494 borrow >>= PyLong_SHIFT;
1495 borrow &= 1;
1496 }
1497 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001498}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001499
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001500/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1501 * result in z[0:m], and return the d bits shifted out of the top.
1502 */
1503static digit
1504v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 Py_ssize_t i;
1507 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 assert(0 <= d && d < PyLong_SHIFT);
1510 for (i=0; i < m; i++) {
1511 twodigits acc = (twodigits)a[i] << d | carry;
1512 z[i] = (digit)acc & PyLong_MASK;
1513 carry = (digit)(acc >> PyLong_SHIFT);
1514 }
1515 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001516}
1517
1518/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1519 * result in z[0:m], and return the d bits shifted out of the bottom.
1520 */
1521static digit
1522v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 Py_ssize_t i;
1525 digit carry = 0;
1526 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 assert(0 <= d && d < PyLong_SHIFT);
1529 for (i=m; i-- > 0;) {
1530 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1531 carry = (digit)acc & mask;
1532 z[i] = (digit)(acc >> d);
1533 }
1534 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001535}
1536
Tim Peters212e6142001-07-14 12:23:19 +00001537/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1538 in pout, and returning the remainder. pin and pout point at the LSD.
1539 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001540 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001541 immutable. */
1542
1543static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001544inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 assert(n > 0 && n <= PyLong_MASK);
1549 pin += size;
1550 pout += size;
1551 while (--size >= 0) {
1552 digit hi;
1553 rem = (rem << PyLong_SHIFT) | *--pin;
1554 *--pout = hi = (digit)(rem / n);
1555 rem -= (twodigits)hi * n;
1556 }
1557 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001558}
1559
Serhiy Storchaka95949422013-08-27 19:40:23 +03001560/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001561 (as function result) and the remainder (through *prem).
1562 The sign of a is ignored; n should not be zero. */
1563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001564static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001565divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001566{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001567 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 assert(n > 0 && n <= PyLong_MASK);
1571 z = _PyLong_New(size);
1572 if (z == NULL)
1573 return NULL;
1574 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1575 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001576}
1577
Serhiy Storchaka95949422013-08-27 19:40:23 +03001578/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001579 string. (Return value is non-shared so that callers can modify the
1580 returned value if necessary.) */
1581
Victor Stinnerd3f08822012-05-29 12:57:52 +02001582static int
1583long_to_decimal_string_internal(PyObject *aa,
1584 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001585 _PyUnicodeWriter *writer,
1586 _PyBytesWriter *bytes_writer,
1587 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001590 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 Py_ssize_t size, strlen, size_a, i, j;
1592 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001594 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001595 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 a = (PyLongObject *)aa;
1598 if (a == NULL || !PyLong_Check(a)) {
1599 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001600 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001602 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 /* quick and dirty upper bound for the number of digits
1606 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 But log2(a) < size_a * PyLong_SHIFT, and
1611 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001612 > 3.3 * _PyLong_DECIMAL_SHIFT
1613
1614 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1615 size_a + size_a / d < size_a + size_a / floor(d),
1616 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1617 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001619 d = (33 * _PyLong_DECIMAL_SHIFT) /
1620 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1621 assert(size_a < PY_SSIZE_T_MAX/2);
1622 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 scratch = _PyLong_New(size);
1624 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001625 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 /* convert array of base _PyLong_BASE digits in pin to an array of
1628 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1629 Volume 2 (3rd edn), section 4.4, Method 1b). */
1630 pin = a->ob_digit;
1631 pout = scratch->ob_digit;
1632 size = 0;
1633 for (i = size_a; --i >= 0; ) {
1634 digit hi = pin[i];
1635 for (j = 0; j < size; j++) {
1636 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1637 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1638 pout[j] = (digit)(z - (twodigits)hi *
1639 _PyLong_DECIMAL_BASE);
1640 }
1641 while (hi) {
1642 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1643 hi /= _PyLong_DECIMAL_BASE;
1644 }
1645 /* check for keyboard interrupt */
1646 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001647 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001648 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001649 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 }
1651 /* pout should have at least one digit, so that the case when a = 0
1652 works correctly */
1653 if (size == 0)
1654 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 /* calculate exact length of output string, and allocate */
1657 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1658 tenpow = 10;
1659 rem = pout[size-1];
1660 while (rem >= tenpow) {
1661 tenpow *= 10;
1662 strlen++;
1663 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001664 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001665 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1666 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001667 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001668 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001669 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001671 else if (bytes_writer) {
1672 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1673 if (*bytes_str == NULL) {
1674 Py_DECREF(scratch);
1675 return -1;
1676 }
1677 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001678 else {
1679 str = PyUnicode_New(strlen, '9');
1680 if (str == NULL) {
1681 Py_DECREF(scratch);
1682 return -1;
1683 }
1684 kind = PyUnicode_KIND(str);
1685 }
1686
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001687#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001688 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001689 /* pout[0] through pout[size-2] contribute exactly \
1690 _PyLong_DECIMAL_SHIFT digits each */ \
1691 for (i=0; i < size - 1; i++) { \
1692 rem = pout[i]; \
1693 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1694 *--p = '0' + rem % 10; \
1695 rem /= 10; \
1696 } \
1697 } \
1698 /* pout[size-1]: always produce at least one decimal digit */ \
1699 rem = pout[i]; \
1700 do { \
1701 *--p = '0' + rem % 10; \
1702 rem /= 10; \
1703 } while (rem != 0); \
1704 \
1705 /* and sign */ \
1706 if (negative) \
1707 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001708 } while (0)
1709
1710#define WRITE_UNICODE_DIGITS(TYPE) \
1711 do { \
1712 if (writer) \
1713 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1714 else \
1715 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1716 \
1717 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001718 \
1719 /* check we've counted correctly */ \
1720 if (writer) \
1721 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1722 else \
1723 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1724 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001727 if (bytes_writer) {
1728 char *p = *bytes_str + strlen;
1729 WRITE_DIGITS(p);
1730 assert(p == *bytes_str);
1731 }
1732 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001733 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001734 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001736 else if (kind == PyUnicode_2BYTE_KIND) {
1737 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001738 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001739 }
1740 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001741 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001742 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001743 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001744 }
1745#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001746#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001749 if (writer) {
1750 writer->pos += strlen;
1751 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001752 else if (bytes_writer) {
1753 (*bytes_str) += strlen;
1754 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001755 else {
1756 assert(_PyUnicode_CheckConsistency(str, 1));
1757 *p_output = (PyObject *)str;
1758 }
1759 return 0;
1760}
1761
1762static PyObject *
1763long_to_decimal_string(PyObject *aa)
1764{
1765 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001766 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001767 return NULL;
1768 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001769}
1770
Serhiy Storchaka95949422013-08-27 19:40:23 +03001771/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001772 which should be one of 2, 8 or 16. Return a string object.
1773 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1774 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001775
Victor Stinnerd3f08822012-05-29 12:57:52 +02001776static int
1777long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001778 PyObject **p_output, _PyUnicodeWriter *writer,
1779 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001780{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001781 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001782 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001783 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001785 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001786 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001788
Victor Stinnerd3f08822012-05-29 12:57:52 +02001789 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 if (a == NULL || !PyLong_Check(a)) {
1791 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001792 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001794 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001795 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 /* Compute a rough upper bound for the length of the string */
1798 switch (base) {
1799 case 16:
1800 bits = 4;
1801 break;
1802 case 8:
1803 bits = 3;
1804 break;
1805 case 2:
1806 bits = 1;
1807 break;
1808 default:
1809 assert(0); /* shouldn't ever get here */
1810 bits = 0; /* to silence gcc warning */
1811 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001812
Mark Dickinsone2846542012-04-20 21:21:24 +01001813 /* Compute exact length 'sz' of output string. */
1814 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001815 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001816 }
1817 else {
1818 Py_ssize_t size_a_in_bits;
1819 /* Ensure overflow doesn't occur during computation of sz. */
1820 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1821 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001822 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001823 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001824 }
1825 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1826 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001827 /* Allow 1 character for a '-' sign. */
1828 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1829 }
1830 if (alternate) {
1831 /* 2 characters for prefix */
1832 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001833 }
1834
Victor Stinnerd3f08822012-05-29 12:57:52 +02001835 if (writer) {
1836 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1837 return -1;
1838 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001840 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001841 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1842 if (*bytes_str == NULL)
1843 return -1;
1844 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001846 v = PyUnicode_New(sz, 'x');
1847 if (v == NULL)
1848 return -1;
1849 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001851
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001852#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001853 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001854 if (size_a == 0) { \
1855 *--p = '0'; \
1856 } \
1857 else { \
1858 /* JRH: special case for power-of-2 bases */ \
1859 twodigits accum = 0; \
1860 int accumbits = 0; /* # of bits in accum */ \
1861 Py_ssize_t i; \
1862 for (i = 0; i < size_a; ++i) { \
1863 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1864 accumbits += PyLong_SHIFT; \
1865 assert(accumbits >= bits); \
1866 do { \
1867 char cdigit; \
1868 cdigit = (char)(accum & (base - 1)); \
1869 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1870 *--p = cdigit; \
1871 accumbits -= bits; \
1872 accum >>= bits; \
1873 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1874 } \
1875 } \
1876 \
1877 if (alternate) { \
1878 if (base == 16) \
1879 *--p = 'x'; \
1880 else if (base == 8) \
1881 *--p = 'o'; \
1882 else /* (base == 2) */ \
1883 *--p = 'b'; \
1884 *--p = '0'; \
1885 } \
1886 if (negative) \
1887 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001888 } while (0)
1889
1890#define WRITE_UNICODE_DIGITS(TYPE) \
1891 do { \
1892 if (writer) \
1893 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1894 else \
1895 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1896 \
1897 WRITE_DIGITS(p); \
1898 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001899 if (writer) \
1900 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1901 else \
1902 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1903 } while (0)
1904
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001905 if (bytes_writer) {
1906 char *p = *bytes_str + sz;
1907 WRITE_DIGITS(p);
1908 assert(p == *bytes_str);
1909 }
1910 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001911 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001912 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001913 }
1914 else if (kind == PyUnicode_2BYTE_KIND) {
1915 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001916 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001917 }
1918 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001919 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001920 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001921 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001922 }
1923#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001924#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02001925
1926 if (writer) {
1927 writer->pos += sz;
1928 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001929 else if (bytes_writer) {
1930 (*bytes_str) += sz;
1931 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001932 else {
1933 assert(_PyUnicode_CheckConsistency(v, 1));
1934 *p_output = v;
1935 }
1936 return 0;
1937}
1938
1939PyObject *
1940_PyLong_Format(PyObject *obj, int base)
1941{
1942 PyObject *str;
1943 int err;
1944 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001945 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001946 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001947 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001948 if (err == -1)
1949 return NULL;
1950 return str;
1951}
1952
1953int
1954_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1955 PyObject *obj,
1956 int base, int alternate)
1957{
1958 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001959 return long_to_decimal_string_internal(obj, NULL, writer,
1960 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001961 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001962 return long_format_binary(obj, base, alternate, NULL, writer,
1963 NULL, NULL);
1964}
1965
1966char*
1967_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
1968 PyObject *obj,
1969 int base, int alternate)
1970{
1971 char *str2;
1972 int res;
1973 str2 = str;
1974 if (base == 10)
1975 res = long_to_decimal_string_internal(obj, NULL, NULL,
1976 writer, &str2);
1977 else
1978 res = long_format_binary(obj, base, alternate, NULL, NULL,
1979 writer, &str2);
1980 if (res < 0)
1981 return NULL;
1982 assert(str2 != NULL);
1983 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001984}
1985
Thomas Wouters477c8d52006-05-27 19:21:47 +00001986/* Table of digit values for 8-bit string -> integer conversion.
1987 * '0' maps to 0, ..., '9' maps to 9.
1988 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1989 * All other indices map to 37.
1990 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001991 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001992 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001993unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1995 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1996 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1997 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1998 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1999 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2000 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2001 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2002 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2003 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2004 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2005 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2006 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2007 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2008 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2009 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002010};
2011
2012/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002013 * 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 +03002014 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002015 * The point to this routine is that it takes time linear in the number of
2016 * string characters.
2017 */
2018static PyLongObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002019long_from_binary_base(const char **str, int base)
Tim Petersbf2674b2003-02-02 07:51:32 +00002020{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002021 const char *p = *str;
2022 const char *start = p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 int bits_per_char;
2024 Py_ssize_t n;
2025 PyLongObject *z;
2026 twodigits accum;
2027 int bits_in_accum;
2028 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2031 n = base;
2032 for (bits_per_char = -1; n; ++bits_per_char)
2033 n >>= 1;
2034 /* n <- total # of bits needed, while setting p to end-of-string */
2035 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
2036 ++p;
2037 *str = p;
2038 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
2039 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
2040 if (n / bits_per_char < p - start) {
2041 PyErr_SetString(PyExc_ValueError,
2042 "int string too large to convert");
2043 return NULL;
2044 }
2045 n = n / PyLong_SHIFT;
2046 z = _PyLong_New(n);
2047 if (z == NULL)
2048 return NULL;
Serhiy Storchaka95949422013-08-27 19:40:23 +03002049 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 * from least to most significant in both.
2051 */
2052 accum = 0;
2053 bits_in_accum = 0;
2054 pdigit = z->ob_digit;
2055 while (--p >= start) {
2056 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
2057 assert(k >= 0 && k < base);
2058 accum |= (twodigits)k << bits_in_accum;
2059 bits_in_accum += bits_per_char;
2060 if (bits_in_accum >= PyLong_SHIFT) {
2061 *pdigit++ = (digit)(accum & PyLong_MASK);
2062 assert(pdigit - z->ob_digit <= n);
2063 accum >>= PyLong_SHIFT;
2064 bits_in_accum -= PyLong_SHIFT;
2065 assert(bits_in_accum < PyLong_SHIFT);
2066 }
2067 }
2068 if (bits_in_accum) {
2069 assert(bits_in_accum <= PyLong_SHIFT);
2070 *pdigit++ = (digit)accum;
2071 assert(pdigit - z->ob_digit <= n);
2072 }
2073 while (pdigit - z->ob_digit < n)
2074 *pdigit++ = 0;
2075 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00002076}
2077
Serhiy Storchaka95949422013-08-27 19:40:23 +03002078/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002079 * ignored.
2080 *
2081 * If successful, a PyLong object will be returned and 'pend' will be pointing
2082 * to the first unused byte unless it's NULL.
2083 *
2084 * If unsuccessful, NULL will be returned.
2085 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002086PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002087PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002090 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 PyLongObject *z = NULL;
2092 PyObject *strobj;
2093 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 if ((base != 0 && base < 2) || base > 36) {
2096 PyErr_SetString(PyExc_ValueError,
2097 "int() arg 2 must be >= 2 and <= 36");
2098 return NULL;
2099 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002100 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 str++;
2102 if (*str == '+')
2103 ++str;
2104 else if (*str == '-') {
2105 ++str;
2106 sign = -1;
2107 }
2108 if (base == 0) {
2109 if (str[0] != '0')
2110 base = 10;
2111 else if (str[1] == 'x' || str[1] == 'X')
2112 base = 16;
2113 else if (str[1] == 'o' || str[1] == 'O')
2114 base = 8;
2115 else if (str[1] == 'b' || str[1] == 'B')
2116 base = 2;
2117 else {
2118 /* "old" (C-style) octal literal, now invalid.
2119 it might still be zero though */
2120 error_if_nonzero = 1;
2121 base = 10;
2122 }
2123 }
2124 if (str[0] == '0' &&
2125 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2126 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2127 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2128 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 start = str;
2131 if ((base & (base - 1)) == 0)
2132 z = long_from_binary_base(&str, base);
2133 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002134/***
2135Binary bases can be converted in time linear in the number of digits, because
2136Python's representation base is binary. Other bases (including decimal!) use
2137the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002138
Thomas Wouters477c8d52006-05-27 19:21:47 +00002139First some math: the largest integer that can be expressed in N base-B digits
2140is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2141case number of Python digits needed to hold it is the smallest integer n s.t.
2142
2143 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2144 BASE**n >= B**N [taking logs to base BASE]
2145 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2146
2147The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002148this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002149and the result is computed into it.
2150
2151The input string is actually treated as being in base base**i (i.e., i digits
2152are processed at a time), where two more static arrays hold:
2153
2154 convwidth_base[base] = the largest integer i such that base**i <= BASE
2155 convmultmax_base[base] = base ** convwidth_base[base]
2156
2157The first of these is the largest i such that i consecutive input digits
2158must fit in a single Python digit. The second is effectively the input
2159base we're really using.
2160
2161Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2162convmultmax_base[base], the result is "simply"
2163
2164 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2165
2166where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002167
2168Error analysis: as above, the number of Python digits `n` needed is worst-
2169case
2170
2171 n >= N * log(B)/log(BASE)
2172
2173where `N` is the number of input digits in base `B`. This is computed via
2174
2175 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2176
2177below. Two numeric concerns are how much space this can waste, and whether
2178the computed result can be too small. To be concrete, assume BASE = 2**15,
2179which is the default (and it's unlikely anyone changes that).
2180
2181Waste isn't a problem: provided the first input digit isn't 0, the difference
2182between the worst-case input with N digits and the smallest input with N
2183digits is about a factor of B, but B is small compared to BASE so at most
2184one allocated Python digit can remain unused on that count. If
2185N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2186and adding 1 returns a result 1 larger than necessary. However, that can't
2187happen: whenever B is a power of 2, long_from_binary_base() is called
2188instead, and it's impossible for B**i to be an integer power of 2**15 when
2189B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2190an exact integer when B is not a power of 2, since B**i has a prime factor
2191other than 2 in that case, but (2**15)**j's only prime factor is 2).
2192
2193The computed result can be too small if the true value of N*log(B)/log(BASE)
2194is a little bit larger than an exact integer, but due to roundoff errors (in
2195computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2196yields a numeric result a little less than that integer. Unfortunately, "how
2197close can a transcendental function get to an integer over some range?"
2198questions are generally theoretically intractable. Computer analysis via
2199continued fractions is practical: expand log(B)/log(BASE) via continued
2200fractions, giving a sequence i/j of "the best" rational approximations. Then
2201j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2202we can get very close to being in trouble, but very rarely. For example,
220376573 is a denominator in one of the continued-fraction approximations to
2204log(10)/log(2**15), and indeed:
2205
2206 >>> log(10)/log(2**15)*76573
2207 16958.000000654003
2208
2209is very close to an integer. If we were working with IEEE single-precision,
2210rounding errors could kill us. Finding worst cases in IEEE double-precision
2211requires better-than-double-precision log() functions, and Tim didn't bother.
2212Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002213new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002214This should happen extremely rarely, and in fact I don't have a test case
2215that triggers it(!). Instead the code was tested by artificially allocating
2216just 1 digit at the start, so that the copying code was exercised for every
2217digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002218***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002219 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 Py_ssize_t size_z;
2221 int i;
2222 int convwidth;
2223 twodigits convmultmax, convmult;
2224 digit *pz, *pzstop;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002225 const char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 static double log_base_BASE[37] = {0.0e0,};
2228 static int convwidth_base[37] = {0,};
2229 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 if (log_base_BASE[base] == 0.0) {
2232 twodigits convmax = base;
2233 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002234
Mark Dickinson22b20182010-05-10 21:27:53 +00002235 log_base_BASE[base] = (log((double)base) /
2236 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 for (;;) {
2238 twodigits next = convmax * base;
2239 if (next > PyLong_BASE)
2240 break;
2241 convmax = next;
2242 ++i;
2243 }
2244 convmultmax_base[base] = convmax;
2245 assert(i > 0);
2246 convwidth_base[base] = i;
2247 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 /* Find length of the string of numeric characters. */
2250 scan = str;
2251 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2252 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002253
Serhiy Storchaka95949422013-08-27 19:40:23 +03002254 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 * integer with this base and length. Note that there's no
2256 * need to initialize z->ob_digit -- no slot is read up before
2257 * being stored into.
2258 */
2259 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2260 /* Uncomment next line to test exceedingly rare copy code */
2261 /* size_z = 1; */
2262 assert(size_z > 0);
2263 z = _PyLong_New(size_z);
2264 if (z == NULL)
2265 return NULL;
2266 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 /* `convwidth` consecutive input digits are treated as a single
2269 * digit in base `convmultmax`.
2270 */
2271 convwidth = convwidth_base[base];
2272 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 /* Work ;-) */
2275 while (str < scan) {
2276 /* grab up to convwidth digits from the input string */
2277 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2278 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2279 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002280 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 assert(c < PyLong_BASE);
2282 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 convmult = convmultmax;
2285 /* Calculate the shift only if we couldn't get
2286 * convwidth digits.
2287 */
2288 if (i != convwidth) {
2289 convmult = base;
2290 for ( ; i > 1; --i)
2291 convmult *= base;
2292 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* Multiply z by convmult, and add c. */
2295 pz = z->ob_digit;
2296 pzstop = pz + Py_SIZE(z);
2297 for (; pz < pzstop; ++pz) {
2298 c += (twodigits)*pz * convmult;
2299 *pz = (digit)(c & PyLong_MASK);
2300 c >>= PyLong_SHIFT;
2301 }
2302 /* carry off the current end? */
2303 if (c) {
2304 assert(c < PyLong_BASE);
2305 if (Py_SIZE(z) < size_z) {
2306 *pz = (digit)c;
2307 ++Py_SIZE(z);
2308 }
2309 else {
2310 PyLongObject *tmp;
2311 /* Extremely rare. Get more space. */
2312 assert(Py_SIZE(z) == size_z);
2313 tmp = _PyLong_New(size_z + 1);
2314 if (tmp == NULL) {
2315 Py_DECREF(z);
2316 return NULL;
2317 }
2318 memcpy(tmp->ob_digit,
2319 z->ob_digit,
2320 sizeof(digit) * size_z);
2321 Py_DECREF(z);
2322 z = tmp;
2323 z->ob_digit[size_z] = (digit)c;
2324 ++size_z;
2325 }
2326 }
2327 }
2328 }
2329 if (z == NULL)
2330 return NULL;
2331 if (error_if_nonzero) {
2332 /* reset the base to 0, else the exception message
2333 doesn't make too much sense */
2334 base = 0;
2335 if (Py_SIZE(z) != 0)
2336 goto onError;
2337 /* there might still be other problems, therefore base
2338 remains zero here for the same reason */
2339 }
2340 if (str == start)
2341 goto onError;
2342 if (sign < 0)
2343 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002344 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 str++;
2346 if (*str != '\0')
2347 goto onError;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002349 z = maybe_small_long(z);
2350 if (z == NULL)
2351 return NULL;
2352 if (pend != NULL)
Serhiy Storchakac6792272013-10-19 21:03:34 +03002353 *pend = (char *)str;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002354 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002355
Mark Dickinson22b20182010-05-10 21:27:53 +00002356 onError:
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002357 if (pend != NULL)
Serhiy Storchakac6792272013-10-19 21:03:34 +03002358 *pend = (char *)str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 Py_XDECREF(z);
2360 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2361 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2362 if (strobj == NULL)
2363 return NULL;
2364 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002365 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 base, strobj);
2367 Py_DECREF(strobj);
2368 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002369}
2370
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002371/* Since PyLong_FromString doesn't have a length parameter,
2372 * check here for possible NULs in the string.
2373 *
2374 * Reports an invalid literal as a bytes object.
2375 */
2376PyObject *
2377_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2378{
2379 PyObject *result, *strobj;
2380 char *end = NULL;
2381
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002382 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002383 if (end == NULL || (result != NULL && end == s + len))
2384 return result;
2385 Py_XDECREF(result);
2386 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2387 if (strobj != NULL) {
2388 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002389 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002390 base, strobj);
2391 Py_DECREF(strobj);
2392 }
2393 return NULL;
2394}
2395
Guido van Rossum9e896b32000-04-05 20:11:21 +00002396PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002397PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002398{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2400 if (unicode == NULL)
2401 return NULL;
2402 v = PyLong_FromUnicodeObject(unicode, base);
2403 Py_DECREF(unicode);
2404 return v;
2405}
2406
2407PyObject *
2408PyLong_FromUnicodeObject(PyObject *u, int base)
2409{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002410 PyObject *result, *asciidig;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002411 char *buffer, *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002413
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002414 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002415 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002418 if (buffer == NULL) {
2419 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002420 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2421 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002423 else {
2424 result = PyLong_FromString(buffer, &end, base);
2425 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2426 Py_DECREF(asciidig);
2427 return result;
2428 }
2429 Py_DECREF(asciidig);
2430 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002431 }
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002432 PyErr_Format(PyExc_ValueError,
2433 "invalid literal for int() with base %d: %.200R",
2434 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002435 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002436}
2437
Tim Peters9f688bf2000-07-07 15:53:28 +00002438/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002439static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002441static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002442
Serhiy Storchaka95949422013-08-27 19:40:23 +03002443/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002444
Guido van Rossume32e0141992-01-19 16:31:05 +00002445static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002446long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002448{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002449 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 if (size_b == 0) {
2453 PyErr_SetString(PyExc_ZeroDivisionError,
2454 "integer division or modulo by zero");
2455 return -1;
2456 }
2457 if (size_a < size_b ||
2458 (size_a == size_b &&
2459 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2460 /* |a| < |b|. */
2461 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2462 if (*pdiv == NULL)
2463 return -1;
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002464 *prem = (PyLongObject *)long_long((PyObject *)a);
2465 if (*prem == NULL) {
2466 Py_CLEAR(*pdiv);
2467 return -1;
2468 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 return 0;
2470 }
2471 if (size_b == 1) {
2472 digit rem = 0;
2473 z = divrem1(a, b->ob_digit[0], &rem);
2474 if (z == NULL)
2475 return -1;
2476 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2477 if (*prem == NULL) {
2478 Py_DECREF(z);
2479 return -1;
2480 }
2481 }
2482 else {
2483 z = x_divrem(a, b, prem);
2484 if (z == NULL)
2485 return -1;
2486 }
2487 /* Set the signs.
2488 The quotient z has the sign of a*b;
2489 the remainder r has the sign of a,
2490 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002491 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2492 _PyLong_Negate(&z);
2493 if (z == NULL) {
2494 Py_CLEAR(*prem);
2495 return -1;
2496 }
2497 }
2498 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2499 _PyLong_Negate(prem);
2500 if (*prem == NULL) {
2501 Py_DECREF(z);
2502 Py_CLEAR(*prem);
2503 return -1;
2504 }
2505 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 *pdiv = maybe_small_long(z);
2507 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002508}
2509
Serhiy Storchaka95949422013-08-27 19:40:23 +03002510/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002511 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002512
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002513static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002514x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 PyLongObject *v, *w, *a;
2517 Py_ssize_t i, k, size_v, size_w;
2518 int d;
2519 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2520 twodigits vv;
2521 sdigit zhi;
2522 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2525 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2526 handle the special case when the initial estimate q for a quotient
2527 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2528 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002531 size_v = Py_ABS(Py_SIZE(v1));
2532 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2534 v = _PyLong_New(size_v+1);
2535 if (v == NULL) {
2536 *prem = NULL;
2537 return NULL;
2538 }
2539 w = _PyLong_New(size_w);
2540 if (w == NULL) {
2541 Py_DECREF(v);
2542 *prem = NULL;
2543 return NULL;
2544 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2547 shift v1 left by the same amount. Results go into w and v. */
2548 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2549 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2550 assert(carry == 0);
2551 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2552 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2553 v->ob_digit[size_v] = carry;
2554 size_v++;
2555 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2558 at most (and usually exactly) k = size_v - size_w digits. */
2559 k = size_v - size_w;
2560 assert(k >= 0);
2561 a = _PyLong_New(k);
2562 if (a == NULL) {
2563 Py_DECREF(w);
2564 Py_DECREF(v);
2565 *prem = NULL;
2566 return NULL;
2567 }
2568 v0 = v->ob_digit;
2569 w0 = w->ob_digit;
2570 wm1 = w0[size_w-1];
2571 wm2 = w0[size_w-2];
2572 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2573 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2574 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002577 Py_DECREF(a);
2578 Py_DECREF(w);
2579 Py_DECREF(v);
2580 *prem = NULL;
2581 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002582 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 /* estimate quotient digit q; may overestimate by 1 (rare) */
2585 vtop = vk[size_w];
2586 assert(vtop <= wm1);
2587 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2588 q = (digit)(vv / wm1);
2589 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2590 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2591 | vk[size_w-2])) {
2592 --q;
2593 r += wm1;
2594 if (r >= PyLong_BASE)
2595 break;
2596 }
2597 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2600 zhi = 0;
2601 for (i = 0; i < size_w; ++i) {
2602 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2603 -PyLong_BASE * q <= z < PyLong_BASE */
2604 z = (sdigit)vk[i] + zhi -
2605 (stwodigits)q * (stwodigits)w0[i];
2606 vk[i] = (digit)z & PyLong_MASK;
2607 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002608 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 /* add w back if q was too large (this branch taken rarely) */
2612 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2613 if ((sdigit)vtop + zhi < 0) {
2614 carry = 0;
2615 for (i = 0; i < size_w; ++i) {
2616 carry += vk[i] + w0[i];
2617 vk[i] = carry & PyLong_MASK;
2618 carry >>= PyLong_SHIFT;
2619 }
2620 --q;
2621 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 /* store quotient digit */
2624 assert(q < PyLong_BASE);
2625 *--ak = q;
2626 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 /* unshift remainder; we reuse w to store the result */
2629 carry = v_rshift(w0, v0, size_w, d);
2630 assert(carry==0);
2631 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 *prem = long_normalize(w);
2634 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002635}
2636
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002637/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2638 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2639 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2640 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2641 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2642 -1.0. */
2643
2644/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2645#if DBL_MANT_DIG == 53
2646#define EXP2_DBL_MANT_DIG 9007199254740992.0
2647#else
2648#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2649#endif
2650
2651double
2652_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2655 /* See below for why x_digits is always large enough. */
2656 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2657 double dx;
2658 /* Correction term for round-half-to-even rounding. For a digit x,
2659 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2660 multiple of 4, rounding ties to a multiple of 8. */
2661 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002662
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002663 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 if (a_size == 0) {
2665 /* Special case for 0: significand 0.0, exponent 0. */
2666 *e = 0;
2667 return 0.0;
2668 }
2669 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2670 /* The following is an overflow-free version of the check
2671 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2672 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2673 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2674 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002675 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2679 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 Number of digits needed for result: write // for floor division.
2682 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2691 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2694 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2695 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 in both cases.
2702 */
2703 if (a_bits <= DBL_MANT_DIG + 2) {
2704 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2705 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2706 x_size = 0;
2707 while (x_size < shift_digits)
2708 x_digits[x_size++] = 0;
2709 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2710 (int)shift_bits);
2711 x_size += a_size;
2712 x_digits[x_size++] = rem;
2713 }
2714 else {
2715 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2716 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2717 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2718 a_size - shift_digits, (int)shift_bits);
2719 x_size = a_size - shift_digits;
2720 /* For correct rounding below, we need the least significant
2721 bit of x to be 'sticky' for this shift: if any of the bits
2722 shifted out was nonzero, we set the least significant bit
2723 of x. */
2724 if (rem)
2725 x_digits[0] |= 1;
2726 else
2727 while (shift_digits > 0)
2728 if (a->ob_digit[--shift_digits]) {
2729 x_digits[0] |= 1;
2730 break;
2731 }
2732 }
Victor Stinner63941882011-09-29 00:42:28 +02002733 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 /* Round, and convert to double. */
2736 x_digits[0] += half_even_correction[x_digits[0] & 7];
2737 dx = x_digits[--x_size];
2738 while (x_size > 0)
2739 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 /* Rescale; make correction if result is 1.0. */
2742 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2743 if (dx == 1.0) {
2744 if (a_bits == PY_SSIZE_T_MAX)
2745 goto overflow;
2746 dx = 0.5;
2747 a_bits += 1;
2748 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 *e = a_bits;
2751 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002752
2753 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 /* exponent > PY_SSIZE_T_MAX */
2755 PyErr_SetString(PyExc_OverflowError,
2756 "huge integer: number of bits overflows a Py_ssize_t");
2757 *e = 0;
2758 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002759}
2760
Serhiy Storchaka95949422013-08-27 19:40:23 +03002761/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002762 using the round-half-to-even rule in the case of a tie. */
2763
2764double
2765PyLong_AsDouble(PyObject *v)
2766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 Py_ssize_t exponent;
2768 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002769
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002770 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 PyErr_BadInternalCall();
2772 return -1.0;
2773 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002774 if (!PyLong_Check(v)) {
2775 PyErr_SetString(PyExc_TypeError, "an integer is required");
2776 return -1.0;
2777 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002778 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002779 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002780 to double. This improves performance of FP/long operations
2781 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002782 */
2783 return (double)MEDIUM_VALUE((PyLongObject *)v);
2784 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2786 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2787 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002788 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 return -1.0;
2790 }
2791 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002792}
2793
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002794/* Methods */
2795
2796static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002797long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002800}
2801
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002802static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002803long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 if (Py_SIZE(a) != Py_SIZE(b)) {
2808 sign = Py_SIZE(a) - Py_SIZE(b);
2809 }
2810 else {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002811 Py_ssize_t i = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2813 ;
2814 if (i < 0)
2815 sign = 0;
2816 else {
2817 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2818 if (Py_SIZE(a) < 0)
2819 sign = -sign;
2820 }
2821 }
2822 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002823}
2824
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002825#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002827
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002828static PyObject *
2829long_richcompare(PyObject *self, PyObject *other, int op)
2830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 int result;
2832 PyObject *v;
2833 CHECK_BINOP(self, other);
2834 if (self == other)
2835 result = 0;
2836 else
2837 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2838 /* Convert the return value to a Boolean */
2839 switch (op) {
2840 case Py_EQ:
2841 v = TEST_COND(result == 0);
2842 break;
2843 case Py_NE:
2844 v = TEST_COND(result != 0);
2845 break;
2846 case Py_LE:
2847 v = TEST_COND(result <= 0);
2848 break;
2849 case Py_GE:
2850 v = TEST_COND(result >= 0);
2851 break;
2852 case Py_LT:
2853 v = TEST_COND(result == -1);
2854 break;
2855 case Py_GT:
2856 v = TEST_COND(result == 1);
2857 break;
2858 default:
2859 PyErr_BadArgument();
2860 return NULL;
2861 }
2862 Py_INCREF(v);
2863 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002864}
2865
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002866static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002867long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002868{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002869 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 Py_ssize_t i;
2871 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 i = Py_SIZE(v);
2874 switch(i) {
2875 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2876 case 0: return 0;
2877 case 1: return v->ob_digit[0];
2878 }
2879 sign = 1;
2880 x = 0;
2881 if (i < 0) {
2882 sign = -1;
2883 i = -(i);
2884 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002886 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2887 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2888 _PyHASH_MODULUS.
2889
2890 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2891 amounts to a rotation of the bits of x. To see this, write
2892
2893 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2894
2895 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2896 PyLong_SHIFT bits of x (those that are shifted out of the
2897 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2898 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2899 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2900 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2901 congruent to y modulo _PyHASH_MODULUS. So
2902
2903 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2904
2905 The right-hand side is just the result of rotating the
2906 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2907 not all _PyHASH_BITS bits of x are 1s, the same is true
2908 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2909 the reduction of x*2**PyLong_SHIFT modulo
2910 _PyHASH_MODULUS. */
2911 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2912 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002914 if (x >= _PyHASH_MODULUS)
2915 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 }
2917 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002918 if (x == (Py_uhash_t)-1)
2919 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002920 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002921}
2922
2923
Serhiy Storchaka95949422013-08-27 19:40:23 +03002924/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002925
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002926static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002927x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002928{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002929 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 PyLongObject *z;
2931 Py_ssize_t i;
2932 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 /* Ensure a is the larger of the two: */
2935 if (size_a < size_b) {
2936 { PyLongObject *temp = a; a = b; b = temp; }
2937 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002938 size_a = size_b;
2939 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 }
2941 z = _PyLong_New(size_a+1);
2942 if (z == NULL)
2943 return NULL;
2944 for (i = 0; i < size_b; ++i) {
2945 carry += a->ob_digit[i] + b->ob_digit[i];
2946 z->ob_digit[i] = carry & PyLong_MASK;
2947 carry >>= PyLong_SHIFT;
2948 }
2949 for (; i < size_a; ++i) {
2950 carry += a->ob_digit[i];
2951 z->ob_digit[i] = carry & PyLong_MASK;
2952 carry >>= PyLong_SHIFT;
2953 }
2954 z->ob_digit[i] = carry;
2955 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002956}
2957
2958/* Subtract the absolute values of two integers. */
2959
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002960static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002961x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002962{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002963 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 PyLongObject *z;
2965 Py_ssize_t i;
2966 int sign = 1;
2967 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 /* Ensure a is the larger of the two: */
2970 if (size_a < size_b) {
2971 sign = -1;
2972 { PyLongObject *temp = a; a = b; b = temp; }
2973 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002974 size_a = size_b;
2975 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 }
2977 else if (size_a == size_b) {
2978 /* Find highest digit where a and b differ: */
2979 i = size_a;
2980 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2981 ;
2982 if (i < 0)
2983 return (PyLongObject *)PyLong_FromLong(0);
2984 if (a->ob_digit[i] < b->ob_digit[i]) {
2985 sign = -1;
2986 { PyLongObject *temp = a; a = b; b = temp; }
2987 }
2988 size_a = size_b = i+1;
2989 }
2990 z = _PyLong_New(size_a);
2991 if (z == NULL)
2992 return NULL;
2993 for (i = 0; i < size_b; ++i) {
2994 /* The following assumes unsigned arithmetic
2995 works module 2**N for some N>PyLong_SHIFT. */
2996 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2997 z->ob_digit[i] = borrow & PyLong_MASK;
2998 borrow >>= PyLong_SHIFT;
2999 borrow &= 1; /* Keep only one sign bit */
3000 }
3001 for (; i < size_a; ++i) {
3002 borrow = a->ob_digit[i] - borrow;
3003 z->ob_digit[i] = borrow & PyLong_MASK;
3004 borrow >>= PyLong_SHIFT;
3005 borrow &= 1; /* Keep only one sign bit */
3006 }
3007 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003008 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003009 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003010 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003012}
3013
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003014static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003015long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003020
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003021 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
3023 MEDIUM_VALUE(b));
3024 return result;
3025 }
3026 if (Py_SIZE(a) < 0) {
3027 if (Py_SIZE(b) < 0) {
3028 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003029 if (z != NULL) {
3030 /* x_add received at least one multiple-digit int,
3031 and thus z must be a multiple-digit int.
3032 That also means z is not an element of
3033 small_ints, so negating it in-place is safe. */
3034 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003036 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 }
3038 else
3039 z = x_sub(b, a);
3040 }
3041 else {
3042 if (Py_SIZE(b) < 0)
3043 z = x_sub(a, b);
3044 else
3045 z = x_add(a, b);
3046 }
3047 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003048}
3049
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003050static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003051long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003056
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003057 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 PyObject* r;
3059 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
3060 return r;
3061 }
3062 if (Py_SIZE(a) < 0) {
3063 if (Py_SIZE(b) < 0)
3064 z = x_sub(a, b);
3065 else
3066 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003067 if (z != NULL) {
3068 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003070 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 }
3072 else {
3073 if (Py_SIZE(b) < 0)
3074 z = x_add(a, b);
3075 else
3076 z = x_sub(a, b);
3077 }
3078 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003079}
3080
Tim Peters5af4e6c2002-08-12 02:31:19 +00003081/* Grade school multiplication, ignoring the signs.
3082 * Returns the absolute value of the product, or NULL if error.
3083 */
3084static PyLongObject *
3085x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003088 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3089 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 z = _PyLong_New(size_a + size_b);
3093 if (z == NULL)
3094 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3097 if (a == b) {
3098 /* Efficient squaring per HAC, Algorithm 14.16:
3099 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3100 * Gives slightly less than a 2x speedup when a == b,
3101 * via exploiting that each entry in the multiplication
3102 * pyramid appears twice (except for the size_a squares).
3103 */
3104 for (i = 0; i < size_a; ++i) {
3105 twodigits carry;
3106 twodigits f = a->ob_digit[i];
3107 digit *pz = z->ob_digit + (i << 1);
3108 digit *pa = a->ob_digit + i + 1;
3109 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003112 Py_DECREF(z);
3113 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003114 });
Tim Peters0973b992004-08-29 22:16:50 +00003115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 carry = *pz + f * f;
3117 *pz++ = (digit)(carry & PyLong_MASK);
3118 carry >>= PyLong_SHIFT;
3119 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 /* Now f is added in twice in each column of the
3122 * pyramid it appears. Same as adding f<<1 once.
3123 */
3124 f <<= 1;
3125 while (pa < paend) {
3126 carry += *pz + *pa++ * f;
3127 *pz++ = (digit)(carry & PyLong_MASK);
3128 carry >>= PyLong_SHIFT;
3129 assert(carry <= (PyLong_MASK << 1));
3130 }
3131 if (carry) {
3132 carry += *pz;
3133 *pz++ = (digit)(carry & PyLong_MASK);
3134 carry >>= PyLong_SHIFT;
3135 }
3136 if (carry)
3137 *pz += (digit)(carry & PyLong_MASK);
3138 assert((carry >> PyLong_SHIFT) == 0);
3139 }
3140 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003141 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 for (i = 0; i < size_a; ++i) {
3143 twodigits carry = 0;
3144 twodigits f = a->ob_digit[i];
3145 digit *pz = z->ob_digit + i;
3146 digit *pb = b->ob_digit;
3147 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003150 Py_DECREF(z);
3151 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003152 });
Tim Peters0973b992004-08-29 22:16:50 +00003153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 while (pb < pbend) {
3155 carry += *pz + *pb++ * f;
3156 *pz++ = (digit)(carry & PyLong_MASK);
3157 carry >>= PyLong_SHIFT;
3158 assert(carry <= PyLong_MASK);
3159 }
3160 if (carry)
3161 *pz += (digit)(carry & PyLong_MASK);
3162 assert((carry >> PyLong_SHIFT) == 0);
3163 }
3164 }
3165 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003166}
3167
3168/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003169 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003170 split, and sets low and high such that abs(n) == (high << size) + low,
3171 viewing the shift as being by digits. The sign bit is ignored, and
3172 the return values are >= 0.
3173 Returns 0 on success, -1 on failure.
3174*/
3175static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003176kmul_split(PyLongObject *n,
3177 Py_ssize_t size,
3178 PyLongObject **high,
3179 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 PyLongObject *hi, *lo;
3182 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003183 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003184
Victor Stinner640c35c2013-06-04 23:14:37 +02003185 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 if ((hi = _PyLong_New(size_hi)) == NULL)
3189 return -1;
3190 if ((lo = _PyLong_New(size_lo)) == NULL) {
3191 Py_DECREF(hi);
3192 return -1;
3193 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3196 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 *high = long_normalize(hi);
3199 *low = long_normalize(lo);
3200 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003201}
3202
Tim Peters60004642002-08-12 22:01:34 +00003203static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3204
Tim Peters5af4e6c2002-08-12 02:31:19 +00003205/* Karatsuba multiplication. Ignores the input signs, and returns the
3206 * absolute value of the product (or NULL if error).
3207 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3208 */
3209static PyLongObject *
3210k_mul(PyLongObject *a, PyLongObject *b)
3211{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003212 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3213 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 PyLongObject *ah = NULL;
3215 PyLongObject *al = NULL;
3216 PyLongObject *bh = NULL;
3217 PyLongObject *bl = NULL;
3218 PyLongObject *ret = NULL;
3219 PyLongObject *t1, *t2, *t3;
3220 Py_ssize_t shift; /* the number of digits we split off */
3221 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3224 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3225 * Then the original product is
3226 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3227 * By picking X to be a power of 2, "*X" is just shifting, and it's
3228 * been reduced to 3 multiplies on numbers half the size.
3229 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 /* We want to split based on the larger number; fiddle so that b
3232 * is largest.
3233 */
3234 if (asize > bsize) {
3235 t1 = a;
3236 a = b;
3237 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 i = asize;
3240 asize = bsize;
3241 bsize = i;
3242 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 /* Use gradeschool math when either number is too small. */
3245 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3246 if (asize <= i) {
3247 if (asize == 0)
3248 return (PyLongObject *)PyLong_FromLong(0);
3249 else
3250 return x_mul(a, b);
3251 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 /* If a is small compared to b, splitting on b gives a degenerate
3254 * case with ah==0, and Karatsuba may be (even much) less efficient
3255 * than "grade school" then. However, we can still win, by viewing
3256 * b as a string of "big digits", each of width a->ob_size. That
3257 * leads to a sequence of balanced calls to k_mul.
3258 */
3259 if (2 * asize <= bsize)
3260 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 /* Split a & b into hi & lo pieces. */
3263 shift = bsize >> 1;
3264 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3265 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 if (a == b) {
3268 bh = ah;
3269 bl = al;
3270 Py_INCREF(bh);
3271 Py_INCREF(bl);
3272 }
3273 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 /* The plan:
3276 * 1. Allocate result space (asize + bsize digits: that's always
3277 * enough).
3278 * 2. Compute ah*bh, and copy into result at 2*shift.
3279 * 3. Compute al*bl, and copy into result at 0. Note that this
3280 * can't overlap with #2.
3281 * 4. Subtract al*bl from the result, starting at shift. This may
3282 * underflow (borrow out of the high digit), but we don't care:
3283 * we're effectively doing unsigned arithmetic mod
3284 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3285 * borrows and carries out of the high digit can be ignored.
3286 * 5. Subtract ah*bh from the result, starting at shift.
3287 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3288 * at shift.
3289 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 /* 1. Allocate result space. */
3292 ret = _PyLong_New(asize + bsize);
3293 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003294#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 /* Fill with trash, to catch reference to uninitialized digits. */
3296 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003297#endif
Tim Peters44121a62002-08-12 06:17:58 +00003298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3300 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3301 assert(Py_SIZE(t1) >= 0);
3302 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3303 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3304 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 /* Zero-out the digits higher than the ah*bh copy. */
3307 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3308 if (i)
3309 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3310 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 /* 3. t2 <- al*bl, and copy into the low digits. */
3313 if ((t2 = k_mul(al, bl)) == NULL) {
3314 Py_DECREF(t1);
3315 goto fail;
3316 }
3317 assert(Py_SIZE(t2) >= 0);
3318 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3319 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 /* Zero out remaining digits. */
3322 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3323 if (i)
3324 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3327 * because it's fresher in cache.
3328 */
3329 i = Py_SIZE(ret) - shift; /* # digits after shift */
3330 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3331 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3334 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3337 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3338 Py_DECREF(ah);
3339 Py_DECREF(al);
3340 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 if (a == b) {
3343 t2 = t1;
3344 Py_INCREF(t2);
3345 }
3346 else if ((t2 = x_add(bh, bl)) == NULL) {
3347 Py_DECREF(t1);
3348 goto fail;
3349 }
3350 Py_DECREF(bh);
3351 Py_DECREF(bl);
3352 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 t3 = k_mul(t1, t2);
3355 Py_DECREF(t1);
3356 Py_DECREF(t2);
3357 if (t3 == NULL) goto fail;
3358 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 /* Add t3. It's not obvious why we can't run out of room here.
3361 * See the (*) comment after this function.
3362 */
3363 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3364 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003367
Mark Dickinson22b20182010-05-10 21:27:53 +00003368 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 Py_XDECREF(ret);
3370 Py_XDECREF(ah);
3371 Py_XDECREF(al);
3372 Py_XDECREF(bh);
3373 Py_XDECREF(bl);
3374 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003375}
3376
Tim Petersd6974a52002-08-13 20:37:51 +00003377/* (*) Why adding t3 can't "run out of room" above.
3378
Tim Petersab86c2b2002-08-15 20:06:00 +00003379Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3380to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003381
Tim Petersab86c2b2002-08-15 20:06:00 +000033821. For any integer i, i = c(i/2) + f(i/2). In particular,
3383 bsize = c(bsize/2) + f(bsize/2).
33842. shift = f(bsize/2)
33853. asize <= bsize
33864. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3387 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003388
Tim Petersab86c2b2002-08-15 20:06:00 +00003389We allocated asize + bsize result digits, and add t3 into them at an offset
3390of shift. This leaves asize+bsize-shift allocated digit positions for t3
3391to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3392asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003393
Tim Petersab86c2b2002-08-15 20:06:00 +00003394bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3395at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003396
Tim Petersab86c2b2002-08-15 20:06:00 +00003397If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3398digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3399most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003400
Tim Petersab86c2b2002-08-15 20:06:00 +00003401The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003402
Tim Petersab86c2b2002-08-15 20:06:00 +00003403 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003404
Tim Petersab86c2b2002-08-15 20:06:00 +00003405and we have asize + c(bsize/2) available digit positions. We need to show
3406this is always enough. An instance of c(bsize/2) cancels out in both, so
3407the question reduces to whether asize digits is enough to hold
3408(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3409then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3410asize 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 +00003411digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003412asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003413c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3414is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3415bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003416
Tim Peters48d52c02002-08-14 17:07:32 +00003417Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3418clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3419ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003420*/
3421
Tim Peters60004642002-08-12 22:01:34 +00003422/* b has at least twice the digits of a, and a is big enough that Karatsuba
3423 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3424 * of slices, each with a->ob_size digits, and multiply the slices by a,
3425 * one at a time. This gives k_mul balanced inputs to work with, and is
3426 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003427 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003428 * single-width slice overlap between successive partial sums).
3429 */
3430static PyLongObject *
3431k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3432{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003433 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3434 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 Py_ssize_t nbdone; /* # of b digits already multiplied */
3436 PyLongObject *ret;
3437 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 assert(asize > KARATSUBA_CUTOFF);
3440 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 /* Allocate result space, and zero it out. */
3443 ret = _PyLong_New(asize + bsize);
3444 if (ret == NULL)
3445 return NULL;
3446 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 /* Successive slices of b are copied into bslice. */
3449 bslice = _PyLong_New(asize);
3450 if (bslice == NULL)
3451 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 nbdone = 0;
3454 while (bsize > 0) {
3455 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003456 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 /* Multiply the next slice of b by a. */
3459 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3460 nbtouse * sizeof(digit));
3461 Py_SIZE(bslice) = nbtouse;
3462 product = k_mul(a, bslice);
3463 if (product == NULL)
3464 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 /* Add into result. */
3467 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3468 product->ob_digit, Py_SIZE(product));
3469 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 bsize -= nbtouse;
3472 nbdone += nbtouse;
3473 }
Tim Peters60004642002-08-12 22:01:34 +00003474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 Py_DECREF(bslice);
3476 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003477
Mark Dickinson22b20182010-05-10 21:27:53 +00003478 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 Py_DECREF(ret);
3480 Py_XDECREF(bslice);
3481 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003482}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003483
3484static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003485long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003492 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003494#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003496#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 /* if we don't have long long then we're almost certainly
3498 using 15-bit digits, so v will fit in a long. In the
3499 unlikely event that we're using 30-bit digits on a platform
3500 without long long, a large v will just cause us to fall
3501 through to the general multiplication code below. */
3502 if (v >= LONG_MIN && v <= LONG_MAX)
3503 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003504#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 z = k_mul(a, b);
3508 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003509 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3510 _PyLong_Negate(&z);
3511 if (z == NULL)
3512 return NULL;
3513 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003515}
3516
Yury Selivanove0b23092016-02-11 10:26:27 -05003517/* Fast modulo division for single-digit longs. */
3518static PyObject *
3519fast_mod(PyLongObject *a, PyLongObject *b)
3520{
3521 sdigit left = a->ob_digit[0];
3522 sdigit right = b->ob_digit[0];
3523 sdigit mod;
3524
3525 assert(Py_ABS(Py_SIZE(a)) == 1);
3526 assert(Py_ABS(Py_SIZE(b)) == 1);
3527
3528 if (Py_SIZE(a) == Py_SIZE(b)) {
3529 /* 'a' and 'b' have the same sign. */
3530 mod = left % right;
3531 }
3532 else {
3533 /* Either 'a' or 'b' is negative. */
3534 mod = right - 1 - (left - 1) % right;
3535 }
3536
Victor Stinnerf963c132016-03-23 18:36:54 +01003537 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003538}
3539
3540/* Fast floor division for single-digit longs. */
3541static PyObject *
3542fast_floor_div(PyLongObject *a, PyLongObject *b)
3543{
3544 sdigit left = a->ob_digit[0];
3545 sdigit right = b->ob_digit[0];
3546 sdigit div;
3547
3548 assert(Py_ABS(Py_SIZE(a)) == 1);
3549 assert(Py_ABS(Py_SIZE(b)) == 1);
3550
3551 if (Py_SIZE(a) == Py_SIZE(b)) {
3552 /* 'a' and 'b' have the same sign. */
3553 div = left / right;
3554 }
3555 else {
3556 /* Either 'a' or 'b' is negative. */
3557 div = -1 - (left - 1) / right;
3558 }
3559
3560 return PyLong_FromLong(div);
3561}
3562
Guido van Rossume32e0141992-01-19 16:31:05 +00003563/* The / and % operators are now defined in terms of divmod().
3564 The expression a mod b has the value a - b*floor(a/b).
3565 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003566 |a| by |b|, with the sign of a. This is also expressed
3567 as a - b*trunc(a/b), if trunc truncates towards zero.
3568 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 a b a rem b a mod b
3570 13 10 3 3
3571 -13 10 -3 7
3572 13 -10 3 -7
3573 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003574 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003575 have different signs. We then subtract one from the 'div'
3576 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003577
Tim Peters47e52ee2004-08-30 02:44:38 +00003578/* Compute
3579 * *pdiv, *pmod = divmod(v, w)
3580 * NULL can be passed for pdiv or pmod, in which case that part of
3581 * the result is simply thrown away. The caller owns a reference to
3582 * each of these it requests (does not pass NULL for).
3583 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003584static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003585l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003589
Yury Selivanove0b23092016-02-11 10:26:27 -05003590 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3591 /* Fast path for single-digit longs */
3592 div = NULL;
3593 if (pdiv != NULL) {
3594 div = (PyLongObject *)fast_floor_div(v, w);
3595 if (div == NULL) {
3596 return -1;
3597 }
3598 }
3599 if (pmod != NULL) {
3600 mod = (PyLongObject *)fast_mod(v, w);
3601 if (mod == NULL) {
3602 Py_XDECREF(div);
3603 return -1;
3604 }
3605 *pmod = mod;
3606 }
3607 if (pdiv != NULL) {
3608 /* We only want to set `*pdiv` when `*pmod` is
3609 set successfully. */
3610 *pdiv = div;
3611 }
3612 return 0;
3613 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 if (long_divrem(v, w, &div, &mod) < 0)
3615 return -1;
3616 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3617 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3618 PyLongObject *temp;
3619 PyLongObject *one;
3620 temp = (PyLongObject *) long_add(mod, w);
3621 Py_DECREF(mod);
3622 mod = temp;
3623 if (mod == NULL) {
3624 Py_DECREF(div);
3625 return -1;
3626 }
3627 one = (PyLongObject *) PyLong_FromLong(1L);
3628 if (one == NULL ||
3629 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3630 Py_DECREF(mod);
3631 Py_DECREF(div);
3632 Py_XDECREF(one);
3633 return -1;
3634 }
3635 Py_DECREF(one);
3636 Py_DECREF(div);
3637 div = temp;
3638 }
3639 if (pdiv != NULL)
3640 *pdiv = div;
3641 else
3642 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 if (pmod != NULL)
3645 *pmod = mod;
3646 else
3647 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003650}
3651
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003652static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003653long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003658
3659 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3660 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3661 }
3662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3664 div = NULL;
3665 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003666}
3667
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003668/* PyLong/PyLong -> float, with correctly rounded result. */
3669
3670#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3671#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3672
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003673static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003674long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 PyLongObject *a, *b, *x;
3677 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3678 digit mask, low;
3679 int inexact, negate, a_is_small, b_is_small;
3680 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 CHECK_BINOP(v, w);
3683 a = (PyLongObject *)v;
3684 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 /*
3687 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3690 1. choose a suitable integer 'shift'
3691 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3692 3. adjust x for correct rounding
3693 4. convert x to a double dx with the same value
3694 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3699 returns either 0.0 or -0.0, depending on the sign of b. For a and
3700 b both nonzero, ignore signs of a and b, and add the sign back in
3701 at the end. Now write a_bits and b_bits for the bit lengths of a
3702 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3703 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3708 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3709 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3710 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003712 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 1. The integer 'shift' is chosen so that x has the right number of
3715 bits for a double, plus two or three extra bits that will be used
3716 in the rounding decisions. Writing a_bits and b_bits for the
3717 number of significant bits in a and b respectively, a
3718 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 This is fine in the usual case, but if a/b is smaller than the
3723 smallest normal float then it can lead to double rounding on an
3724 IEEE 754 platform, giving incorrectly rounded results. So we
3725 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 2. The quantity x is computed by first shifting a (left -shift bits
3730 if shift <= 0, right shift bits if shift > 0) and then dividing by
3731 b. For both the shift and the division, we keep track of whether
3732 the result is inexact, in a flag 'inexact'; this information is
3733 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 With the choice of shift above, together with our assumption that
3736 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3737 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3740 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 For float representability, we need x/2**extra_bits <
3745 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3746 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 To round, we just modify the bottom digit of x in-place; this can
3751 end up giving a digit with value > PyLONG_MASK, but that's not a
3752 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 With the original choices for shift above, extra_bits will always
3755 be 2 or 3. Then rounding under the round-half-to-even rule, we
3756 round up iff the most significant of the extra bits is 1, and
3757 either: (a) the computation of x in step 2 had an inexact result,
3758 or (b) at least one other of the extra bits is 1, or (c) the least
3759 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 4. Conversion to a double is straightforward; all floating-point
3762 operations involved in the conversion are exact, so there's no
3763 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3766 The result will always be exactly representable as a double, except
3767 in the case that it overflows. To avoid dependence on the exact
3768 behaviour of ldexp on overflow, we check for overflow before
3769 applying ldexp. The result of ldexp is adjusted for sign before
3770 returning.
3771 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003774 a_size = Py_ABS(Py_SIZE(a));
3775 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3777 if (b_size == 0) {
3778 PyErr_SetString(PyExc_ZeroDivisionError,
3779 "division by zero");
3780 goto error;
3781 }
3782 if (a_size == 0)
3783 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 /* Fast path for a and b small (exactly representable in a double).
3786 Relies on floating-point division being correctly rounded; results
3787 may be subject to double rounding on x86 machines that operate with
3788 the x87 FPU set to 64-bit precision. */
3789 a_is_small = a_size <= MANT_DIG_DIGITS ||
3790 (a_size == MANT_DIG_DIGITS+1 &&
3791 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3792 b_is_small = b_size <= MANT_DIG_DIGITS ||
3793 (b_size == MANT_DIG_DIGITS+1 &&
3794 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3795 if (a_is_small && b_is_small) {
3796 double da, db;
3797 da = a->ob_digit[--a_size];
3798 while (a_size > 0)
3799 da = da * PyLong_BASE + a->ob_digit[--a_size];
3800 db = b->ob_digit[--b_size];
3801 while (b_size > 0)
3802 db = db * PyLong_BASE + b->ob_digit[--b_size];
3803 result = da / db;
3804 goto success;
3805 }
Tim Peterse2a60002001-09-04 06:17:36 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 /* Catch obvious cases of underflow and overflow */
3808 diff = a_size - b_size;
3809 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3810 /* Extreme overflow */
3811 goto overflow;
3812 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3813 /* Extreme underflow */
3814 goto underflow_or_zero;
3815 /* Next line is now safe from overflowing a Py_ssize_t */
3816 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3817 bits_in_digit(b->ob_digit[b_size - 1]);
3818 /* Now diff = a_bits - b_bits. */
3819 if (diff > DBL_MAX_EXP)
3820 goto overflow;
3821 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3822 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003825 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 /* x = abs(a * 2**-shift) */
3830 if (shift <= 0) {
3831 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3832 digit rem;
3833 /* x = a << -shift */
3834 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3835 /* In practice, it's probably impossible to end up
3836 here. Both a and b would have to be enormous,
3837 using close to SIZE_T_MAX bytes of memory each. */
3838 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003839 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 goto error;
3841 }
3842 x = _PyLong_New(a_size + shift_digits + 1);
3843 if (x == NULL)
3844 goto error;
3845 for (i = 0; i < shift_digits; i++)
3846 x->ob_digit[i] = 0;
3847 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3848 a_size, -shift % PyLong_SHIFT);
3849 x->ob_digit[a_size + shift_digits] = rem;
3850 }
3851 else {
3852 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3853 digit rem;
3854 /* x = a >> shift */
3855 assert(a_size >= shift_digits);
3856 x = _PyLong_New(a_size - shift_digits);
3857 if (x == NULL)
3858 goto error;
3859 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3860 a_size - shift_digits, shift % PyLong_SHIFT);
3861 /* set inexact if any of the bits shifted out is nonzero */
3862 if (rem)
3863 inexact = 1;
3864 while (!inexact && shift_digits > 0)
3865 if (a->ob_digit[--shift_digits])
3866 inexact = 1;
3867 }
3868 long_normalize(x);
3869 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3872 reference to x, so it's safe to modify it in-place. */
3873 if (b_size == 1) {
3874 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3875 b->ob_digit[0]);
3876 long_normalize(x);
3877 if (rem)
3878 inexact = 1;
3879 }
3880 else {
3881 PyLongObject *div, *rem;
3882 div = x_divrem(x, b, &rem);
3883 Py_DECREF(x);
3884 x = div;
3885 if (x == NULL)
3886 goto error;
3887 if (Py_SIZE(rem))
3888 inexact = 1;
3889 Py_DECREF(rem);
3890 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003891 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 assert(x_size > 0); /* result of division is never zero */
3893 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003896 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 /* Round by directly modifying the low digit of x. */
3900 mask = (digit)1 << (extra_bits - 1);
3901 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003902 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003904 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003906 /* Convert x to a double dx; the conversion is exact. */
3907 dx = x->ob_digit[--x_size];
3908 while (x_size > 0)
3909 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3910 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 /* Check whether ldexp result will overflow a double. */
3913 if (shift + x_bits >= DBL_MAX_EXP &&
3914 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3915 goto overflow;
3916 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003917
3918 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003920
3921 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003923
3924 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 PyErr_SetString(PyExc_OverflowError,
3926 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003927 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003929}
3930
3931static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003932long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 CHECK_BINOP(a, b);
3937
Yury Selivanove0b23092016-02-11 10:26:27 -05003938 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3939 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
3940 }
3941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3943 mod = NULL;
3944 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003945}
3946
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003947static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003948long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 PyLongObject *div, *mod;
3951 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3956 return NULL;
3957 }
3958 z = PyTuple_New(2);
3959 if (z != NULL) {
3960 PyTuple_SetItem(z, 0, (PyObject *) div);
3961 PyTuple_SetItem(z, 1, (PyObject *) mod);
3962 }
3963 else {
3964 Py_DECREF(div);
3965 Py_DECREF(mod);
3966 }
3967 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003968}
3969
Tim Peters47e52ee2004-08-30 02:44:38 +00003970/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003971static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003972long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3975 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 PyLongObject *z = NULL; /* accumulated result */
3978 Py_ssize_t i, j, k; /* counters */
3979 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 /* 5-ary values. If the exponent is large enough, table is
3982 * precomputed so that table[i] == a**i % c for i in range(32).
3983 */
3984 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3985 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 /* a, b, c = v, w, x */
3988 CHECK_BINOP(v, w);
3989 a = (PyLongObject*)v; Py_INCREF(a);
3990 b = (PyLongObject*)w; Py_INCREF(b);
3991 if (PyLong_Check(x)) {
3992 c = (PyLongObject *)x;
3993 Py_INCREF(x);
3994 }
3995 else if (x == Py_None)
3996 c = NULL;
3997 else {
3998 Py_DECREF(a);
3999 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004000 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 }
Tim Peters4c483c42001-09-05 06:24:58 +00004002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 if (Py_SIZE(b) < 0) { /* if exponent is negative */
4004 if (c) {
Mark Dickinson0c346d82014-04-11 14:34:40 -04004005 PyErr_SetString(PyExc_ValueError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00004006 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 goto Error;
4008 }
4009 else {
4010 /* else return a float. This works because we know
4011 that this calls float_pow() which converts its
4012 arguments to double. */
4013 Py_DECREF(a);
4014 Py_DECREF(b);
4015 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
4016 }
4017 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 if (c) {
4020 /* if modulus == 0:
4021 raise ValueError() */
4022 if (Py_SIZE(c) == 0) {
4023 PyErr_SetString(PyExc_ValueError,
4024 "pow() 3rd argument cannot be 0");
4025 goto Error;
4026 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 /* if modulus < 0:
4029 negativeOutput = True
4030 modulus = -modulus */
4031 if (Py_SIZE(c) < 0) {
4032 negativeOutput = 1;
4033 temp = (PyLongObject *)_PyLong_Copy(c);
4034 if (temp == NULL)
4035 goto Error;
4036 Py_DECREF(c);
4037 c = temp;
4038 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004039 _PyLong_Negate(&c);
4040 if (c == NULL)
4041 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 /* if modulus == 1:
4045 return 0 */
4046 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4047 z = (PyLongObject *)PyLong_FromLong(0L);
4048 goto Done;
4049 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004050
Tim Peters81a93152013-10-05 16:53:52 -05004051 /* Reduce base by modulus in some cases:
4052 1. If base < 0. Forcing the base non-negative makes things easier.
4053 2. If base is obviously larger than the modulus. The "small
4054 exponent" case later can multiply directly by base repeatedly,
4055 while the "large exponent" case multiplies directly by base 31
4056 times. It can be unboundedly faster to multiply by
4057 base % modulus instead.
4058 We could _always_ do this reduction, but l_divmod() isn't cheap,
4059 so we only do it when it buys something. */
4060 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 if (l_divmod(a, c, NULL, &temp) < 0)
4062 goto Error;
4063 Py_DECREF(a);
4064 a = temp;
4065 temp = NULL;
4066 }
4067 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 /* At this point a, b, and c are guaranteed non-negative UNLESS
4070 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 z = (PyLongObject *)PyLong_FromLong(1L);
4073 if (z == NULL)
4074 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 /* Perform a modular reduction, X = X % c, but leave X alone if c
4077 * is NULL.
4078 */
4079#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004080 do { \
4081 if (c != NULL) { \
4082 if (l_divmod(X, c, NULL, &temp) < 0) \
4083 goto Error; \
4084 Py_XDECREF(X); \
4085 X = temp; \
4086 temp = NULL; \
4087 } \
4088 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004090 /* Multiply two values, then reduce the result:
4091 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004092#define MULT(X, Y, result) \
4093 do { \
4094 temp = (PyLongObject *)long_mul(X, Y); \
4095 if (temp == NULL) \
4096 goto Error; \
4097 Py_XDECREF(result); \
4098 result = temp; \
4099 temp = NULL; \
4100 REDUCE(result); \
4101 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4104 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4105 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4106 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4107 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004110 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004112 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 }
4114 }
4115 }
4116 else {
4117 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4118 Py_INCREF(z); /* still holds 1L */
4119 table[0] = z;
4120 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004121 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4124 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4127 const int index = (bi >> j) & 0x1f;
4128 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004129 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004131 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 }
4133 }
4134 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 if (negativeOutput && (Py_SIZE(z) != 0)) {
4137 temp = (PyLongObject *)long_sub(z, c);
4138 if (temp == NULL)
4139 goto Error;
4140 Py_DECREF(z);
4141 z = temp;
4142 temp = NULL;
4143 }
4144 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004145
Mark Dickinson22b20182010-05-10 21:27:53 +00004146 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004147 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004149 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4151 for (i = 0; i < 32; ++i)
4152 Py_XDECREF(table[i]);
4153 }
4154 Py_DECREF(a);
4155 Py_DECREF(b);
4156 Py_XDECREF(c);
4157 Py_XDECREF(temp);
4158 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004159}
4160
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004161static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004162long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 /* Implement ~x as -(x+1) */
4165 PyLongObject *x;
4166 PyLongObject *w;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004167 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
4169 w = (PyLongObject *)PyLong_FromLong(1L);
4170 if (w == NULL)
4171 return NULL;
4172 x = (PyLongObject *) long_add(v, w);
4173 Py_DECREF(w);
4174 if (x == NULL)
4175 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004176 _PyLong_Negate(&x);
4177 /* No need for maybe_small_long here, since any small
4178 longs will have been caught in the Py_SIZE <= 1 fast path. */
4179 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004180}
4181
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004182static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004183long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004186 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 return PyLong_FromLong(-MEDIUM_VALUE(v));
4188 z = (PyLongObject *)_PyLong_Copy(v);
4189 if (z != NULL)
4190 Py_SIZE(z) = -(Py_SIZE(v));
4191 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004192}
4193
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004194static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004195long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 if (Py_SIZE(v) < 0)
4198 return long_neg(v);
4199 else
4200 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004201}
4202
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004203static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004204long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004207}
4208
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004209static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004210long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 PyLongObject *z = NULL;
4213 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4214 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 if (Py_SIZE(a) < 0) {
4219 /* Right shifting negative numbers is harder */
4220 PyLongObject *a1, *a2;
4221 a1 = (PyLongObject *) long_invert(a);
4222 if (a1 == NULL)
4223 goto rshift_error;
4224 a2 = (PyLongObject *) long_rshift(a1, b);
4225 Py_DECREF(a1);
4226 if (a2 == NULL)
4227 goto rshift_error;
4228 z = (PyLongObject *) long_invert(a2);
4229 Py_DECREF(a2);
4230 }
4231 else {
4232 shiftby = PyLong_AsSsize_t((PyObject *)b);
4233 if (shiftby == -1L && PyErr_Occurred())
4234 goto rshift_error;
4235 if (shiftby < 0) {
4236 PyErr_SetString(PyExc_ValueError,
4237 "negative shift count");
4238 goto rshift_error;
4239 }
4240 wordshift = shiftby / PyLong_SHIFT;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004241 newsize = Py_ABS(Py_SIZE(a)) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 if (newsize <= 0)
4243 return PyLong_FromLong(0);
4244 loshift = shiftby % PyLong_SHIFT;
4245 hishift = PyLong_SHIFT - loshift;
4246 lomask = ((digit)1 << hishift) - 1;
4247 himask = PyLong_MASK ^ lomask;
4248 z = _PyLong_New(newsize);
4249 if (z == NULL)
4250 goto rshift_error;
4251 if (Py_SIZE(a) < 0)
4252 Py_SIZE(z) = -(Py_SIZE(z));
4253 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4254 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4255 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004256 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 }
4258 z = long_normalize(z);
4259 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004260 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004262
Guido van Rossumc6913e71991-11-19 20:26:46 +00004263}
4264
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004265static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004266long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 /* This version due to Tim Peters */
4269 PyLongObject *a = (PyLongObject*)v;
4270 PyLongObject *b = (PyLongObject*)w;
4271 PyLongObject *z = NULL;
4272 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4273 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 shiftby = PyLong_AsSsize_t((PyObject *)b);
4278 if (shiftby == -1L && PyErr_Occurred())
Victor Stinner8aed6f12013-07-17 22:31:17 +02004279 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 if (shiftby < 0) {
4281 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004282 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 }
4284 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4285 wordshift = shiftby / PyLong_SHIFT;
4286 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004287
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004288 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 newsize = oldsize + wordshift;
4290 if (remshift)
4291 ++newsize;
4292 z = _PyLong_New(newsize);
4293 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004294 return NULL;
4295 if (Py_SIZE(a) < 0) {
4296 assert(Py_REFCNT(z) == 1);
4297 Py_SIZE(z) = -Py_SIZE(z);
4298 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299 for (i = 0; i < wordshift; i++)
4300 z->ob_digit[i] = 0;
4301 accum = 0;
4302 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4303 accum |= (twodigits)a->ob_digit[j] << remshift;
4304 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4305 accum >>= PyLong_SHIFT;
4306 }
4307 if (remshift)
4308 z->ob_digit[newsize-1] = (digit)accum;
4309 else
4310 assert(!accum);
4311 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004313}
4314
Mark Dickinson27a87a22009-10-25 20:43:34 +00004315/* Compute two's complement of digit vector a[0:m], writing result to
4316 z[0:m]. The digit vector a need not be normalized, but should not
4317 be entirely zero. a and z may point to the same digit vector. */
4318
4319static void
4320v_complement(digit *z, digit *a, Py_ssize_t m)
4321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 Py_ssize_t i;
4323 digit carry = 1;
4324 for (i = 0; i < m; ++i) {
4325 carry += a[i] ^ PyLong_MASK;
4326 z[i] = carry & PyLong_MASK;
4327 carry >>= PyLong_SHIFT;
4328 }
4329 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004330}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004331
4332/* Bitwise and/xor/or operations */
4333
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004334static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004335long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004336 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004337 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 int nega, negb, negz;
4340 Py_ssize_t size_a, size_b, size_z, i;
4341 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 /* Bitwise operations for negative numbers operate as though
4344 on a two's complement representation. So convert arguments
4345 from sign-magnitude to two's complement, and convert the
4346 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004349 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 nega = Py_SIZE(a) < 0;
4351 if (nega) {
4352 z = _PyLong_New(size_a);
4353 if (z == NULL)
4354 return NULL;
4355 v_complement(z->ob_digit, a->ob_digit, size_a);
4356 a = z;
4357 }
4358 else
4359 /* Keep reference count consistent. */
4360 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004363 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 negb = Py_SIZE(b) < 0;
4365 if (negb) {
4366 z = _PyLong_New(size_b);
4367 if (z == NULL) {
4368 Py_DECREF(a);
4369 return NULL;
4370 }
4371 v_complement(z->ob_digit, b->ob_digit, size_b);
4372 b = z;
4373 }
4374 else
4375 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 /* Swap a and b if necessary to ensure size_a >= size_b. */
4378 if (size_a < size_b) {
4379 z = a; a = b; b = z;
4380 size_z = size_a; size_a = size_b; size_b = size_z;
4381 negz = nega; nega = negb; negb = negz;
4382 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 /* JRH: The original logic here was to allocate the result value (z)
4385 as the longer of the two operands. However, there are some cases
4386 where the result is guaranteed to be shorter than that: AND of two
4387 positives, OR of two negatives: use the shorter number. AND with
4388 mixed signs: use the positive number. OR with mixed signs: use the
4389 negative number.
4390 */
4391 switch (op) {
4392 case '^':
4393 negz = nega ^ negb;
4394 size_z = size_a;
4395 break;
4396 case '&':
4397 negz = nega & negb;
4398 size_z = negb ? size_a : size_b;
4399 break;
4400 case '|':
4401 negz = nega | negb;
4402 size_z = negb ? size_b : size_a;
4403 break;
4404 default:
4405 PyErr_BadArgument();
4406 return NULL;
4407 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004409 /* We allow an extra digit if z is negative, to make sure that
4410 the final two's complement of z doesn't overflow. */
4411 z = _PyLong_New(size_z + negz);
4412 if (z == NULL) {
4413 Py_DECREF(a);
4414 Py_DECREF(b);
4415 return NULL;
4416 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 /* Compute digits for overlap of a and b. */
4419 switch(op) {
4420 case '&':
4421 for (i = 0; i < size_b; ++i)
4422 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4423 break;
4424 case '|':
4425 for (i = 0; i < size_b; ++i)
4426 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4427 break;
4428 case '^':
4429 for (i = 0; i < size_b; ++i)
4430 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4431 break;
4432 default:
4433 PyErr_BadArgument();
4434 return NULL;
4435 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 /* Copy any remaining digits of a, inverting if necessary. */
4438 if (op == '^' && negb)
4439 for (; i < size_z; ++i)
4440 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4441 else if (i < size_z)
4442 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4443 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 /* Complement result if negative. */
4446 if (negz) {
4447 Py_SIZE(z) = -(Py_SIZE(z));
4448 z->ob_digit[size_z] = PyLong_MASK;
4449 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4450 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 Py_DECREF(a);
4453 Py_DECREF(b);
4454 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004455}
4456
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004457static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004458long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 PyObject *c;
4461 CHECK_BINOP(a, b);
4462 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4463 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004464}
4465
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004466static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004467long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 PyObject *c;
4470 CHECK_BINOP(a, b);
4471 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4472 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004473}
4474
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004475static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004476long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004478 PyObject *c;
4479 CHECK_BINOP(a, b);
4480 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4481 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004482}
4483
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004484static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004485long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 if (PyLong_CheckExact(v))
4488 Py_INCREF(v);
4489 else
4490 v = _PyLong_Copy((PyLongObject *)v);
4491 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004492}
4493
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004494PyObject *
4495_PyLong_GCD(PyObject *aarg, PyObject *barg)
4496{
4497 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4498 stwodigits x, y, q, s, t, c_carry, d_carry;
4499 stwodigits A, B, C, D, T;
4500 int nbits, k;
4501 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4502 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4503
4504 a = (PyLongObject *)aarg;
4505 b = (PyLongObject *)barg;
4506 size_a = Py_SIZE(a);
4507 size_b = Py_SIZE(b);
4508 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4509 Py_INCREF(a);
4510 Py_INCREF(b);
4511 goto simple;
4512 }
4513
4514 /* Initial reduction: make sure that 0 <= b <= a. */
4515 a = (PyLongObject *)long_abs(a);
4516 if (a == NULL)
4517 return NULL;
4518 b = (PyLongObject *)long_abs(b);
4519 if (b == NULL) {
4520 Py_DECREF(a);
4521 return NULL;
4522 }
4523 if (long_compare(a, b) < 0) {
4524 r = a;
4525 a = b;
4526 b = r;
4527 }
4528 /* We now own references to a and b */
4529
4530 alloc_a = Py_SIZE(a);
4531 alloc_b = Py_SIZE(b);
4532 /* reduce until a fits into 2 digits */
4533 while ((size_a = Py_SIZE(a)) > 2) {
4534 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4535 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4536 corresponding bits of b into y */
4537 size_b = Py_SIZE(b);
4538 assert(size_b <= size_a);
4539 if (size_b == 0) {
4540 if (size_a < alloc_a) {
4541 r = (PyLongObject *)_PyLong_Copy(a);
4542 Py_DECREF(a);
4543 }
4544 else
4545 r = a;
4546 Py_DECREF(b);
4547 Py_XDECREF(c);
4548 Py_XDECREF(d);
4549 return (PyObject *)r;
4550 }
4551 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4552 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4553 (a->ob_digit[size_a-3] >> nbits));
4554
4555 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4556 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4557 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4558
4559 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4560 larger than PyLong_MASK during the algorithm. */
4561 A = 1; B = 0; C = 0; D = 1;
4562 for (k=0;; k++) {
4563 if (y-C == 0)
4564 break;
4565 q = (x+(A-1))/(y-C);
4566 s = B+q*D;
4567 t = x-q*y;
4568 if (s > t)
4569 break;
4570 x = y; y = t;
4571 t = A+q*C; A = D; B = C; C = s; D = t;
4572 }
4573
4574 if (k == 0) {
4575 /* no progress; do a Euclidean step */
4576 if (l_divmod(a, b, NULL, &r) < 0)
4577 goto error;
4578 Py_DECREF(a);
4579 a = b;
4580 b = r;
4581 alloc_a = alloc_b;
4582 alloc_b = Py_SIZE(b);
4583 continue;
4584 }
4585
4586 /*
4587 a, b = A*b-B*a, D*a-C*b if k is odd
4588 a, b = A*a-B*b, D*b-C*a if k is even
4589 */
4590 if (k&1) {
4591 T = -A; A = -B; B = T;
4592 T = -C; C = -D; D = T;
4593 }
4594 if (c != NULL)
4595 Py_SIZE(c) = size_a;
4596 else if (Py_REFCNT(a) == 1) {
4597 Py_INCREF(a);
4598 c = a;
4599 }
4600 else {
4601 alloc_a = size_a;
4602 c = _PyLong_New(size_a);
4603 if (c == NULL)
4604 goto error;
4605 }
4606
4607 if (d != NULL)
4608 Py_SIZE(d) = size_a;
4609 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4610 Py_INCREF(b);
4611 d = b;
4612 Py_SIZE(d) = size_a;
4613 }
4614 else {
4615 alloc_b = size_a;
4616 d = _PyLong_New(size_a);
4617 if (d == NULL)
4618 goto error;
4619 }
4620 a_end = a->ob_digit + size_a;
4621 b_end = b->ob_digit + size_b;
4622
4623 /* compute new a and new b in parallel */
4624 a_digit = a->ob_digit;
4625 b_digit = b->ob_digit;
4626 c_digit = c->ob_digit;
4627 d_digit = d->ob_digit;
4628 c_carry = 0;
4629 d_carry = 0;
4630 while (b_digit < b_end) {
4631 c_carry += (A * *a_digit) - (B * *b_digit);
4632 d_carry += (D * *b_digit++) - (C * *a_digit++);
4633 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4634 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4635 c_carry >>= PyLong_SHIFT;
4636 d_carry >>= PyLong_SHIFT;
4637 }
4638 while (a_digit < a_end) {
4639 c_carry += A * *a_digit;
4640 d_carry -= C * *a_digit++;
4641 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4642 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4643 c_carry >>= PyLong_SHIFT;
4644 d_carry >>= PyLong_SHIFT;
4645 }
4646 assert(c_carry == 0);
4647 assert(d_carry == 0);
4648
4649 Py_INCREF(c);
4650 Py_INCREF(d);
4651 Py_DECREF(a);
4652 Py_DECREF(b);
4653 a = long_normalize(c);
4654 b = long_normalize(d);
4655 }
4656 Py_XDECREF(c);
4657 Py_XDECREF(d);
4658
4659simple:
4660 assert(Py_REFCNT(a) > 0);
4661 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004662/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4663 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4664#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004665 /* a fits into a long, so b must too */
4666 x = PyLong_AsLong((PyObject *)a);
4667 y = PyLong_AsLong((PyObject *)b);
Victor Stinner5783fd22015-09-19 13:39:03 +02004668#elif defined(PY_LONG_LONG) && PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004669 x = PyLong_AsLongLong((PyObject *)a);
4670 y = PyLong_AsLongLong((PyObject *)b);
4671#else
4672# error "_PyLong_GCD"
4673#endif
4674 x = Py_ABS(x);
4675 y = Py_ABS(y);
4676 Py_DECREF(a);
4677 Py_DECREF(b);
4678
4679 /* usual Euclidean algorithm for longs */
4680 while (y != 0) {
4681 t = y;
4682 y = x % y;
4683 x = t;
4684 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004685#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004686 return PyLong_FromLong(x);
Victor Stinner5783fd22015-09-19 13:39:03 +02004687#elif defined(PY_LONG_LONG) && PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004688 return PyLong_FromLongLong(x);
4689#else
4690# error "_PyLong_GCD"
4691#endif
4692
4693error:
4694 Py_DECREF(a);
4695 Py_DECREF(b);
4696 Py_XDECREF(c);
4697 Py_XDECREF(d);
4698 return NULL;
4699}
4700
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004701static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004702long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704 double result;
4705 result = PyLong_AsDouble(v);
4706 if (result == -1.0 && PyErr_Occurred())
4707 return NULL;
4708 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004709}
4710
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004711static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004712long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004713
Tim Peters6d6c1a32001-08-02 04:15:00 +00004714static PyObject *
4715long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4716{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004717 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004718 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 if (type != &PyLong_Type)
4722 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004723 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4724 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004725 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004726 if (x == NULL) {
4727 if (obase != NULL) {
4728 PyErr_SetString(PyExc_TypeError,
4729 "int() missing string argument");
4730 return NULL;
4731 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004733 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004734 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004736
Gregory P. Smitha689e522012-12-25 22:38:32 -08004737 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004738 if (base == -1 && PyErr_Occurred())
4739 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004740 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004741 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004742 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004743 return NULL;
4744 }
4745
4746 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004747 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004749 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 if (PyByteArray_Check(x))
4751 string = PyByteArray_AS_STRING(x);
4752 else
4753 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004754 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004755 }
4756 else {
4757 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004758 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 return NULL;
4760 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004761}
4762
Serhiy Storchaka95949422013-08-27 19:40:23 +03004763/* Wimpy, slow approach to tp_new calls for subtypes of int:
4764 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004765 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004766 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004767*/
4768static PyObject *
4769long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004771 PyLongObject *tmp, *newobj;
4772 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 assert(PyType_IsSubtype(type, &PyLong_Type));
4775 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4776 if (tmp == NULL)
4777 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02004778 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 n = Py_SIZE(tmp);
4780 if (n < 0)
4781 n = -n;
4782 newobj = (PyLongObject *)type->tp_alloc(type, n);
4783 if (newobj == NULL) {
4784 Py_DECREF(tmp);
4785 return NULL;
4786 }
4787 assert(PyLong_Check(newobj));
4788 Py_SIZE(newobj) = Py_SIZE(tmp);
4789 for (i = 0; i < n; i++)
4790 newobj->ob_digit[i] = tmp->ob_digit[i];
4791 Py_DECREF(tmp);
4792 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004793}
4794
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004795static PyObject *
4796long_getnewargs(PyLongObject *v)
4797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004799}
4800
Guido van Rossumb43daf72007-08-01 18:08:08 +00004801static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004802long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004804}
4805
4806static PyObject *
4807long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004808 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004809}
4810
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004811static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004812long__format__(PyObject *self, PyObject *args)
4813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004814 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004815 _PyUnicodeWriter writer;
4816 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004818 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4819 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004820
Victor Stinner8f674cc2013-04-17 23:02:17 +02004821 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004822 ret = _PyLong_FormatAdvancedWriter(
4823 &writer,
4824 self,
4825 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4826 if (ret == -1) {
4827 _PyUnicodeWriter_Dealloc(&writer);
4828 return NULL;
4829 }
4830 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004831}
4832
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004833/* Return a pair (q, r) such that a = b * q + r, and
4834 abs(r) <= abs(b)/2, with equality possible only if q is even.
4835 In other words, q == a / b, rounded to the nearest integer using
4836 round-half-to-even. */
4837
4838PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004839_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004840{
4841 PyLongObject *quo = NULL, *rem = NULL;
4842 PyObject *one = NULL, *twice_rem, *result, *temp;
4843 int cmp, quo_is_odd, quo_is_neg;
4844
4845 /* Equivalent Python code:
4846
4847 def divmod_near(a, b):
4848 q, r = divmod(a, b)
4849 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4850 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4851 # positive, 2 * r < b if b negative.
4852 greater_than_half = 2*r > b if b > 0 else 2*r < b
4853 exactly_half = 2*r == b
4854 if greater_than_half or exactly_half and q % 2 == 1:
4855 q += 1
4856 r -= b
4857 return q, r
4858
4859 */
4860 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4861 PyErr_SetString(PyExc_TypeError,
4862 "non-integer arguments in division");
4863 return NULL;
4864 }
4865
4866 /* Do a and b have different signs? If so, quotient is negative. */
4867 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4868
4869 one = PyLong_FromLong(1L);
4870 if (one == NULL)
4871 return NULL;
4872
4873 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4874 goto error;
4875
4876 /* compare twice the remainder with the divisor, to see
4877 if we need to adjust the quotient and remainder */
4878 twice_rem = long_lshift((PyObject *)rem, one);
4879 if (twice_rem == NULL)
4880 goto error;
4881 if (quo_is_neg) {
4882 temp = long_neg((PyLongObject*)twice_rem);
4883 Py_DECREF(twice_rem);
4884 twice_rem = temp;
4885 if (twice_rem == NULL)
4886 goto error;
4887 }
4888 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4889 Py_DECREF(twice_rem);
4890
4891 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4892 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4893 /* fix up quotient */
4894 if (quo_is_neg)
4895 temp = long_sub(quo, (PyLongObject *)one);
4896 else
4897 temp = long_add(quo, (PyLongObject *)one);
4898 Py_DECREF(quo);
4899 quo = (PyLongObject *)temp;
4900 if (quo == NULL)
4901 goto error;
4902 /* and remainder */
4903 if (quo_is_neg)
4904 temp = long_add(rem, (PyLongObject *)b);
4905 else
4906 temp = long_sub(rem, (PyLongObject *)b);
4907 Py_DECREF(rem);
4908 rem = (PyLongObject *)temp;
4909 if (rem == NULL)
4910 goto error;
4911 }
4912
4913 result = PyTuple_New(2);
4914 if (result == NULL)
4915 goto error;
4916
4917 /* PyTuple_SET_ITEM steals references */
4918 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4919 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4920 Py_DECREF(one);
4921 return result;
4922
4923 error:
4924 Py_XDECREF(quo);
4925 Py_XDECREF(rem);
4926 Py_XDECREF(one);
4927 return NULL;
4928}
4929
Eric Smith8c663262007-08-25 02:26:07 +00004930static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004931long_round(PyObject *self, PyObject *args)
4932{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004933 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004934
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004935 /* To round an integer m to the nearest 10**n (n positive), we make use of
4936 * the divmod_near operation, defined by:
4937 *
4938 * divmod_near(a, b) = (q, r)
4939 *
4940 * where q is the nearest integer to the quotient a / b (the
4941 * nearest even integer in the case of a tie) and r == a - q * b.
4942 * Hence q * b = a - r is the nearest multiple of b to a,
4943 * preferring even multiples in the case of a tie.
4944 *
4945 * So the nearest multiple of 10**n to m is:
4946 *
4947 * m - divmod_near(m, 10**n)[1].
4948 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004949 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4950 return NULL;
4951 if (o_ndigits == NULL)
4952 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004953
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004954 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 if (ndigits == NULL)
4956 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004957
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004958 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004959 if (Py_SIZE(ndigits) >= 0) {
4960 Py_DECREF(ndigits);
4961 return long_long(self);
4962 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004963
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004964 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4965 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004966 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004967 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004969 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004970
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004971 result = PyLong_FromLong(10L);
4972 if (result == NULL) {
4973 Py_DECREF(ndigits);
4974 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004976
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004977 temp = long_pow(result, ndigits, Py_None);
4978 Py_DECREF(ndigits);
4979 Py_DECREF(result);
4980 result = temp;
4981 if (result == NULL)
4982 return NULL;
4983
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004984 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004985 Py_DECREF(result);
4986 result = temp;
4987 if (result == NULL)
4988 return NULL;
4989
4990 temp = long_sub((PyLongObject *)self,
4991 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4992 Py_DECREF(result);
4993 result = temp;
4994
4995 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004996}
4997
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004998static PyObject *
4999long_sizeof(PyLongObject *v)
5000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005002
Victor Stinner45e8e2f2014-05-14 17:24:35 +02005003 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(v))*sizeof(digit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005004 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005005}
5006
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005007static PyObject *
5008long_bit_length(PyLongObject *v)
5009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 PyLongObject *result, *x, *y;
5011 Py_ssize_t ndigits, msd_bits = 0;
5012 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 assert(v != NULL);
5015 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005016
Victor Stinner45e8e2f2014-05-14 17:24:35 +02005017 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005018 if (ndigits == 0)
5019 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 msd = v->ob_digit[ndigits-1];
5022 while (msd >= 32) {
5023 msd_bits += 6;
5024 msd >>= 6;
5025 }
5026 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5029 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005031 /* expression above may overflow; use Python integers instead */
5032 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5033 if (result == NULL)
5034 return NULL;
5035 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5036 if (x == NULL)
5037 goto error;
5038 y = (PyLongObject *)long_mul(result, x);
5039 Py_DECREF(x);
5040 if (y == NULL)
5041 goto error;
5042 Py_DECREF(result);
5043 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5046 if (x == NULL)
5047 goto error;
5048 y = (PyLongObject *)long_add(result, x);
5049 Py_DECREF(x);
5050 if (y == NULL)
5051 goto error;
5052 Py_DECREF(result);
5053 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005056
Mark Dickinson22b20182010-05-10 21:27:53 +00005057 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 Py_DECREF(result);
5059 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005060}
5061
5062PyDoc_STRVAR(long_bit_length_doc,
5063"int.bit_length() -> int\n\
5064\n\
5065Number of bits necessary to represent self in binary.\n\
5066>>> bin(37)\n\
5067'0b100101'\n\
5068>>> (37).bit_length()\n\
50696");
5070
Christian Heimes53876d92008-04-19 00:31:39 +00005071#if 0
5072static PyObject *
5073long_is_finite(PyObject *v)
5074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005075 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005076}
5077#endif
5078
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005079
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005080static PyObject *
5081long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
5082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 PyObject *byteorder_str;
5084 PyObject *is_signed_obj = NULL;
5085 Py_ssize_t length;
5086 int little_endian;
5087 int is_signed;
5088 PyObject *bytes;
5089 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
5092 &length, &byteorder_str,
5093 &is_signed_obj))
5094 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 if (args != NULL && Py_SIZE(args) > 2) {
5097 PyErr_SetString(PyExc_TypeError,
5098 "'signed' is a keyword-only argument");
5099 return NULL;
5100 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
5103 little_endian = 1;
5104 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
5105 little_endian = 0;
5106 else {
5107 PyErr_SetString(PyExc_ValueError,
5108 "byteorder must be either 'little' or 'big'");
5109 return NULL;
5110 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 if (is_signed_obj != NULL) {
5113 int cmp = PyObject_IsTrue(is_signed_obj);
5114 if (cmp < 0)
5115 return NULL;
5116 is_signed = cmp ? 1 : 0;
5117 }
5118 else {
5119 /* If the signed argument was omitted, use False as the
5120 default. */
5121 is_signed = 0;
5122 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 if (length < 0) {
5125 PyErr_SetString(PyExc_ValueError,
5126 "length argument must be non-negative");
5127 return NULL;
5128 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 bytes = PyBytes_FromStringAndSize(NULL, length);
5131 if (bytes == NULL)
5132 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
5135 length, little_endian, is_signed) < 0) {
5136 Py_DECREF(bytes);
5137 return NULL;
5138 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005140 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005141}
5142
Mark Dickinson078c2532010-01-30 18:06:17 +00005143PyDoc_STRVAR(long_to_bytes_doc,
5144"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005145\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005146Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005147\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005149raised if the integer is not representable with the given number of\n\
5150bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005151\n\
5152The byteorder argument determines the byte order used to represent the\n\
5153integer. If byteorder is 'big', the most significant byte is at the\n\
5154beginning of the byte array. If byteorder is 'little', the most\n\
5155significant byte is at the end of the byte array. To request the native\n\
5156byte order of the host system, use `sys.byteorder' as the byte order value.\n\
5157\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005158The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005159used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005160is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005161
5162static PyObject *
5163long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
5164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 PyObject *byteorder_str;
5166 PyObject *is_signed_obj = NULL;
5167 int little_endian;
5168 int is_signed;
5169 PyObject *obj;
5170 PyObject *bytes;
5171 PyObject *long_obj;
5172 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
5175 &obj, &byteorder_str,
5176 &is_signed_obj))
5177 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005179 if (args != NULL && Py_SIZE(args) > 2) {
5180 PyErr_SetString(PyExc_TypeError,
5181 "'signed' is a keyword-only argument");
5182 return NULL;
5183 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
5186 little_endian = 1;
5187 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
5188 little_endian = 0;
5189 else {
5190 PyErr_SetString(PyExc_ValueError,
5191 "byteorder must be either 'little' or 'big'");
5192 return NULL;
5193 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 if (is_signed_obj != NULL) {
5196 int cmp = PyObject_IsTrue(is_signed_obj);
5197 if (cmp < 0)
5198 return NULL;
5199 is_signed = cmp ? 1 : 0;
5200 }
5201 else {
5202 /* If the signed argument was omitted, use False as the
5203 default. */
5204 is_signed = 0;
5205 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 bytes = PyObject_Bytes(obj);
5208 if (bytes == NULL)
5209 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005211 long_obj = _PyLong_FromByteArray(
5212 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5213 little_endian, is_signed);
5214 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005215
Serhiy Storchakaea36c942016-05-12 10:37:58 +03005216 if (type != &PyLong_Type) {
5217 Py_SETREF(long_obj, PyObject_CallFunctionObjArgs((PyObject *)type,
5218 long_obj, NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005219 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005221 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005222}
5223
Mark Dickinson078c2532010-01-30 18:06:17 +00005224PyDoc_STRVAR(long_from_bytes_doc,
5225"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
5226\n\
5227Return the integer represented by the given array of bytes.\n\
5228\n\
R David Murray861470c2014-10-05 11:47:01 -04005229The bytes argument must be a bytes-like object (e.g. bytes or bytearray).\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005230\n\
5231The byteorder argument determines the byte order used to represent the\n\
5232integer. If byteorder is 'big', the most significant byte is at the\n\
5233beginning of the byte array. If byteorder is 'little', the most\n\
5234significant byte is at the end of the byte array. To request the native\n\
5235byte order of the host system, use `sys.byteorder' as the byte order value.\n\
5236\n\
5237The signed keyword-only argument indicates whether two's complement is\n\
5238used to represent the integer.");
5239
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005240static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005241 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
5242 "Returns self, the complex conjugate of any int."},
5243 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
5244 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00005245#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005246 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5247 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005248#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 {"to_bytes", (PyCFunction)long_to_bytes,
5250 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
5251 {"from_bytes", (PyCFunction)long_from_bytes,
5252 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
5253 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
5254 "Truncating an Integral returns itself."},
5255 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
5256 "Flooring an Integral returns itself."},
5257 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
5258 "Ceiling of an Integral returns itself."},
5259 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5260 "Rounding an Integral returns itself.\n"
5261 "Rounding with an ndigits argument also returns an integer."},
5262 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
5263 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
5264 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
5265 "Returns size in memory, in bytes"},
5266 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005267};
5268
Guido van Rossumb43daf72007-08-01 18:08:08 +00005269static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005270 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005271 (getter)long_long, (setter)NULL,
5272 "the real part of a complex number",
5273 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005274 {"imag",
5275 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005276 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005277 NULL},
5278 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005279 (getter)long_long, (setter)NULL,
5280 "the numerator of a rational number in lowest terms",
5281 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005282 {"denominator",
5283 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005284 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005285 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005286 {NULL} /* Sentinel */
5287};
5288
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005289PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005290"int(x=0) -> integer\n\
5291int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005292\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005293Convert a number or string to an integer, or return 0 if no arguments\n\
5294are given. If x is a number, return x.__int__(). For floating point\n\
5295numbers, this truncates towards zero.\n\
5296\n\
5297If x is not a number or if base is given, then x must be a string,\n\
5298bytes, or bytearray instance representing an integer literal in the\n\
5299given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5300by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5301Base 0 means to interpret the base from the string as an integer literal.\n\
5302>>> int('0b100', base=0)\n\
53034");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005304
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005305static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005306 (binaryfunc)long_add, /*nb_add*/
5307 (binaryfunc)long_sub, /*nb_subtract*/
5308 (binaryfunc)long_mul, /*nb_multiply*/
5309 long_mod, /*nb_remainder*/
5310 long_divmod, /*nb_divmod*/
5311 long_pow, /*nb_power*/
5312 (unaryfunc)long_neg, /*nb_negative*/
5313 (unaryfunc)long_long, /*tp_positive*/
5314 (unaryfunc)long_abs, /*tp_absolute*/
5315 (inquiry)long_bool, /*tp_bool*/
5316 (unaryfunc)long_invert, /*nb_invert*/
5317 long_lshift, /*nb_lshift*/
5318 (binaryfunc)long_rshift, /*nb_rshift*/
5319 long_and, /*nb_and*/
5320 long_xor, /*nb_xor*/
5321 long_or, /*nb_or*/
5322 long_long, /*nb_int*/
5323 0, /*nb_reserved*/
5324 long_float, /*nb_float*/
5325 0, /* nb_inplace_add */
5326 0, /* nb_inplace_subtract */
5327 0, /* nb_inplace_multiply */
5328 0, /* nb_inplace_remainder */
5329 0, /* nb_inplace_power */
5330 0, /* nb_inplace_lshift */
5331 0, /* nb_inplace_rshift */
5332 0, /* nb_inplace_and */
5333 0, /* nb_inplace_xor */
5334 0, /* nb_inplace_or */
5335 long_div, /* nb_floor_divide */
5336 long_true_divide, /* nb_true_divide */
5337 0, /* nb_inplace_floor_divide */
5338 0, /* nb_inplace_true_divide */
5339 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005340};
5341
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005342PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005343 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5344 "int", /* tp_name */
5345 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5346 sizeof(digit), /* tp_itemsize */
5347 long_dealloc, /* tp_dealloc */
5348 0, /* tp_print */
5349 0, /* tp_getattr */
5350 0, /* tp_setattr */
5351 0, /* tp_reserved */
5352 long_to_decimal_string, /* tp_repr */
5353 &long_as_number, /* tp_as_number */
5354 0, /* tp_as_sequence */
5355 0, /* tp_as_mapping */
5356 (hashfunc)long_hash, /* tp_hash */
5357 0, /* tp_call */
5358 long_to_decimal_string, /* tp_str */
5359 PyObject_GenericGetAttr, /* tp_getattro */
5360 0, /* tp_setattro */
5361 0, /* tp_as_buffer */
5362 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5363 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5364 long_doc, /* tp_doc */
5365 0, /* tp_traverse */
5366 0, /* tp_clear */
5367 long_richcompare, /* tp_richcompare */
5368 0, /* tp_weaklistoffset */
5369 0, /* tp_iter */
5370 0, /* tp_iternext */
5371 long_methods, /* tp_methods */
5372 0, /* tp_members */
5373 long_getset, /* tp_getset */
5374 0, /* tp_base */
5375 0, /* tp_dict */
5376 0, /* tp_descr_get */
5377 0, /* tp_descr_set */
5378 0, /* tp_dictoffset */
5379 0, /* tp_init */
5380 0, /* tp_alloc */
5381 long_new, /* tp_new */
5382 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005383};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005384
Mark Dickinsonbd792642009-03-18 20:06:12 +00005385static PyTypeObject Int_InfoType;
5386
5387PyDoc_STRVAR(int_info__doc__,
5388"sys.int_info\n\
5389\n\
5390A struct sequence that holds information about Python's\n\
5391internal representation of integers. The attributes are read only.");
5392
5393static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005395 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005397};
5398
5399static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005400 "sys.int_info", /* name */
5401 int_info__doc__, /* doc */
5402 int_info_fields, /* fields */
5403 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005404};
5405
5406PyObject *
5407PyLong_GetInfo(void)
5408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005409 PyObject* int_info;
5410 int field = 0;
5411 int_info = PyStructSequence_New(&Int_InfoType);
5412 if (int_info == NULL)
5413 return NULL;
5414 PyStructSequence_SET_ITEM(int_info, field++,
5415 PyLong_FromLong(PyLong_SHIFT));
5416 PyStructSequence_SET_ITEM(int_info, field++,
5417 PyLong_FromLong(sizeof(digit)));
5418 if (PyErr_Occurred()) {
5419 Py_CLEAR(int_info);
5420 return NULL;
5421 }
5422 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005423}
5424
Guido van Rossumddefaf32007-01-14 03:31:43 +00005425int
5426_PyLong_Init(void)
5427{
5428#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429 int ival, size;
5430 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5433 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5434 if (Py_TYPE(v) == &PyLong_Type) {
5435 /* The element is already initialized, most likely
5436 * the Python interpreter was initialized before.
5437 */
5438 Py_ssize_t refcnt;
5439 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5442 _Py_NewReference(op);
5443 /* _Py_NewReference sets the ref count to 1 but
5444 * the ref count might be larger. Set the refcnt
5445 * to the original refcnt + 1 */
5446 Py_REFCNT(op) = refcnt + 1;
5447 assert(Py_SIZE(op) == size);
Victor Stinner12174a52014-08-15 23:17:38 +02005448 assert(v->ob_digit[0] == (digit)abs(ival));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 }
5450 else {
Christian Heimesd3afe782013-12-04 09:27:47 +01005451 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005452 }
5453 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005454 v->ob_digit[0] = (digit)abs(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005455 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005456#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005457 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005458 if (Int_InfoType.tp_name == NULL) {
5459 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5460 return 0;
5461 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005463 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005464}
5465
5466void
5467PyLong_Fini(void)
5468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 /* Integers are currently statically allocated. Py_DECREF is not
5470 needed, but Python must forget about the reference or multiple
5471 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005472#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 int i;
5474 PyLongObject *v = small_ints;
5475 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5476 _Py_DEC_REFTOTAL;
5477 _Py_ForgetReference((PyObject*)v);
5478 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005479#endif
5480}