blob: dc459fd01ea0c516d40ffa68e061fa6209a9140c [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
Eric Smith8c663262007-08-25 02:26:07 +00008#include "formatter_unicode.h"
9
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
13#define NSMALLPOSINTS 257
14#endif
15#ifndef NSMALLNEGINTS
16#define NSMALLNEGINTS 5
17#endif
18#if NSMALLNEGINTS + NSMALLPOSINTS > 0
19/* Small integers are preallocated in this array so that they
20 can be shared.
21 The integers that are preallocated are those in the range
22 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
23*/
24static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
25#ifdef COUNT_ALLOCS
26int quick_int_allocs, quick_neg_int_allocs;
27#endif
28
Guido van Rossum7eaf8222007-06-18 17:58:50 +000029static PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +000030get_small_int(int ival)
31{
32 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
33 Py_INCREF(v);
34#ifdef COUNT_ALLOCS
35 if (ival >= 0)
36 quick_int_allocs++;
37 else
38 quick_neg_int_allocs++;
39#endif
40 return v;
41}
42#define CHECK_SMALL_INT(ival) \
43 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
44 return get_small_int(ival); \
45 } while(0)
46
47#else
48#define CHECK_SMALL_INT(ival)
49#endif
50
Christian Heimes90aa7642007-12-19 02:45:37 +000051#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(x)->ob_digit[0] : (Py_SIZE(x) == 0 ? 0 : (x)->ob_digit[0]))
Guido van Rossumddefaf32007-01-14 03:31:43 +000052/* If a freshly-allocated long is already shared, it must
53 be a small integer, so negating it must go to PyLong_FromLong */
54#define NEGATE(x) \
Christian Heimes90aa7642007-12-19 02:45:37 +000055 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
Christian Heimes217cfd12007-12-02 14:31:20 +000056 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000057 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
58 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000059/* For long multiplication, use the O(N**2) school algorithm unless
60 * both operands contain more than KARATSUBA_CUTOFF digits (this
61 * being an internal Python long digit, in base BASE).
62 */
Tim Peters0973b992004-08-29 22:16:50 +000063#define KARATSUBA_CUTOFF 70
64#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000065
Tim Peters47e52ee2004-08-30 02:44:38 +000066/* For exponentiation, use the binary left-to-right algorithm
67 * unless the exponent contains more than FIVEARY_CUTOFF digits.
68 * In that case, do 5 bits at a time. The potential drawback is that
69 * a table of 2**5 intermediate results is computed.
70 */
71#define FIVEARY_CUTOFF 8
72
Guido van Rossume32e0141992-01-19 16:31:05 +000073#define ABS(x) ((x) < 0 ? -(x) : (x))
74
Tim Peters5af4e6c2002-08-12 02:31:19 +000075#undef MIN
76#undef MAX
77#define MAX(x, y) ((x) < (y) ? (y) : (x))
78#define MIN(x, y) ((x) > (y) ? (y) : (x))
79
Guido van Rossume32e0141992-01-19 16:31:05 +000080/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000081static PyLongObject *long_normalize(PyLongObject *);
82static PyLongObject *mul1(PyLongObject *, wdigit);
83static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000084static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Guido van Rossume32e0141992-01-19 16:31:05 +000085
Guido van Rossumc0b618a1997-05-02 03:12:38 +000086#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000087 if (--_Py_Ticker < 0) { \
88 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +000089 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000090 }
91
Guido van Rossumedcc38a1991-05-05 20:09:44 +000092/* Normalize (remove leading zeros from) a long int object.
93 Doesn't attempt to free the storage--in most cases, due to the nature
94 of the algorithms used, this could save at most be one word anyway. */
95
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000097long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000098{
Christian Heimes90aa7642007-12-19 02:45:37 +000099 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000100 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102 while (i > 0 && v->ob_digit[i-1] == 0)
103 --i;
104 if (i != j)
Christian Heimes90aa7642007-12-19 02:45:37 +0000105 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000106 return v;
107}
108
109/* Allocate a new long int object with size digits.
110 Return NULL and set exception if we run out of memory. */
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000113_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000114{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000115 PyLongObject *result;
116 /* Can't use sizeof(PyLongObject) here, since the
117 compiler takes padding at the end into account.
118 As the consequence, this would waste 2 bytes on
119 a 32-bit system, and 6 bytes on a 64-bit system.
120 This computation would be incorrect on systems
121 which have padding before the digits; with 16-bit
122 digits this should not happen. */
123 result = PyObject_MALLOC(sizeof(PyVarObject) +
124 size*sizeof(digit));
125 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126 PyErr_NoMemory();
127 return NULL;
128 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000129 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000130}
131
Tim Peters64b5ce32001-09-10 20:52:51 +0000132PyObject *
133_PyLong_Copy(PyLongObject *src)
134{
135 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000136 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000137
138 assert(src != NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +0000139 i = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000140 if (i < 0)
141 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000142 if (i < 2) {
143 int ival = src->ob_digit[0];
Christian Heimes90aa7642007-12-19 02:45:37 +0000144 if (Py_SIZE(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000145 ival = -ival;
146 CHECK_SMALL_INT(ival);
147 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000148 result = _PyLong_New(i);
149 if (result != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000150 Py_SIZE(result) = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000151 while (--i >= 0)
152 result->ob_digit[i] = src->ob_digit[i];
153 }
154 return (PyObject *)result;
155}
156
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000157/* Create a new long int object from a C long int */
158
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000160PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000161{
Tim Petersce9de2f2001-06-14 04:56:19 +0000162 PyLongObject *v;
163 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
164 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000165 int sign = 1;
166
167 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000168
169 if (ival < 0) {
170 ival = -ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000171 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000172 }
173
Guido van Rossumddefaf32007-01-14 03:31:43 +0000174 /* Fast path for single-digits ints */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000175 if (!(ival>>PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000176 v = _PyLong_New(1);
177 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000178 Py_SIZE(v) = sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000179 v->ob_digit[0] = ival;
180 }
181 return (PyObject*)v;
182 }
183
184 /* 2 digits */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000185 if (!(ival >> 2*PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000186 v = _PyLong_New(2);
187 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000188 Py_SIZE(v) = 2*sign;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000189 v->ob_digit[0] = (digit)ival & PyLong_MASK;
190 v->ob_digit[1] = ival >> PyLong_SHIFT;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000191 }
192 return (PyObject*)v;
193 }
194
195 /* Larger numbers: loop to determine number of digits */
Tim Petersce9de2f2001-06-14 04:56:19 +0000196 t = (unsigned long)ival;
197 while (t) {
198 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000199 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000200 }
201 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000202 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000203 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000204 Py_SIZE(v) = ndigits*sign;
Tim Petersce9de2f2001-06-14 04:56:19 +0000205 t = (unsigned long)ival;
206 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000207 *p++ = (digit)(t & PyLong_MASK);
208 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000209 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000210 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000212}
213
Guido van Rossum53756b11997-01-03 17:14:46 +0000214/* Create a new long int object from a C unsigned long int */
215
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000216PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000217PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000218{
Tim Petersce9de2f2001-06-14 04:56:19 +0000219 PyLongObject *v;
220 unsigned long t;
221 int ndigits = 0;
222
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000223 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000224 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000225 /* Count the number of Python digits. */
226 t = (unsigned long)ival;
227 while (t) {
228 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000229 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000230 }
231 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000232 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000233 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000234 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000235 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000236 *p++ = (digit)(ival & PyLong_MASK);
237 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000238 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000239 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000240 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000241}
242
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000243/* Create a new long int object from a C double */
244
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000245PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000247{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000248 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000249 double frac;
250 int i, ndig, expo, neg;
251 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000252 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000253 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000254 "cannot convert float infinity to int");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000255 return NULL;
256 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000257 if (dval < 0.0) {
258 neg = 1;
259 dval = -dval;
260 }
261 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
262 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000263 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000264 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000265 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000266 if (v == NULL)
267 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000268 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269 for (i = ndig; --i >= 0; ) {
270 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000271 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000272 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000273 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000274 }
275 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000276 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000277 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000278}
279
Thomas Wouters89f507f2006-12-13 04:49:30 +0000280/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
281 * anything about what happens when a signed integer operation overflows,
282 * and some compilers think they're doing you a favor by being "clever"
283 * then. The bit pattern for the largest postive signed long is
284 * (unsigned long)LONG_MAX, and for the smallest negative signed long
285 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
286 * However, some other compilers warn about applying unary minus to an
287 * unsigned operand. Hence the weird "0-".
288 */
289#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
290#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
291
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000292/* Get a C long int from a long int object.
293 Returns -1 and sets an error condition if overflow occurs. */
294
295long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000296PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000297{
Guido van Rossumf7531811998-05-26 14:33:37 +0000298 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000300 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000301 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000302 Py_ssize_t i;
303 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000304 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000305
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000306 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000307 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000309 return -1;
310 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000311
312 if (!PyLong_Check(vv)) {
313 PyNumberMethods *nb;
314 if ((nb = vv->ob_type->tp_as_number) == NULL ||
315 nb->nb_int == NULL) {
316 PyErr_SetString(PyExc_TypeError, "an integer is required");
317 return -1;
318 }
319 vv = (*nb->nb_int) (vv);
320 if (vv == NULL)
321 return -1;
322 do_decref = 1;
323 if (!PyLong_Check(vv)) {
324 Py_DECREF(vv);
325 PyErr_SetString(PyExc_TypeError,
326 "nb_int should return int object");
327 return -1;
328 }
329 }
330
Georg Brandl61c31b02007-02-26 14:46:30 +0000331 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000332 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000333 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000334
Georg Brandl61c31b02007-02-26 14:46:30 +0000335 switch (i) {
336 case -1:
337 res = -v->ob_digit[0];
338 break;
339 case 0:
340 res = 0;
341 break;
342 case 1:
343 res = v->ob_digit[0];
344 break;
345 default:
346 sign = 1;
347 x = 0;
348 if (i < 0) {
349 sign = -1;
350 i = -(i);
351 }
352 while (--i >= 0) {
353 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000354 x = (x << PyLong_SHIFT) + v->ob_digit[i];
355 if ((x >> PyLong_SHIFT) != prev) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000356 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000357 goto exit;
358 }
359 }
360 /* Haven't lost any bits, but casting to long requires extra care
361 * (see comment above).
362 */
363 if (x <= (unsigned long)LONG_MAX) {
364 res = (long)x * sign;
365 }
366 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
367 res = LONG_MIN;
368 }
369 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000370 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000371 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000372 }
373 }
374 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000375 if (do_decref) {
376 Py_DECREF(vv);
377 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000378 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000379}
380
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000381long
382PyLong_AsLong(PyObject *obj)
383{
384 int overflow;
385 long result = PyLong_AsLongAndOverflow(obj, &overflow);
386 if (overflow) {
387 /* XXX: could be cute and give a different
388 message for overflow == -1 */
389 PyErr_SetString(PyExc_OverflowError,
390 "Python int too large to convert to C long");
391 }
392 return result;
393}
394
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000395/* Get a Py_ssize_t from a long int object.
396 Returns -1 and sets an error condition if overflow occurs. */
397
398Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000399PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000400 register PyLongObject *v;
401 size_t x, prev;
402 Py_ssize_t i;
403 int sign;
404
405 if (vv == NULL || !PyLong_Check(vv)) {
406 PyErr_BadInternalCall();
407 return -1;
408 }
409 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000410 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000411 switch (i) {
412 case -1: return -v->ob_digit[0];
413 case 0: return 0;
414 case 1: return v->ob_digit[0];
415 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000416 sign = 1;
417 x = 0;
418 if (i < 0) {
419 sign = -1;
420 i = -(i);
421 }
422 while (--i >= 0) {
423 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000424 x = (x << PyLong_SHIFT) + v->ob_digit[i];
425 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000426 goto overflow;
427 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000428 /* Haven't lost any bits, but casting to a signed type requires
429 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000430 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000431 if (x <= (size_t)PY_SSIZE_T_MAX) {
432 return (Py_ssize_t)x * sign;
433 }
434 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
435 return PY_SSIZE_T_MIN;
436 }
437 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000438
439 overflow:
440 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000441 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000442 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000443}
444
Guido van Rossumd8c80482002-08-13 00:24:58 +0000445/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000446 Returns -1 and sets an error condition if overflow occurs. */
447
448unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000449PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000450{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000451 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000452 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000453 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000454
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455 if (vv == NULL || !PyLong_Check(vv)) {
456 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000457 return (unsigned long) -1;
458 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000459 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000460 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000461 x = 0;
462 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000463 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000464 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000465 return (unsigned long) -1;
466 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000467 switch (i) {
468 case 0: return 0;
469 case 1: return v->ob_digit[0];
470 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000471 while (--i >= 0) {
472 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000473 x = (x << PyLong_SHIFT) + v->ob_digit[i];
474 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000475 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000476 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000477 return (unsigned long) -1;
478 }
479 }
480 return x;
481}
482
483/* Get a C unsigned long int from a long int object.
484 Returns -1 and sets an error condition if overflow occurs. */
485
486size_t
487PyLong_AsSize_t(PyObject *vv)
488{
489 register PyLongObject *v;
490 size_t x, prev;
491 Py_ssize_t i;
492
493 if (vv == NULL || !PyLong_Check(vv)) {
494 PyErr_BadInternalCall();
495 return (unsigned long) -1;
496 }
497 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000498 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000499 x = 0;
500 if (i < 0) {
501 PyErr_SetString(PyExc_OverflowError,
502 "can't convert negative value to size_t");
503 return (size_t) -1;
504 }
505 switch (i) {
506 case 0: return 0;
507 case 1: return v->ob_digit[0];
508 }
509 while (--i >= 0) {
510 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000511 x = (x << PyLong_SHIFT) + v->ob_digit[i];
512 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000513 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000514 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000515 return (unsigned long) -1;
516 }
517 }
518 return x;
519}
520
Thomas Hellera4ea6032003-04-17 18:55:45 +0000521/* Get a C unsigned long int from a long int object, ignoring the high bits.
522 Returns -1 and sets an error condition if an error occurs. */
523
Guido van Rossumddefaf32007-01-14 03:31:43 +0000524static unsigned long
525_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000526{
527 register PyLongObject *v;
528 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000529 Py_ssize_t i;
530 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000531
532 if (vv == NULL || !PyLong_Check(vv)) {
533 PyErr_BadInternalCall();
534 return (unsigned long) -1;
535 }
536 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000537 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000538 switch (i) {
539 case 0: return 0;
540 case 1: return v->ob_digit[0];
541 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000542 sign = 1;
543 x = 0;
544 if (i < 0) {
545 sign = -1;
546 i = -i;
547 }
548 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000549 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000550 }
551 return x * sign;
552}
553
Guido van Rossumddefaf32007-01-14 03:31:43 +0000554unsigned long
555PyLong_AsUnsignedLongMask(register PyObject *op)
556{
557 PyNumberMethods *nb;
558 PyLongObject *lo;
559 unsigned long val;
560
561 if (op && PyLong_Check(op))
562 return _PyLong_AsUnsignedLongMask(op);
563
564 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
565 nb->nb_int == NULL) {
566 PyErr_SetString(PyExc_TypeError, "an integer is required");
567 return (unsigned long)-1;
568 }
569
570 lo = (PyLongObject*) (*nb->nb_int) (op);
571 if (lo == NULL)
572 return (unsigned long)-1;
573 if (PyLong_Check(lo)) {
574 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
575 Py_DECREF(lo);
576 if (PyErr_Occurred())
577 return (unsigned long)-1;
578 return val;
579 }
580 else
581 {
582 Py_DECREF(lo);
583 PyErr_SetString(PyExc_TypeError,
584 "nb_int should return int object");
585 return (unsigned long)-1;
586 }
587}
588
Tim Peters5b8132f2003-01-31 15:52:05 +0000589int
590_PyLong_Sign(PyObject *vv)
591{
592 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000593
594 assert(v != NULL);
595 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000596
Christian Heimes90aa7642007-12-19 02:45:37 +0000597 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000598}
599
Tim Petersbaefd9e2003-01-28 20:37:45 +0000600size_t
601_PyLong_NumBits(PyObject *vv)
602{
603 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000604 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000605 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000606
607 assert(v != NULL);
608 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000609 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000610 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
611 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000612 digit msd = v->ob_digit[ndigits - 1];
613
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000614 result = (ndigits - 1) * PyLong_SHIFT;
615 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000616 goto Overflow;
617 do {
618 ++result;
619 if (result == 0)
620 goto Overflow;
621 msd >>= 1;
622 } while (msd);
623 }
624 return result;
625
626Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000627 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000628 "to express in a platform size_t");
629 return (size_t)-1;
630}
631
Tim Peters2a9b3672001-06-11 21:23:58 +0000632PyObject *
633_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
634 int little_endian, int is_signed)
635{
636 const unsigned char* pstartbyte;/* LSB of bytes */
637 int incr; /* direction to move pstartbyte */
638 const unsigned char* pendbyte; /* MSB of bytes */
639 size_t numsignificantbytes; /* number of bytes that matter */
640 size_t ndigits; /* number of Python long digits */
641 PyLongObject* v; /* result */
642 int idigit = 0; /* next free index in v->ob_digit */
643
644 if (n == 0)
645 return PyLong_FromLong(0L);
646
647 if (little_endian) {
648 pstartbyte = bytes;
649 pendbyte = bytes + n - 1;
650 incr = 1;
651 }
652 else {
653 pstartbyte = bytes + n - 1;
654 pendbyte = bytes;
655 incr = -1;
656 }
657
658 if (is_signed)
659 is_signed = *pendbyte >= 0x80;
660
661 /* Compute numsignificantbytes. This consists of finding the most
662 significant byte. Leading 0 bytes are insignficant if the number
663 is positive, and leading 0xff bytes if negative. */
664 {
665 size_t i;
666 const unsigned char* p = pendbyte;
667 const int pincr = -incr; /* search MSB to LSB */
668 const unsigned char insignficant = is_signed ? 0xff : 0x00;
669
670 for (i = 0; i < n; ++i, p += pincr) {
671 if (*p != insignficant)
672 break;
673 }
674 numsignificantbytes = n - i;
675 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
676 actually has 2 significant bytes. OTOH, 0xff0001 ==
677 -0x00ffff, so we wouldn't *need* to bump it there; but we
678 do for 0xffff = -0x0001. To be safe without bothering to
679 check every case, bump it regardless. */
680 if (is_signed && numsignificantbytes < n)
681 ++numsignificantbytes;
682 }
683
684 /* How many Python long digits do we need? We have
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000685 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000686 bits, so it's the ceiling of the quotient. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000687 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000688 if (ndigits > (size_t)INT_MAX)
689 return PyErr_NoMemory();
690 v = _PyLong_New((int)ndigits);
691 if (v == NULL)
692 return NULL;
693
694 /* Copy the bits over. The tricky parts are computing 2's-comp on
695 the fly for signed numbers, and dealing with the mismatch between
696 8-bit bytes and (probably) 15-bit Python digits.*/
697 {
698 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000699 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000700 twodigits accum = 0; /* sliding register */
701 unsigned int accumbits = 0; /* number of bits in accum */
702 const unsigned char* p = pstartbyte;
703
704 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000705 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000706 /* Compute correction for 2's comp, if needed. */
707 if (is_signed) {
708 thisbyte = (0xff ^ thisbyte) + carry;
709 carry = thisbyte >> 8;
710 thisbyte &= 0xff;
711 }
712 /* Because we're going LSB to MSB, thisbyte is
713 more significant than what's already in accum,
714 so needs to be prepended to accum. */
715 accum |= thisbyte << accumbits;
716 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000717 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000718 /* There's enough to fill a Python digit. */
719 assert(idigit < (int)ndigits);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000720 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000721 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000722 accum >>= PyLong_SHIFT;
723 accumbits -= PyLong_SHIFT;
724 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000725 }
726 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000727 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000728 if (accumbits) {
729 assert(idigit < (int)ndigits);
730 v->ob_digit[idigit] = (digit)accum;
731 ++idigit;
732 }
733 }
734
Christian Heimes90aa7642007-12-19 02:45:37 +0000735 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000736 return (PyObject *)long_normalize(v);
737}
738
739int
740_PyLong_AsByteArray(PyLongObject* v,
741 unsigned char* bytes, size_t n,
742 int little_endian, int is_signed)
743{
744 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000745 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000746 twodigits accum; /* sliding register */
747 unsigned int accumbits; /* # bits in accum */
748 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
749 twodigits carry; /* for computing 2's-comp */
750 size_t j; /* # bytes filled */
751 unsigned char* p; /* pointer to next byte in bytes */
752 int pincr; /* direction to move p */
753
754 assert(v != NULL && PyLong_Check(v));
755
Christian Heimes90aa7642007-12-19 02:45:37 +0000756 if (Py_SIZE(v) < 0) {
757 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000758 if (!is_signed) {
759 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000760 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000761 return -1;
762 }
763 do_twos_comp = 1;
764 }
765 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000766 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000767 do_twos_comp = 0;
768 }
769
770 if (little_endian) {
771 p = bytes;
772 pincr = 1;
773 }
774 else {
775 p = bytes + n - 1;
776 pincr = -1;
777 }
778
Tim Peters898cf852001-06-13 20:50:08 +0000779 /* Copy over all the Python digits.
780 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000781 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000782 normalized. */
783 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000784 j = 0;
785 accum = 0;
786 accumbits = 0;
787 carry = do_twos_comp ? 1 : 0;
788 for (i = 0; i < ndigits; ++i) {
789 twodigits thisdigit = v->ob_digit[i];
790 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000791 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
792 carry = thisdigit >> PyLong_SHIFT;
793 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000794 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000795 /* Because we're going LSB to MSB, thisdigit is more
796 significant than what's already in accum, so needs to be
797 prepended to accum. */
798 accum |= thisdigit << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000799 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000800
Tim Petersede05092001-06-14 08:53:38 +0000801 /* The most-significant digit may be (probably is) at least
802 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000803 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000804 /* Count # of sign bits -- they needn't be stored,
805 * although for signed conversion we need later to
806 * make sure at least one sign bit gets stored.
807 * First shift conceptual sign bit to real sign bit.
808 */
809 stwodigits s = (stwodigits)(thisdigit <<
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000810 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000811 unsigned int nsignbits = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000812 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000813 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000814 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000815 }
Tim Petersede05092001-06-14 08:53:38 +0000816 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000817 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000818
Tim Peters2a9b3672001-06-11 21:23:58 +0000819 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000820 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000821 if (j >= n)
822 goto Overflow;
823 ++j;
824 *p = (unsigned char)(accum & 0xff);
825 p += pincr;
826 accumbits -= 8;
827 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000828 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000829 }
830
831 /* Store the straggler (if any). */
832 assert(accumbits < 8);
833 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000834 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000835 if (j >= n)
836 goto Overflow;
837 ++j;
838 if (do_twos_comp) {
839 /* Fill leading bits of the byte with sign bits
840 (appropriately pretending that the long had an
841 infinite supply of sign bits). */
842 accum |= (~(twodigits)0) << accumbits;
843 }
844 *p = (unsigned char)(accum & 0xff);
845 p += pincr;
846 }
Tim Peters05607ad2001-06-13 21:01:27 +0000847 else if (j == n && n > 0 && is_signed) {
848 /* The main loop filled the byte array exactly, so the code
849 just above didn't get to ensure there's a sign bit, and the
850 loop below wouldn't add one either. Make sure a sign bit
851 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000852 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000853 int sign_bit_set = msb >= 0x80;
854 assert(accumbits == 0);
855 if (sign_bit_set == do_twos_comp)
856 return 0;
857 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000858 goto Overflow;
859 }
Tim Peters05607ad2001-06-13 21:01:27 +0000860
861 /* Fill remaining bytes with copies of the sign bit. */
862 {
863 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
864 for ( ; j < n; ++j, p += pincr)
865 *p = signbyte;
866 }
867
Tim Peters2a9b3672001-06-11 21:23:58 +0000868 return 0;
869
870Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000871 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000872 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000873
Tim Peters2a9b3672001-06-11 21:23:58 +0000874}
875
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000876double
877_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
878{
879/* NBITS_WANTED should be > the number of bits in a double's precision,
880 but small enough so that 2**NBITS_WANTED is within the normal double
881 range. nbitsneeded is set to 1 less than that because the most-significant
882 Python digit contains at least 1 significant bit, but we don't want to
883 bother counting them (catering to the worst case cheaply).
884
885 57 is one more than VAX-D double precision; I (Tim) don't know of a double
886 format with more precision than that; it's 1 larger so that we add in at
887 least one round bit to stand in for the ignored least-significant bits.
888*/
889#define NBITS_WANTED 57
890 PyLongObject *v;
891 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000892 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000893 Py_ssize_t i;
894 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000895 int nbitsneeded;
896
897 if (vv == NULL || !PyLong_Check(vv)) {
898 PyErr_BadInternalCall();
899 return -1;
900 }
901 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000902 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000903 sign = 1;
904 if (i < 0) {
905 sign = -1;
906 i = -(i);
907 }
908 else if (i == 0) {
909 *exponent = 0;
910 return 0.0;
911 }
912 --i;
913 x = (double)v->ob_digit[i];
914 nbitsneeded = NBITS_WANTED - 1;
915 /* Invariant: i Python digits remain unaccounted for. */
916 while (i > 0 && nbitsneeded > 0) {
917 --i;
918 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000919 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000920 }
921 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000922 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000923 *exponent = i;
924 assert(x > 0.0);
925 return x * sign;
926#undef NBITS_WANTED
927}
928
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000929/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000930
931double
Tim Peters9f688bf2000-07-07 15:53:28 +0000932PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000933{
Thomas Wouters553489a2006-02-01 21:32:04 +0000934 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000935 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000936
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000937 if (vv == NULL || !PyLong_Check(vv)) {
938 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000939 return -1;
940 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000941 x = _PyLong_AsScaledDouble(vv, &e);
942 if (x == -1.0 && PyErr_Occurred())
943 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000944 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
945 set correctly after a successful _PyLong_AsScaledDouble() call */
946 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000947 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000948 goto overflow;
949 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000950 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000951 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000952 goto overflow;
953 return x;
954
955overflow:
956 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000957 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000958 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000959}
960
Guido van Rossum78694d91998-09-18 14:14:13 +0000961/* Create a new long (or int) object from a C pointer */
962
963PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000964PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000965{
Tim Peters70128a12001-06-16 08:48:40 +0000966#ifndef HAVE_LONG_LONG
967# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
968#endif
969#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000970# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000971#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000972 /* special-case null pointer */
973 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +0000974 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000975 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000976
Guido van Rossum78694d91998-09-18 14:14:13 +0000977}
978
979/* Get a C pointer from a long object (or an int object in some cases) */
980
981void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000982PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000983{
984 /* This function will allow int or long objects. If vv is neither,
985 then the PyLong_AsLong*() functions will raise the exception:
986 PyExc_SystemError, "bad argument to internal function"
987 */
Tim Peters70128a12001-06-16 08:48:40 +0000988#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000989 long x;
990
Guido van Rossumddefaf32007-01-14 03:31:43 +0000991 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000992 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000993 else
994 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000995#else
Tim Peters70128a12001-06-16 08:48:40 +0000996
997#ifndef HAVE_LONG_LONG
998# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
999#endif
1000#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001001# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001002#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001003 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001004
Guido van Rossumddefaf32007-01-14 03:31:43 +00001005 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001006 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001007 else
1008 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001009
1010#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001011
1012 if (x == -1 && PyErr_Occurred())
1013 return NULL;
1014 return (void *)x;
1015}
1016
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001017#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001018
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001019/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001020 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001021 */
1022
Tim Peterscf37dfc2001-06-14 18:42:50 +00001023#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001024
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001025/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001026
1027PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001028PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001029{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001030 PyLongObject *v;
1031 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1032 int ndigits = 0;
1033 int negative = 0;
1034
Guido van Rossumddefaf32007-01-14 03:31:43 +00001035 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001036 if (ival < 0) {
1037 ival = -ival;
1038 negative = 1;
1039 }
1040
1041 /* Count the number of Python digits.
1042 We used to pick 5 ("big enough for anything"), but that's a
1043 waste of time and space given that 5*15 = 75 bits are rarely
1044 needed. */
1045 t = (unsigned PY_LONG_LONG)ival;
1046 while (t) {
1047 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001048 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049 }
1050 v = _PyLong_New(ndigits);
1051 if (v != NULL) {
1052 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001053 Py_SIZE(v) = negative ? -ndigits : ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001054 t = (unsigned PY_LONG_LONG)ival;
1055 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001056 *p++ = (digit)(t & PyLong_MASK);
1057 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001058 }
1059 }
1060 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001061}
1062
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001063/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001064
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001065PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001066PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001067{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001068 PyLongObject *v;
1069 unsigned PY_LONG_LONG t;
1070 int ndigits = 0;
1071
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001072 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001073 return PyLong_FromLong(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001074 /* Count the number of Python digits. */
1075 t = (unsigned PY_LONG_LONG)ival;
1076 while (t) {
1077 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001078 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079 }
1080 v = _PyLong_New(ndigits);
1081 if (v != NULL) {
1082 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001083 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001085 *p++ = (digit)(ival & PyLong_MASK);
1086 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001087 }
1088 }
1089 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001090}
1091
Martin v. Löwis18e16552006-02-15 17:27:45 +00001092/* Create a new long int object from a C Py_ssize_t. */
1093
1094PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001095PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001096{
1097 Py_ssize_t bytes = ival;
1098 int one = 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001099 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001100 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001101 return _PyLong_FromByteArray(
1102 (unsigned char *)&bytes,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001103 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001104}
1105
1106/* Create a new long int object from a C size_t. */
1107
1108PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001109PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001110{
1111 size_t bytes = ival;
1112 int one = 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001113 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001114 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001115 return _PyLong_FromByteArray(
1116 (unsigned char *)&bytes,
1117 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
1118}
1119
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001120/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001121 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001122
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001123PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001124PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001125{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001126 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001127 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001128 int one = 1;
1129 int res;
1130
Tim Petersd38b1c72001-09-30 05:09:37 +00001131 if (vv == NULL) {
1132 PyErr_BadInternalCall();
1133 return -1;
1134 }
1135 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001136 PyNumberMethods *nb;
1137 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001138 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1139 nb->nb_int == NULL) {
1140 PyErr_SetString(PyExc_TypeError, "an integer is required");
1141 return -1;
1142 }
1143 io = (*nb->nb_int) (vv);
1144 if (io == NULL)
1145 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001146 if (PyLong_Check(io)) {
1147 bytes = PyLong_AsLongLong(io);
1148 Py_DECREF(io);
1149 return bytes;
1150 }
1151 Py_DECREF(io);
1152 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001153 return -1;
1154 }
1155
Guido van Rossumddefaf32007-01-14 03:31:43 +00001156 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001157 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001158 case -1: return -v->ob_digit[0];
1159 case 0: return 0;
1160 case 1: return v->ob_digit[0];
1161 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001162 res = _PyLong_AsByteArray(
1163 (PyLongObject *)vv, (unsigned char *)&bytes,
1164 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001165
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001166 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001167 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001168 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001169 else
1170 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001171}
1172
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001173/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001174 Return -1 and set an error if overflow occurs. */
1175
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001176unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001177PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001178{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001179 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001180 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001181 int one = 1;
1182 int res;
1183
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001184 if (vv == NULL || !PyLong_Check(vv)) {
1185 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001186 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001187 }
1188
Guido van Rossumddefaf32007-01-14 03:31:43 +00001189 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001190 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001191 case 0: return 0;
1192 case 1: return v->ob_digit[0];
1193 }
1194
Tim Petersd1a7da62001-06-13 00:35:57 +00001195 res = _PyLong_AsByteArray(
1196 (PyLongObject *)vv, (unsigned char *)&bytes,
1197 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001198
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001199 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001200 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001201 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001202 else
1203 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001204}
Tim Petersd1a7da62001-06-13 00:35:57 +00001205
Thomas Hellera4ea6032003-04-17 18:55:45 +00001206/* Get a C unsigned long int from a long int object, ignoring the high bits.
1207 Returns -1 and sets an error condition if an error occurs. */
1208
Guido van Rossumddefaf32007-01-14 03:31:43 +00001209static unsigned PY_LONG_LONG
1210_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001211{
1212 register PyLongObject *v;
1213 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001214 Py_ssize_t i;
1215 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001216
1217 if (vv == NULL || !PyLong_Check(vv)) {
1218 PyErr_BadInternalCall();
1219 return (unsigned long) -1;
1220 }
1221 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001222 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001223 case 0: return 0;
1224 case 1: return v->ob_digit[0];
1225 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001226 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001227 sign = 1;
1228 x = 0;
1229 if (i < 0) {
1230 sign = -1;
1231 i = -i;
1232 }
1233 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001234 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001235 }
1236 return x * sign;
1237}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001238
1239unsigned PY_LONG_LONG
1240PyLong_AsUnsignedLongLongMask(register PyObject *op)
1241{
1242 PyNumberMethods *nb;
1243 PyLongObject *lo;
1244 unsigned PY_LONG_LONG val;
1245
1246 if (op && PyLong_Check(op))
1247 return _PyLong_AsUnsignedLongLongMask(op);
1248
1249 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1250 nb->nb_int == NULL) {
1251 PyErr_SetString(PyExc_TypeError, "an integer is required");
1252 return (unsigned PY_LONG_LONG)-1;
1253 }
1254
1255 lo = (PyLongObject*) (*nb->nb_int) (op);
1256 if (lo == NULL)
1257 return (unsigned PY_LONG_LONG)-1;
1258 if (PyLong_Check(lo)) {
1259 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1260 Py_DECREF(lo);
1261 if (PyErr_Occurred())
1262 return (unsigned PY_LONG_LONG)-1;
1263 return val;
1264 }
1265 else
1266 {
1267 Py_DECREF(lo);
1268 PyErr_SetString(PyExc_TypeError,
1269 "nb_int should return int object");
1270 return (unsigned PY_LONG_LONG)-1;
1271 }
1272}
Tim Petersd1a7da62001-06-13 00:35:57 +00001273#undef IS_LITTLE_ENDIAN
1274
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001275#endif /* HAVE_LONG_LONG */
1276
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001277#define CHECK_BINOP(v,w) \
1278 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001279 Py_INCREF(Py_NotImplemented); \
1280 return Py_NotImplemented; \
1281 }
1282
Tim Peters877a2122002-08-12 05:09:36 +00001283/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1284 * is modified in place, by adding y to it. Carries are propagated as far as
1285 * x[m-1], and the remaining carry (0 or 1) is returned.
1286 */
1287static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001288v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001289{
1290 int i;
1291 digit carry = 0;
1292
1293 assert(m >= n);
1294 for (i = 0; i < n; ++i) {
1295 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001296 x[i] = carry & PyLong_MASK;
1297 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001298 assert((carry & 1) == carry);
1299 }
1300 for (; carry && i < m; ++i) {
1301 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001302 x[i] = carry & PyLong_MASK;
1303 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001304 assert((carry & 1) == carry);
1305 }
1306 return carry;
1307}
1308
1309/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1310 * is modified in place, by subtracting y from it. Borrows are propagated as
1311 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1312 */
1313static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001314v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001315{
1316 int i;
1317 digit borrow = 0;
1318
1319 assert(m >= n);
1320 for (i = 0; i < n; ++i) {
1321 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001322 x[i] = borrow & PyLong_MASK;
1323 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001324 borrow &= 1; /* keep only 1 sign bit */
1325 }
1326 for (; borrow && i < m; ++i) {
1327 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001328 x[i] = borrow & PyLong_MASK;
1329 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001330 borrow &= 1;
1331 }
1332 return borrow;
1333}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001334
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001335/* Multiply by a single digit, ignoring the sign. */
1336
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001337static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001338mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001339{
1340 return muladd1(a, n, (digit)0);
1341}
1342
1343/* Multiply by a single digit and add a single digit, ignoring the sign. */
1344
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001345static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001346muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001347{
Christian Heimes90aa7642007-12-19 02:45:37 +00001348 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001349 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001350 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001351 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001352
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001353 if (z == NULL)
1354 return NULL;
1355 for (i = 0; i < size_a; ++i) {
1356 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001357 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1358 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001359 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001360 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001361 return long_normalize(z);
1362}
1363
Tim Peters212e6142001-07-14 12:23:19 +00001364/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1365 in pout, and returning the remainder. pin and pout point at the LSD.
1366 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001367 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001368 immutable. */
1369
1370static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001371inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001372{
1373 twodigits rem = 0;
1374
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001375 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001376 pin += size;
1377 pout += size;
1378 while (--size >= 0) {
1379 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001380 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001381 *--pout = hi = (digit)(rem / n);
1382 rem -= hi * n;
1383 }
1384 return (digit)rem;
1385}
1386
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001387/* Divide a long integer by a digit, returning both the quotient
1388 (as function result) and the remainder (through *prem).
1389 The sign of a is ignored; n should not be zero. */
1390
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001391static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001392divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001393{
Christian Heimes90aa7642007-12-19 02:45:37 +00001394 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001395 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001396
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001397 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001398 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001399 if (z == NULL)
1400 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001401 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001402 return long_normalize(z);
1403}
1404
1405/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001406 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001407 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001408
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001409PyObject *
1410_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001411{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001412 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001413 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001414 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001415 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001416 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001417 int bits;
1418 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001419
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001420 if (a == NULL || !PyLong_Check(a)) {
1421 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001422 return NULL;
1423 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001424 assert(base >= 2 && base <= 36);
Christian Heimes90aa7642007-12-19 02:45:37 +00001425 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001426
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001427 /* Compute a rough upper bound for the length of the string */
1428 i = base;
1429 bits = 0;
1430 while (i > 1) {
1431 ++bits;
1432 i >>= 1;
1433 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001434 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001435 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001436 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001437 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001438 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001439 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001440 return NULL;
1441 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001442 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001443 if (str == NULL)
1444 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001445 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001446 *p = '\0';
Christian Heimes90aa7642007-12-19 02:45:37 +00001447 if (Py_SIZE(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001448 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001449
Christian Heimes90aa7642007-12-19 02:45:37 +00001450 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001451 *--p = '0';
1452 }
1453 else if ((base & (base - 1)) == 0) {
1454 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001455 twodigits accum = 0;
1456 int accumbits = 0; /* # of bits in accum */
1457 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001458 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001459 while ((i >>= 1) > 1)
1460 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001461
1462 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001463 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001464 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001465 assert(accumbits >= basebits);
1466 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001467 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001468 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001469 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001470 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001471 accumbits -= basebits;
1472 accum >>= basebits;
1473 } while (i < size_a-1 ? accumbits >= basebits :
1474 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001475 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001476 }
1477 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001478 /* Not 0, and base not a power of 2. Divide repeatedly by
1479 base, but for speed use the highest power of base that
1480 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001481 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001482 digit *pin = a->ob_digit;
1483 PyLongObject *scratch;
1484 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001485 digit powbase = base; /* powbase == base ** power */
1486 int power = 1;
1487 for (;;) {
1488 unsigned long newpow = powbase * (unsigned long)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001489 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001490 break;
1491 powbase = (digit)newpow;
1492 ++power;
1493 }
Tim Peters212e6142001-07-14 12:23:19 +00001494
1495 /* Get a scratch area for repeated division. */
1496 scratch = _PyLong_New(size);
1497 if (scratch == NULL) {
1498 Py_DECREF(str);
1499 return NULL;
1500 }
1501
1502 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001503 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001504 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001505 digit rem = inplace_divrem1(scratch->ob_digit,
1506 pin, size, powbase);
1507 pin = scratch->ob_digit; /* no need to use a again */
1508 if (pin[size - 1] == 0)
1509 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001510 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001511 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001512 Py_DECREF(str);
1513 return NULL;
1514 })
Tim Peters212e6142001-07-14 12:23:19 +00001515
1516 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001517 assert(ntostore > 0);
1518 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001519 digit nextrem = (digit)(rem / base);
1520 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001521 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001522 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001523 *--p = c;
1524 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001525 --ntostore;
1526 /* Termination is a bit delicate: must not
1527 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001528 remaining quotient and rem are both 0. */
1529 } while (ntostore && (size || rem));
1530 } while (size != 0);
1531 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001532 }
1533
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001534 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001535 *--p = 'x';
1536 *--p = '0';
1537 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001538 else if (base == 8) {
1539 *--p = 'o';
1540 *--p = '0';
1541 }
1542 else if (base == 2) {
1543 *--p = 'b';
1544 *--p = '0';
1545 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001546 else if (base != 10) {
1547 *--p = '#';
1548 *--p = '0' + base%10;
1549 if (base > 10)
1550 *--p = '0' + base/10;
1551 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001552 if (sign)
1553 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001554 if (p != PyUnicode_AS_UNICODE(str)) {
1555 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001556 assert(p > q);
1557 do {
1558 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001559 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001560 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1561 Py_DECREF(str);
1562 return NULL;
1563 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001564 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001565 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001566}
1567
Thomas Wouters477c8d52006-05-27 19:21:47 +00001568/* Table of digit values for 8-bit string -> integer conversion.
1569 * '0' maps to 0, ..., '9' maps to 9.
1570 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1571 * All other indices map to 37.
1572 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001573 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001574 */
1575int _PyLong_DigitValue[256] = {
1576 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1577 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1578 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1579 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1580 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1581 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1582 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1583 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1584 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1585 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1586 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1587 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1588 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1589 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1590 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1591 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1592};
1593
1594/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001595 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1596 * non-digit (which may be *str!). A normalized long is returned.
1597 * The point to this routine is that it takes time linear in the number of
1598 * string characters.
1599 */
1600static PyLongObject *
1601long_from_binary_base(char **str, int base)
1602{
1603 char *p = *str;
1604 char *start = p;
1605 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001606 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001607 PyLongObject *z;
1608 twodigits accum;
1609 int bits_in_accum;
1610 digit *pdigit;
1611
1612 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1613 n = base;
1614 for (bits_per_char = -1; n; ++bits_per_char)
1615 n >>= 1;
1616 /* n <- total # of bits needed, while setting p to end-of-string */
1617 n = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001618 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001619 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001620 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001621 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1622 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001623 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001624 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001625 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001626 return NULL;
1627 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001628 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001629 z = _PyLong_New(n);
1630 if (z == NULL)
1631 return NULL;
1632 /* Read string from right, and fill in long from left; i.e.,
1633 * from least to most significant in both.
1634 */
1635 accum = 0;
1636 bits_in_accum = 0;
1637 pdigit = z->ob_digit;
1638 while (--p >= start) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001639 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001640 assert(k >= 0 && k < base);
1641 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001642 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001643 if (bits_in_accum >= PyLong_SHIFT) {
1644 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001645 assert(pdigit - z->ob_digit <= (int)n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001646 accum >>= PyLong_SHIFT;
1647 bits_in_accum -= PyLong_SHIFT;
1648 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001649 }
1650 }
1651 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001652 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001653 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001654 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001655 }
1656 while (pdigit - z->ob_digit < n)
1657 *pdigit++ = 0;
1658 return long_normalize(z);
1659}
1660
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001661PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001662PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001663{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001664 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001665 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001666 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001667 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001668 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001669
Guido van Rossum472c04f1996-12-05 21:57:21 +00001670 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001671 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001672 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001673 return NULL;
1674 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001675 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001676 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001677 if (*str == '+')
1678 ++str;
1679 else if (*str == '-') {
1680 ++str;
1681 sign = -1;
1682 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001683 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001684 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001685 if (base == 0) {
1686 if (str[0] != '0')
1687 base = 10;
1688 else if (str[1] == 'x' || str[1] == 'X')
1689 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001690 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001691 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001692 else if (str[1] == 'b' || str[1] == 'B')
1693 base = 2;
1694 else {
1695 /* "old" (C-style) octal literal, now invalid.
1696 it might still be zero though */
1697 error_if_nonzero = 1;
1698 base = 10;
1699 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001700 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001701 if (str[0] == '0' &&
1702 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1703 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1704 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001705 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001706
Guido van Rossume6762971998-06-22 03:54:46 +00001707 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001708 if ((base & (base - 1)) == 0)
1709 z = long_from_binary_base(&str, base);
1710 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001711/***
1712Binary bases can be converted in time linear in the number of digits, because
1713Python's representation base is binary. Other bases (including decimal!) use
1714the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001715
Thomas Wouters477c8d52006-05-27 19:21:47 +00001716First some math: the largest integer that can be expressed in N base-B digits
1717is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1718case number of Python digits needed to hold it is the smallest integer n s.t.
1719
1720 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1721 BASE**n >= B**N [taking logs to base BASE]
1722 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1723
1724The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1725this quickly. A Python long with that much space is reserved near the start,
1726and the result is computed into it.
1727
1728The input string is actually treated as being in base base**i (i.e., i digits
1729are processed at a time), where two more static arrays hold:
1730
1731 convwidth_base[base] = the largest integer i such that base**i <= BASE
1732 convmultmax_base[base] = base ** convwidth_base[base]
1733
1734The first of these is the largest i such that i consecutive input digits
1735must fit in a single Python digit. The second is effectively the input
1736base we're really using.
1737
1738Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1739convmultmax_base[base], the result is "simply"
1740
1741 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1742
1743where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001744
1745Error analysis: as above, the number of Python digits `n` needed is worst-
1746case
1747
1748 n >= N * log(B)/log(BASE)
1749
1750where `N` is the number of input digits in base `B`. This is computed via
1751
1752 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1753
1754below. Two numeric concerns are how much space this can waste, and whether
1755the computed result can be too small. To be concrete, assume BASE = 2**15,
1756which is the default (and it's unlikely anyone changes that).
1757
1758Waste isn't a problem: provided the first input digit isn't 0, the difference
1759between the worst-case input with N digits and the smallest input with N
1760digits is about a factor of B, but B is small compared to BASE so at most
1761one allocated Python digit can remain unused on that count. If
1762N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1763and adding 1 returns a result 1 larger than necessary. However, that can't
1764happen: whenever B is a power of 2, long_from_binary_base() is called
1765instead, and it's impossible for B**i to be an integer power of 2**15 when
1766B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1767an exact integer when B is not a power of 2, since B**i has a prime factor
1768other than 2 in that case, but (2**15)**j's only prime factor is 2).
1769
1770The computed result can be too small if the true value of N*log(B)/log(BASE)
1771is a little bit larger than an exact integer, but due to roundoff errors (in
1772computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1773yields a numeric result a little less than that integer. Unfortunately, "how
1774close can a transcendental function get to an integer over some range?"
1775questions are generally theoretically intractable. Computer analysis via
1776continued fractions is practical: expand log(B)/log(BASE) via continued
1777fractions, giving a sequence i/j of "the best" rational approximations. Then
1778j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1779we can get very close to being in trouble, but very rarely. For example,
178076573 is a denominator in one of the continued-fraction approximations to
1781log(10)/log(2**15), and indeed:
1782
1783 >>> log(10)/log(2**15)*76573
1784 16958.000000654003
1785
1786is very close to an integer. If we were working with IEEE single-precision,
1787rounding errors could kill us. Finding worst cases in IEEE double-precision
1788requires better-than-double-precision log() functions, and Tim didn't bother.
1789Instead the code checks to see whether the allocated space is enough as each
1790new Python digit is added, and copies the whole thing to a larger long if not.
1791This should happen extremely rarely, and in fact I don't have a test case
1792that triggers it(!). Instead the code was tested by artificially allocating
1793just 1 digit at the start, so that the copying code was exercised for every
1794digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001795***/
1796 register twodigits c; /* current input character */
1797 Py_ssize_t size_z;
1798 int i;
1799 int convwidth;
1800 twodigits convmultmax, convmult;
1801 digit *pz, *pzstop;
1802 char* scan;
1803
1804 static double log_base_BASE[37] = {0.0e0,};
1805 static int convwidth_base[37] = {0,};
1806 static twodigits convmultmax_base[37] = {0,};
1807
1808 if (log_base_BASE[base] == 0.0) {
1809 twodigits convmax = base;
1810 int i = 1;
1811
1812 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001813 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001814 for (;;) {
1815 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001816 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001817 break;
1818 convmax = next;
1819 ++i;
1820 }
1821 convmultmax_base[base] = convmax;
1822 assert(i > 0);
1823 convwidth_base[base] = i;
1824 }
1825
1826 /* Find length of the string of numeric characters. */
1827 scan = str;
1828 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1829 ++scan;
1830
1831 /* Create a long object that can contain the largest possible
1832 * integer with this base and length. Note that there's no
1833 * need to initialize z->ob_digit -- no slot is read up before
1834 * being stored into.
1835 */
1836 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001837 /* Uncomment next line to test exceedingly rare copy code */
1838 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001839 assert(size_z > 0);
1840 z = _PyLong_New(size_z);
1841 if (z == NULL)
1842 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00001843 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001844
1845 /* `convwidth` consecutive input digits are treated as a single
1846 * digit in base `convmultmax`.
1847 */
1848 convwidth = convwidth_base[base];
1849 convmultmax = convmultmax_base[base];
1850
1851 /* Work ;-) */
1852 while (str < scan) {
1853 /* grab up to convwidth digits from the input string */
1854 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1855 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1856 c = (twodigits)(c * base +
1857 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001858 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001859 }
1860
1861 convmult = convmultmax;
1862 /* Calculate the shift only if we couldn't get
1863 * convwidth digits.
1864 */
1865 if (i != convwidth) {
1866 convmult = base;
1867 for ( ; i > 1; --i)
1868 convmult *= base;
1869 }
1870
1871 /* Multiply z by convmult, and add c. */
1872 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001873 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001874 for (; pz < pzstop; ++pz) {
1875 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001876 *pz = (digit)(c & PyLong_MASK);
1877 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001878 }
1879 /* carry off the current end? */
1880 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001881 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00001882 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001883 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00001884 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001885 }
1886 else {
1887 PyLongObject *tmp;
1888 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00001889 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001890 tmp = _PyLong_New(size_z + 1);
1891 if (tmp == NULL) {
1892 Py_DECREF(z);
1893 return NULL;
1894 }
1895 memcpy(tmp->ob_digit,
1896 z->ob_digit,
1897 sizeof(digit) * size_z);
1898 Py_DECREF(z);
1899 z = tmp;
1900 z->ob_digit[size_z] = (digit)c;
1901 ++size_z;
1902 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001903 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001904 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001905 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001906 if (z == NULL)
1907 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001908 if (error_if_nonzero) {
1909 /* reset the base to 0, else the exception message
1910 doesn't make too much sense */
1911 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00001912 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001913 goto onError;
1914 /* there might still be other problems, therefore base
1915 remains zero here for the same reason */
1916 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001917 if (str == start)
1918 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001919 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00001920 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001921 if (*str == 'L' || *str == 'l')
1922 str++;
1923 while (*str && isspace(Py_CHARMASK(*str)))
1924 str++;
1925 if (*str != '\0')
1926 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001927 if (pend)
1928 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001929 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001930
1931 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001932 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001933 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00001934 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001935 if (strobj == NULL)
1936 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001937 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00001938 "invalid literal for int() with base %d: %R",
1939 base, strobj);
1940 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001941 return NULL;
1942}
1943
1944PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001945PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001946{
Walter Dörwald07e14762002-11-06 16:15:14 +00001947 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001948 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001949
Walter Dörwald07e14762002-11-06 16:15:14 +00001950 if (buffer == NULL)
1951 return NULL;
1952
1953 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1954 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001955 return NULL;
1956 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001957 result = PyLong_FromString(buffer, NULL, base);
1958 PyMem_FREE(buffer);
1959 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001960}
1961
Tim Peters9f688bf2000-07-07 15:53:28 +00001962/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001963static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001964 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001965static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00001966static int long_divrem(PyLongObject *, PyLongObject *,
1967 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001968
1969/* Long division with remainder, top-level routine */
1970
Guido van Rossume32e0141992-01-19 16:31:05 +00001971static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001972long_divrem(PyLongObject *a, PyLongObject *b,
1973 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001974{
Christian Heimes90aa7642007-12-19 02:45:37 +00001975 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001976 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001977
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001978 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001979 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001980 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001981 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001982 }
1983 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001984 (size_a == size_b &&
1985 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001986 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00001987 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001988 if (*pdiv == NULL)
1989 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001990 Py_INCREF(a);
1991 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001992 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001993 }
1994 if (size_b == 1) {
1995 digit rem = 0;
1996 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001997 if (z == NULL)
1998 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001999 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002000 if (*prem == NULL) {
2001 Py_DECREF(z);
2002 return -1;
2003 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002004 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002005 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002006 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002007 if (z == NULL)
2008 return -1;
2009 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002010 /* Set the signs.
2011 The quotient z has the sign of a*b;
2012 the remainder r has the sign of a,
2013 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002014 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002015 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002016 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002017 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002018 *pdiv = z;
2019 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002020}
2021
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002022/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002023
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002024static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002025x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002026{
Christian Heimes90aa7642007-12-19 02:45:37 +00002027 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002028 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002029 PyLongObject *v = mul1(v1, d);
2030 PyLongObject *w = mul1(w1, d);
2031 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002032 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002033
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002034 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002035 Py_XDECREF(v);
2036 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002037 return NULL;
2038 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002039
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002040 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002041 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
2042 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002043
Christian Heimes90aa7642007-12-19 02:45:37 +00002044 size_v = ABS(Py_SIZE(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002045 k = size_v - size_w;
2046 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002047
Thomas Wouters477c8d52006-05-27 19:21:47 +00002048 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002049 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2050 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002051 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002052 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002053
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002054 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002055 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002056 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002057 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002058 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002059 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002060 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002061 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002062 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002063 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002064
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002065 while (w->ob_digit[size_w-2]*q >
2066 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002067 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002068 + v->ob_digit[j-1]
2069 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002070 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002071 + v->ob_digit[j-2])
2072 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002073
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002074 for (i = 0; i < size_w && i+k < size_v; ++i) {
2075 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002076 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002077 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002078 + ((twodigits)zz << PyLong_SHIFT);
2079 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002080 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002081 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002082 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002083 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002084
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002085 if (i+k < size_v) {
2086 carry += v->ob_digit[i+k];
2087 v->ob_digit[i+k] = 0;
2088 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002089
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002091 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002092 else {
2093 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002094 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002095 carry = 0;
2096 for (i = 0; i < size_w && i+k < size_v; ++i) {
2097 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002098 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002099 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2100 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002101 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002102 }
2103 }
2104 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002105
Guido van Rossumc206c761995-01-10 15:23:19 +00002106 if (a == NULL)
2107 *prem = NULL;
2108 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002109 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002110 *prem = divrem1(v, d, &d);
2111 /* d receives the (unused) remainder */
2112 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002113 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002114 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002115 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002116 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002117 Py_DECREF(v);
2118 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002119 return a;
2120}
2121
2122/* Methods */
2123
2124static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002125long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002126{
Christian Heimes90aa7642007-12-19 02:45:37 +00002127 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002128}
2129
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002130static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002131long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002132{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002133 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002134}
2135
2136static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002137long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002138{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002139 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002140
Christian Heimes90aa7642007-12-19 02:45:37 +00002141 if (Py_SIZE(a) != Py_SIZE(b)) {
2142 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002143 sign = 0;
2144 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002145 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002146 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002147 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002148 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002149 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2150 ;
2151 if (i < 0)
2152 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002153 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002154 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002155 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002156 sign = -sign;
2157 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002158 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002159 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002160}
2161
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002162static PyObject *
2163long_richcompare(PyObject *self, PyObject *other, int op)
2164{
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002165 PyObject *result;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002166 CHECK_BINOP(self, other);
2167 result = Py_CmpToRich(op, long_compare((PyLongObject*)self,
2168 (PyLongObject*)other));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002169 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002170}
2171
Guido van Rossum9bfef441993-03-29 10:43:31 +00002172static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002173long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002174{
2175 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002176 Py_ssize_t i;
2177 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002178
2179 /* This is designed so that Python ints and longs with the
2180 same value hash to the same value, otherwise comparisons
2181 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002182 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002183 switch(i) {
2184 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2185 case 0: return 0;
2186 case 1: return v->ob_digit[0];
2187 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002188 sign = 1;
2189 x = 0;
2190 if (i < 0) {
2191 sign = -1;
2192 i = -(i);
2193 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002194#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Thomas Woutersce272b62007-09-19 21:19:28 +00002195 /* The following loop produces a C long x such that (unsigned long)x
2196 is congruent to the absolute value of v modulo ULONG_MAX. The
2197 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002198 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002199 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002200 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002201 x += v->ob_digit[i];
Thomas Woutersce272b62007-09-19 21:19:28 +00002202 /* If the addition above overflowed (thinking of x as
2203 unsigned), we compensate by incrementing. This preserves
2204 the value modulo ULONG_MAX. */
2205 if ((unsigned long)x < v->ob_digit[i])
2206 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002207 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002208#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002209 x = x * sign;
2210 if (x == -1)
2211 x = -2;
2212 return x;
2213}
2214
2215
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002216/* Add the absolute values of two long integers. */
2217
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002218static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002219x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002220{
Christian Heimes90aa7642007-12-19 02:45:37 +00002221 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002222 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002223 int i;
2224 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002225
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002226 /* Ensure a is the larger of the two: */
2227 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002228 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002229 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002230 size_a = size_b;
2231 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002232 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002233 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002234 if (z == NULL)
2235 return NULL;
2236 for (i = 0; i < size_b; ++i) {
2237 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002238 z->ob_digit[i] = carry & PyLong_MASK;
2239 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002240 }
2241 for (; i < size_a; ++i) {
2242 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002243 z->ob_digit[i] = carry & PyLong_MASK;
2244 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002245 }
2246 z->ob_digit[i] = carry;
2247 return long_normalize(z);
2248}
2249
2250/* Subtract the absolute values of two integers. */
2251
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002252static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002253x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002254{
Christian Heimes90aa7642007-12-19 02:45:37 +00002255 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002256 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002257 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002258 int sign = 1;
2259 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002260
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002261 /* Ensure a is the larger of the two: */
2262 if (size_a < size_b) {
2263 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002264 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002265 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002266 size_a = size_b;
2267 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002268 }
2269 else if (size_a == size_b) {
2270 /* Find highest digit where a and b differ: */
2271 i = size_a;
2272 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2273 ;
2274 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002275 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002276 if (a->ob_digit[i] < b->ob_digit[i]) {
2277 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002278 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002279 }
2280 size_a = size_b = i+1;
2281 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002282 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002283 if (z == NULL)
2284 return NULL;
2285 for (i = 0; i < size_b; ++i) {
2286 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002287 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002288 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002289 z->ob_digit[i] = borrow & PyLong_MASK;
2290 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002291 borrow &= 1; /* Keep only one sign bit */
2292 }
2293 for (; i < size_a; ++i) {
2294 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002295 z->ob_digit[i] = borrow & PyLong_MASK;
2296 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002297 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002298 }
2299 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002300 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002301 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002302 return long_normalize(z);
2303}
2304
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002305static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002306long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002307{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002308 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002309
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002310 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002311
Christian Heimes90aa7642007-12-19 02:45:37 +00002312 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002313 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002314 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002315 return result;
2316 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002317 if (Py_SIZE(a) < 0) {
2318 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002319 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002320 if (z != NULL && Py_SIZE(z) != 0)
2321 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002322 }
2323 else
2324 z = x_sub(b, a);
2325 }
2326 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002327 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002328 z = x_sub(a, b);
2329 else
2330 z = x_add(a, b);
2331 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002332 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002333}
2334
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002335static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002336long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002337{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002338 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002339
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002340 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002341
Christian Heimes90aa7642007-12-19 02:45:37 +00002342 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002343 PyObject* r;
2344 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002345 return r;
2346 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002347 if (Py_SIZE(a) < 0) {
2348 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002349 z = x_sub(a, b);
2350 else
2351 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002352 if (z != NULL && Py_SIZE(z) != 0)
2353 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002354 }
2355 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002356 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002357 z = x_add(a, b);
2358 else
2359 z = x_sub(a, b);
2360 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002361 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002362}
2363
Tim Peters5af4e6c2002-08-12 02:31:19 +00002364/* Grade school multiplication, ignoring the signs.
2365 * Returns the absolute value of the product, or NULL if error.
2366 */
2367static PyLongObject *
2368x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002369{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002370 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002371 Py_ssize_t size_a = ABS(Py_SIZE(a));
2372 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002373 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002374
Tim Peters5af4e6c2002-08-12 02:31:19 +00002375 z = _PyLong_New(size_a + size_b);
2376 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002377 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002378
Christian Heimes90aa7642007-12-19 02:45:37 +00002379 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002380 if (a == b) {
2381 /* Efficient squaring per HAC, Algorithm 14.16:
2382 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2383 * Gives slightly less than a 2x speedup when a == b,
2384 * via exploiting that each entry in the multiplication
2385 * pyramid appears twice (except for the size_a squares).
2386 */
2387 for (i = 0; i < size_a; ++i) {
2388 twodigits carry;
2389 twodigits f = a->ob_digit[i];
2390 digit *pz = z->ob_digit + (i << 1);
2391 digit *pa = a->ob_digit + i + 1;
2392 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002393
Tim Peters0973b992004-08-29 22:16:50 +00002394 SIGCHECK({
2395 Py_DECREF(z);
2396 return NULL;
2397 })
2398
2399 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002400 *pz++ = (digit)(carry & PyLong_MASK);
2401 carry >>= PyLong_SHIFT;
2402 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002403
2404 /* Now f is added in twice in each column of the
2405 * pyramid it appears. Same as adding f<<1 once.
2406 */
2407 f <<= 1;
2408 while (pa < paend) {
2409 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002410 *pz++ = (digit)(carry & PyLong_MASK);
2411 carry >>= PyLong_SHIFT;
2412 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002413 }
2414 if (carry) {
2415 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002416 *pz++ = (digit)(carry & PyLong_MASK);
2417 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002418 }
2419 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002420 *pz += (digit)(carry & PyLong_MASK);
2421 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002422 }
Tim Peters0973b992004-08-29 22:16:50 +00002423 }
2424 else { /* a is not the same as b -- gradeschool long mult */
2425 for (i = 0; i < size_a; ++i) {
2426 twodigits carry = 0;
2427 twodigits f = a->ob_digit[i];
2428 digit *pz = z->ob_digit + i;
2429 digit *pb = b->ob_digit;
2430 digit *pbend = b->ob_digit + size_b;
2431
2432 SIGCHECK({
2433 Py_DECREF(z);
2434 return NULL;
2435 })
2436
2437 while (pb < pbend) {
2438 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002439 *pz++ = (digit)(carry & PyLong_MASK);
2440 carry >>= PyLong_SHIFT;
2441 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002442 }
2443 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002444 *pz += (digit)(carry & PyLong_MASK);
2445 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002446 }
2447 }
Tim Peters44121a62002-08-12 06:17:58 +00002448 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002449}
2450
2451/* A helper for Karatsuba multiplication (k_mul).
2452 Takes a long "n" and an integer "size" representing the place to
2453 split, and sets low and high such that abs(n) == (high << size) + low,
2454 viewing the shift as being by digits. The sign bit is ignored, and
2455 the return values are >= 0.
2456 Returns 0 on success, -1 on failure.
2457*/
2458static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002459kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002460{
2461 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002462 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002463 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002464
2465 size_lo = MIN(size_n, size);
2466 size_hi = size_n - size_lo;
2467
2468 if ((hi = _PyLong_New(size_hi)) == NULL)
2469 return -1;
2470 if ((lo = _PyLong_New(size_lo)) == NULL) {
2471 Py_DECREF(hi);
2472 return -1;
2473 }
2474
2475 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2476 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2477
2478 *high = long_normalize(hi);
2479 *low = long_normalize(lo);
2480 return 0;
2481}
2482
Tim Peters60004642002-08-12 22:01:34 +00002483static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2484
Tim Peters5af4e6c2002-08-12 02:31:19 +00002485/* Karatsuba multiplication. Ignores the input signs, and returns the
2486 * absolute value of the product (or NULL if error).
2487 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2488 */
2489static PyLongObject *
2490k_mul(PyLongObject *a, PyLongObject *b)
2491{
Christian Heimes90aa7642007-12-19 02:45:37 +00002492 Py_ssize_t asize = ABS(Py_SIZE(a));
2493 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002494 PyLongObject *ah = NULL;
2495 PyLongObject *al = NULL;
2496 PyLongObject *bh = NULL;
2497 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002498 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002499 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002500 Py_ssize_t shift; /* the number of digits we split off */
2501 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002502
Tim Peters5af4e6c2002-08-12 02:31:19 +00002503 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2504 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2505 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002506 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002507 * By picking X to be a power of 2, "*X" is just shifting, and it's
2508 * been reduced to 3 multiplies on numbers half the size.
2509 */
2510
Tim Petersfc07e562002-08-12 02:54:10 +00002511 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002512 * is largest.
2513 */
Tim Peters738eda72002-08-12 15:08:20 +00002514 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002515 t1 = a;
2516 a = b;
2517 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002518
2519 i = asize;
2520 asize = bsize;
2521 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002522 }
2523
2524 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002525 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2526 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002527 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002528 return _PyLong_New(0);
2529 else
2530 return x_mul(a, b);
2531 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002532
Tim Peters60004642002-08-12 22:01:34 +00002533 /* If a is small compared to b, splitting on b gives a degenerate
2534 * case with ah==0, and Karatsuba may be (even much) less efficient
2535 * than "grade school" then. However, we can still win, by viewing
2536 * b as a string of "big digits", each of width a->ob_size. That
2537 * leads to a sequence of balanced calls to k_mul.
2538 */
2539 if (2 * asize <= bsize)
2540 return k_lopsided_mul(a, b);
2541
Tim Petersd6974a52002-08-13 20:37:51 +00002542 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002543 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002544 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002545 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002546
Tim Peters0973b992004-08-29 22:16:50 +00002547 if (a == b) {
2548 bh = ah;
2549 bl = al;
2550 Py_INCREF(bh);
2551 Py_INCREF(bl);
2552 }
2553 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002554
Tim Petersd64c1de2002-08-12 17:36:03 +00002555 /* The plan:
2556 * 1. Allocate result space (asize + bsize digits: that's always
2557 * enough).
2558 * 2. Compute ah*bh, and copy into result at 2*shift.
2559 * 3. Compute al*bl, and copy into result at 0. Note that this
2560 * can't overlap with #2.
2561 * 4. Subtract al*bl from the result, starting at shift. This may
2562 * underflow (borrow out of the high digit), but we don't care:
2563 * we're effectively doing unsigned arithmetic mod
2564 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2565 * borrows and carries out of the high digit can be ignored.
2566 * 5. Subtract ah*bh from the result, starting at shift.
2567 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2568 * at shift.
2569 */
2570
2571 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002572 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002573 if (ret == NULL) goto fail;
2574#ifdef Py_DEBUG
2575 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002576 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002577#endif
Tim Peters44121a62002-08-12 06:17:58 +00002578
Tim Petersd64c1de2002-08-12 17:36:03 +00002579 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002580 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002581 assert(Py_SIZE(t1) >= 0);
2582 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002583 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002584 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002585
2586 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002587 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002588 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002589 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002590 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002591
Tim Petersd64c1de2002-08-12 17:36:03 +00002592 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002593 if ((t2 = k_mul(al, bl)) == NULL) {
2594 Py_DECREF(t1);
2595 goto fail;
2596 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002597 assert(Py_SIZE(t2) >= 0);
2598 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2599 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002600
2601 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002602 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002603 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002604 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002605
Tim Petersd64c1de2002-08-12 17:36:03 +00002606 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2607 * because it's fresher in cache.
2608 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002609 i = Py_SIZE(ret) - shift; /* # digits after shift */
2610 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002611 Py_DECREF(t2);
2612
Christian Heimes90aa7642007-12-19 02:45:37 +00002613 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002614 Py_DECREF(t1);
2615
Tim Petersd64c1de2002-08-12 17:36:03 +00002616 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002617 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2618 Py_DECREF(ah);
2619 Py_DECREF(al);
2620 ah = al = NULL;
2621
Tim Peters0973b992004-08-29 22:16:50 +00002622 if (a == b) {
2623 t2 = t1;
2624 Py_INCREF(t2);
2625 }
2626 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002627 Py_DECREF(t1);
2628 goto fail;
2629 }
2630 Py_DECREF(bh);
2631 Py_DECREF(bl);
2632 bh = bl = NULL;
2633
Tim Peters738eda72002-08-12 15:08:20 +00002634 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002635 Py_DECREF(t1);
2636 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002637 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002638 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002639
Tim Petersd6974a52002-08-13 20:37:51 +00002640 /* Add t3. It's not obvious why we can't run out of room here.
2641 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002642 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002643 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002644 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002645
Tim Peters5af4e6c2002-08-12 02:31:19 +00002646 return long_normalize(ret);
2647
2648 fail:
2649 Py_XDECREF(ret);
2650 Py_XDECREF(ah);
2651 Py_XDECREF(al);
2652 Py_XDECREF(bh);
2653 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002654 return NULL;
2655}
2656
Tim Petersd6974a52002-08-13 20:37:51 +00002657/* (*) Why adding t3 can't "run out of room" above.
2658
Tim Petersab86c2b2002-08-15 20:06:00 +00002659Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2660to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002661
Tim Petersab86c2b2002-08-15 20:06:00 +000026621. For any integer i, i = c(i/2) + f(i/2). In particular,
2663 bsize = c(bsize/2) + f(bsize/2).
26642. shift = f(bsize/2)
26653. asize <= bsize
26664. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2667 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002668
Tim Petersab86c2b2002-08-15 20:06:00 +00002669We allocated asize + bsize result digits, and add t3 into them at an offset
2670of shift. This leaves asize+bsize-shift allocated digit positions for t3
2671to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2672asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002673
Tim Petersab86c2b2002-08-15 20:06:00 +00002674bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2675at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002676
Tim Petersab86c2b2002-08-15 20:06:00 +00002677If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2678digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2679most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002680
Tim Petersab86c2b2002-08-15 20:06:00 +00002681The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002682
Tim Petersab86c2b2002-08-15 20:06:00 +00002683 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002684
Tim Petersab86c2b2002-08-15 20:06:00 +00002685and we have asize + c(bsize/2) available digit positions. We need to show
2686this is always enough. An instance of c(bsize/2) cancels out in both, so
2687the question reduces to whether asize digits is enough to hold
2688(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2689then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2690asize 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 +00002691digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002692asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002693c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2694is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2695bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002696
Tim Peters48d52c02002-08-14 17:07:32 +00002697Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2698clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2699ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002700*/
2701
Tim Peters60004642002-08-12 22:01:34 +00002702/* b has at least twice the digits of a, and a is big enough that Karatsuba
2703 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2704 * of slices, each with a->ob_size digits, and multiply the slices by a,
2705 * one at a time. This gives k_mul balanced inputs to work with, and is
2706 * also cache-friendly (we compute one double-width slice of the result
2707 * at a time, then move on, never bactracking except for the helpful
2708 * single-width slice overlap between successive partial sums).
2709 */
2710static PyLongObject *
2711k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2712{
Christian Heimes90aa7642007-12-19 02:45:37 +00002713 const Py_ssize_t asize = ABS(Py_SIZE(a));
2714 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002715 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002716 PyLongObject *ret;
2717 PyLongObject *bslice = NULL;
2718
2719 assert(asize > KARATSUBA_CUTOFF);
2720 assert(2 * asize <= bsize);
2721
2722 /* Allocate result space, and zero it out. */
2723 ret = _PyLong_New(asize + bsize);
2724 if (ret == NULL)
2725 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002726 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002727
2728 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002729 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002730 if (bslice == NULL)
2731 goto fail;
2732
2733 nbdone = 0;
2734 while (bsize > 0) {
2735 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002736 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002737
2738 /* Multiply the next slice of b by a. */
2739 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2740 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00002741 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002742 product = k_mul(a, bslice);
2743 if (product == NULL)
2744 goto fail;
2745
2746 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002747 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2748 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002749 Py_DECREF(product);
2750
2751 bsize -= nbtouse;
2752 nbdone += nbtouse;
2753 }
2754
2755 Py_DECREF(bslice);
2756 return long_normalize(ret);
2757
2758 fail:
2759 Py_DECREF(ret);
2760 Py_XDECREF(bslice);
2761 return NULL;
2762}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002763
2764static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002765long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002766{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002767 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002768
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002769 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002770
Christian Heimes90aa7642007-12-19 02:45:37 +00002771 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002772 PyObject *r;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002773 r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002774 return r;
2775 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002776
Tim Petersd64c1de2002-08-12 17:36:03 +00002777 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002778 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002779 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002780 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002781 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002782}
2783
Guido van Rossume32e0141992-01-19 16:31:05 +00002784/* The / and % operators are now defined in terms of divmod().
2785 The expression a mod b has the value a - b*floor(a/b).
2786 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002787 |a| by |b|, with the sign of a. This is also expressed
2788 as a - b*trunc(a/b), if trunc truncates towards zero.
2789 Some examples:
2790 a b a rem b a mod b
2791 13 10 3 3
2792 -13 10 -3 7
2793 13 -10 3 -7
2794 -13 -10 -3 -3
2795 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002796 have different signs. We then subtract one from the 'div'
2797 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002798
Tim Peters47e52ee2004-08-30 02:44:38 +00002799/* Compute
2800 * *pdiv, *pmod = divmod(v, w)
2801 * NULL can be passed for pdiv or pmod, in which case that part of
2802 * the result is simply thrown away. The caller owns a reference to
2803 * each of these it requests (does not pass NULL for).
2804 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002805static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002806l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002807 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002808{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002809 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002810
Guido van Rossume32e0141992-01-19 16:31:05 +00002811 if (long_divrem(v, w, &div, &mod) < 0)
2812 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00002813 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2814 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002815 PyLongObject *temp;
2816 PyLongObject *one;
2817 temp = (PyLongObject *) long_add(mod, w);
2818 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002819 mod = temp;
2820 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002821 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002822 return -1;
2823 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002824 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002825 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002826 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2827 Py_DECREF(mod);
2828 Py_DECREF(div);
2829 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002830 return -1;
2831 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002832 Py_DECREF(one);
2833 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002834 div = temp;
2835 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002836 if (pdiv != NULL)
2837 *pdiv = div;
2838 else
2839 Py_DECREF(div);
2840
2841 if (pmod != NULL)
2842 *pmod = mod;
2843 else
2844 Py_DECREF(mod);
2845
Guido van Rossume32e0141992-01-19 16:31:05 +00002846 return 0;
2847}
2848
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002849static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002850long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002851{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002852 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002853
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002854 CHECK_BINOP(a, b);
2855 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002856 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002857 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002858}
2859
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002860static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002861long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002862{
Tim Peterse2a60002001-09-04 06:17:36 +00002863 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002864 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002865
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002866 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002867 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2868 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002869 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002870 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002871 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002872 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2873 but should really be set correctly after sucessful calls to
2874 _PyLong_AsScaledDouble() */
2875 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002876
2877 if (bd == 0.0) {
2878 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002879 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002880 return NULL;
2881 }
2882
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002883 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002884 ad /= bd; /* overflow/underflow impossible here */
2885 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002886 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002887 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002888 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002889 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002890 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002891 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002892 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002893 goto overflow;
2894 return PyFloat_FromDouble(ad);
2895
2896overflow:
2897 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002898 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002899 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002900
Tim Peters20dab9f2001-09-04 05:31:47 +00002901}
2902
2903static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002904long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002905{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002906 PyLongObject *mod;
2907
2908 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002909
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002910 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002911 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002912 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002913}
2914
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002915static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002916long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002917{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002918 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002919 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002920
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002921 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002922
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002923 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002924 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002925 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002926 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002927 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002928 PyTuple_SetItem(z, 0, (PyObject *) div);
2929 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002930 }
2931 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002932 Py_DECREF(div);
2933 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002934 }
2935 return z;
2936}
2937
Tim Peters47e52ee2004-08-30 02:44:38 +00002938/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002939static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002940long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002941{
Tim Peters47e52ee2004-08-30 02:44:38 +00002942 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2943 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002944
Tim Peters47e52ee2004-08-30 02:44:38 +00002945 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002946 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002947 PyLongObject *temp = NULL;
2948
2949 /* 5-ary values. If the exponent is large enough, table is
2950 * precomputed so that table[i] == a**i % c for i in range(32).
2951 */
2952 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2953 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2954
2955 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002956 CHECK_BINOP(v, w);
2957 a = (PyLongObject*)v; Py_INCREF(a);
2958 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002959 if (PyLong_Check(x)) {
2960 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002961 Py_INCREF(x);
2962 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002963 else if (x == Py_None)
2964 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002965 else {
2966 Py_DECREF(a);
2967 Py_DECREF(b);
2968 Py_INCREF(Py_NotImplemented);
2969 return Py_NotImplemented;
2970 }
Tim Peters4c483c42001-09-05 06:24:58 +00002971
Christian Heimes90aa7642007-12-19 02:45:37 +00002972 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00002973 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002974 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002975 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002976 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002977 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002978 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002979 /* else return a float. This works because we know
2980 that this calls float_pow() which converts its
2981 arguments to double. */
2982 Py_DECREF(a);
2983 Py_DECREF(b);
2984 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002985 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002986 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002987
2988 if (c) {
2989 /* if modulus == 0:
2990 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002991 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002992 PyErr_SetString(PyExc_ValueError,
2993 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002994 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002995 }
2996
2997 /* if modulus < 0:
2998 negativeOutput = True
2999 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003000 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003001 negativeOutput = 1;
3002 temp = (PyLongObject *)_PyLong_Copy(c);
3003 if (temp == NULL)
3004 goto Error;
3005 Py_DECREF(c);
3006 c = temp;
3007 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003008 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003009 }
3010
3011 /* if modulus == 1:
3012 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003013 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003014 z = (PyLongObject *)PyLong_FromLong(0L);
3015 goto Done;
3016 }
3017
3018 /* if base < 0:
3019 base = base % modulus
3020 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003021 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003022 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003023 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003024 Py_DECREF(a);
3025 a = temp;
3026 temp = NULL;
3027 }
3028 }
3029
3030 /* At this point a, b, and c are guaranteed non-negative UNLESS
3031 c is NULL, in which case a may be negative. */
3032
3033 z = (PyLongObject *)PyLong_FromLong(1L);
3034 if (z == NULL)
3035 goto Error;
3036
3037 /* Perform a modular reduction, X = X % c, but leave X alone if c
3038 * is NULL.
3039 */
3040#define REDUCE(X) \
3041 if (c != NULL) { \
3042 if (l_divmod(X, c, NULL, &temp) < 0) \
3043 goto Error; \
3044 Py_XDECREF(X); \
3045 X = temp; \
3046 temp = NULL; \
3047 }
3048
3049 /* Multiply two values, then reduce the result:
3050 result = X*Y % c. If c is NULL, skip the mod. */
3051#define MULT(X, Y, result) \
3052{ \
3053 temp = (PyLongObject *)long_mul(X, Y); \
3054 if (temp == NULL) \
3055 goto Error; \
3056 Py_XDECREF(result); \
3057 result = temp; \
3058 temp = NULL; \
3059 REDUCE(result) \
3060}
3061
Christian Heimes90aa7642007-12-19 02:45:37 +00003062 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003063 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3064 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003065 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003066 digit bi = b->ob_digit[i];
3067
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003068 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003069 MULT(z, z, z)
3070 if (bi & j)
3071 MULT(z, a, z)
3072 }
3073 }
3074 }
3075 else {
3076 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3077 Py_INCREF(z); /* still holds 1L */
3078 table[0] = z;
3079 for (i = 1; i < 32; ++i)
3080 MULT(table[i-1], a, table[i])
3081
Christian Heimes90aa7642007-12-19 02:45:37 +00003082 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003083 const digit bi = b->ob_digit[i];
3084
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003085 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003086 const int index = (bi >> j) & 0x1f;
3087 for (k = 0; k < 5; ++k)
3088 MULT(z, z, z)
3089 if (index)
3090 MULT(z, table[index], z)
3091 }
3092 }
3093 }
3094
Christian Heimes90aa7642007-12-19 02:45:37 +00003095 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003096 temp = (PyLongObject *)long_sub(z, c);
3097 if (temp == NULL)
3098 goto Error;
3099 Py_DECREF(z);
3100 z = temp;
3101 temp = NULL;
3102 }
3103 goto Done;
3104
3105 Error:
3106 if (z != NULL) {
3107 Py_DECREF(z);
3108 z = NULL;
3109 }
3110 /* fall through */
3111 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003112 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003113 for (i = 0; i < 32; ++i)
3114 Py_XDECREF(table[i]);
3115 }
Tim Petersde7990b2005-07-17 23:45:23 +00003116 Py_DECREF(a);
3117 Py_DECREF(b);
3118 Py_XDECREF(c);
3119 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003120 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003121}
3122
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003123static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003124long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003125{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003126 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003127 PyLongObject *x;
3128 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003129 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003130 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003131 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003132 if (w == NULL)
3133 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003134 x = (PyLongObject *) long_add(v, w);
3135 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003136 if (x == NULL)
3137 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003138 Py_SIZE(x) = -(Py_SIZE(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003139 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003140}
3141
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003142static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003143long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003144{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003145 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003146 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003147 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003148 z = (PyLongObject *)_PyLong_Copy(v);
3149 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003150 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003151 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003152}
3153
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003154static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003155long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003156{
Christian Heimes90aa7642007-12-19 02:45:37 +00003157 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003158 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003159 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003160 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003161}
3162
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003163static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003164long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003165{
Christian Heimes90aa7642007-12-19 02:45:37 +00003166 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003167}
3168
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003169static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003170long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003171{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003172 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003173 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003174 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003175 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003176
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003177 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003178
Christian Heimes90aa7642007-12-19 02:45:37 +00003179 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003180 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003181 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003182 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003183 if (a1 == NULL)
3184 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003185 a2 = (PyLongObject *) long_rshift(a1, b);
3186 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003187 if (a2 == NULL)
3188 goto rshift_error;
3189 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003190 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003191 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003192 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003193
Neil Schemenauerba872e22001-01-04 01:46:03 +00003194 shiftby = PyLong_AsLong((PyObject *)b);
3195 if (shiftby == -1L && PyErr_Occurred())
3196 goto rshift_error;
3197 if (shiftby < 0) {
3198 PyErr_SetString(PyExc_ValueError,
3199 "negative shift count");
3200 goto rshift_error;
3201 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003202 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003203 newsize = ABS(Py_SIZE(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003204 if (newsize <= 0) {
3205 z = _PyLong_New(0);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003206 return (PyObject *)z;
3207 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003208 loshift = shiftby % PyLong_SHIFT;
3209 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003210 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003211 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003212 z = _PyLong_New(newsize);
3213 if (z == NULL)
3214 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003215 if (Py_SIZE(a) < 0)
3216 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003217 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3218 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3219 if (i+1 < newsize)
3220 z->ob_digit[i] |=
3221 (a->ob_digit[j+1] << hishift) & himask;
3222 }
3223 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003224 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003225rshift_error:
Neil Schemenauerba872e22001-01-04 01:46:03 +00003226 return (PyObject *) z;
3227
Guido van Rossumc6913e71991-11-19 20:26:46 +00003228}
3229
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003230static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003231long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003232{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003233 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003234 PyLongObject *a = (PyLongObject*)v;
3235 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003236 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003237 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003238 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003239 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003240
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003241 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003242
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003243 shiftby = PyLong_AsLong((PyObject *)b);
3244 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003245 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003246 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003247 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003248 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003249 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003250 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003251 PyErr_SetString(PyExc_ValueError,
3252 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003253 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003254 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003255 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3256 wordshift = (int)shiftby / PyLong_SHIFT;
3257 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003258
Christian Heimes90aa7642007-12-19 02:45:37 +00003259 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003260 newsize = oldsize + wordshift;
3261 if (remshift)
3262 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003263 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003264 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003265 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003266 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003267 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003268 for (i = 0; i < wordshift; i++)
3269 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003270 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003271 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003272 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003273 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3274 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003275 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003276 if (remshift)
3277 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003278 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003279 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003280 z = long_normalize(z);
3281lshift_error:
Neil Schemenauerba872e22001-01-04 01:46:03 +00003282 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003283}
3284
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003285
3286/* Bitwise and/xor/or operations */
3287
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003288static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003289long_bitwise(PyLongObject *a,
3290 int op, /* '&', '|', '^' */
3291 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003292{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003293 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003294 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003295 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003296 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003297 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003298 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003299 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003300
Christian Heimes90aa7642007-12-19 02:45:37 +00003301 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003302 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003303 if (a == NULL)
3304 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003305 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003306 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003307 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003308 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003309 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003310 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003311 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003312 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003313 if (b == NULL) {
3314 Py_DECREF(a);
3315 return NULL;
3316 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003317 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003318 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003319 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003320 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003321 maskb = 0;
3322 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003323
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003324 negz = 0;
3325 switch (op) {
3326 case '^':
3327 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003328 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003329 negz = -1;
3330 }
3331 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003332 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003333 if (maska && maskb) {
3334 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003335 maska ^= PyLong_MASK;
3336 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003337 negz = -1;
3338 }
3339 break;
3340 case '|':
3341 if (maska || maskb) {
3342 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003343 maska ^= PyLong_MASK;
3344 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003345 negz = -1;
3346 }
3347 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003348 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003349
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003350 /* JRH: The original logic here was to allocate the result value (z)
3351 as the longer of the two operands. However, there are some cases
3352 where the result is guaranteed to be shorter than that: AND of two
3353 positives, OR of two negatives: use the shorter number. AND with
3354 mixed signs: use the positive number. OR with mixed signs: use the
3355 negative number. After the transformations above, op will be '&'
3356 iff one of these cases applies, and mask will be non-0 for operands
3357 whose length should be ignored.
3358 */
3359
Christian Heimes90aa7642007-12-19 02:45:37 +00003360 size_a = Py_SIZE(a);
3361 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003362 size_z = op == '&'
3363 ? (maska
3364 ? size_b
3365 : (maskb ? size_a : MIN(size_a, size_b)))
3366 : MAX(size_a, size_b);
3367 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003368 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003369 Py_DECREF(a);
3370 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003371 return NULL;
3372 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003373
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003374 for (i = 0; i < size_z; ++i) {
3375 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3376 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3377 switch (op) {
3378 case '&': z->ob_digit[i] = diga & digb; break;
3379 case '|': z->ob_digit[i] = diga | digb; break;
3380 case '^': z->ob_digit[i] = diga ^ digb; break;
3381 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003382 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003383
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003384 Py_DECREF(a);
3385 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003386 z = long_normalize(z);
3387 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003388 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003389 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003390 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003391 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003392}
3393
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003394static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003395long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003396{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003397 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003398 CHECK_BINOP(a, b);
3399 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003400 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003401}
3402
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003403static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003404long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003405{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003406 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003407 CHECK_BINOP(a, b);
3408 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003409 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003410}
3411
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003412static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003413long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003414{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003415 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003416 CHECK_BINOP(a, b);
3417 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003418 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003419}
3420
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003421static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003422long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003423{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003424 if (PyLong_CheckExact(v))
3425 Py_INCREF(v);
3426 else
3427 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003428 return v;
3429}
3430
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003431static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003432long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003433{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003434 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003435 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003436 if (result == -1.0 && PyErr_Occurred())
3437 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003438 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003439}
3440
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003441static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003442long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003443
Tim Peters6d6c1a32001-08-02 04:15:00 +00003444static PyObject *
3445long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3446{
3447 PyObject *x = NULL;
3448 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003449 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003450
Guido van Rossumbef14172001-08-29 15:47:46 +00003451 if (type != &PyLong_Type)
3452 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003453 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003454 &x, &base))
3455 return NULL;
3456 if (x == NULL)
3457 return PyLong_FromLong(0L);
3458 if (base == -909)
3459 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003460 else if (PyUnicode_Check(x))
3461 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3462 PyUnicode_GET_SIZE(x),
3463 base);
3464 else if (PyBytes_Check(x) || PyString_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003465 /* Since PyLong_FromString doesn't have a length parameter,
3466 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003467 char *string;
Christian Heimes90aa7642007-12-19 02:45:37 +00003468 int size = Py_SIZE(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003469 if (PyBytes_Check(x))
3470 string = PyBytes_AS_STRING(x);
3471 else
3472 string = PyString_AS_STRING(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003473 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003474 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003475 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003476 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003477 "invalid literal for int() with base %d: %R",
3478 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003479 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003480 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003481 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003482 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483 else {
3484 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003485 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003486 return NULL;
3487 }
3488}
3489
Guido van Rossumbef14172001-08-29 15:47:46 +00003490/* Wimpy, slow approach to tp_new calls for subtypes of long:
3491 first create a regular long from whatever arguments we got,
3492 then allocate a subtype instance and initialize it from
3493 the regular long. The regular long is then thrown away.
3494*/
3495static PyObject *
3496long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3497{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003498 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003499 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003500
3501 assert(PyType_IsSubtype(type, &PyLong_Type));
3502 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3503 if (tmp == NULL)
3504 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003505 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003506 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003507 if (n < 0)
3508 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003509 newobj = (PyLongObject *)type->tp_alloc(type, n);
3510 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003511 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003512 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003513 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003514 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003515 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003516 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003517 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003518 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003519 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003520}
3521
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003522static PyObject *
3523long_getnewargs(PyLongObject *v)
3524{
3525 return Py_BuildValue("(N)", _PyLong_Copy(v));
3526}
3527
Guido van Rossumb43daf72007-08-01 18:08:08 +00003528static PyObject *
3529long_getN(PyLongObject *v, void *context) {
3530 return PyLong_FromLong((intptr_t)context);
3531}
3532
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003533static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003534long__format__(PyObject *self, PyObject *args)
3535{
3536 /* when back porting this to 2.6, check type of the format_spec
3537 and call either unicode_long__format__ or
3538 string_long__format__ */
3539 return unicode_long__format__(self, args);
3540}
3541
3542
3543static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003544long_round(PyObject *self, PyObject *args)
3545{
3546#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
3547 int ndigits = UNDEF_NDIGITS;
3548 double x;
3549 PyObject *res;
3550
3551 if (!PyArg_ParseTuple(args, "|i", &ndigits))
3552 return NULL;
3553
3554 if (ndigits == UNDEF_NDIGITS)
3555 return long_long(self);
3556
3557 /* If called with two args, defer to float.__round__(). */
3558 x = PyLong_AsDouble(self);
3559 if (x == -1.0 && PyErr_Occurred())
3560 return NULL;
3561 self = PyFloat_FromDouble(x);
3562 if (self == NULL)
3563 return NULL;
3564 res = PyObject_CallMethod(self, "__round__", "i", ndigits);
3565 Py_DECREF(self);
3566 return res;
3567#undef UNDEF_NDIGITS
3568}
3569
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003570static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003571 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3572 "Returns self, the complex conjugate of any int."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003573 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3574 "Truncating an Integral returns itself."},
3575 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3576 "Flooring an Integral returns itself."},
3577 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3578 "Ceiling of an Integral returns itself."},
3579 {"__round__", (PyCFunction)long_round, METH_VARARGS,
3580 "Rounding an Integral returns itself.\n"
3581 "Rounding with an ndigits arguments defers to float.__round__."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003582 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003583 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003584 {NULL, NULL} /* sentinel */
3585};
3586
Guido van Rossumb43daf72007-08-01 18:08:08 +00003587static PyGetSetDef long_getset[] = {
3588 {"real",
3589 (getter)long_long, (setter)NULL,
3590 "the real part of a complex number",
3591 NULL},
3592 {"imag",
3593 (getter)long_getN, (setter)NULL,
3594 "the imaginary part of a complex number",
3595 (void*)0},
3596 {"numerator",
3597 (getter)long_long, (setter)NULL,
3598 "the numerator of a rational number in lowest terms",
3599 NULL},
3600 {"denominator",
3601 (getter)long_getN, (setter)NULL,
3602 "the denominator of a rational number in lowest terms",
3603 (void*)1},
3604 {NULL} /* Sentinel */
3605};
3606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003607PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003608"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003610Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003611point argument will be truncated towards zero (this does not include a\n\
3612string representation of a floating point number!) When converting a\n\
3613string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003614converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003615
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003616static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003617 (binaryfunc) long_add, /*nb_add*/
3618 (binaryfunc) long_sub, /*nb_subtract*/
3619 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003620 long_mod, /*nb_remainder*/
3621 long_divmod, /*nb_divmod*/
3622 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003623 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003624 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003625 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003626 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003627 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003628 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003629 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003630 long_and, /*nb_and*/
3631 long_xor, /*nb_xor*/
3632 long_or, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00003633 0, /*nb_reserved*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003634 long_long, /*nb_int*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003635 long_long, /*nb_long*/
3636 long_float, /*nb_float*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003637 0, /*nb_oct*/ /* not used */
3638 0, /*nb_hex*/ /* not used */
Guido van Rossum4668b002001-08-08 05:00:18 +00003639 0, /* nb_inplace_add */
3640 0, /* nb_inplace_subtract */
3641 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003642 0, /* nb_inplace_remainder */
3643 0, /* nb_inplace_power */
3644 0, /* nb_inplace_lshift */
3645 0, /* nb_inplace_rshift */
3646 0, /* nb_inplace_and */
3647 0, /* nb_inplace_xor */
3648 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003649 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003650 long_true_divide, /* nb_true_divide */
3651 0, /* nb_inplace_floor_divide */
3652 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003653 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003654};
3655
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003656PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003657 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003658 "int", /* tp_name */
3659 /* See _PyLong_New for why this isn't
3660 sizeof(PyLongObject) - sizeof(digit) */
3661 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003662 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003663 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003664 0, /* tp_print */
3665 0, /* tp_getattr */
3666 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003667 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003668 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003669 &long_as_number, /* tp_as_number */
3670 0, /* tp_as_sequence */
3671 0, /* tp_as_mapping */
3672 (hashfunc)long_hash, /* tp_hash */
3673 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003674 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003675 PyObject_GenericGetAttr, /* tp_getattro */
3676 0, /* tp_setattro */
3677 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003678 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3679 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003680 long_doc, /* tp_doc */
3681 0, /* tp_traverse */
3682 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003683 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003684 0, /* tp_weaklistoffset */
3685 0, /* tp_iter */
3686 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003687 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003689 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003690 0, /* tp_base */
3691 0, /* tp_dict */
3692 0, /* tp_descr_get */
3693 0, /* tp_descr_set */
3694 0, /* tp_dictoffset */
3695 0, /* tp_init */
3696 0, /* tp_alloc */
3697 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003698 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003699};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003700
3701int
3702_PyLong_Init(void)
3703{
3704#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3705 int ival;
3706 PyLongObject *v = small_ints;
3707 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3708 PyObject_INIT(v, &PyLong_Type);
Christian Heimes90aa7642007-12-19 02:45:37 +00003709 Py_SIZE(v) = -1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003710 v->ob_digit[0] = -ival;
3711 }
3712 for (; ival < NSMALLPOSINTS; ival++, v++) {
3713 PyObject_INIT(v, &PyLong_Type);
Christian Heimes90aa7642007-12-19 02:45:37 +00003714 Py_SIZE(v) = ival ? 1 : 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003715 v->ob_digit[0] = ival;
3716 }
3717#endif
3718 return 1;
3719}
3720
3721void
3722PyLong_Fini(void)
3723{
3724#if 0
3725 int i;
3726 /* This is currently not needed; the small integers
3727 are statically allocated */
3728#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3729 PyIntObject **q;
3730
3731 i = NSMALLNEGINTS + NSMALLPOSINTS;
3732 q = small_ints;
3733 while (--i >= 0) {
3734 Py_XDECREF(*q);
3735 *q++ = NULL;
3736 }
3737#endif
3738#endif
3739}