blob: 6eb40e40df7257948db31975bb64c3ea9dce948a [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"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700371 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000372 * (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
Benjamin Petersonca470632016-09-06 13:47:26 -0700992 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100993#else
994
Tim Peters70128a12001-06-16 08:48:40 +0000995#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700996# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000997#endif
Benjamin Petersonca470632016-09-06 13:47:26 -0700998 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100999#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001000
Guido van Rossum78694d91998-09-18 14:14:13 +00001001}
1002
Serhiy Storchaka95949422013-08-27 19:40:23 +03001003/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001004
1005void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001006PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001007{
Tim Peters70128a12001-06-16 08:48:40 +00001008#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1012 x = PyLong_AsLong(vv);
1013 else
1014 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001015#else
Tim Peters70128a12001-06-16 08:48:40 +00001016
Tim Peters70128a12001-06-16 08:48:40 +00001017#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001018# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001019#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001020 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1023 x = PyLong_AsLongLong(vv);
1024 else
1025 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001026
1027#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 if (x == -1 && PyErr_Occurred())
1030 return NULL;
1031 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001032}
1033
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001034/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001035 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001036 */
1037
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001038#define PY_ABS_LLONG_MIN (0-(unsigned long long)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001039
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001040/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001041
1042PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001043PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001046 unsigned long long abs_ival;
1047 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 int ndigits = 0;
1049 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 CHECK_SMALL_INT(ival);
1052 if (ival < 0) {
1053 /* avoid signed overflow on negation; see comments
1054 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001055 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 negative = 1;
1057 }
1058 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001059 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 /* Count the number of Python digits.
1063 We used to pick 5 ("big enough for anything"), but that's a
1064 waste of time and space given that 5*15 = 75 bits are rarely
1065 needed. */
1066 t = abs_ival;
1067 while (t) {
1068 ++ndigits;
1069 t >>= PyLong_SHIFT;
1070 }
1071 v = _PyLong_New(ndigits);
1072 if (v != NULL) {
1073 digit *p = v->ob_digit;
1074 Py_SIZE(v) = negative ? -ndigits : ndigits;
1075 t = abs_ival;
1076 while (t) {
1077 *p++ = (digit)(t & PyLong_MASK);
1078 t >>= PyLong_SHIFT;
1079 }
1080 }
1081 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001082}
1083
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001084/* Create a new int object from a C unsigned long long int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001085
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001086PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001087PyLong_FromUnsignedLongLong(unsigned long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001090 unsigned long long t;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 if (ival < PyLong_BASE)
1094 return PyLong_FromLong((long)ival);
1095 /* Count the number of Python digits. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001096 t = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 while (t) {
1098 ++ndigits;
1099 t >>= PyLong_SHIFT;
1100 }
1101 v = _PyLong_New(ndigits);
1102 if (v != NULL) {
1103 digit *p = v->ob_digit;
1104 Py_SIZE(v) = ndigits;
1105 while (ival) {
1106 *p++ = (digit)(ival & PyLong_MASK);
1107 ival >>= PyLong_SHIFT;
1108 }
1109 }
1110 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001111}
1112
Serhiy Storchaka95949422013-08-27 19:40:23 +03001113/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114
1115PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001116PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 PyLongObject *v;
1119 size_t abs_ival;
1120 size_t t; /* unsigned so >> doesn't propagate sign bit */
1121 int ndigits = 0;
1122 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 CHECK_SMALL_INT(ival);
1125 if (ival < 0) {
1126 /* avoid signed overflow when ival = SIZE_T_MIN */
1127 abs_ival = (size_t)(-1-ival)+1;
1128 negative = 1;
1129 }
1130 else {
1131 abs_ival = (size_t)ival;
1132 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 /* Count the number of Python digits. */
1135 t = abs_ival;
1136 while (t) {
1137 ++ndigits;
1138 t >>= PyLong_SHIFT;
1139 }
1140 v = _PyLong_New(ndigits);
1141 if (v != NULL) {
1142 digit *p = v->ob_digit;
1143 Py_SIZE(v) = negative ? -ndigits : ndigits;
1144 t = abs_ival;
1145 while (t) {
1146 *p++ = (digit)(t & PyLong_MASK);
1147 t >>= PyLong_SHIFT;
1148 }
1149 }
1150 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001151}
1152
Serhiy Storchaka95949422013-08-27 19:40:23 +03001153/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001154
1155PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001156PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 PyLongObject *v;
1159 size_t t;
1160 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (ival < PyLong_BASE)
1163 return PyLong_FromLong((long)ival);
1164 /* Count the number of Python digits. */
1165 t = ival;
1166 while (t) {
1167 ++ndigits;
1168 t >>= PyLong_SHIFT;
1169 }
1170 v = _PyLong_New(ndigits);
1171 if (v != NULL) {
1172 digit *p = v->ob_digit;
1173 Py_SIZE(v) = ndigits;
1174 while (ival) {
1175 *p++ = (digit)(ival & PyLong_MASK);
1176 ival >>= PyLong_SHIFT;
1177 }
1178 }
1179 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001180}
1181
Serhiy Storchaka95949422013-08-27 19:40:23 +03001182/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001183 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001184
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001185long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001186PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001189 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001191 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (vv == NULL) {
1194 PyErr_BadInternalCall();
1195 return -1;
1196 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001197
1198 if (PyLong_Check(vv)) {
1199 v = (PyLongObject *)vv;
1200 }
1201 else {
1202 v = _PyLong_FromNbInt(vv);
1203 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001205 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001207
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001208 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001210 case -1:
1211 bytes = -(sdigit)v->ob_digit[0];
1212 break;
1213 case 0:
1214 bytes = 0;
1215 break;
1216 case 1:
1217 bytes = v->ob_digit[0];
1218 break;
1219 default:
1220 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001221 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001223 if (do_decref) {
1224 Py_DECREF(v);
1225 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001226
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001227 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001229 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 else
1231 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001232}
1233
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001234/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001235 Return -1 and set an error if overflow occurs. */
1236
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001237unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001238PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001241 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001243
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001244 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001246 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001248 if (!PyLong_Check(vv)) {
1249 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001250 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001251 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 v = (PyLongObject*)vv;
1254 switch(Py_SIZE(v)) {
1255 case 0: return 0;
1256 case 1: return v->ob_digit[0];
1257 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001258
Mark Dickinson22b20182010-05-10 21:27:53 +00001259 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001260 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001261
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001262 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001264 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 else
1266 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001267}
Tim Petersd1a7da62001-06-13 00:35:57 +00001268
Serhiy Storchaka95949422013-08-27 19:40:23 +03001269/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001270 Returns -1 and sets an error condition if an error occurs. */
1271
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001272static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001273_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001274{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001275 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001276 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 Py_ssize_t i;
1278 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (vv == NULL || !PyLong_Check(vv)) {
1281 PyErr_BadInternalCall();
1282 return (unsigned long) -1;
1283 }
1284 v = (PyLongObject *)vv;
1285 switch(Py_SIZE(v)) {
1286 case 0: return 0;
1287 case 1: return v->ob_digit[0];
1288 }
1289 i = Py_SIZE(v);
1290 sign = 1;
1291 x = 0;
1292 if (i < 0) {
1293 sign = -1;
1294 i = -i;
1295 }
1296 while (--i >= 0) {
1297 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1298 }
1299 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001300}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001301
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001302unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001303PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001306 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001307
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001308 if (op == NULL) {
1309 PyErr_BadInternalCall();
1310 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001312
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001313 if (PyLong_Check(op)) {
1314 return _PyLong_AsUnsignedLongLongMask(op);
1315 }
1316
1317 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001319 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001320
1321 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1322 Py_DECREF(lo);
1323 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001324}
Tim Petersd1a7da62001-06-13 00:35:57 +00001325
Serhiy Storchaka95949422013-08-27 19:40:23 +03001326/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001327 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001328
Mark Dickinson8d48b432011-10-23 20:47:14 +01001329 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1330 the result. Otherwise *overflow is 0.
1331
1332 For other errors (e.g., TypeError), return -1 and set an error condition.
1333 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001334*/
1335
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001336long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001337PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001340 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001341 unsigned long long x, prev;
1342 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 Py_ssize_t i;
1344 int sign;
1345 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 *overflow = 0;
1348 if (vv == NULL) {
1349 PyErr_BadInternalCall();
1350 return -1;
1351 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001352
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001353 if (PyLong_Check(vv)) {
1354 v = (PyLongObject *)vv;
1355 }
1356 else {
1357 v = _PyLong_FromNbInt(vv);
1358 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 return -1;
1360 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 switch (i) {
1367 case -1:
1368 res = -(sdigit)v->ob_digit[0];
1369 break;
1370 case 0:
1371 res = 0;
1372 break;
1373 case 1:
1374 res = v->ob_digit[0];
1375 break;
1376 default:
1377 sign = 1;
1378 x = 0;
1379 if (i < 0) {
1380 sign = -1;
1381 i = -(i);
1382 }
1383 while (--i >= 0) {
1384 prev = x;
1385 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1386 if ((x >> PyLong_SHIFT) != prev) {
1387 *overflow = sign;
1388 goto exit;
1389 }
1390 }
1391 /* Haven't lost any bits, but casting to long requires extra
1392 * care (see comment above).
1393 */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001394 if (x <= (unsigned long long)PY_LLONG_MAX) {
1395 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 }
1397 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1398 res = PY_LLONG_MIN;
1399 }
1400 else {
1401 *overflow = sign;
1402 /* res is already set to -1 */
1403 }
1404 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001405 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001407 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 }
1409 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001410}
1411
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001412#define CHECK_BINOP(v,w) \
1413 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001414 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1415 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001416 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001417
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001418/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1419 2**k if d is nonzero, else 0. */
1420
1421static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1423 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001424};
1425
1426static int
1427bits_in_digit(digit d)
1428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 int d_bits = 0;
1430 while (d >= 32) {
1431 d_bits += 6;
1432 d >>= 6;
1433 }
1434 d_bits += (int)BitLengthTable[d];
1435 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001436}
1437
Tim Peters877a2122002-08-12 05:09:36 +00001438/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1439 * is modified in place, by adding y to it. Carries are propagated as far as
1440 * x[m-1], and the remaining carry (0 or 1) is returned.
1441 */
1442static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001443v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 Py_ssize_t i;
1446 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 assert(m >= n);
1449 for (i = 0; i < n; ++i) {
1450 carry += x[i] + y[i];
1451 x[i] = carry & PyLong_MASK;
1452 carry >>= PyLong_SHIFT;
1453 assert((carry & 1) == carry);
1454 }
1455 for (; carry && i < m; ++i) {
1456 carry += x[i];
1457 x[i] = carry & PyLong_MASK;
1458 carry >>= PyLong_SHIFT;
1459 assert((carry & 1) == carry);
1460 }
1461 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001462}
1463
1464/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1465 * is modified in place, by subtracting y from it. Borrows are propagated as
1466 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1467 */
1468static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001469v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 Py_ssize_t i;
1472 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 assert(m >= n);
1475 for (i = 0; i < n; ++i) {
1476 borrow = x[i] - y[i] - borrow;
1477 x[i] = borrow & PyLong_MASK;
1478 borrow >>= PyLong_SHIFT;
1479 borrow &= 1; /* keep only 1 sign bit */
1480 }
1481 for (; borrow && i < m; ++i) {
1482 borrow = x[i] - borrow;
1483 x[i] = borrow & PyLong_MASK;
1484 borrow >>= PyLong_SHIFT;
1485 borrow &= 1;
1486 }
1487 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001488}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001489
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001490/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1491 * result in z[0:m], and return the d bits shifted out of the top.
1492 */
1493static digit
1494v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 Py_ssize_t i;
1497 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 assert(0 <= d && d < PyLong_SHIFT);
1500 for (i=0; i < m; i++) {
1501 twodigits acc = (twodigits)a[i] << d | carry;
1502 z[i] = (digit)acc & PyLong_MASK;
1503 carry = (digit)(acc >> PyLong_SHIFT);
1504 }
1505 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001506}
1507
1508/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1509 * result in z[0:m], and return the d bits shifted out of the bottom.
1510 */
1511static digit
1512v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 Py_ssize_t i;
1515 digit carry = 0;
1516 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 assert(0 <= d && d < PyLong_SHIFT);
1519 for (i=m; i-- > 0;) {
1520 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1521 carry = (digit)acc & mask;
1522 z[i] = (digit)(acc >> d);
1523 }
1524 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001525}
1526
Tim Peters212e6142001-07-14 12:23:19 +00001527/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1528 in pout, and returning the remainder. pin and pout point at the LSD.
1529 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001530 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001531 immutable. */
1532
1533static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001534inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 assert(n > 0 && n <= PyLong_MASK);
1539 pin += size;
1540 pout += size;
1541 while (--size >= 0) {
1542 digit hi;
1543 rem = (rem << PyLong_SHIFT) | *--pin;
1544 *--pout = hi = (digit)(rem / n);
1545 rem -= (twodigits)hi * n;
1546 }
1547 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001548}
1549
Serhiy Storchaka95949422013-08-27 19:40:23 +03001550/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001551 (as function result) and the remainder (through *prem).
1552 The sign of a is ignored; n should not be zero. */
1553
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001554static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001555divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001556{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001557 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 assert(n > 0 && n <= PyLong_MASK);
1561 z = _PyLong_New(size);
1562 if (z == NULL)
1563 return NULL;
1564 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1565 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001566}
1567
Serhiy Storchaka95949422013-08-27 19:40:23 +03001568/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001569 string. (Return value is non-shared so that callers can modify the
1570 returned value if necessary.) */
1571
Victor Stinnerd3f08822012-05-29 12:57:52 +02001572static int
1573long_to_decimal_string_internal(PyObject *aa,
1574 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001575 _PyUnicodeWriter *writer,
1576 _PyBytesWriter *bytes_writer,
1577 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001580 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 Py_ssize_t size, strlen, size_a, i, j;
1582 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001584 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001585 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 a = (PyLongObject *)aa;
1588 if (a == NULL || !PyLong_Check(a)) {
1589 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001590 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001592 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 /* quick and dirty upper bound for the number of digits
1596 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 But log2(a) < size_a * PyLong_SHIFT, and
1601 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001602 > 3.3 * _PyLong_DECIMAL_SHIFT
1603
1604 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1605 size_a + size_a / d < size_a + size_a / floor(d),
1606 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1607 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001609 d = (33 * _PyLong_DECIMAL_SHIFT) /
1610 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1611 assert(size_a < PY_SSIZE_T_MAX/2);
1612 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 scratch = _PyLong_New(size);
1614 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001615 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 /* convert array of base _PyLong_BASE digits in pin to an array of
1618 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1619 Volume 2 (3rd edn), section 4.4, Method 1b). */
1620 pin = a->ob_digit;
1621 pout = scratch->ob_digit;
1622 size = 0;
1623 for (i = size_a; --i >= 0; ) {
1624 digit hi = pin[i];
1625 for (j = 0; j < size; j++) {
1626 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1627 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1628 pout[j] = (digit)(z - (twodigits)hi *
1629 _PyLong_DECIMAL_BASE);
1630 }
1631 while (hi) {
1632 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1633 hi /= _PyLong_DECIMAL_BASE;
1634 }
1635 /* check for keyboard interrupt */
1636 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001637 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001638 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001639 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 }
1641 /* pout should have at least one digit, so that the case when a = 0
1642 works correctly */
1643 if (size == 0)
1644 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 /* calculate exact length of output string, and allocate */
1647 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1648 tenpow = 10;
1649 rem = pout[size-1];
1650 while (rem >= tenpow) {
1651 tenpow *= 10;
1652 strlen++;
1653 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001654 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001655 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1656 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001657 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001658 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001659 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001661 else if (bytes_writer) {
1662 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1663 if (*bytes_str == NULL) {
1664 Py_DECREF(scratch);
1665 return -1;
1666 }
1667 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001668 else {
1669 str = PyUnicode_New(strlen, '9');
1670 if (str == NULL) {
1671 Py_DECREF(scratch);
1672 return -1;
1673 }
1674 kind = PyUnicode_KIND(str);
1675 }
1676
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001677#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001678 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001679 /* pout[0] through pout[size-2] contribute exactly \
1680 _PyLong_DECIMAL_SHIFT digits each */ \
1681 for (i=0; i < size - 1; i++) { \
1682 rem = pout[i]; \
1683 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1684 *--p = '0' + rem % 10; \
1685 rem /= 10; \
1686 } \
1687 } \
1688 /* pout[size-1]: always produce at least one decimal digit */ \
1689 rem = pout[i]; \
1690 do { \
1691 *--p = '0' + rem % 10; \
1692 rem /= 10; \
1693 } while (rem != 0); \
1694 \
1695 /* and sign */ \
1696 if (negative) \
1697 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001698 } while (0)
1699
1700#define WRITE_UNICODE_DIGITS(TYPE) \
1701 do { \
1702 if (writer) \
1703 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1704 else \
1705 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1706 \
1707 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001708 \
1709 /* check we've counted correctly */ \
1710 if (writer) \
1711 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1712 else \
1713 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1714 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001717 if (bytes_writer) {
1718 char *p = *bytes_str + strlen;
1719 WRITE_DIGITS(p);
1720 assert(p == *bytes_str);
1721 }
1722 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001723 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001724 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001726 else if (kind == PyUnicode_2BYTE_KIND) {
1727 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001728 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001729 }
1730 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001731 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001732 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001733 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001734 }
1735#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001736#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001739 if (writer) {
1740 writer->pos += strlen;
1741 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001742 else if (bytes_writer) {
1743 (*bytes_str) += strlen;
1744 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001745 else {
1746 assert(_PyUnicode_CheckConsistency(str, 1));
1747 *p_output = (PyObject *)str;
1748 }
1749 return 0;
1750}
1751
1752static PyObject *
1753long_to_decimal_string(PyObject *aa)
1754{
1755 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001756 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001757 return NULL;
1758 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001759}
1760
Serhiy Storchaka95949422013-08-27 19:40:23 +03001761/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001762 which should be one of 2, 8 or 16. Return a string object.
1763 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1764 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001765
Victor Stinnerd3f08822012-05-29 12:57:52 +02001766static int
1767long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001768 PyObject **p_output, _PyUnicodeWriter *writer,
1769 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001770{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001771 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001772 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001773 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001775 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001776 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001778
Victor Stinnerd3f08822012-05-29 12:57:52 +02001779 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 if (a == NULL || !PyLong_Check(a)) {
1781 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001782 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001784 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001785 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 /* Compute a rough upper bound for the length of the string */
1788 switch (base) {
1789 case 16:
1790 bits = 4;
1791 break;
1792 case 8:
1793 bits = 3;
1794 break;
1795 case 2:
1796 bits = 1;
1797 break;
1798 default:
1799 assert(0); /* shouldn't ever get here */
1800 bits = 0; /* to silence gcc warning */
1801 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001802
Mark Dickinsone2846542012-04-20 21:21:24 +01001803 /* Compute exact length 'sz' of output string. */
1804 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001805 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001806 }
1807 else {
1808 Py_ssize_t size_a_in_bits;
1809 /* Ensure overflow doesn't occur during computation of sz. */
1810 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1811 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001812 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001813 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001814 }
1815 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1816 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001817 /* Allow 1 character for a '-' sign. */
1818 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1819 }
1820 if (alternate) {
1821 /* 2 characters for prefix */
1822 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001823 }
1824
Victor Stinnerd3f08822012-05-29 12:57:52 +02001825 if (writer) {
1826 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1827 return -1;
1828 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001830 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001831 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1832 if (*bytes_str == NULL)
1833 return -1;
1834 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001836 v = PyUnicode_New(sz, 'x');
1837 if (v == NULL)
1838 return -1;
1839 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001841
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001842#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001843 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001844 if (size_a == 0) { \
1845 *--p = '0'; \
1846 } \
1847 else { \
1848 /* JRH: special case for power-of-2 bases */ \
1849 twodigits accum = 0; \
1850 int accumbits = 0; /* # of bits in accum */ \
1851 Py_ssize_t i; \
1852 for (i = 0; i < size_a; ++i) { \
1853 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1854 accumbits += PyLong_SHIFT; \
1855 assert(accumbits >= bits); \
1856 do { \
1857 char cdigit; \
1858 cdigit = (char)(accum & (base - 1)); \
1859 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1860 *--p = cdigit; \
1861 accumbits -= bits; \
1862 accum >>= bits; \
1863 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1864 } \
1865 } \
1866 \
1867 if (alternate) { \
1868 if (base == 16) \
1869 *--p = 'x'; \
1870 else if (base == 8) \
1871 *--p = 'o'; \
1872 else /* (base == 2) */ \
1873 *--p = 'b'; \
1874 *--p = '0'; \
1875 } \
1876 if (negative) \
1877 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001878 } while (0)
1879
1880#define WRITE_UNICODE_DIGITS(TYPE) \
1881 do { \
1882 if (writer) \
1883 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1884 else \
1885 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1886 \
1887 WRITE_DIGITS(p); \
1888 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001889 if (writer) \
1890 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1891 else \
1892 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1893 } while (0)
1894
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001895 if (bytes_writer) {
1896 char *p = *bytes_str + sz;
1897 WRITE_DIGITS(p);
1898 assert(p == *bytes_str);
1899 }
1900 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001901 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001902 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001903 }
1904 else if (kind == PyUnicode_2BYTE_KIND) {
1905 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001906 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001907 }
1908 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001909 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001910 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001911 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001912 }
1913#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001914#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02001915
1916 if (writer) {
1917 writer->pos += sz;
1918 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001919 else if (bytes_writer) {
1920 (*bytes_str) += sz;
1921 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001922 else {
1923 assert(_PyUnicode_CheckConsistency(v, 1));
1924 *p_output = v;
1925 }
1926 return 0;
1927}
1928
1929PyObject *
1930_PyLong_Format(PyObject *obj, int base)
1931{
1932 PyObject *str;
1933 int err;
1934 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001935 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001936 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001937 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001938 if (err == -1)
1939 return NULL;
1940 return str;
1941}
1942
1943int
1944_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1945 PyObject *obj,
1946 int base, int alternate)
1947{
1948 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001949 return long_to_decimal_string_internal(obj, NULL, writer,
1950 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001951 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001952 return long_format_binary(obj, base, alternate, NULL, writer,
1953 NULL, NULL);
1954}
1955
1956char*
1957_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
1958 PyObject *obj,
1959 int base, int alternate)
1960{
1961 char *str2;
1962 int res;
1963 str2 = str;
1964 if (base == 10)
1965 res = long_to_decimal_string_internal(obj, NULL, NULL,
1966 writer, &str2);
1967 else
1968 res = long_format_binary(obj, base, alternate, NULL, NULL,
1969 writer, &str2);
1970 if (res < 0)
1971 return NULL;
1972 assert(str2 != NULL);
1973 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001974}
1975
Thomas Wouters477c8d52006-05-27 19:21:47 +00001976/* Table of digit values for 8-bit string -> integer conversion.
1977 * '0' maps to 0, ..., '9' maps to 9.
1978 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1979 * All other indices map to 37.
1980 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001981 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001982 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001983unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1985 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1986 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1987 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1988 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1989 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1990 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1991 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1992 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1993 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1994 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 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1998 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1999 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002000};
2001
2002/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002003 * 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 +03002004 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002005 * The point to this routine is that it takes time linear in the number of
2006 * string characters.
2007 */
2008static PyLongObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002009long_from_binary_base(const char **str, int base)
Tim Petersbf2674b2003-02-02 07:51:32 +00002010{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002011 const char *p = *str;
2012 const char *start = p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 int bits_per_char;
2014 Py_ssize_t n;
2015 PyLongObject *z;
2016 twodigits accum;
2017 int bits_in_accum;
2018 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2021 n = base;
2022 for (bits_per_char = -1; n; ++bits_per_char)
2023 n >>= 1;
2024 /* n <- total # of bits needed, while setting p to end-of-string */
2025 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
2026 ++p;
2027 *str = p;
2028 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
2029 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
2030 if (n / bits_per_char < p - start) {
2031 PyErr_SetString(PyExc_ValueError,
2032 "int string too large to convert");
2033 return NULL;
2034 }
2035 n = n / PyLong_SHIFT;
2036 z = _PyLong_New(n);
2037 if (z == NULL)
2038 return NULL;
Serhiy Storchaka95949422013-08-27 19:40:23 +03002039 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 * from least to most significant in both.
2041 */
2042 accum = 0;
2043 bits_in_accum = 0;
2044 pdigit = z->ob_digit;
2045 while (--p >= start) {
2046 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
2047 assert(k >= 0 && k < base);
2048 accum |= (twodigits)k << bits_in_accum;
2049 bits_in_accum += bits_per_char;
2050 if (bits_in_accum >= PyLong_SHIFT) {
2051 *pdigit++ = (digit)(accum & PyLong_MASK);
2052 assert(pdigit - z->ob_digit <= n);
2053 accum >>= PyLong_SHIFT;
2054 bits_in_accum -= PyLong_SHIFT;
2055 assert(bits_in_accum < PyLong_SHIFT);
2056 }
2057 }
2058 if (bits_in_accum) {
2059 assert(bits_in_accum <= PyLong_SHIFT);
2060 *pdigit++ = (digit)accum;
2061 assert(pdigit - z->ob_digit <= n);
2062 }
2063 while (pdigit - z->ob_digit < n)
2064 *pdigit++ = 0;
2065 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00002066}
2067
Serhiy Storchaka95949422013-08-27 19:40:23 +03002068/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002069 * ignored.
2070 *
2071 * If successful, a PyLong object will be returned and 'pend' will be pointing
2072 * to the first unused byte unless it's NULL.
2073 *
2074 * If unsuccessful, NULL will be returned.
2075 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002076PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002077PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002080 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 PyLongObject *z = NULL;
2082 PyObject *strobj;
2083 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 if ((base != 0 && base < 2) || base > 36) {
2086 PyErr_SetString(PyExc_ValueError,
2087 "int() arg 2 must be >= 2 and <= 36");
2088 return NULL;
2089 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002090 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 str++;
2092 if (*str == '+')
2093 ++str;
2094 else if (*str == '-') {
2095 ++str;
2096 sign = -1;
2097 }
2098 if (base == 0) {
2099 if (str[0] != '0')
2100 base = 10;
2101 else if (str[1] == 'x' || str[1] == 'X')
2102 base = 16;
2103 else if (str[1] == 'o' || str[1] == 'O')
2104 base = 8;
2105 else if (str[1] == 'b' || str[1] == 'B')
2106 base = 2;
2107 else {
2108 /* "old" (C-style) octal literal, now invalid.
2109 it might still be zero though */
2110 error_if_nonzero = 1;
2111 base = 10;
2112 }
2113 }
2114 if (str[0] == '0' &&
2115 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2116 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2117 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2118 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 start = str;
2121 if ((base & (base - 1)) == 0)
2122 z = long_from_binary_base(&str, base);
2123 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002124/***
2125Binary bases can be converted in time linear in the number of digits, because
2126Python's representation base is binary. Other bases (including decimal!) use
2127the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002128
Thomas Wouters477c8d52006-05-27 19:21:47 +00002129First some math: the largest integer that can be expressed in N base-B digits
2130is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2131case number of Python digits needed to hold it is the smallest integer n s.t.
2132
2133 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2134 BASE**n >= B**N [taking logs to base BASE]
2135 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2136
2137The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002138this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002139and the result is computed into it.
2140
2141The input string is actually treated as being in base base**i (i.e., i digits
2142are processed at a time), where two more static arrays hold:
2143
2144 convwidth_base[base] = the largest integer i such that base**i <= BASE
2145 convmultmax_base[base] = base ** convwidth_base[base]
2146
2147The first of these is the largest i such that i consecutive input digits
2148must fit in a single Python digit. The second is effectively the input
2149base we're really using.
2150
2151Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2152convmultmax_base[base], the result is "simply"
2153
2154 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2155
2156where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002157
2158Error analysis: as above, the number of Python digits `n` needed is worst-
2159case
2160
2161 n >= N * log(B)/log(BASE)
2162
2163where `N` is the number of input digits in base `B`. This is computed via
2164
2165 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2166
2167below. Two numeric concerns are how much space this can waste, and whether
2168the computed result can be too small. To be concrete, assume BASE = 2**15,
2169which is the default (and it's unlikely anyone changes that).
2170
2171Waste isn't a problem: provided the first input digit isn't 0, the difference
2172between the worst-case input with N digits and the smallest input with N
2173digits is about a factor of B, but B is small compared to BASE so at most
2174one allocated Python digit can remain unused on that count. If
2175N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2176and adding 1 returns a result 1 larger than necessary. However, that can't
2177happen: whenever B is a power of 2, long_from_binary_base() is called
2178instead, and it's impossible for B**i to be an integer power of 2**15 when
2179B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2180an exact integer when B is not a power of 2, since B**i has a prime factor
2181other than 2 in that case, but (2**15)**j's only prime factor is 2).
2182
2183The computed result can be too small if the true value of N*log(B)/log(BASE)
2184is a little bit larger than an exact integer, but due to roundoff errors (in
2185computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2186yields a numeric result a little less than that integer. Unfortunately, "how
2187close can a transcendental function get to an integer over some range?"
2188questions are generally theoretically intractable. Computer analysis via
2189continued fractions is practical: expand log(B)/log(BASE) via continued
2190fractions, giving a sequence i/j of "the best" rational approximations. Then
2191j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2192we can get very close to being in trouble, but very rarely. For example,
219376573 is a denominator in one of the continued-fraction approximations to
2194log(10)/log(2**15), and indeed:
2195
2196 >>> log(10)/log(2**15)*76573
2197 16958.000000654003
2198
2199is very close to an integer. If we were working with IEEE single-precision,
2200rounding errors could kill us. Finding worst cases in IEEE double-precision
2201requires better-than-double-precision log() functions, and Tim didn't bother.
2202Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002203new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002204This should happen extremely rarely, and in fact I don't have a test case
2205that triggers it(!). Instead the code was tested by artificially allocating
2206just 1 digit at the start, so that the copying code was exercised for every
2207digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002208***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002209 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 Py_ssize_t size_z;
2211 int i;
2212 int convwidth;
2213 twodigits convmultmax, convmult;
2214 digit *pz, *pzstop;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002215 const char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 static double log_base_BASE[37] = {0.0e0,};
2218 static int convwidth_base[37] = {0,};
2219 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 if (log_base_BASE[base] == 0.0) {
2222 twodigits convmax = base;
2223 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002224
Mark Dickinson22b20182010-05-10 21:27:53 +00002225 log_base_BASE[base] = (log((double)base) /
2226 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 for (;;) {
2228 twodigits next = convmax * base;
2229 if (next > PyLong_BASE)
2230 break;
2231 convmax = next;
2232 ++i;
2233 }
2234 convmultmax_base[base] = convmax;
2235 assert(i > 0);
2236 convwidth_base[base] = i;
2237 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 /* Find length of the string of numeric characters. */
2240 scan = str;
2241 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2242 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002243
Serhiy Storchaka95949422013-08-27 19:40:23 +03002244 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 * integer with this base and length. Note that there's no
2246 * need to initialize z->ob_digit -- no slot is read up before
2247 * being stored into.
2248 */
2249 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2250 /* Uncomment next line to test exceedingly rare copy code */
2251 /* size_z = 1; */
2252 assert(size_z > 0);
2253 z = _PyLong_New(size_z);
2254 if (z == NULL)
2255 return NULL;
2256 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 /* `convwidth` consecutive input digits are treated as a single
2259 * digit in base `convmultmax`.
2260 */
2261 convwidth = convwidth_base[base];
2262 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 /* Work ;-) */
2265 while (str < scan) {
2266 /* grab up to convwidth digits from the input string */
2267 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2268 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2269 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002270 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 assert(c < PyLong_BASE);
2272 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 convmult = convmultmax;
2275 /* Calculate the shift only if we couldn't get
2276 * convwidth digits.
2277 */
2278 if (i != convwidth) {
2279 convmult = base;
2280 for ( ; i > 1; --i)
2281 convmult *= base;
2282 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 /* Multiply z by convmult, and add c. */
2285 pz = z->ob_digit;
2286 pzstop = pz + Py_SIZE(z);
2287 for (; pz < pzstop; ++pz) {
2288 c += (twodigits)*pz * convmult;
2289 *pz = (digit)(c & PyLong_MASK);
2290 c >>= PyLong_SHIFT;
2291 }
2292 /* carry off the current end? */
2293 if (c) {
2294 assert(c < PyLong_BASE);
2295 if (Py_SIZE(z) < size_z) {
2296 *pz = (digit)c;
2297 ++Py_SIZE(z);
2298 }
2299 else {
2300 PyLongObject *tmp;
2301 /* Extremely rare. Get more space. */
2302 assert(Py_SIZE(z) == size_z);
2303 tmp = _PyLong_New(size_z + 1);
2304 if (tmp == NULL) {
2305 Py_DECREF(z);
2306 return NULL;
2307 }
2308 memcpy(tmp->ob_digit,
2309 z->ob_digit,
2310 sizeof(digit) * size_z);
2311 Py_DECREF(z);
2312 z = tmp;
2313 z->ob_digit[size_z] = (digit)c;
2314 ++size_z;
2315 }
2316 }
2317 }
2318 }
2319 if (z == NULL)
2320 return NULL;
2321 if (error_if_nonzero) {
2322 /* reset the base to 0, else the exception message
2323 doesn't make too much sense */
2324 base = 0;
2325 if (Py_SIZE(z) != 0)
2326 goto onError;
2327 /* there might still be other problems, therefore base
2328 remains zero here for the same reason */
2329 }
2330 if (str == start)
2331 goto onError;
2332 if (sign < 0)
2333 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002334 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 str++;
2336 if (*str != '\0')
2337 goto onError;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002339 z = maybe_small_long(z);
2340 if (z == NULL)
2341 return NULL;
2342 if (pend != NULL)
Serhiy Storchakac6792272013-10-19 21:03:34 +03002343 *pend = (char *)str;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002344 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002345
Mark Dickinson22b20182010-05-10 21:27:53 +00002346 onError:
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002347 if (pend != NULL)
Serhiy Storchakac6792272013-10-19 21:03:34 +03002348 *pend = (char *)str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 Py_XDECREF(z);
2350 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2351 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2352 if (strobj == NULL)
2353 return NULL;
2354 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002355 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 base, strobj);
2357 Py_DECREF(strobj);
2358 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002359}
2360
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002361/* Since PyLong_FromString doesn't have a length parameter,
2362 * check here for possible NULs in the string.
2363 *
2364 * Reports an invalid literal as a bytes object.
2365 */
2366PyObject *
2367_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2368{
2369 PyObject *result, *strobj;
2370 char *end = NULL;
2371
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002372 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002373 if (end == NULL || (result != NULL && end == s + len))
2374 return result;
2375 Py_XDECREF(result);
2376 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2377 if (strobj != NULL) {
2378 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002379 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002380 base, strobj);
2381 Py_DECREF(strobj);
2382 }
2383 return NULL;
2384}
2385
Guido van Rossum9e896b32000-04-05 20:11:21 +00002386PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002387PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002388{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002389 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2390 if (unicode == NULL)
2391 return NULL;
2392 v = PyLong_FromUnicodeObject(unicode, base);
2393 Py_DECREF(unicode);
2394 return v;
2395}
2396
2397PyObject *
2398PyLong_FromUnicodeObject(PyObject *u, int base)
2399{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002400 PyObject *result, *asciidig;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002401 char *buffer, *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002402 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002403
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002404 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002405 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002407 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002408 if (buffer == NULL) {
2409 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002410 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2411 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002413 else {
2414 result = PyLong_FromString(buffer, &end, base);
2415 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2416 Py_DECREF(asciidig);
2417 return result;
2418 }
2419 Py_DECREF(asciidig);
2420 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002421 }
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002422 PyErr_Format(PyExc_ValueError,
2423 "invalid literal for int() with base %d: %.200R",
2424 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002425 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002426}
2427
Tim Peters9f688bf2000-07-07 15:53:28 +00002428/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002429static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002431static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002432
Serhiy Storchaka95949422013-08-27 19:40:23 +03002433/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002434
Guido van Rossume32e0141992-01-19 16:31:05 +00002435static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002436long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002438{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002439 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 if (size_b == 0) {
2443 PyErr_SetString(PyExc_ZeroDivisionError,
2444 "integer division or modulo by zero");
2445 return -1;
2446 }
2447 if (size_a < size_b ||
2448 (size_a == size_b &&
2449 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2450 /* |a| < |b|. */
2451 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2452 if (*pdiv == NULL)
2453 return -1;
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002454 *prem = (PyLongObject *)long_long((PyObject *)a);
2455 if (*prem == NULL) {
2456 Py_CLEAR(*pdiv);
2457 return -1;
2458 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 return 0;
2460 }
2461 if (size_b == 1) {
2462 digit rem = 0;
2463 z = divrem1(a, b->ob_digit[0], &rem);
2464 if (z == NULL)
2465 return -1;
2466 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2467 if (*prem == NULL) {
2468 Py_DECREF(z);
2469 return -1;
2470 }
2471 }
2472 else {
2473 z = x_divrem(a, b, prem);
2474 if (z == NULL)
2475 return -1;
2476 }
2477 /* Set the signs.
2478 The quotient z has the sign of a*b;
2479 the remainder r has the sign of a,
2480 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002481 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2482 _PyLong_Negate(&z);
2483 if (z == NULL) {
2484 Py_CLEAR(*prem);
2485 return -1;
2486 }
2487 }
2488 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2489 _PyLong_Negate(prem);
2490 if (*prem == NULL) {
2491 Py_DECREF(z);
2492 Py_CLEAR(*prem);
2493 return -1;
2494 }
2495 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 *pdiv = maybe_small_long(z);
2497 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002498}
2499
Serhiy Storchaka95949422013-08-27 19:40:23 +03002500/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002501 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002502
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002503static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002504x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 PyLongObject *v, *w, *a;
2507 Py_ssize_t i, k, size_v, size_w;
2508 int d;
2509 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2510 twodigits vv;
2511 sdigit zhi;
2512 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2515 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2516 handle the special case when the initial estimate q for a quotient
2517 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2518 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002521 size_v = Py_ABS(Py_SIZE(v1));
2522 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2524 v = _PyLong_New(size_v+1);
2525 if (v == NULL) {
2526 *prem = NULL;
2527 return NULL;
2528 }
2529 w = _PyLong_New(size_w);
2530 if (w == NULL) {
2531 Py_DECREF(v);
2532 *prem = NULL;
2533 return NULL;
2534 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2537 shift v1 left by the same amount. Results go into w and v. */
2538 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2539 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2540 assert(carry == 0);
2541 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2542 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2543 v->ob_digit[size_v] = carry;
2544 size_v++;
2545 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2548 at most (and usually exactly) k = size_v - size_w digits. */
2549 k = size_v - size_w;
2550 assert(k >= 0);
2551 a = _PyLong_New(k);
2552 if (a == NULL) {
2553 Py_DECREF(w);
2554 Py_DECREF(v);
2555 *prem = NULL;
2556 return NULL;
2557 }
2558 v0 = v->ob_digit;
2559 w0 = w->ob_digit;
2560 wm1 = w0[size_w-1];
2561 wm2 = w0[size_w-2];
2562 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2563 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2564 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002567 Py_DECREF(a);
2568 Py_DECREF(w);
2569 Py_DECREF(v);
2570 *prem = NULL;
2571 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002572 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 /* estimate quotient digit q; may overestimate by 1 (rare) */
2575 vtop = vk[size_w];
2576 assert(vtop <= wm1);
2577 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2578 q = (digit)(vv / wm1);
2579 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2580 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2581 | vk[size_w-2])) {
2582 --q;
2583 r += wm1;
2584 if (r >= PyLong_BASE)
2585 break;
2586 }
2587 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2590 zhi = 0;
2591 for (i = 0; i < size_w; ++i) {
2592 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2593 -PyLong_BASE * q <= z < PyLong_BASE */
2594 z = (sdigit)vk[i] + zhi -
2595 (stwodigits)q * (stwodigits)w0[i];
2596 vk[i] = (digit)z & PyLong_MASK;
2597 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002598 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 /* add w back if q was too large (this branch taken rarely) */
2602 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2603 if ((sdigit)vtop + zhi < 0) {
2604 carry = 0;
2605 for (i = 0; i < size_w; ++i) {
2606 carry += vk[i] + w0[i];
2607 vk[i] = carry & PyLong_MASK;
2608 carry >>= PyLong_SHIFT;
2609 }
2610 --q;
2611 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 /* store quotient digit */
2614 assert(q < PyLong_BASE);
2615 *--ak = q;
2616 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 /* unshift remainder; we reuse w to store the result */
2619 carry = v_rshift(w0, v0, size_w, d);
2620 assert(carry==0);
2621 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 *prem = long_normalize(w);
2624 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002625}
2626
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002627/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2628 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2629 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2630 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2631 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2632 -1.0. */
2633
2634/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2635#if DBL_MANT_DIG == 53
2636#define EXP2_DBL_MANT_DIG 9007199254740992.0
2637#else
2638#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2639#endif
2640
2641double
2642_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2645 /* See below for why x_digits is always large enough. */
2646 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2647 double dx;
2648 /* Correction term for round-half-to-even rounding. For a digit x,
2649 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2650 multiple of 4, rounding ties to a multiple of 8. */
2651 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002652
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002653 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 if (a_size == 0) {
2655 /* Special case for 0: significand 0.0, exponent 0. */
2656 *e = 0;
2657 return 0.0;
2658 }
2659 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2660 /* The following is an overflow-free version of the check
2661 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2662 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2663 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2664 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002665 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2669 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 Number of digits needed for result: write // for floor division.
2672 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2681 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2684 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2685 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 in both cases.
2692 */
2693 if (a_bits <= DBL_MANT_DIG + 2) {
2694 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2695 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2696 x_size = 0;
2697 while (x_size < shift_digits)
2698 x_digits[x_size++] = 0;
2699 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2700 (int)shift_bits);
2701 x_size += a_size;
2702 x_digits[x_size++] = rem;
2703 }
2704 else {
2705 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2706 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2707 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2708 a_size - shift_digits, (int)shift_bits);
2709 x_size = a_size - shift_digits;
2710 /* For correct rounding below, we need the least significant
2711 bit of x to be 'sticky' for this shift: if any of the bits
2712 shifted out was nonzero, we set the least significant bit
2713 of x. */
2714 if (rem)
2715 x_digits[0] |= 1;
2716 else
2717 while (shift_digits > 0)
2718 if (a->ob_digit[--shift_digits]) {
2719 x_digits[0] |= 1;
2720 break;
2721 }
2722 }
Victor Stinner63941882011-09-29 00:42:28 +02002723 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 /* Round, and convert to double. */
2726 x_digits[0] += half_even_correction[x_digits[0] & 7];
2727 dx = x_digits[--x_size];
2728 while (x_size > 0)
2729 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 /* Rescale; make correction if result is 1.0. */
2732 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2733 if (dx == 1.0) {
2734 if (a_bits == PY_SSIZE_T_MAX)
2735 goto overflow;
2736 dx = 0.5;
2737 a_bits += 1;
2738 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 *e = a_bits;
2741 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002742
2743 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 /* exponent > PY_SSIZE_T_MAX */
2745 PyErr_SetString(PyExc_OverflowError,
2746 "huge integer: number of bits overflows a Py_ssize_t");
2747 *e = 0;
2748 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002749}
2750
Serhiy Storchaka95949422013-08-27 19:40:23 +03002751/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002752 using the round-half-to-even rule in the case of a tie. */
2753
2754double
2755PyLong_AsDouble(PyObject *v)
2756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 Py_ssize_t exponent;
2758 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002759
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002760 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 PyErr_BadInternalCall();
2762 return -1.0;
2763 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002764 if (!PyLong_Check(v)) {
2765 PyErr_SetString(PyExc_TypeError, "an integer is required");
2766 return -1.0;
2767 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002768 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002769 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002770 to double. This improves performance of FP/long operations
2771 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002772 */
2773 return (double)MEDIUM_VALUE((PyLongObject *)v);
2774 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2776 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2777 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002778 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 return -1.0;
2780 }
2781 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002782}
2783
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002784/* Methods */
2785
2786static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002787long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002790}
2791
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002792static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002793long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 if (Py_SIZE(a) != Py_SIZE(b)) {
2798 sign = Py_SIZE(a) - Py_SIZE(b);
2799 }
2800 else {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002801 Py_ssize_t i = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2803 ;
2804 if (i < 0)
2805 sign = 0;
2806 else {
2807 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2808 if (Py_SIZE(a) < 0)
2809 sign = -sign;
2810 }
2811 }
2812 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002813}
2814
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002815#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002817
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002818static PyObject *
2819long_richcompare(PyObject *self, PyObject *other, int op)
2820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 int result;
2822 PyObject *v;
2823 CHECK_BINOP(self, other);
2824 if (self == other)
2825 result = 0;
2826 else
2827 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2828 /* Convert the return value to a Boolean */
2829 switch (op) {
2830 case Py_EQ:
2831 v = TEST_COND(result == 0);
2832 break;
2833 case Py_NE:
2834 v = TEST_COND(result != 0);
2835 break;
2836 case Py_LE:
2837 v = TEST_COND(result <= 0);
2838 break;
2839 case Py_GE:
2840 v = TEST_COND(result >= 0);
2841 break;
2842 case Py_LT:
2843 v = TEST_COND(result == -1);
2844 break;
2845 case Py_GT:
2846 v = TEST_COND(result == 1);
2847 break;
2848 default:
2849 PyErr_BadArgument();
2850 return NULL;
2851 }
2852 Py_INCREF(v);
2853 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002854}
2855
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002856static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002857long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002858{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002859 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 Py_ssize_t i;
2861 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 i = Py_SIZE(v);
2864 switch(i) {
2865 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2866 case 0: return 0;
2867 case 1: return v->ob_digit[0];
2868 }
2869 sign = 1;
2870 x = 0;
2871 if (i < 0) {
2872 sign = -1;
2873 i = -(i);
2874 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002876 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2877 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2878 _PyHASH_MODULUS.
2879
2880 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2881 amounts to a rotation of the bits of x. To see this, write
2882
2883 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2884
2885 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2886 PyLong_SHIFT bits of x (those that are shifted out of the
2887 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2888 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2889 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2890 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2891 congruent to y modulo _PyHASH_MODULUS. So
2892
2893 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2894
2895 The right-hand side is just the result of rotating the
2896 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2897 not all _PyHASH_BITS bits of x are 1s, the same is true
2898 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2899 the reduction of x*2**PyLong_SHIFT modulo
2900 _PyHASH_MODULUS. */
2901 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2902 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002904 if (x >= _PyHASH_MODULUS)
2905 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 }
2907 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002908 if (x == (Py_uhash_t)-1)
2909 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002910 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002911}
2912
2913
Serhiy Storchaka95949422013-08-27 19:40:23 +03002914/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002915
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002916static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002917x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002918{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002919 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 PyLongObject *z;
2921 Py_ssize_t i;
2922 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 /* Ensure a is the larger of the two: */
2925 if (size_a < size_b) {
2926 { PyLongObject *temp = a; a = b; b = temp; }
2927 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002928 size_a = size_b;
2929 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 }
2931 z = _PyLong_New(size_a+1);
2932 if (z == NULL)
2933 return NULL;
2934 for (i = 0; i < size_b; ++i) {
2935 carry += a->ob_digit[i] + b->ob_digit[i];
2936 z->ob_digit[i] = carry & PyLong_MASK;
2937 carry >>= PyLong_SHIFT;
2938 }
2939 for (; i < size_a; ++i) {
2940 carry += a->ob_digit[i];
2941 z->ob_digit[i] = carry & PyLong_MASK;
2942 carry >>= PyLong_SHIFT;
2943 }
2944 z->ob_digit[i] = carry;
2945 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002946}
2947
2948/* Subtract the absolute values of two integers. */
2949
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002950static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002951x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002952{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002953 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 PyLongObject *z;
2955 Py_ssize_t i;
2956 int sign = 1;
2957 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 /* Ensure a is the larger of the two: */
2960 if (size_a < size_b) {
2961 sign = -1;
2962 { PyLongObject *temp = a; a = b; b = temp; }
2963 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002964 size_a = size_b;
2965 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 }
2967 else if (size_a == size_b) {
2968 /* Find highest digit where a and b differ: */
2969 i = size_a;
2970 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2971 ;
2972 if (i < 0)
2973 return (PyLongObject *)PyLong_FromLong(0);
2974 if (a->ob_digit[i] < b->ob_digit[i]) {
2975 sign = -1;
2976 { PyLongObject *temp = a; a = b; b = temp; }
2977 }
2978 size_a = size_b = i+1;
2979 }
2980 z = _PyLong_New(size_a);
2981 if (z == NULL)
2982 return NULL;
2983 for (i = 0; i < size_b; ++i) {
2984 /* The following assumes unsigned arithmetic
2985 works module 2**N for some N>PyLong_SHIFT. */
2986 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2987 z->ob_digit[i] = borrow & PyLong_MASK;
2988 borrow >>= PyLong_SHIFT;
2989 borrow &= 1; /* Keep only one sign bit */
2990 }
2991 for (; i < size_a; ++i) {
2992 borrow = a->ob_digit[i] - borrow;
2993 z->ob_digit[i] = borrow & PyLong_MASK;
2994 borrow >>= PyLong_SHIFT;
2995 borrow &= 1; /* Keep only one sign bit */
2996 }
2997 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02002998 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02002999 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003000 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003002}
3003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003004static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003005long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003010
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003011 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
3013 MEDIUM_VALUE(b));
3014 return result;
3015 }
3016 if (Py_SIZE(a) < 0) {
3017 if (Py_SIZE(b) < 0) {
3018 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003019 if (z != NULL) {
3020 /* x_add received at least one multiple-digit int,
3021 and thus z must be a multiple-digit int.
3022 That also means z is not an element of
3023 small_ints, so negating it in-place is safe. */
3024 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003026 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 }
3028 else
3029 z = x_sub(b, a);
3030 }
3031 else {
3032 if (Py_SIZE(b) < 0)
3033 z = x_sub(a, b);
3034 else
3035 z = x_add(a, b);
3036 }
3037 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003038}
3039
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003040static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003041long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003046
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003047 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 PyObject* r;
3049 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
3050 return r;
3051 }
3052 if (Py_SIZE(a) < 0) {
3053 if (Py_SIZE(b) < 0)
3054 z = x_sub(a, b);
3055 else
3056 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003057 if (z != NULL) {
3058 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003060 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 }
3062 else {
3063 if (Py_SIZE(b) < 0)
3064 z = x_add(a, b);
3065 else
3066 z = x_sub(a, b);
3067 }
3068 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003069}
3070
Tim Peters5af4e6c2002-08-12 02:31:19 +00003071/* Grade school multiplication, ignoring the signs.
3072 * Returns the absolute value of the product, or NULL if error.
3073 */
3074static PyLongObject *
3075x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003078 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3079 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 z = _PyLong_New(size_a + size_b);
3083 if (z == NULL)
3084 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3087 if (a == b) {
3088 /* Efficient squaring per HAC, Algorithm 14.16:
3089 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3090 * Gives slightly less than a 2x speedup when a == b,
3091 * via exploiting that each entry in the multiplication
3092 * pyramid appears twice (except for the size_a squares).
3093 */
3094 for (i = 0; i < size_a; ++i) {
3095 twodigits carry;
3096 twodigits f = a->ob_digit[i];
3097 digit *pz = z->ob_digit + (i << 1);
3098 digit *pa = a->ob_digit + i + 1;
3099 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003102 Py_DECREF(z);
3103 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003104 });
Tim Peters0973b992004-08-29 22:16:50 +00003105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 carry = *pz + f * f;
3107 *pz++ = (digit)(carry & PyLong_MASK);
3108 carry >>= PyLong_SHIFT;
3109 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 /* Now f is added in twice in each column of the
3112 * pyramid it appears. Same as adding f<<1 once.
3113 */
3114 f <<= 1;
3115 while (pa < paend) {
3116 carry += *pz + *pa++ * f;
3117 *pz++ = (digit)(carry & PyLong_MASK);
3118 carry >>= PyLong_SHIFT;
3119 assert(carry <= (PyLong_MASK << 1));
3120 }
3121 if (carry) {
3122 carry += *pz;
3123 *pz++ = (digit)(carry & PyLong_MASK);
3124 carry >>= PyLong_SHIFT;
3125 }
3126 if (carry)
3127 *pz += (digit)(carry & PyLong_MASK);
3128 assert((carry >> PyLong_SHIFT) == 0);
3129 }
3130 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003131 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 for (i = 0; i < size_a; ++i) {
3133 twodigits carry = 0;
3134 twodigits f = a->ob_digit[i];
3135 digit *pz = z->ob_digit + i;
3136 digit *pb = b->ob_digit;
3137 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003140 Py_DECREF(z);
3141 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003142 });
Tim Peters0973b992004-08-29 22:16:50 +00003143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 while (pb < pbend) {
3145 carry += *pz + *pb++ * f;
3146 *pz++ = (digit)(carry & PyLong_MASK);
3147 carry >>= PyLong_SHIFT;
3148 assert(carry <= PyLong_MASK);
3149 }
3150 if (carry)
3151 *pz += (digit)(carry & PyLong_MASK);
3152 assert((carry >> PyLong_SHIFT) == 0);
3153 }
3154 }
3155 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003156}
3157
3158/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003159 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003160 split, and sets low and high such that abs(n) == (high << size) + low,
3161 viewing the shift as being by digits. The sign bit is ignored, and
3162 the return values are >= 0.
3163 Returns 0 on success, -1 on failure.
3164*/
3165static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003166kmul_split(PyLongObject *n,
3167 Py_ssize_t size,
3168 PyLongObject **high,
3169 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 PyLongObject *hi, *lo;
3172 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003173 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003174
Victor Stinner640c35c2013-06-04 23:14:37 +02003175 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 if ((hi = _PyLong_New(size_hi)) == NULL)
3179 return -1;
3180 if ((lo = _PyLong_New(size_lo)) == NULL) {
3181 Py_DECREF(hi);
3182 return -1;
3183 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3186 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 *high = long_normalize(hi);
3189 *low = long_normalize(lo);
3190 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003191}
3192
Tim Peters60004642002-08-12 22:01:34 +00003193static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3194
Tim Peters5af4e6c2002-08-12 02:31:19 +00003195/* Karatsuba multiplication. Ignores the input signs, and returns the
3196 * absolute value of the product (or NULL if error).
3197 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3198 */
3199static PyLongObject *
3200k_mul(PyLongObject *a, PyLongObject *b)
3201{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003202 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3203 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 PyLongObject *ah = NULL;
3205 PyLongObject *al = NULL;
3206 PyLongObject *bh = NULL;
3207 PyLongObject *bl = NULL;
3208 PyLongObject *ret = NULL;
3209 PyLongObject *t1, *t2, *t3;
3210 Py_ssize_t shift; /* the number of digits we split off */
3211 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3214 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3215 * Then the original product is
3216 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3217 * By picking X to be a power of 2, "*X" is just shifting, and it's
3218 * been reduced to 3 multiplies on numbers half the size.
3219 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 /* We want to split based on the larger number; fiddle so that b
3222 * is largest.
3223 */
3224 if (asize > bsize) {
3225 t1 = a;
3226 a = b;
3227 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 i = asize;
3230 asize = bsize;
3231 bsize = i;
3232 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 /* Use gradeschool math when either number is too small. */
3235 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3236 if (asize <= i) {
3237 if (asize == 0)
3238 return (PyLongObject *)PyLong_FromLong(0);
3239 else
3240 return x_mul(a, b);
3241 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 /* If a is small compared to b, splitting on b gives a degenerate
3244 * case with ah==0, and Karatsuba may be (even much) less efficient
3245 * than "grade school" then. However, we can still win, by viewing
3246 * b as a string of "big digits", each of width a->ob_size. That
3247 * leads to a sequence of balanced calls to k_mul.
3248 */
3249 if (2 * asize <= bsize)
3250 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 /* Split a & b into hi & lo pieces. */
3253 shift = bsize >> 1;
3254 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3255 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 if (a == b) {
3258 bh = ah;
3259 bl = al;
3260 Py_INCREF(bh);
3261 Py_INCREF(bl);
3262 }
3263 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 /* The plan:
3266 * 1. Allocate result space (asize + bsize digits: that's always
3267 * enough).
3268 * 2. Compute ah*bh, and copy into result at 2*shift.
3269 * 3. Compute al*bl, and copy into result at 0. Note that this
3270 * can't overlap with #2.
3271 * 4. Subtract al*bl from the result, starting at shift. This may
3272 * underflow (borrow out of the high digit), but we don't care:
3273 * we're effectively doing unsigned arithmetic mod
3274 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3275 * borrows and carries out of the high digit can be ignored.
3276 * 5. Subtract ah*bh from the result, starting at shift.
3277 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3278 * at shift.
3279 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 /* 1. Allocate result space. */
3282 ret = _PyLong_New(asize + bsize);
3283 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003284#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 /* Fill with trash, to catch reference to uninitialized digits. */
3286 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003287#endif
Tim Peters44121a62002-08-12 06:17:58 +00003288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3290 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3291 assert(Py_SIZE(t1) >= 0);
3292 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3293 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3294 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 /* Zero-out the digits higher than the ah*bh copy. */
3297 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3298 if (i)
3299 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3300 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 /* 3. t2 <- al*bl, and copy into the low digits. */
3303 if ((t2 = k_mul(al, bl)) == NULL) {
3304 Py_DECREF(t1);
3305 goto fail;
3306 }
3307 assert(Py_SIZE(t2) >= 0);
3308 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3309 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 /* Zero out remaining digits. */
3312 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3313 if (i)
3314 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3317 * because it's fresher in cache.
3318 */
3319 i = Py_SIZE(ret) - shift; /* # digits after shift */
3320 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3321 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3324 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3327 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3328 Py_DECREF(ah);
3329 Py_DECREF(al);
3330 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 if (a == b) {
3333 t2 = t1;
3334 Py_INCREF(t2);
3335 }
3336 else if ((t2 = x_add(bh, bl)) == NULL) {
3337 Py_DECREF(t1);
3338 goto fail;
3339 }
3340 Py_DECREF(bh);
3341 Py_DECREF(bl);
3342 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 t3 = k_mul(t1, t2);
3345 Py_DECREF(t1);
3346 Py_DECREF(t2);
3347 if (t3 == NULL) goto fail;
3348 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 /* Add t3. It's not obvious why we can't run out of room here.
3351 * See the (*) comment after this function.
3352 */
3353 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3354 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003357
Mark Dickinson22b20182010-05-10 21:27:53 +00003358 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 Py_XDECREF(ret);
3360 Py_XDECREF(ah);
3361 Py_XDECREF(al);
3362 Py_XDECREF(bh);
3363 Py_XDECREF(bl);
3364 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003365}
3366
Tim Petersd6974a52002-08-13 20:37:51 +00003367/* (*) Why adding t3 can't "run out of room" above.
3368
Tim Petersab86c2b2002-08-15 20:06:00 +00003369Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3370to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003371
Tim Petersab86c2b2002-08-15 20:06:00 +000033721. For any integer i, i = c(i/2) + f(i/2). In particular,
3373 bsize = c(bsize/2) + f(bsize/2).
33742. shift = f(bsize/2)
33753. asize <= bsize
33764. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3377 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003378
Tim Petersab86c2b2002-08-15 20:06:00 +00003379We allocated asize + bsize result digits, and add t3 into them at an offset
3380of shift. This leaves asize+bsize-shift allocated digit positions for t3
3381to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3382asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003383
Tim Petersab86c2b2002-08-15 20:06:00 +00003384bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3385at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003386
Tim Petersab86c2b2002-08-15 20:06:00 +00003387If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3388digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3389most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003390
Tim Petersab86c2b2002-08-15 20:06:00 +00003391The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003392
Tim Petersab86c2b2002-08-15 20:06:00 +00003393 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003394
Tim Petersab86c2b2002-08-15 20:06:00 +00003395and we have asize + c(bsize/2) available digit positions. We need to show
3396this is always enough. An instance of c(bsize/2) cancels out in both, so
3397the question reduces to whether asize digits is enough to hold
3398(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3399then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3400asize 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 +00003401digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003402asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003403c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3404is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3405bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003406
Tim Peters48d52c02002-08-14 17:07:32 +00003407Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3408clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3409ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003410*/
3411
Tim Peters60004642002-08-12 22:01:34 +00003412/* b has at least twice the digits of a, and a is big enough that Karatsuba
3413 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3414 * of slices, each with a->ob_size digits, and multiply the slices by a,
3415 * one at a time. This gives k_mul balanced inputs to work with, and is
3416 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003417 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003418 * single-width slice overlap between successive partial sums).
3419 */
3420static PyLongObject *
3421k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3422{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003423 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3424 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 Py_ssize_t nbdone; /* # of b digits already multiplied */
3426 PyLongObject *ret;
3427 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 assert(asize > KARATSUBA_CUTOFF);
3430 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 /* Allocate result space, and zero it out. */
3433 ret = _PyLong_New(asize + bsize);
3434 if (ret == NULL)
3435 return NULL;
3436 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 /* Successive slices of b are copied into bslice. */
3439 bslice = _PyLong_New(asize);
3440 if (bslice == NULL)
3441 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 nbdone = 0;
3444 while (bsize > 0) {
3445 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003446 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 /* Multiply the next slice of b by a. */
3449 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3450 nbtouse * sizeof(digit));
3451 Py_SIZE(bslice) = nbtouse;
3452 product = k_mul(a, bslice);
3453 if (product == NULL)
3454 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 /* Add into result. */
3457 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3458 product->ob_digit, Py_SIZE(product));
3459 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 bsize -= nbtouse;
3462 nbdone += nbtouse;
3463 }
Tim Peters60004642002-08-12 22:01:34 +00003464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 Py_DECREF(bslice);
3466 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003467
Mark Dickinson22b20182010-05-10 21:27:53 +00003468 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 Py_DECREF(ret);
3470 Py_XDECREF(bslice);
3471 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003472}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003473
3474static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003475long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003477 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003482 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003484 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 z = k_mul(a, b);
3488 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003489 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3490 _PyLong_Negate(&z);
3491 if (z == NULL)
3492 return NULL;
3493 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003495}
3496
Yury Selivanove0b23092016-02-11 10:26:27 -05003497/* Fast modulo division for single-digit longs. */
3498static PyObject *
3499fast_mod(PyLongObject *a, PyLongObject *b)
3500{
3501 sdigit left = a->ob_digit[0];
3502 sdigit right = b->ob_digit[0];
3503 sdigit mod;
3504
3505 assert(Py_ABS(Py_SIZE(a)) == 1);
3506 assert(Py_ABS(Py_SIZE(b)) == 1);
3507
3508 if (Py_SIZE(a) == Py_SIZE(b)) {
3509 /* 'a' and 'b' have the same sign. */
3510 mod = left % right;
3511 }
3512 else {
3513 /* Either 'a' or 'b' is negative. */
3514 mod = right - 1 - (left - 1) % right;
3515 }
3516
Victor Stinnerf963c132016-03-23 18:36:54 +01003517 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003518}
3519
3520/* Fast floor division for single-digit longs. */
3521static PyObject *
3522fast_floor_div(PyLongObject *a, PyLongObject *b)
3523{
3524 sdigit left = a->ob_digit[0];
3525 sdigit right = b->ob_digit[0];
3526 sdigit div;
3527
3528 assert(Py_ABS(Py_SIZE(a)) == 1);
3529 assert(Py_ABS(Py_SIZE(b)) == 1);
3530
3531 if (Py_SIZE(a) == Py_SIZE(b)) {
3532 /* 'a' and 'b' have the same sign. */
3533 div = left / right;
3534 }
3535 else {
3536 /* Either 'a' or 'b' is negative. */
3537 div = -1 - (left - 1) / right;
3538 }
3539
3540 return PyLong_FromLong(div);
3541}
3542
Guido van Rossume32e0141992-01-19 16:31:05 +00003543/* The / and % operators are now defined in terms of divmod().
3544 The expression a mod b has the value a - b*floor(a/b).
3545 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003546 |a| by |b|, with the sign of a. This is also expressed
3547 as a - b*trunc(a/b), if trunc truncates towards zero.
3548 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 a b a rem b a mod b
3550 13 10 3 3
3551 -13 10 -3 7
3552 13 -10 3 -7
3553 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003554 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003555 have different signs. We then subtract one from the 'div'
3556 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003557
Tim Peters47e52ee2004-08-30 02:44:38 +00003558/* Compute
3559 * *pdiv, *pmod = divmod(v, w)
3560 * NULL can be passed for pdiv or pmod, in which case that part of
3561 * the result is simply thrown away. The caller owns a reference to
3562 * each of these it requests (does not pass NULL for).
3563 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003564static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003565l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003569
Yury Selivanove0b23092016-02-11 10:26:27 -05003570 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3571 /* Fast path for single-digit longs */
3572 div = NULL;
3573 if (pdiv != NULL) {
3574 div = (PyLongObject *)fast_floor_div(v, w);
3575 if (div == NULL) {
3576 return -1;
3577 }
3578 }
3579 if (pmod != NULL) {
3580 mod = (PyLongObject *)fast_mod(v, w);
3581 if (mod == NULL) {
3582 Py_XDECREF(div);
3583 return -1;
3584 }
3585 *pmod = mod;
3586 }
3587 if (pdiv != NULL) {
3588 /* We only want to set `*pdiv` when `*pmod` is
3589 set successfully. */
3590 *pdiv = div;
3591 }
3592 return 0;
3593 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 if (long_divrem(v, w, &div, &mod) < 0)
3595 return -1;
3596 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3597 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3598 PyLongObject *temp;
3599 PyLongObject *one;
3600 temp = (PyLongObject *) long_add(mod, w);
3601 Py_DECREF(mod);
3602 mod = temp;
3603 if (mod == NULL) {
3604 Py_DECREF(div);
3605 return -1;
3606 }
3607 one = (PyLongObject *) PyLong_FromLong(1L);
3608 if (one == NULL ||
3609 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3610 Py_DECREF(mod);
3611 Py_DECREF(div);
3612 Py_XDECREF(one);
3613 return -1;
3614 }
3615 Py_DECREF(one);
3616 Py_DECREF(div);
3617 div = temp;
3618 }
3619 if (pdiv != NULL)
3620 *pdiv = div;
3621 else
3622 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 if (pmod != NULL)
3625 *pmod = mod;
3626 else
3627 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003630}
3631
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003632static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003633long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003638
3639 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3640 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3641 }
3642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3644 div = NULL;
3645 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003646}
3647
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003648/* PyLong/PyLong -> float, with correctly rounded result. */
3649
3650#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3651#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3652
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003653static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003654long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 PyLongObject *a, *b, *x;
3657 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3658 digit mask, low;
3659 int inexact, negate, a_is_small, b_is_small;
3660 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 CHECK_BINOP(v, w);
3663 a = (PyLongObject *)v;
3664 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 /*
3667 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3670 1. choose a suitable integer 'shift'
3671 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3672 3. adjust x for correct rounding
3673 4. convert x to a double dx with the same value
3674 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3679 returns either 0.0 or -0.0, depending on the sign of b. For a and
3680 b both nonzero, ignore signs of a and b, and add the sign back in
3681 at the end. Now write a_bits and b_bits for the bit lengths of a
3682 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3683 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3688 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3689 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3690 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003694 1. The integer 'shift' is chosen so that x has the right number of
3695 bits for a double, plus two or three extra bits that will be used
3696 in the rounding decisions. Writing a_bits and b_bits for the
3697 number of significant bits in a and b respectively, a
3698 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 This is fine in the usual case, but if a/b is smaller than the
3703 smallest normal float then it can lead to double rounding on an
3704 IEEE 754 platform, giving incorrectly rounded results. So we
3705 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003709 2. The quantity x is computed by first shifting a (left -shift bits
3710 if shift <= 0, right shift bits if shift > 0) and then dividing by
3711 b. For both the shift and the division, we keep track of whether
3712 the result is inexact, in a flag 'inexact'; this information is
3713 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003715 With the choice of shift above, together with our assumption that
3716 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3717 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3720 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 For float representability, we need x/2**extra_bits <
3725 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3726 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 To round, we just modify the bottom digit of x in-place; this can
3731 end up giving a digit with value > PyLONG_MASK, but that's not a
3732 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 With the original choices for shift above, extra_bits will always
3735 be 2 or 3. Then rounding under the round-half-to-even rule, we
3736 round up iff the most significant of the extra bits is 1, and
3737 either: (a) the computation of x in step 2 had an inexact result,
3738 or (b) at least one other of the extra bits is 1, or (c) the least
3739 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 4. Conversion to a double is straightforward; all floating-point
3742 operations involved in the conversion are exact, so there's no
3743 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3746 The result will always be exactly representable as a double, except
3747 in the case that it overflows. To avoid dependence on the exact
3748 behaviour of ldexp on overflow, we check for overflow before
3749 applying ldexp. The result of ldexp is adjusted for sign before
3750 returning.
3751 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003754 a_size = Py_ABS(Py_SIZE(a));
3755 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3757 if (b_size == 0) {
3758 PyErr_SetString(PyExc_ZeroDivisionError,
3759 "division by zero");
3760 goto error;
3761 }
3762 if (a_size == 0)
3763 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 /* Fast path for a and b small (exactly representable in a double).
3766 Relies on floating-point division being correctly rounded; results
3767 may be subject to double rounding on x86 machines that operate with
3768 the x87 FPU set to 64-bit precision. */
3769 a_is_small = a_size <= MANT_DIG_DIGITS ||
3770 (a_size == MANT_DIG_DIGITS+1 &&
3771 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3772 b_is_small = b_size <= MANT_DIG_DIGITS ||
3773 (b_size == MANT_DIG_DIGITS+1 &&
3774 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3775 if (a_is_small && b_is_small) {
3776 double da, db;
3777 da = a->ob_digit[--a_size];
3778 while (a_size > 0)
3779 da = da * PyLong_BASE + a->ob_digit[--a_size];
3780 db = b->ob_digit[--b_size];
3781 while (b_size > 0)
3782 db = db * PyLong_BASE + b->ob_digit[--b_size];
3783 result = da / db;
3784 goto success;
3785 }
Tim Peterse2a60002001-09-04 06:17:36 +00003786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 /* Catch obvious cases of underflow and overflow */
3788 diff = a_size - b_size;
3789 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3790 /* Extreme overflow */
3791 goto overflow;
3792 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3793 /* Extreme underflow */
3794 goto underflow_or_zero;
3795 /* Next line is now safe from overflowing a Py_ssize_t */
3796 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3797 bits_in_digit(b->ob_digit[b_size - 1]);
3798 /* Now diff = a_bits - b_bits. */
3799 if (diff > DBL_MAX_EXP)
3800 goto overflow;
3801 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3802 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003805 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 /* x = abs(a * 2**-shift) */
3810 if (shift <= 0) {
3811 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3812 digit rem;
3813 /* x = a << -shift */
3814 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3815 /* In practice, it's probably impossible to end up
3816 here. Both a and b would have to be enormous,
3817 using close to SIZE_T_MAX bytes of memory each. */
3818 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003819 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 goto error;
3821 }
3822 x = _PyLong_New(a_size + shift_digits + 1);
3823 if (x == NULL)
3824 goto error;
3825 for (i = 0; i < shift_digits; i++)
3826 x->ob_digit[i] = 0;
3827 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3828 a_size, -shift % PyLong_SHIFT);
3829 x->ob_digit[a_size + shift_digits] = rem;
3830 }
3831 else {
3832 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3833 digit rem;
3834 /* x = a >> shift */
3835 assert(a_size >= shift_digits);
3836 x = _PyLong_New(a_size - shift_digits);
3837 if (x == NULL)
3838 goto error;
3839 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3840 a_size - shift_digits, shift % PyLong_SHIFT);
3841 /* set inexact if any of the bits shifted out is nonzero */
3842 if (rem)
3843 inexact = 1;
3844 while (!inexact && shift_digits > 0)
3845 if (a->ob_digit[--shift_digits])
3846 inexact = 1;
3847 }
3848 long_normalize(x);
3849 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3852 reference to x, so it's safe to modify it in-place. */
3853 if (b_size == 1) {
3854 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3855 b->ob_digit[0]);
3856 long_normalize(x);
3857 if (rem)
3858 inexact = 1;
3859 }
3860 else {
3861 PyLongObject *div, *rem;
3862 div = x_divrem(x, b, &rem);
3863 Py_DECREF(x);
3864 x = div;
3865 if (x == NULL)
3866 goto error;
3867 if (Py_SIZE(rem))
3868 inexact = 1;
3869 Py_DECREF(rem);
3870 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003871 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 assert(x_size > 0); /* result of division is never zero */
3873 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003876 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 /* Round by directly modifying the low digit of x. */
3880 mask = (digit)1 << (extra_bits - 1);
3881 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003882 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003884 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 /* Convert x to a double dx; the conversion is exact. */
3887 dx = x->ob_digit[--x_size];
3888 while (x_size > 0)
3889 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3890 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 /* Check whether ldexp result will overflow a double. */
3893 if (shift + x_bits >= DBL_MAX_EXP &&
3894 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3895 goto overflow;
3896 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003897
3898 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003900
3901 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003903
3904 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 PyErr_SetString(PyExc_OverflowError,
3906 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003907 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003909}
3910
3911static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003912long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 CHECK_BINOP(a, b);
3917
Yury Selivanove0b23092016-02-11 10:26:27 -05003918 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3919 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
3920 }
3921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3923 mod = NULL;
3924 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003925}
3926
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003927static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003928long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 PyLongObject *div, *mod;
3931 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3936 return NULL;
3937 }
3938 z = PyTuple_New(2);
3939 if (z != NULL) {
3940 PyTuple_SetItem(z, 0, (PyObject *) div);
3941 PyTuple_SetItem(z, 1, (PyObject *) mod);
3942 }
3943 else {
3944 Py_DECREF(div);
3945 Py_DECREF(mod);
3946 }
3947 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003948}
3949
Tim Peters47e52ee2004-08-30 02:44:38 +00003950/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003951static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003952long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3955 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 PyLongObject *z = NULL; /* accumulated result */
3958 Py_ssize_t i, j, k; /* counters */
3959 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 /* 5-ary values. If the exponent is large enough, table is
3962 * precomputed so that table[i] == a**i % c for i in range(32).
3963 */
3964 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3965 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 /* a, b, c = v, w, x */
3968 CHECK_BINOP(v, w);
3969 a = (PyLongObject*)v; Py_INCREF(a);
3970 b = (PyLongObject*)w; Py_INCREF(b);
3971 if (PyLong_Check(x)) {
3972 c = (PyLongObject *)x;
3973 Py_INCREF(x);
3974 }
3975 else if (x == Py_None)
3976 c = NULL;
3977 else {
3978 Py_DECREF(a);
3979 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003980 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 }
Tim Peters4c483c42001-09-05 06:24:58 +00003982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3984 if (c) {
Mark Dickinson0c346d82014-04-11 14:34:40 -04003985 PyErr_SetString(PyExc_ValueError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003986 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 goto Error;
3988 }
3989 else {
3990 /* else return a float. This works because we know
3991 that this calls float_pow() which converts its
3992 arguments to double. */
3993 Py_DECREF(a);
3994 Py_DECREF(b);
3995 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3996 }
3997 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 if (c) {
4000 /* if modulus == 0:
4001 raise ValueError() */
4002 if (Py_SIZE(c) == 0) {
4003 PyErr_SetString(PyExc_ValueError,
4004 "pow() 3rd argument cannot be 0");
4005 goto Error;
4006 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 /* if modulus < 0:
4009 negativeOutput = True
4010 modulus = -modulus */
4011 if (Py_SIZE(c) < 0) {
4012 negativeOutput = 1;
4013 temp = (PyLongObject *)_PyLong_Copy(c);
4014 if (temp == NULL)
4015 goto Error;
4016 Py_DECREF(c);
4017 c = temp;
4018 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004019 _PyLong_Negate(&c);
4020 if (c == NULL)
4021 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 /* if modulus == 1:
4025 return 0 */
4026 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4027 z = (PyLongObject *)PyLong_FromLong(0L);
4028 goto Done;
4029 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004030
Tim Peters81a93152013-10-05 16:53:52 -05004031 /* Reduce base by modulus in some cases:
4032 1. If base < 0. Forcing the base non-negative makes things easier.
4033 2. If base is obviously larger than the modulus. The "small
4034 exponent" case later can multiply directly by base repeatedly,
4035 while the "large exponent" case multiplies directly by base 31
4036 times. It can be unboundedly faster to multiply by
4037 base % modulus instead.
4038 We could _always_ do this reduction, but l_divmod() isn't cheap,
4039 so we only do it when it buys something. */
4040 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 if (l_divmod(a, c, NULL, &temp) < 0)
4042 goto Error;
4043 Py_DECREF(a);
4044 a = temp;
4045 temp = NULL;
4046 }
4047 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 /* At this point a, b, and c are guaranteed non-negative UNLESS
4050 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 z = (PyLongObject *)PyLong_FromLong(1L);
4053 if (z == NULL)
4054 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 /* Perform a modular reduction, X = X % c, but leave X alone if c
4057 * is NULL.
4058 */
4059#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004060 do { \
4061 if (c != NULL) { \
4062 if (l_divmod(X, c, NULL, &temp) < 0) \
4063 goto Error; \
4064 Py_XDECREF(X); \
4065 X = temp; \
4066 temp = NULL; \
4067 } \
4068 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004070 /* Multiply two values, then reduce the result:
4071 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004072#define MULT(X, Y, result) \
4073 do { \
4074 temp = (PyLongObject *)long_mul(X, Y); \
4075 if (temp == NULL) \
4076 goto Error; \
4077 Py_XDECREF(result); \
4078 result = temp; \
4079 temp = NULL; \
4080 REDUCE(result); \
4081 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4084 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4085 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4086 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4087 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004090 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004092 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004093 }
4094 }
4095 }
4096 else {
4097 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4098 Py_INCREF(z); /* still holds 1L */
4099 table[0] = z;
4100 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004101 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4104 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4107 const int index = (bi >> j) & 0x1f;
4108 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004109 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004111 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 }
4113 }
4114 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 if (negativeOutput && (Py_SIZE(z) != 0)) {
4117 temp = (PyLongObject *)long_sub(z, c);
4118 if (temp == NULL)
4119 goto Error;
4120 Py_DECREF(z);
4121 z = temp;
4122 temp = NULL;
4123 }
4124 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004125
Mark Dickinson22b20182010-05-10 21:27:53 +00004126 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004127 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004129 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4131 for (i = 0; i < 32; ++i)
4132 Py_XDECREF(table[i]);
4133 }
4134 Py_DECREF(a);
4135 Py_DECREF(b);
4136 Py_XDECREF(c);
4137 Py_XDECREF(temp);
4138 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004139}
4140
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004141static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004142long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 /* Implement ~x as -(x+1) */
4145 PyLongObject *x;
4146 PyLongObject *w;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004147 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
4149 w = (PyLongObject *)PyLong_FromLong(1L);
4150 if (w == NULL)
4151 return NULL;
4152 x = (PyLongObject *) long_add(v, w);
4153 Py_DECREF(w);
4154 if (x == NULL)
4155 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004156 _PyLong_Negate(&x);
4157 /* No need for maybe_small_long here, since any small
4158 longs will have been caught in the Py_SIZE <= 1 fast path. */
4159 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004160}
4161
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004162static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004163long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004166 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 return PyLong_FromLong(-MEDIUM_VALUE(v));
4168 z = (PyLongObject *)_PyLong_Copy(v);
4169 if (z != NULL)
4170 Py_SIZE(z) = -(Py_SIZE(v));
4171 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004172}
4173
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004174static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004175long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 if (Py_SIZE(v) < 0)
4178 return long_neg(v);
4179 else
4180 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004181}
4182
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004183static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004184long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004187}
4188
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004189static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004190long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 PyLongObject *z = NULL;
4193 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4194 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 if (Py_SIZE(a) < 0) {
4199 /* Right shifting negative numbers is harder */
4200 PyLongObject *a1, *a2;
4201 a1 = (PyLongObject *) long_invert(a);
4202 if (a1 == NULL)
4203 goto rshift_error;
4204 a2 = (PyLongObject *) long_rshift(a1, b);
4205 Py_DECREF(a1);
4206 if (a2 == NULL)
4207 goto rshift_error;
4208 z = (PyLongObject *) long_invert(a2);
4209 Py_DECREF(a2);
4210 }
4211 else {
4212 shiftby = PyLong_AsSsize_t((PyObject *)b);
4213 if (shiftby == -1L && PyErr_Occurred())
4214 goto rshift_error;
4215 if (shiftby < 0) {
4216 PyErr_SetString(PyExc_ValueError,
4217 "negative shift count");
4218 goto rshift_error;
4219 }
4220 wordshift = shiftby / PyLong_SHIFT;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004221 newsize = Py_ABS(Py_SIZE(a)) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 if (newsize <= 0)
4223 return PyLong_FromLong(0);
4224 loshift = shiftby % PyLong_SHIFT;
4225 hishift = PyLong_SHIFT - loshift;
4226 lomask = ((digit)1 << hishift) - 1;
4227 himask = PyLong_MASK ^ lomask;
4228 z = _PyLong_New(newsize);
4229 if (z == NULL)
4230 goto rshift_error;
4231 if (Py_SIZE(a) < 0)
4232 Py_SIZE(z) = -(Py_SIZE(z));
4233 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4234 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4235 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004236 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 }
4238 z = long_normalize(z);
4239 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004240 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004242
Guido van Rossumc6913e71991-11-19 20:26:46 +00004243}
4244
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004245static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004246long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 /* This version due to Tim Peters */
4249 PyLongObject *a = (PyLongObject*)v;
4250 PyLongObject *b = (PyLongObject*)w;
4251 PyLongObject *z = NULL;
4252 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4253 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 shiftby = PyLong_AsSsize_t((PyObject *)b);
4258 if (shiftby == -1L && PyErr_Occurred())
Victor Stinner8aed6f12013-07-17 22:31:17 +02004259 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 if (shiftby < 0) {
4261 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004262 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004264
4265 if (Py_SIZE(a) == 0) {
4266 return PyLong_FromLong(0);
4267 }
4268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4270 wordshift = shiftby / PyLong_SHIFT;
4271 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004272
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004273 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 newsize = oldsize + wordshift;
4275 if (remshift)
4276 ++newsize;
4277 z = _PyLong_New(newsize);
4278 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004279 return NULL;
4280 if (Py_SIZE(a) < 0) {
4281 assert(Py_REFCNT(z) == 1);
4282 Py_SIZE(z) = -Py_SIZE(z);
4283 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 for (i = 0; i < wordshift; i++)
4285 z->ob_digit[i] = 0;
4286 accum = 0;
4287 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4288 accum |= (twodigits)a->ob_digit[j] << remshift;
4289 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4290 accum >>= PyLong_SHIFT;
4291 }
4292 if (remshift)
4293 z->ob_digit[newsize-1] = (digit)accum;
4294 else
4295 assert(!accum);
4296 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004298}
4299
Mark Dickinson27a87a22009-10-25 20:43:34 +00004300/* Compute two's complement of digit vector a[0:m], writing result to
4301 z[0:m]. The digit vector a need not be normalized, but should not
4302 be entirely zero. a and z may point to the same digit vector. */
4303
4304static void
4305v_complement(digit *z, digit *a, Py_ssize_t m)
4306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 Py_ssize_t i;
4308 digit carry = 1;
4309 for (i = 0; i < m; ++i) {
4310 carry += a[i] ^ PyLong_MASK;
4311 z[i] = carry & PyLong_MASK;
4312 carry >>= PyLong_SHIFT;
4313 }
4314 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004315}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004316
4317/* Bitwise and/xor/or operations */
4318
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004319static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004320long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004321 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004322 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 int nega, negb, negz;
4325 Py_ssize_t size_a, size_b, size_z, i;
4326 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 /* Bitwise operations for negative numbers operate as though
4329 on a two's complement representation. So convert arguments
4330 from sign-magnitude to two's complement, and convert the
4331 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004334 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 nega = Py_SIZE(a) < 0;
4336 if (nega) {
4337 z = _PyLong_New(size_a);
4338 if (z == NULL)
4339 return NULL;
4340 v_complement(z->ob_digit, a->ob_digit, size_a);
4341 a = z;
4342 }
4343 else
4344 /* Keep reference count consistent. */
4345 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004348 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 negb = Py_SIZE(b) < 0;
4350 if (negb) {
4351 z = _PyLong_New(size_b);
4352 if (z == NULL) {
4353 Py_DECREF(a);
4354 return NULL;
4355 }
4356 v_complement(z->ob_digit, b->ob_digit, size_b);
4357 b = z;
4358 }
4359 else
4360 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 /* Swap a and b if necessary to ensure size_a >= size_b. */
4363 if (size_a < size_b) {
4364 z = a; a = b; b = z;
4365 size_z = size_a; size_a = size_b; size_b = size_z;
4366 negz = nega; nega = negb; negb = negz;
4367 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 /* JRH: The original logic here was to allocate the result value (z)
4370 as the longer of the two operands. However, there are some cases
4371 where the result is guaranteed to be shorter than that: AND of two
4372 positives, OR of two negatives: use the shorter number. AND with
4373 mixed signs: use the positive number. OR with mixed signs: use the
4374 negative number.
4375 */
4376 switch (op) {
4377 case '^':
4378 negz = nega ^ negb;
4379 size_z = size_a;
4380 break;
4381 case '&':
4382 negz = nega & negb;
4383 size_z = negb ? size_a : size_b;
4384 break;
4385 case '|':
4386 negz = nega | negb;
4387 size_z = negb ? size_b : size_a;
4388 break;
4389 default:
4390 PyErr_BadArgument();
4391 return NULL;
4392 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004394 /* We allow an extra digit if z is negative, to make sure that
4395 the final two's complement of z doesn't overflow. */
4396 z = _PyLong_New(size_z + negz);
4397 if (z == NULL) {
4398 Py_DECREF(a);
4399 Py_DECREF(b);
4400 return NULL;
4401 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 /* Compute digits for overlap of a and b. */
4404 switch(op) {
4405 case '&':
4406 for (i = 0; i < size_b; ++i)
4407 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4408 break;
4409 case '|':
4410 for (i = 0; i < size_b; ++i)
4411 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4412 break;
4413 case '^':
4414 for (i = 0; i < size_b; ++i)
4415 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4416 break;
4417 default:
4418 PyErr_BadArgument();
4419 return NULL;
4420 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 /* Copy any remaining digits of a, inverting if necessary. */
4423 if (op == '^' && negb)
4424 for (; i < size_z; ++i)
4425 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4426 else if (i < size_z)
4427 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4428 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 /* Complement result if negative. */
4431 if (negz) {
4432 Py_SIZE(z) = -(Py_SIZE(z));
4433 z->ob_digit[size_z] = PyLong_MASK;
4434 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4435 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 Py_DECREF(a);
4438 Py_DECREF(b);
4439 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004440}
4441
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004442static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004443long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 PyObject *c;
4446 CHECK_BINOP(a, b);
4447 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4448 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004449}
4450
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004451static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004452long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 PyObject *c;
4455 CHECK_BINOP(a, b);
4456 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4457 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004458}
4459
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004460static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004461long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 PyObject *c;
4464 CHECK_BINOP(a, b);
4465 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4466 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004467}
4468
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004469static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004470long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 if (PyLong_CheckExact(v))
4473 Py_INCREF(v);
4474 else
4475 v = _PyLong_Copy((PyLongObject *)v);
4476 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004477}
4478
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004479PyObject *
4480_PyLong_GCD(PyObject *aarg, PyObject *barg)
4481{
4482 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4483 stwodigits x, y, q, s, t, c_carry, d_carry;
4484 stwodigits A, B, C, D, T;
4485 int nbits, k;
4486 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4487 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4488
4489 a = (PyLongObject *)aarg;
4490 b = (PyLongObject *)barg;
4491 size_a = Py_SIZE(a);
4492 size_b = Py_SIZE(b);
4493 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4494 Py_INCREF(a);
4495 Py_INCREF(b);
4496 goto simple;
4497 }
4498
4499 /* Initial reduction: make sure that 0 <= b <= a. */
4500 a = (PyLongObject *)long_abs(a);
4501 if (a == NULL)
4502 return NULL;
4503 b = (PyLongObject *)long_abs(b);
4504 if (b == NULL) {
4505 Py_DECREF(a);
4506 return NULL;
4507 }
4508 if (long_compare(a, b) < 0) {
4509 r = a;
4510 a = b;
4511 b = r;
4512 }
4513 /* We now own references to a and b */
4514
4515 alloc_a = Py_SIZE(a);
4516 alloc_b = Py_SIZE(b);
4517 /* reduce until a fits into 2 digits */
4518 while ((size_a = Py_SIZE(a)) > 2) {
4519 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4520 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4521 corresponding bits of b into y */
4522 size_b = Py_SIZE(b);
4523 assert(size_b <= size_a);
4524 if (size_b == 0) {
4525 if (size_a < alloc_a) {
4526 r = (PyLongObject *)_PyLong_Copy(a);
4527 Py_DECREF(a);
4528 }
4529 else
4530 r = a;
4531 Py_DECREF(b);
4532 Py_XDECREF(c);
4533 Py_XDECREF(d);
4534 return (PyObject *)r;
4535 }
4536 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4537 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4538 (a->ob_digit[size_a-3] >> nbits));
4539
4540 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4541 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4542 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4543
4544 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4545 larger than PyLong_MASK during the algorithm. */
4546 A = 1; B = 0; C = 0; D = 1;
4547 for (k=0;; k++) {
4548 if (y-C == 0)
4549 break;
4550 q = (x+(A-1))/(y-C);
4551 s = B+q*D;
4552 t = x-q*y;
4553 if (s > t)
4554 break;
4555 x = y; y = t;
4556 t = A+q*C; A = D; B = C; C = s; D = t;
4557 }
4558
4559 if (k == 0) {
4560 /* no progress; do a Euclidean step */
4561 if (l_divmod(a, b, NULL, &r) < 0)
4562 goto error;
4563 Py_DECREF(a);
4564 a = b;
4565 b = r;
4566 alloc_a = alloc_b;
4567 alloc_b = Py_SIZE(b);
4568 continue;
4569 }
4570
4571 /*
4572 a, b = A*b-B*a, D*a-C*b if k is odd
4573 a, b = A*a-B*b, D*b-C*a if k is even
4574 */
4575 if (k&1) {
4576 T = -A; A = -B; B = T;
4577 T = -C; C = -D; D = T;
4578 }
4579 if (c != NULL)
4580 Py_SIZE(c) = size_a;
4581 else if (Py_REFCNT(a) == 1) {
4582 Py_INCREF(a);
4583 c = a;
4584 }
4585 else {
4586 alloc_a = size_a;
4587 c = _PyLong_New(size_a);
4588 if (c == NULL)
4589 goto error;
4590 }
4591
4592 if (d != NULL)
4593 Py_SIZE(d) = size_a;
4594 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4595 Py_INCREF(b);
4596 d = b;
4597 Py_SIZE(d) = size_a;
4598 }
4599 else {
4600 alloc_b = size_a;
4601 d = _PyLong_New(size_a);
4602 if (d == NULL)
4603 goto error;
4604 }
4605 a_end = a->ob_digit + size_a;
4606 b_end = b->ob_digit + size_b;
4607
4608 /* compute new a and new b in parallel */
4609 a_digit = a->ob_digit;
4610 b_digit = b->ob_digit;
4611 c_digit = c->ob_digit;
4612 d_digit = d->ob_digit;
4613 c_carry = 0;
4614 d_carry = 0;
4615 while (b_digit < b_end) {
4616 c_carry += (A * *a_digit) - (B * *b_digit);
4617 d_carry += (D * *b_digit++) - (C * *a_digit++);
4618 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4619 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4620 c_carry >>= PyLong_SHIFT;
4621 d_carry >>= PyLong_SHIFT;
4622 }
4623 while (a_digit < a_end) {
4624 c_carry += A * *a_digit;
4625 d_carry -= C * *a_digit++;
4626 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4627 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4628 c_carry >>= PyLong_SHIFT;
4629 d_carry >>= PyLong_SHIFT;
4630 }
4631 assert(c_carry == 0);
4632 assert(d_carry == 0);
4633
4634 Py_INCREF(c);
4635 Py_INCREF(d);
4636 Py_DECREF(a);
4637 Py_DECREF(b);
4638 a = long_normalize(c);
4639 b = long_normalize(d);
4640 }
4641 Py_XDECREF(c);
4642 Py_XDECREF(d);
4643
4644simple:
4645 assert(Py_REFCNT(a) > 0);
4646 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004647/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4648 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4649#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004650 /* a fits into a long, so b must too */
4651 x = PyLong_AsLong((PyObject *)a);
4652 y = PyLong_AsLong((PyObject *)b);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004653#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004654 x = PyLong_AsLongLong((PyObject *)a);
4655 y = PyLong_AsLongLong((PyObject *)b);
4656#else
4657# error "_PyLong_GCD"
4658#endif
4659 x = Py_ABS(x);
4660 y = Py_ABS(y);
4661 Py_DECREF(a);
4662 Py_DECREF(b);
4663
4664 /* usual Euclidean algorithm for longs */
4665 while (y != 0) {
4666 t = y;
4667 y = x % y;
4668 x = t;
4669 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004670#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004671 return PyLong_FromLong(x);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004672#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004673 return PyLong_FromLongLong(x);
4674#else
4675# error "_PyLong_GCD"
4676#endif
4677
4678error:
4679 Py_DECREF(a);
4680 Py_DECREF(b);
4681 Py_XDECREF(c);
4682 Py_XDECREF(d);
4683 return NULL;
4684}
4685
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004686static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004687long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689 double result;
4690 result = PyLong_AsDouble(v);
4691 if (result == -1.0 && PyErr_Occurred())
4692 return NULL;
4693 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004694}
4695
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004696static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004697long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004698
Tim Peters6d6c1a32001-08-02 04:15:00 +00004699static PyObject *
4700long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4701{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004702 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004703 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 if (type != &PyLong_Type)
4707 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004708 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4709 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004711 if (x == NULL) {
4712 if (obase != NULL) {
4713 PyErr_SetString(PyExc_TypeError,
4714 "int() missing string argument");
4715 return NULL;
4716 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004718 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004719 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004721
Gregory P. Smitha689e522012-12-25 22:38:32 -08004722 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004723 if (base == -1 && PyErr_Occurred())
4724 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004725 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004726 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004727 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004728 return NULL;
4729 }
4730
4731 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004732 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 if (PyByteArray_Check(x))
4736 string = PyByteArray_AS_STRING(x);
4737 else
4738 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004739 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 }
4741 else {
4742 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004743 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004744 return NULL;
4745 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004746}
4747
Serhiy Storchaka95949422013-08-27 19:40:23 +03004748/* Wimpy, slow approach to tp_new calls for subtypes of int:
4749 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004750 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004751 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004752*/
4753static PyObject *
4754long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 PyLongObject *tmp, *newobj;
4757 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 assert(PyType_IsSubtype(type, &PyLong_Type));
4760 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4761 if (tmp == NULL)
4762 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02004763 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 n = Py_SIZE(tmp);
4765 if (n < 0)
4766 n = -n;
4767 newobj = (PyLongObject *)type->tp_alloc(type, n);
4768 if (newobj == NULL) {
4769 Py_DECREF(tmp);
4770 return NULL;
4771 }
4772 assert(PyLong_Check(newobj));
4773 Py_SIZE(newobj) = Py_SIZE(tmp);
4774 for (i = 0; i < n; i++)
4775 newobj->ob_digit[i] = tmp->ob_digit[i];
4776 Py_DECREF(tmp);
4777 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004778}
4779
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004780static PyObject *
4781long_getnewargs(PyLongObject *v)
4782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004783 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004784}
4785
Guido van Rossumb43daf72007-08-01 18:08:08 +00004786static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004787long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004789}
4790
4791static PyObject *
4792long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004794}
4795
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004796static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004797long__format__(PyObject *self, PyObject *args)
4798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004799 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004800 _PyUnicodeWriter writer;
4801 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4804 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004805
Victor Stinner8f674cc2013-04-17 23:02:17 +02004806 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004807 ret = _PyLong_FormatAdvancedWriter(
4808 &writer,
4809 self,
4810 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4811 if (ret == -1) {
4812 _PyUnicodeWriter_Dealloc(&writer);
4813 return NULL;
4814 }
4815 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004816}
4817
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004818/* Return a pair (q, r) such that a = b * q + r, and
4819 abs(r) <= abs(b)/2, with equality possible only if q is even.
4820 In other words, q == a / b, rounded to the nearest integer using
4821 round-half-to-even. */
4822
4823PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004824_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004825{
4826 PyLongObject *quo = NULL, *rem = NULL;
4827 PyObject *one = NULL, *twice_rem, *result, *temp;
4828 int cmp, quo_is_odd, quo_is_neg;
4829
4830 /* Equivalent Python code:
4831
4832 def divmod_near(a, b):
4833 q, r = divmod(a, b)
4834 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4835 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4836 # positive, 2 * r < b if b negative.
4837 greater_than_half = 2*r > b if b > 0 else 2*r < b
4838 exactly_half = 2*r == b
4839 if greater_than_half or exactly_half and q % 2 == 1:
4840 q += 1
4841 r -= b
4842 return q, r
4843
4844 */
4845 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4846 PyErr_SetString(PyExc_TypeError,
4847 "non-integer arguments in division");
4848 return NULL;
4849 }
4850
4851 /* Do a and b have different signs? If so, quotient is negative. */
4852 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4853
4854 one = PyLong_FromLong(1L);
4855 if (one == NULL)
4856 return NULL;
4857
4858 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4859 goto error;
4860
4861 /* compare twice the remainder with the divisor, to see
4862 if we need to adjust the quotient and remainder */
4863 twice_rem = long_lshift((PyObject *)rem, one);
4864 if (twice_rem == NULL)
4865 goto error;
4866 if (quo_is_neg) {
4867 temp = long_neg((PyLongObject*)twice_rem);
4868 Py_DECREF(twice_rem);
4869 twice_rem = temp;
4870 if (twice_rem == NULL)
4871 goto error;
4872 }
4873 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4874 Py_DECREF(twice_rem);
4875
4876 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4877 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4878 /* fix up quotient */
4879 if (quo_is_neg)
4880 temp = long_sub(quo, (PyLongObject *)one);
4881 else
4882 temp = long_add(quo, (PyLongObject *)one);
4883 Py_DECREF(quo);
4884 quo = (PyLongObject *)temp;
4885 if (quo == NULL)
4886 goto error;
4887 /* and remainder */
4888 if (quo_is_neg)
4889 temp = long_add(rem, (PyLongObject *)b);
4890 else
4891 temp = long_sub(rem, (PyLongObject *)b);
4892 Py_DECREF(rem);
4893 rem = (PyLongObject *)temp;
4894 if (rem == NULL)
4895 goto error;
4896 }
4897
4898 result = PyTuple_New(2);
4899 if (result == NULL)
4900 goto error;
4901
4902 /* PyTuple_SET_ITEM steals references */
4903 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4904 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4905 Py_DECREF(one);
4906 return result;
4907
4908 error:
4909 Py_XDECREF(quo);
4910 Py_XDECREF(rem);
4911 Py_XDECREF(one);
4912 return NULL;
4913}
4914
Eric Smith8c663262007-08-25 02:26:07 +00004915static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004916long_round(PyObject *self, PyObject *args)
4917{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004918 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004919
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004920 /* To round an integer m to the nearest 10**n (n positive), we make use of
4921 * the divmod_near operation, defined by:
4922 *
4923 * divmod_near(a, b) = (q, r)
4924 *
4925 * where q is the nearest integer to the quotient a / b (the
4926 * nearest even integer in the case of a tie) and r == a - q * b.
4927 * Hence q * b = a - r is the nearest multiple of b to a,
4928 * preferring even multiples in the case of a tie.
4929 *
4930 * So the nearest multiple of 10**n to m is:
4931 *
4932 * m - divmod_near(m, 10**n)[1].
4933 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4935 return NULL;
4936 if (o_ndigits == NULL)
4937 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004938
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004939 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004940 if (ndigits == NULL)
4941 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004942
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004943 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004944 if (Py_SIZE(ndigits) >= 0) {
4945 Py_DECREF(ndigits);
4946 return long_long(self);
4947 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004948
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004949 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4950 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004952 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004953 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004954 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004955
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004956 result = PyLong_FromLong(10L);
4957 if (result == NULL) {
4958 Py_DECREF(ndigits);
4959 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004961
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004962 temp = long_pow(result, ndigits, Py_None);
4963 Py_DECREF(ndigits);
4964 Py_DECREF(result);
4965 result = temp;
4966 if (result == NULL)
4967 return NULL;
4968
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004969 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004970 Py_DECREF(result);
4971 result = temp;
4972 if (result == NULL)
4973 return NULL;
4974
4975 temp = long_sub((PyLongObject *)self,
4976 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4977 Py_DECREF(result);
4978 result = temp;
4979
4980 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004981}
4982
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004983static PyObject *
4984long_sizeof(PyLongObject *v)
4985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004987
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004988 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(v))*sizeof(digit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004990}
4991
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004992static PyObject *
4993long_bit_length(PyLongObject *v)
4994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 PyLongObject *result, *x, *y;
4996 Py_ssize_t ndigits, msd_bits = 0;
4997 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 assert(v != NULL);
5000 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005001
Victor Stinner45e8e2f2014-05-14 17:24:35 +02005002 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 if (ndigits == 0)
5004 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005006 msd = v->ob_digit[ndigits-1];
5007 while (msd >= 32) {
5008 msd_bits += 6;
5009 msd >>= 6;
5010 }
5011 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5014 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 /* expression above may overflow; use Python integers instead */
5017 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5018 if (result == NULL)
5019 return NULL;
5020 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5021 if (x == NULL)
5022 goto error;
5023 y = (PyLongObject *)long_mul(result, x);
5024 Py_DECREF(x);
5025 if (y == NULL)
5026 goto error;
5027 Py_DECREF(result);
5028 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5031 if (x == NULL)
5032 goto error;
5033 y = (PyLongObject *)long_add(result, x);
5034 Py_DECREF(x);
5035 if (y == NULL)
5036 goto error;
5037 Py_DECREF(result);
5038 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005040 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005041
Mark Dickinson22b20182010-05-10 21:27:53 +00005042 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005043 Py_DECREF(result);
5044 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005045}
5046
5047PyDoc_STRVAR(long_bit_length_doc,
5048"int.bit_length() -> int\n\
5049\n\
5050Number of bits necessary to represent self in binary.\n\
5051>>> bin(37)\n\
5052'0b100101'\n\
5053>>> (37).bit_length()\n\
50546");
5055
Christian Heimes53876d92008-04-19 00:31:39 +00005056#if 0
5057static PyObject *
5058long_is_finite(PyObject *v)
5059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005061}
5062#endif
5063
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005064
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005065static PyObject *
5066long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
5067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005068 PyObject *byteorder_str;
5069 PyObject *is_signed_obj = NULL;
5070 Py_ssize_t length;
5071 int little_endian;
5072 int is_signed;
5073 PyObject *bytes;
5074 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
5077 &length, &byteorder_str,
5078 &is_signed_obj))
5079 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005081 if (args != NULL && Py_SIZE(args) > 2) {
5082 PyErr_SetString(PyExc_TypeError,
5083 "'signed' is a keyword-only argument");
5084 return NULL;
5085 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
5088 little_endian = 1;
5089 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
5090 little_endian = 0;
5091 else {
5092 PyErr_SetString(PyExc_ValueError,
5093 "byteorder must be either 'little' or 'big'");
5094 return NULL;
5095 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005097 if (is_signed_obj != NULL) {
5098 int cmp = PyObject_IsTrue(is_signed_obj);
5099 if (cmp < 0)
5100 return NULL;
5101 is_signed = cmp ? 1 : 0;
5102 }
5103 else {
5104 /* If the signed argument was omitted, use False as the
5105 default. */
5106 is_signed = 0;
5107 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 if (length < 0) {
5110 PyErr_SetString(PyExc_ValueError,
5111 "length argument must be non-negative");
5112 return NULL;
5113 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 bytes = PyBytes_FromStringAndSize(NULL, length);
5116 if (bytes == NULL)
5117 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
5120 length, little_endian, is_signed) < 0) {
5121 Py_DECREF(bytes);
5122 return NULL;
5123 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005126}
5127
Mark Dickinson078c2532010-01-30 18:06:17 +00005128PyDoc_STRVAR(long_to_bytes_doc,
5129"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005130\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005131Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005132\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005133The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005134raised if the integer is not representable with the given number of\n\
5135bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005136\n\
5137The byteorder argument determines the byte order used to represent the\n\
5138integer. If byteorder is 'big', the most significant byte is at the\n\
5139beginning of the byte array. If byteorder is 'little', the most\n\
5140significant byte is at the end of the byte array. To request the native\n\
5141byte order of the host system, use `sys.byteorder' as the byte order value.\n\
5142\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005143The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005144used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005145is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005146
5147static PyObject *
5148long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
5149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005150 PyObject *byteorder_str;
5151 PyObject *is_signed_obj = NULL;
5152 int little_endian;
5153 int is_signed;
5154 PyObject *obj;
5155 PyObject *bytes;
5156 PyObject *long_obj;
5157 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005159 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
5160 &obj, &byteorder_str,
5161 &is_signed_obj))
5162 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 if (args != NULL && Py_SIZE(args) > 2) {
5165 PyErr_SetString(PyExc_TypeError,
5166 "'signed' is a keyword-only argument");
5167 return NULL;
5168 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005170 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
5171 little_endian = 1;
5172 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
5173 little_endian = 0;
5174 else {
5175 PyErr_SetString(PyExc_ValueError,
5176 "byteorder must be either 'little' or 'big'");
5177 return NULL;
5178 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005180 if (is_signed_obj != NULL) {
5181 int cmp = PyObject_IsTrue(is_signed_obj);
5182 if (cmp < 0)
5183 return NULL;
5184 is_signed = cmp ? 1 : 0;
5185 }
5186 else {
5187 /* If the signed argument was omitted, use False as the
5188 default. */
5189 is_signed = 0;
5190 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 bytes = PyObject_Bytes(obj);
5193 if (bytes == NULL)
5194 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 long_obj = _PyLong_FromByteArray(
5197 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5198 little_endian, is_signed);
5199 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005200
Serhiy Storchakaea36c942016-05-12 10:37:58 +03005201 if (type != &PyLong_Type) {
5202 Py_SETREF(long_obj, PyObject_CallFunctionObjArgs((PyObject *)type,
5203 long_obj, NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005206 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005207}
5208
Mark Dickinson078c2532010-01-30 18:06:17 +00005209PyDoc_STRVAR(long_from_bytes_doc,
5210"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
5211\n\
5212Return the integer represented by the given array of bytes.\n\
5213\n\
R David Murray861470c2014-10-05 11:47:01 -04005214The bytes argument must be a bytes-like object (e.g. bytes or bytearray).\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005215\n\
5216The byteorder argument determines the byte order used to represent the\n\
5217integer. If byteorder is 'big', the most significant byte is at the\n\
5218beginning of the byte array. If byteorder is 'little', the most\n\
5219significant byte is at the end of the byte array. To request the native\n\
5220byte order of the host system, use `sys.byteorder' as the byte order value.\n\
5221\n\
5222The signed keyword-only argument indicates whether two's complement is\n\
5223used to represent the integer.");
5224
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005225static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005226 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
5227 "Returns self, the complex conjugate of any int."},
5228 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
5229 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00005230#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005231 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5232 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005233#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005234 {"to_bytes", (PyCFunction)long_to_bytes,
5235 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
5236 {"from_bytes", (PyCFunction)long_from_bytes,
5237 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
5238 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
5239 "Truncating an Integral returns itself."},
5240 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
5241 "Flooring an Integral returns itself."},
5242 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
5243 "Ceiling of an Integral returns itself."},
5244 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5245 "Rounding an Integral returns itself.\n"
5246 "Rounding with an ndigits argument also returns an integer."},
5247 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
5248 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
5249 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
5250 "Returns size in memory, in bytes"},
5251 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005252};
5253
Guido van Rossumb43daf72007-08-01 18:08:08 +00005254static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005255 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005256 (getter)long_long, (setter)NULL,
5257 "the real part of a complex number",
5258 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005259 {"imag",
5260 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005261 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005262 NULL},
5263 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005264 (getter)long_long, (setter)NULL,
5265 "the numerator of a rational number in lowest terms",
5266 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005267 {"denominator",
5268 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005269 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005270 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005271 {NULL} /* Sentinel */
5272};
5273
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005274PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005275"int(x=0) -> integer\n\
5276int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005277\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005278Convert a number or string to an integer, or return 0 if no arguments\n\
5279are given. If x is a number, return x.__int__(). For floating point\n\
5280numbers, this truncates towards zero.\n\
5281\n\
5282If x is not a number or if base is given, then x must be a string,\n\
5283bytes, or bytearray instance representing an integer literal in the\n\
5284given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5285by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5286Base 0 means to interpret the base from the string as an integer literal.\n\
5287>>> int('0b100', base=0)\n\
52884");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005289
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005290static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005291 (binaryfunc)long_add, /*nb_add*/
5292 (binaryfunc)long_sub, /*nb_subtract*/
5293 (binaryfunc)long_mul, /*nb_multiply*/
5294 long_mod, /*nb_remainder*/
5295 long_divmod, /*nb_divmod*/
5296 long_pow, /*nb_power*/
5297 (unaryfunc)long_neg, /*nb_negative*/
5298 (unaryfunc)long_long, /*tp_positive*/
5299 (unaryfunc)long_abs, /*tp_absolute*/
5300 (inquiry)long_bool, /*tp_bool*/
5301 (unaryfunc)long_invert, /*nb_invert*/
5302 long_lshift, /*nb_lshift*/
5303 (binaryfunc)long_rshift, /*nb_rshift*/
5304 long_and, /*nb_and*/
5305 long_xor, /*nb_xor*/
5306 long_or, /*nb_or*/
5307 long_long, /*nb_int*/
5308 0, /*nb_reserved*/
5309 long_float, /*nb_float*/
5310 0, /* nb_inplace_add */
5311 0, /* nb_inplace_subtract */
5312 0, /* nb_inplace_multiply */
5313 0, /* nb_inplace_remainder */
5314 0, /* nb_inplace_power */
5315 0, /* nb_inplace_lshift */
5316 0, /* nb_inplace_rshift */
5317 0, /* nb_inplace_and */
5318 0, /* nb_inplace_xor */
5319 0, /* nb_inplace_or */
5320 long_div, /* nb_floor_divide */
5321 long_true_divide, /* nb_true_divide */
5322 0, /* nb_inplace_floor_divide */
5323 0, /* nb_inplace_true_divide */
5324 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005325};
5326
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005327PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5329 "int", /* tp_name */
5330 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5331 sizeof(digit), /* tp_itemsize */
5332 long_dealloc, /* tp_dealloc */
5333 0, /* tp_print */
5334 0, /* tp_getattr */
5335 0, /* tp_setattr */
5336 0, /* tp_reserved */
5337 long_to_decimal_string, /* tp_repr */
5338 &long_as_number, /* tp_as_number */
5339 0, /* tp_as_sequence */
5340 0, /* tp_as_mapping */
5341 (hashfunc)long_hash, /* tp_hash */
5342 0, /* tp_call */
5343 long_to_decimal_string, /* tp_str */
5344 PyObject_GenericGetAttr, /* tp_getattro */
5345 0, /* tp_setattro */
5346 0, /* tp_as_buffer */
5347 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5348 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5349 long_doc, /* tp_doc */
5350 0, /* tp_traverse */
5351 0, /* tp_clear */
5352 long_richcompare, /* tp_richcompare */
5353 0, /* tp_weaklistoffset */
5354 0, /* tp_iter */
5355 0, /* tp_iternext */
5356 long_methods, /* tp_methods */
5357 0, /* tp_members */
5358 long_getset, /* tp_getset */
5359 0, /* tp_base */
5360 0, /* tp_dict */
5361 0, /* tp_descr_get */
5362 0, /* tp_descr_set */
5363 0, /* tp_dictoffset */
5364 0, /* tp_init */
5365 0, /* tp_alloc */
5366 long_new, /* tp_new */
5367 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005368};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005369
Mark Dickinsonbd792642009-03-18 20:06:12 +00005370static PyTypeObject Int_InfoType;
5371
5372PyDoc_STRVAR(int_info__doc__,
5373"sys.int_info\n\
5374\n\
5375A struct sequence that holds information about Python's\n\
5376internal representation of integers. The attributes are read only.");
5377
5378static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005380 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005382};
5383
5384static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 "sys.int_info", /* name */
5386 int_info__doc__, /* doc */
5387 int_info_fields, /* fields */
5388 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005389};
5390
5391PyObject *
5392PyLong_GetInfo(void)
5393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 PyObject* int_info;
5395 int field = 0;
5396 int_info = PyStructSequence_New(&Int_InfoType);
5397 if (int_info == NULL)
5398 return NULL;
5399 PyStructSequence_SET_ITEM(int_info, field++,
5400 PyLong_FromLong(PyLong_SHIFT));
5401 PyStructSequence_SET_ITEM(int_info, field++,
5402 PyLong_FromLong(sizeof(digit)));
5403 if (PyErr_Occurred()) {
5404 Py_CLEAR(int_info);
5405 return NULL;
5406 }
5407 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005408}
5409
Guido van Rossumddefaf32007-01-14 03:31:43 +00005410int
5411_PyLong_Init(void)
5412{
5413#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 int ival, size;
5415 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5418 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5419 if (Py_TYPE(v) == &PyLong_Type) {
5420 /* The element is already initialized, most likely
5421 * the Python interpreter was initialized before.
5422 */
5423 Py_ssize_t refcnt;
5424 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005426 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5427 _Py_NewReference(op);
5428 /* _Py_NewReference sets the ref count to 1 but
5429 * the ref count might be larger. Set the refcnt
5430 * to the original refcnt + 1 */
5431 Py_REFCNT(op) = refcnt + 1;
5432 assert(Py_SIZE(op) == size);
Victor Stinner12174a52014-08-15 23:17:38 +02005433 assert(v->ob_digit[0] == (digit)abs(ival));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005434 }
5435 else {
Christian Heimesd3afe782013-12-04 09:27:47 +01005436 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005437 }
5438 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005439 v->ob_digit[0] = (digit)abs(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005441#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005443 if (Int_InfoType.tp_name == NULL) {
5444 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5445 return 0;
5446 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005449}
5450
5451void
5452PyLong_Fini(void)
5453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005454 /* Integers are currently statically allocated. Py_DECREF is not
5455 needed, but Python must forget about the reference or multiple
5456 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005457#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 int i;
5459 PyLongObject *v = small_ints;
5460 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5461 _Py_DEC_REFTOTAL;
5462 _Py_ForgetReference((PyObject*)v);
5463 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005464#endif
5465}