blob: bfef437cdadd28582cd7d66cae3751a3efe11b0a [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
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00008#include <ctype.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +00009
Guido van Rossumddefaf32007-01-14 03:31:43 +000010#ifndef NSMALLPOSINTS
11#define NSMALLPOSINTS 257
12#endif
13#ifndef NSMALLNEGINTS
14#define NSMALLNEGINTS 5
15#endif
16#if NSMALLNEGINTS + NSMALLPOSINTS > 0
17/* Small integers are preallocated in this array so that they
18 can be shared.
19 The integers that are preallocated are those in the range
20 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
21*/
22static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
23#ifdef COUNT_ALLOCS
24int quick_int_allocs, quick_neg_int_allocs;
25#endif
26
Guido van Rossum7eaf8222007-06-18 17:58:50 +000027static PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +000028get_small_int(int ival)
29{
30 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
31 Py_INCREF(v);
32#ifdef COUNT_ALLOCS
33 if (ival >= 0)
34 quick_int_allocs++;
35 else
36 quick_neg_int_allocs++;
37#endif
38 return v;
39}
40#define CHECK_SMALL_INT(ival) \
41 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
42 return get_small_int(ival); \
43 } while(0)
44
45#else
46#define CHECK_SMALL_INT(ival)
47#endif
48
49#define MEDIUM_VALUE(x) ((x)->ob_size < 0 ? -(x)->ob_digit[0] : ((x)->ob_size == 0 ? 0 : (x)->ob_digit[0]))
50/* If a freshly-allocated long is already shared, it must
51 be a small integer, so negating it must go to PyLong_FromLong */
52#define NEGATE(x) \
53 do if ((x)->ob_refcnt == 1) (x)->ob_size = -(x)->ob_size; \
54 else { PyObject* tmp=PyInt_FromLong(-MEDIUM_VALUE(x)); \
55 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
56 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000057/* For long multiplication, use the O(N**2) school algorithm unless
58 * both operands contain more than KARATSUBA_CUTOFF digits (this
59 * being an internal Python long digit, in base BASE).
60 */
Tim Peters0973b992004-08-29 22:16:50 +000061#define KARATSUBA_CUTOFF 70
62#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000063
Tim Peters47e52ee2004-08-30 02:44:38 +000064/* For exponentiation, use the binary left-to-right algorithm
65 * unless the exponent contains more than FIVEARY_CUTOFF digits.
66 * In that case, do 5 bits at a time. The potential drawback is that
67 * a table of 2**5 intermediate results is computed.
68 */
69#define FIVEARY_CUTOFF 8
70
Guido van Rossume32e0141992-01-19 16:31:05 +000071#define ABS(x) ((x) < 0 ? -(x) : (x))
72
Tim Peters5af4e6c2002-08-12 02:31:19 +000073#undef MIN
74#undef MAX
75#define MAX(x, y) ((x) < (y) ? (y) : (x))
76#define MIN(x, y) ((x) > (y) ? (y) : (x))
77
Guido van Rossume32e0141992-01-19 16:31:05 +000078/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000079static PyLongObject *long_normalize(PyLongObject *);
80static PyLongObject *mul1(PyLongObject *, wdigit);
81static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000082static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Guido van Rossume32e0141992-01-19 16:31:05 +000083
Guido van Rossumc0b618a1997-05-02 03:12:38 +000084#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000085 if (--_Py_Ticker < 0) { \
86 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +000087 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000088 }
89
Guido van Rossumedcc38a1991-05-05 20:09:44 +000090/* Normalize (remove leading zeros from) a long int object.
91 Doesn't attempt to free the storage--in most cases, due to the nature
92 of the algorithms used, this could save at most be one word anyway. */
93
Guido van Rossumc0b618a1997-05-02 03:12:38 +000094static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000095long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000096{
Martin v. Löwis18e16552006-02-15 17:27:45 +000097 Py_ssize_t j = ABS(v->ob_size);
98 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +000099
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000100 while (i > 0 && v->ob_digit[i-1] == 0)
101 --i;
102 if (i != j)
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000103 v->ob_size = (v->ob_size < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000104 return v;
105}
106
107/* Allocate a new long int object with size digits.
108 Return NULL and set exception if we run out of memory. */
109
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000110PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000111_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000112{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000113 PyLongObject *result;
114 /* Can't use sizeof(PyLongObject) here, since the
115 compiler takes padding at the end into account.
116 As the consequence, this would waste 2 bytes on
117 a 32-bit system, and 6 bytes on a 64-bit system.
118 This computation would be incorrect on systems
119 which have padding before the digits; with 16-bit
120 digits this should not happen. */
121 result = PyObject_MALLOC(sizeof(PyVarObject) +
122 size*sizeof(digit));
123 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000124 PyErr_NoMemory();
125 return NULL;
126 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000127 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128}
129
Tim Peters64b5ce32001-09-10 20:52:51 +0000130PyObject *
131_PyLong_Copy(PyLongObject *src)
132{
133 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000134 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000135
136 assert(src != NULL);
137 i = src->ob_size;
138 if (i < 0)
139 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000140 if (i < 2) {
141 int ival = src->ob_digit[0];
142 if (src->ob_size < 0)
143 ival = -ival;
144 CHECK_SMALL_INT(ival);
145 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000146 result = _PyLong_New(i);
147 if (result != NULL) {
Tim Peters5329cdb2002-03-02 04:18:04 +0000148 result->ob_size = src->ob_size;
Tim Peters64b5ce32001-09-10 20:52:51 +0000149 while (--i >= 0)
150 result->ob_digit[i] = src->ob_digit[i];
151 }
152 return (PyObject *)result;
153}
154
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000155/* Create a new long int object from a C long int */
156
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000158PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000159{
Tim Petersce9de2f2001-06-14 04:56:19 +0000160 PyLongObject *v;
161 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
162 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000163 int sign = 1;
164
165 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000166
167 if (ival < 0) {
168 ival = -ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000169 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000170 }
171
Guido van Rossumddefaf32007-01-14 03:31:43 +0000172 /* Fast path for single-digits ints */
173 if (!(ival>>SHIFT)) {
174 v = _PyLong_New(1);
175 if (v) {
176 v->ob_size = sign;
177 v->ob_digit[0] = ival;
178 }
179 return (PyObject*)v;
180 }
181
182 /* 2 digits */
183 if (!(ival >> 2*SHIFT)) {
184 v = _PyLong_New(2);
185 if (v) {
186 v->ob_size = 2*sign;
187 v->ob_digit[0] = (digit)ival & MASK;
188 v->ob_digit[1] = ival >> SHIFT;
189 }
190 return (PyObject*)v;
191 }
192
193 /* Larger numbers: loop to determine number of digits */
Tim Petersce9de2f2001-06-14 04:56:19 +0000194 t = (unsigned long)ival;
195 while (t) {
196 ++ndigits;
197 t >>= SHIFT;
198 }
199 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000200 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000201 digit *p = v->ob_digit;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000202 v->ob_size = ndigits*sign;
Tim Petersce9de2f2001-06-14 04:56:19 +0000203 t = (unsigned long)ival;
204 while (t) {
205 *p++ = (digit)(t & MASK);
Guido van Rossum472c04f1996-12-05 21:57:21 +0000206 t >>= SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000207 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000208 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000209 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000210}
211
Guido van Rossum53756b11997-01-03 17:14:46 +0000212/* Create a new long int object from a C unsigned long int */
213
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000215PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000216{
Tim Petersce9de2f2001-06-14 04:56:19 +0000217 PyLongObject *v;
218 unsigned long t;
219 int ndigits = 0;
220
Guido van Rossumddefaf32007-01-14 03:31:43 +0000221 if (ival < BASE)
222 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000223 /* Count the number of Python digits. */
224 t = (unsigned long)ival;
225 while (t) {
226 ++ndigits;
227 t >>= SHIFT;
228 }
229 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000230 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000231 digit *p = v->ob_digit;
232 v->ob_size = ndigits;
233 while (ival) {
234 *p++ = (digit)(ival & MASK);
235 ival >>= SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000236 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000237 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000239}
240
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000241/* Create a new long int object from a C double */
242
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000245{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000247 double frac;
248 int i, ndig, expo, neg;
249 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000250 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000251 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000252 "cannot convert float infinity to int");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000253 return NULL;
254 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000255 CHECK_SMALL_INT((int)dval);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000256 if (dval < 0.0) {
257 neg = 1;
258 dval = -dval;
259 }
260 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
261 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000262 return PyLong_FromLong(0L);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000263 ndig = (expo-1) / SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000264 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000265 if (v == NULL)
266 return NULL;
267 frac = ldexp(frac, (expo-1) % SHIFT + 1);
268 for (i = ndig; --i >= 0; ) {
269 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000270 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000271 frac = frac - (double)bits;
272 frac = ldexp(frac, SHIFT);
273 }
274 if (neg)
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000275 v->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000276 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000277}
278
Thomas Wouters89f507f2006-12-13 04:49:30 +0000279/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
280 * anything about what happens when a signed integer operation overflows,
281 * and some compilers think they're doing you a favor by being "clever"
282 * then. The bit pattern for the largest postive signed long is
283 * (unsigned long)LONG_MAX, and for the smallest negative signed long
284 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
285 * However, some other compilers warn about applying unary minus to an
286 * unsigned operand. Hence the weird "0-".
287 */
288#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
289#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
290
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000291/* Get a C long int from a long int object.
292 Returns -1 and sets an error condition if overflow occurs. */
293
294long
Tim Peters9f688bf2000-07-07 15:53:28 +0000295PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000296{
Guido van Rossumf7531811998-05-26 14:33:37 +0000297 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000298 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000299 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000300 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000301 Py_ssize_t i;
302 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000303 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000304
Guido van Rossumddefaf32007-01-14 03:31:43 +0000305 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000306 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000307 return -1;
308 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000309
310 if (!PyLong_Check(vv)) {
311 PyNumberMethods *nb;
312 if ((nb = vv->ob_type->tp_as_number) == NULL ||
313 nb->nb_int == NULL) {
314 PyErr_SetString(PyExc_TypeError, "an integer is required");
315 return -1;
316 }
317 vv = (*nb->nb_int) (vv);
318 if (vv == NULL)
319 return -1;
320 do_decref = 1;
321 if (!PyLong_Check(vv)) {
322 Py_DECREF(vv);
323 PyErr_SetString(PyExc_TypeError,
324 "nb_int should return int object");
325 return -1;
326 }
327 }
328
Georg Brandl61c31b02007-02-26 14:46:30 +0000329 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000330 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000331 i = v->ob_size;
Guido van Rossumf7531811998-05-26 14:33:37 +0000332
Georg Brandl61c31b02007-02-26 14:46:30 +0000333 switch (i) {
334 case -1:
335 res = -v->ob_digit[0];
336 break;
337 case 0:
338 res = 0;
339 break;
340 case 1:
341 res = v->ob_digit[0];
342 break;
343 default:
344 sign = 1;
345 x = 0;
346 if (i < 0) {
347 sign = -1;
348 i = -(i);
349 }
350 while (--i >= 0) {
351 prev = x;
352 x = (x << SHIFT) + v->ob_digit[i];
353 if ((x >> SHIFT) != prev) {
354 PyErr_SetString(PyExc_OverflowError,
355 "Python int too large to convert to C long");
356 goto exit;
357 }
358 }
359 /* Haven't lost any bits, but casting to long requires extra care
360 * (see comment above).
361 */
362 if (x <= (unsigned long)LONG_MAX) {
363 res = (long)x * sign;
364 }
365 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
366 res = LONG_MIN;
367 }
368 else {
369 PyErr_SetString(PyExc_OverflowError,
370 "Python int too large to convert to C long");
371 }
372 }
373 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000374 if (do_decref) {
375 Py_DECREF(vv);
376 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000377 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000378}
379
Guido van Rossumddefaf32007-01-14 03:31:43 +0000380int
381_PyLong_FitsInLong(PyObject *vv)
382{
383 int size;
384 if (!PyLong_CheckExact(vv)) {
385 PyErr_BadInternalCall();
386 return 0;
387 }
388 /* conservative estimate */
389 size = ((PyLongObject*)vv)->ob_size;
390 return -2 <= size && size <= 2;
391}
392
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000393/* Get a Py_ssize_t from a long int object.
394 Returns -1 and sets an error condition if overflow occurs. */
395
396Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000397PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000398 register PyLongObject *v;
399 size_t x, prev;
400 Py_ssize_t i;
401 int sign;
402
403 if (vv == NULL || !PyLong_Check(vv)) {
404 PyErr_BadInternalCall();
405 return -1;
406 }
407 v = (PyLongObject *)vv;
408 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000409 switch (i) {
410 case -1: return -v->ob_digit[0];
411 case 0: return 0;
412 case 1: return v->ob_digit[0];
413 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000414 sign = 1;
415 x = 0;
416 if (i < 0) {
417 sign = -1;
418 i = -(i);
419 }
420 while (--i >= 0) {
421 prev = x;
422 x = (x << SHIFT) + v->ob_digit[i];
423 if ((x >> SHIFT) != prev)
424 goto overflow;
425 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000426 /* Haven't lost any bits, but casting to a signed type requires
427 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000428 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000429 if (x <= (size_t)PY_SSIZE_T_MAX) {
430 return (Py_ssize_t)x * sign;
431 }
432 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
433 return PY_SSIZE_T_MIN;
434 }
435 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000436
437 overflow:
438 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000439 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000440 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000441}
442
Guido van Rossumd8c80482002-08-13 00:24:58 +0000443/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000444 Returns -1 and sets an error condition if overflow occurs. */
445
446unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000447PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000448{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000449 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000450 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000451 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000452
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000453 if (vv == NULL || !PyLong_Check(vv)) {
454 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000455 return (unsigned long) -1;
456 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457 v = (PyLongObject *)vv;
Guido van Rossum53756b11997-01-03 17:14:46 +0000458 i = v->ob_size;
459 x = 0;
460 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000461 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000462 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000463 return (unsigned long) -1;
464 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000465 switch (i) {
466 case 0: return 0;
467 case 1: return v->ob_digit[0];
468 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000469 while (--i >= 0) {
470 prev = x;
471 x = (x << SHIFT) + v->ob_digit[i];
472 if ((x >> SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000473 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000474 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000475 return (unsigned long) -1;
476 }
477 }
478 return x;
479}
480
481/* Get a C unsigned long int from a long int object.
482 Returns -1 and sets an error condition if overflow occurs. */
483
484size_t
485PyLong_AsSize_t(PyObject *vv)
486{
487 register PyLongObject *v;
488 size_t x, prev;
489 Py_ssize_t i;
490
491 if (vv == NULL || !PyLong_Check(vv)) {
492 PyErr_BadInternalCall();
493 return (unsigned long) -1;
494 }
495 v = (PyLongObject *)vv;
496 i = v->ob_size;
497 x = 0;
498 if (i < 0) {
499 PyErr_SetString(PyExc_OverflowError,
500 "can't convert negative value to size_t");
501 return (size_t) -1;
502 }
503 switch (i) {
504 case 0: return 0;
505 case 1: return v->ob_digit[0];
506 }
507 while (--i >= 0) {
508 prev = x;
509 x = (x << SHIFT) + v->ob_digit[i];
510 if ((x >> SHIFT) != prev) {
511 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000512 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000513 return (unsigned long) -1;
514 }
515 }
516 return x;
517}
518
Thomas Hellera4ea6032003-04-17 18:55:45 +0000519/* Get a C unsigned long int from a long int object, ignoring the high bits.
520 Returns -1 and sets an error condition if an error occurs. */
521
Guido van Rossumddefaf32007-01-14 03:31:43 +0000522static unsigned long
523_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000524{
525 register PyLongObject *v;
526 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000527 Py_ssize_t i;
528 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000529
530 if (vv == NULL || !PyLong_Check(vv)) {
531 PyErr_BadInternalCall();
532 return (unsigned long) -1;
533 }
534 v = (PyLongObject *)vv;
535 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000536 switch (i) {
537 case 0: return 0;
538 case 1: return v->ob_digit[0];
539 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000540 sign = 1;
541 x = 0;
542 if (i < 0) {
543 sign = -1;
544 i = -i;
545 }
546 while (--i >= 0) {
547 x = (x << SHIFT) + v->ob_digit[i];
548 }
549 return x * sign;
550}
551
Guido van Rossumddefaf32007-01-14 03:31:43 +0000552unsigned long
553PyLong_AsUnsignedLongMask(register PyObject *op)
554{
555 PyNumberMethods *nb;
556 PyLongObject *lo;
557 unsigned long val;
558
559 if (op && PyLong_Check(op))
560 return _PyLong_AsUnsignedLongMask(op);
561
562 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
563 nb->nb_int == NULL) {
564 PyErr_SetString(PyExc_TypeError, "an integer is required");
565 return (unsigned long)-1;
566 }
567
568 lo = (PyLongObject*) (*nb->nb_int) (op);
569 if (lo == NULL)
570 return (unsigned long)-1;
571 if (PyLong_Check(lo)) {
572 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
573 Py_DECREF(lo);
574 if (PyErr_Occurred())
575 return (unsigned long)-1;
576 return val;
577 }
578 else
579 {
580 Py_DECREF(lo);
581 PyErr_SetString(PyExc_TypeError,
582 "nb_int should return int object");
583 return (unsigned long)-1;
584 }
585}
586
Tim Peters5b8132f2003-01-31 15:52:05 +0000587int
588_PyLong_Sign(PyObject *vv)
589{
590 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000591
592 assert(v != NULL);
593 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000594
Tim Petersee1a53c2003-02-02 02:57:53 +0000595 return v->ob_size == 0 ? 0 : (v->ob_size < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000596}
597
Tim Petersbaefd9e2003-01-28 20:37:45 +0000598size_t
599_PyLong_NumBits(PyObject *vv)
600{
601 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000602 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000603 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000604
605 assert(v != NULL);
606 assert(PyLong_Check(v));
Guido van Rossum004a65c2003-02-03 15:28:19 +0000607 ndigits = ABS(v->ob_size);
Tim Petersbaefd9e2003-01-28 20:37:45 +0000608 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
609 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000610 digit msd = v->ob_digit[ndigits - 1];
611
Tim Peters5b8132f2003-01-31 15:52:05 +0000612 result = (ndigits - 1) * SHIFT;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000613 if (result / SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000614 goto Overflow;
615 do {
616 ++result;
617 if (result == 0)
618 goto Overflow;
619 msd >>= 1;
620 } while (msd);
621 }
622 return result;
623
624Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000625 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000626 "to express in a platform size_t");
627 return (size_t)-1;
628}
629
Tim Peters2a9b3672001-06-11 21:23:58 +0000630PyObject *
631_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
632 int little_endian, int is_signed)
633{
634 const unsigned char* pstartbyte;/* LSB of bytes */
635 int incr; /* direction to move pstartbyte */
636 const unsigned char* pendbyte; /* MSB of bytes */
637 size_t numsignificantbytes; /* number of bytes that matter */
638 size_t ndigits; /* number of Python long digits */
639 PyLongObject* v; /* result */
640 int idigit = 0; /* next free index in v->ob_digit */
641
642 if (n == 0)
643 return PyLong_FromLong(0L);
644
645 if (little_endian) {
646 pstartbyte = bytes;
647 pendbyte = bytes + n - 1;
648 incr = 1;
649 }
650 else {
651 pstartbyte = bytes + n - 1;
652 pendbyte = bytes;
653 incr = -1;
654 }
655
656 if (is_signed)
657 is_signed = *pendbyte >= 0x80;
658
659 /* Compute numsignificantbytes. This consists of finding the most
660 significant byte. Leading 0 bytes are insignficant if the number
661 is positive, and leading 0xff bytes if negative. */
662 {
663 size_t i;
664 const unsigned char* p = pendbyte;
665 const int pincr = -incr; /* search MSB to LSB */
666 const unsigned char insignficant = is_signed ? 0xff : 0x00;
667
668 for (i = 0; i < n; ++i, p += pincr) {
669 if (*p != insignficant)
670 break;
671 }
672 numsignificantbytes = n - i;
673 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
674 actually has 2 significant bytes. OTOH, 0xff0001 ==
675 -0x00ffff, so we wouldn't *need* to bump it there; but we
676 do for 0xffff = -0x0001. To be safe without bothering to
677 check every case, bump it regardless. */
678 if (is_signed && numsignificantbytes < n)
679 ++numsignificantbytes;
680 }
681
682 /* How many Python long digits do we need? We have
683 8*numsignificantbytes bits, and each Python long digit has SHIFT
684 bits, so it's the ceiling of the quotient. */
685 ndigits = (numsignificantbytes * 8 + SHIFT - 1) / SHIFT;
686 if (ndigits > (size_t)INT_MAX)
687 return PyErr_NoMemory();
688 v = _PyLong_New((int)ndigits);
689 if (v == NULL)
690 return NULL;
691
692 /* Copy the bits over. The tricky parts are computing 2's-comp on
693 the fly for signed numbers, and dealing with the mismatch between
694 8-bit bytes and (probably) 15-bit Python digits.*/
695 {
696 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000697 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000698 twodigits accum = 0; /* sliding register */
699 unsigned int accumbits = 0; /* number of bits in accum */
700 const unsigned char* p = pstartbyte;
701
702 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000703 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000704 /* Compute correction for 2's comp, if needed. */
705 if (is_signed) {
706 thisbyte = (0xff ^ thisbyte) + carry;
707 carry = thisbyte >> 8;
708 thisbyte &= 0xff;
709 }
710 /* Because we're going LSB to MSB, thisbyte is
711 more significant than what's already in accum,
712 so needs to be prepended to accum. */
713 accum |= thisbyte << accumbits;
714 accumbits += 8;
715 if (accumbits >= SHIFT) {
716 /* There's enough to fill a Python digit. */
717 assert(idigit < (int)ndigits);
718 v->ob_digit[idigit] = (digit)(accum & MASK);
719 ++idigit;
720 accum >>= SHIFT;
721 accumbits -= SHIFT;
722 assert(accumbits < SHIFT);
723 }
724 }
725 assert(accumbits < SHIFT);
726 if (accumbits) {
727 assert(idigit < (int)ndigits);
728 v->ob_digit[idigit] = (digit)accum;
729 ++idigit;
730 }
731 }
732
733 v->ob_size = is_signed ? -idigit : idigit;
734 return (PyObject *)long_normalize(v);
735}
736
737int
738_PyLong_AsByteArray(PyLongObject* v,
739 unsigned char* bytes, size_t n,
740 int little_endian, int is_signed)
741{
742 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000743 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000744 twodigits accum; /* sliding register */
745 unsigned int accumbits; /* # bits in accum */
746 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
747 twodigits carry; /* for computing 2's-comp */
748 size_t j; /* # bytes filled */
749 unsigned char* p; /* pointer to next byte in bytes */
750 int pincr; /* direction to move p */
751
752 assert(v != NULL && PyLong_Check(v));
753
754 if (v->ob_size < 0) {
755 ndigits = -(v->ob_size);
756 if (!is_signed) {
757 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000758 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000759 return -1;
760 }
761 do_twos_comp = 1;
762 }
763 else {
764 ndigits = v->ob_size;
765 do_twos_comp = 0;
766 }
767
768 if (little_endian) {
769 p = bytes;
770 pincr = 1;
771 }
772 else {
773 p = bytes + n - 1;
774 pincr = -1;
775 }
776
Tim Peters898cf852001-06-13 20:50:08 +0000777 /* Copy over all the Python digits.
778 It's crucial that every Python digit except for the MSD contribute
779 exactly SHIFT bits to the total, so first assert that the long is
780 normalized. */
781 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000782 j = 0;
783 accum = 0;
784 accumbits = 0;
785 carry = do_twos_comp ? 1 : 0;
786 for (i = 0; i < ndigits; ++i) {
787 twodigits thisdigit = v->ob_digit[i];
788 if (do_twos_comp) {
789 thisdigit = (thisdigit ^ MASK) + carry;
790 carry = thisdigit >> SHIFT;
791 thisdigit &= MASK;
792 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000793 /* Because we're going LSB to MSB, thisdigit is more
794 significant than what's already in accum, so needs to be
795 prepended to accum. */
796 accum |= thisdigit << accumbits;
Tim Petersede05092001-06-14 08:53:38 +0000797 accumbits += SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000798
Tim Petersede05092001-06-14 08:53:38 +0000799 /* The most-significant digit may be (probably is) at least
800 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000801 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000802 /* Count # of sign bits -- they needn't be stored,
803 * although for signed conversion we need later to
804 * make sure at least one sign bit gets stored.
805 * First shift conceptual sign bit to real sign bit.
806 */
807 stwodigits s = (stwodigits)(thisdigit <<
808 (8*sizeof(stwodigits) - SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000809 unsigned int nsignbits = 0;
Tim Petersede05092001-06-14 08:53:38 +0000810 while ((s < 0) == do_twos_comp && nsignbits < SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000811 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000812 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000813 }
Tim Petersede05092001-06-14 08:53:38 +0000814 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000815 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000816
Tim Peters2a9b3672001-06-11 21:23:58 +0000817 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000818 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000819 if (j >= n)
820 goto Overflow;
821 ++j;
822 *p = (unsigned char)(accum & 0xff);
823 p += pincr;
824 accumbits -= 8;
825 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000826 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000827 }
828
829 /* Store the straggler (if any). */
830 assert(accumbits < 8);
831 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000832 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000833 if (j >= n)
834 goto Overflow;
835 ++j;
836 if (do_twos_comp) {
837 /* Fill leading bits of the byte with sign bits
838 (appropriately pretending that the long had an
839 infinite supply of sign bits). */
840 accum |= (~(twodigits)0) << accumbits;
841 }
842 *p = (unsigned char)(accum & 0xff);
843 p += pincr;
844 }
Tim Peters05607ad2001-06-13 21:01:27 +0000845 else if (j == n && n > 0 && is_signed) {
846 /* The main loop filled the byte array exactly, so the code
847 just above didn't get to ensure there's a sign bit, and the
848 loop below wouldn't add one either. Make sure a sign bit
849 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000850 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000851 int sign_bit_set = msb >= 0x80;
852 assert(accumbits == 0);
853 if (sign_bit_set == do_twos_comp)
854 return 0;
855 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000856 goto Overflow;
857 }
Tim Peters05607ad2001-06-13 21:01:27 +0000858
859 /* Fill remaining bytes with copies of the sign bit. */
860 {
861 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
862 for ( ; j < n; ++j, p += pincr)
863 *p = signbyte;
864 }
865
Tim Peters2a9b3672001-06-11 21:23:58 +0000866 return 0;
867
868Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000869 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000870 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000871
Tim Peters2a9b3672001-06-11 21:23:58 +0000872}
873
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000874double
875_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
876{
877/* NBITS_WANTED should be > the number of bits in a double's precision,
878 but small enough so that 2**NBITS_WANTED is within the normal double
879 range. nbitsneeded is set to 1 less than that because the most-significant
880 Python digit contains at least 1 significant bit, but we don't want to
881 bother counting them (catering to the worst case cheaply).
882
883 57 is one more than VAX-D double precision; I (Tim) don't know of a double
884 format with more precision than that; it's 1 larger so that we add in at
885 least one round bit to stand in for the ignored least-significant bits.
886*/
887#define NBITS_WANTED 57
888 PyLongObject *v;
889 double x;
890 const double multiplier = (double)(1L << SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000891 Py_ssize_t i;
892 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000893 int nbitsneeded;
894
895 if (vv == NULL || !PyLong_Check(vv)) {
896 PyErr_BadInternalCall();
897 return -1;
898 }
899 v = (PyLongObject *)vv;
900 i = v->ob_size;
901 sign = 1;
902 if (i < 0) {
903 sign = -1;
904 i = -(i);
905 }
906 else if (i == 0) {
907 *exponent = 0;
908 return 0.0;
909 }
910 --i;
911 x = (double)v->ob_digit[i];
912 nbitsneeded = NBITS_WANTED - 1;
913 /* Invariant: i Python digits remain unaccounted for. */
914 while (i > 0 && nbitsneeded > 0) {
915 --i;
916 x = x * multiplier + (double)v->ob_digit[i];
917 nbitsneeded -= SHIFT;
918 }
919 /* There are i digits we didn't shift in. Pretending they're all
920 zeroes, the true value is x * 2**(i*SHIFT). */
921 *exponent = i;
922 assert(x > 0.0);
923 return x * sign;
924#undef NBITS_WANTED
925}
926
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000927/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000928
929double
Tim Peters9f688bf2000-07-07 15:53:28 +0000930PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000931{
Thomas Wouters553489a2006-02-01 21:32:04 +0000932 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000933 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000934
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000935 if (vv == NULL || !PyLong_Check(vv)) {
936 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000937 return -1;
938 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000939 x = _PyLong_AsScaledDouble(vv, &e);
940 if (x == -1.0 && PyErr_Occurred())
941 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000942 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
943 set correctly after a successful _PyLong_AsScaledDouble() call */
944 assert(e >= 0);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000945 if (e > INT_MAX / SHIFT)
946 goto overflow;
947 errno = 0;
948 x = ldexp(x, e * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000949 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000950 goto overflow;
951 return x;
952
953overflow:
954 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000955 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000956 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000957}
958
Guido van Rossum78694d91998-09-18 14:14:13 +0000959/* Create a new long (or int) object from a C pointer */
960
961PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000962PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000963{
Tim Peters70128a12001-06-16 08:48:40 +0000964#ifndef HAVE_LONG_LONG
965# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
966#endif
967#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000968# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000969#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000970 /* special-case null pointer */
971 if (!p)
Tim Peters70128a12001-06-16 08:48:40 +0000972 return PyInt_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000973 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000974
Guido van Rossum78694d91998-09-18 14:14:13 +0000975}
976
977/* Get a C pointer from a long object (or an int object in some cases) */
978
979void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000980PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000981{
982 /* This function will allow int or long objects. If vv is neither,
983 then the PyLong_AsLong*() functions will raise the exception:
984 PyExc_SystemError, "bad argument to internal function"
985 */
Tim Peters70128a12001-06-16 08:48:40 +0000986#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000987 long x;
988
Guido van Rossumddefaf32007-01-14 03:31:43 +0000989 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000990 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000991 else
992 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000993#else
Tim Peters70128a12001-06-16 08:48:40 +0000994
995#ifndef HAVE_LONG_LONG
996# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
997#endif
998#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000999# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001000#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001001 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001002
Guido van Rossumddefaf32007-01-14 03:31:43 +00001003 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001004 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001005 else
1006 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001007
1008#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001009
1010 if (x == -1 && PyErr_Occurred())
1011 return NULL;
1012 return (void *)x;
1013}
1014
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001015#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001016
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001017/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001018 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001019 */
1020
Tim Peterscf37dfc2001-06-14 18:42:50 +00001021#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001022
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001023/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001024
1025PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001026PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001027{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001028 PyLongObject *v;
1029 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1030 int ndigits = 0;
1031 int negative = 0;
1032
Guido van Rossumddefaf32007-01-14 03:31:43 +00001033 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001034 if (ival < 0) {
1035 ival = -ival;
1036 negative = 1;
1037 }
1038
1039 /* Count the number of Python digits.
1040 We used to pick 5 ("big enough for anything"), but that's a
1041 waste of time and space given that 5*15 = 75 bits are rarely
1042 needed. */
1043 t = (unsigned PY_LONG_LONG)ival;
1044 while (t) {
1045 ++ndigits;
1046 t >>= SHIFT;
1047 }
1048 v = _PyLong_New(ndigits);
1049 if (v != NULL) {
1050 digit *p = v->ob_digit;
1051 v->ob_size = negative ? -ndigits : ndigits;
1052 t = (unsigned PY_LONG_LONG)ival;
1053 while (t) {
1054 *p++ = (digit)(t & MASK);
1055 t >>= SHIFT;
1056 }
1057 }
1058 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001059}
1060
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001061/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001062
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001063PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001064PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001065{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001066 PyLongObject *v;
1067 unsigned PY_LONG_LONG t;
1068 int ndigits = 0;
1069
Guido van Rossumddefaf32007-01-14 03:31:43 +00001070 if (ival < BASE)
1071 return PyLong_FromLong(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001072 /* Count the number of Python digits. */
1073 t = (unsigned PY_LONG_LONG)ival;
1074 while (t) {
1075 ++ndigits;
1076 t >>= SHIFT;
1077 }
1078 v = _PyLong_New(ndigits);
1079 if (v != NULL) {
1080 digit *p = v->ob_digit;
1081 v->ob_size = ndigits;
1082 while (ival) {
1083 *p++ = (digit)(ival & MASK);
1084 ival >>= SHIFT;
1085 }
1086 }
1087 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001088}
1089
Martin v. Löwis18e16552006-02-15 17:27:45 +00001090/* Create a new long int object from a C Py_ssize_t. */
1091
1092PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001093PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001094{
1095 Py_ssize_t bytes = ival;
1096 int one = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001097 if (ival < BASE)
1098 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001099 return _PyLong_FromByteArray(
1100 (unsigned char *)&bytes,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001101 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001102}
1103
1104/* Create a new long int object from a C size_t. */
1105
1106PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001107PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001108{
1109 size_t bytes = ival;
1110 int one = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001111 if (ival < BASE)
1112 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001113 return _PyLong_FromByteArray(
1114 (unsigned char *)&bytes,
1115 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
1116}
1117
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001118/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001119 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001120
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001121PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001122PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001123{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001124 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001125 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001126 int one = 1;
1127 int res;
1128
Tim Petersd38b1c72001-09-30 05:09:37 +00001129 if (vv == NULL) {
1130 PyErr_BadInternalCall();
1131 return -1;
1132 }
1133 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001134 PyNumberMethods *nb;
1135 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001136 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1137 nb->nb_int == NULL) {
1138 PyErr_SetString(PyExc_TypeError, "an integer is required");
1139 return -1;
1140 }
1141 io = (*nb->nb_int) (vv);
1142 if (io == NULL)
1143 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001144 if (PyLong_Check(io)) {
1145 bytes = PyLong_AsLongLong(io);
1146 Py_DECREF(io);
1147 return bytes;
1148 }
1149 Py_DECREF(io);
1150 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001151 return -1;
1152 }
1153
Guido van Rossumddefaf32007-01-14 03:31:43 +00001154 v = (PyLongObject*)vv;
1155 switch(v->ob_size) {
1156 case -1: return -v->ob_digit[0];
1157 case 0: return 0;
1158 case 1: return v->ob_digit[0];
1159 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001160 res = _PyLong_AsByteArray(
1161 (PyLongObject *)vv, (unsigned char *)&bytes,
1162 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001163
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001164 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001165 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001166 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001167 else
1168 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001169}
1170
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001171/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001172 Return -1 and set an error if overflow occurs. */
1173
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001174unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001175PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001176{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001177 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001178 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001179 int one = 1;
1180 int res;
1181
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001182 if (vv == NULL || !PyLong_Check(vv)) {
1183 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001184 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001185 }
1186
Guido van Rossumddefaf32007-01-14 03:31:43 +00001187 v = (PyLongObject*)vv;
1188 switch(v->ob_size) {
1189 case 0: return 0;
1190 case 1: return v->ob_digit[0];
1191 }
1192
Tim Petersd1a7da62001-06-13 00:35:57 +00001193 res = _PyLong_AsByteArray(
1194 (PyLongObject *)vv, (unsigned char *)&bytes,
1195 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001196
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001197 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001198 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001199 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001200 else
1201 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001202}
Tim Petersd1a7da62001-06-13 00:35:57 +00001203
Thomas Hellera4ea6032003-04-17 18:55:45 +00001204/* Get a C unsigned long int from a long int object, ignoring the high bits.
1205 Returns -1 and sets an error condition if an error occurs. */
1206
Guido van Rossumddefaf32007-01-14 03:31:43 +00001207static unsigned PY_LONG_LONG
1208_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001209{
1210 register PyLongObject *v;
1211 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001212 Py_ssize_t i;
1213 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001214
1215 if (vv == NULL || !PyLong_Check(vv)) {
1216 PyErr_BadInternalCall();
1217 return (unsigned long) -1;
1218 }
1219 v = (PyLongObject *)vv;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001220 switch(v->ob_size) {
1221 case 0: return 0;
1222 case 1: return v->ob_digit[0];
1223 }
Thomas Hellera4ea6032003-04-17 18:55:45 +00001224 i = v->ob_size;
1225 sign = 1;
1226 x = 0;
1227 if (i < 0) {
1228 sign = -1;
1229 i = -i;
1230 }
1231 while (--i >= 0) {
1232 x = (x << SHIFT) + v->ob_digit[i];
1233 }
1234 return x * sign;
1235}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001236
1237unsigned PY_LONG_LONG
1238PyLong_AsUnsignedLongLongMask(register PyObject *op)
1239{
1240 PyNumberMethods *nb;
1241 PyLongObject *lo;
1242 unsigned PY_LONG_LONG val;
1243
1244 if (op && PyLong_Check(op))
1245 return _PyLong_AsUnsignedLongLongMask(op);
1246
1247 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1248 nb->nb_int == NULL) {
1249 PyErr_SetString(PyExc_TypeError, "an integer is required");
1250 return (unsigned PY_LONG_LONG)-1;
1251 }
1252
1253 lo = (PyLongObject*) (*nb->nb_int) (op);
1254 if (lo == NULL)
1255 return (unsigned PY_LONG_LONG)-1;
1256 if (PyLong_Check(lo)) {
1257 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1258 Py_DECREF(lo);
1259 if (PyErr_Occurred())
1260 return (unsigned PY_LONG_LONG)-1;
1261 return val;
1262 }
1263 else
1264 {
1265 Py_DECREF(lo);
1266 PyErr_SetString(PyExc_TypeError,
1267 "nb_int should return int object");
1268 return (unsigned PY_LONG_LONG)-1;
1269 }
1270}
Tim Petersd1a7da62001-06-13 00:35:57 +00001271#undef IS_LITTLE_ENDIAN
1272
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001273#endif /* HAVE_LONG_LONG */
1274
Neil Schemenauerba872e22001-01-04 01:46:03 +00001275
1276static int
1277convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001278 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001279 *a = (PyLongObject *) v;
1280 Py_INCREF(v);
1281 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001282 else {
1283 return 0;
1284 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001285 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001286 *b = (PyLongObject *) w;
1287 Py_INCREF(w);
1288 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001289 else {
1290 Py_DECREF(*a);
1291 return 0;
1292 }
1293 return 1;
1294}
1295
1296#define CONVERT_BINOP(v, w, a, b) \
1297 if (!convert_binop(v, w, a, b)) { \
1298 Py_INCREF(Py_NotImplemented); \
1299 return Py_NotImplemented; \
1300 }
1301
Tim Peters877a2122002-08-12 05:09:36 +00001302/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1303 * is modified in place, by adding y to it. Carries are propagated as far as
1304 * x[m-1], and the remaining carry (0 or 1) is returned.
1305 */
1306static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001307v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001308{
1309 int i;
1310 digit carry = 0;
1311
1312 assert(m >= n);
1313 for (i = 0; i < n; ++i) {
1314 carry += x[i] + y[i];
1315 x[i] = carry & MASK;
1316 carry >>= SHIFT;
1317 assert((carry & 1) == carry);
1318 }
1319 for (; carry && i < m; ++i) {
1320 carry += x[i];
1321 x[i] = carry & MASK;
1322 carry >>= SHIFT;
1323 assert((carry & 1) == carry);
1324 }
1325 return carry;
1326}
1327
1328/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1329 * is modified in place, by subtracting y from it. Borrows are propagated as
1330 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1331 */
1332static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001333v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001334{
1335 int i;
1336 digit borrow = 0;
1337
1338 assert(m >= n);
1339 for (i = 0; i < n; ++i) {
1340 borrow = x[i] - y[i] - borrow;
1341 x[i] = borrow & MASK;
1342 borrow >>= SHIFT;
1343 borrow &= 1; /* keep only 1 sign bit */
1344 }
1345 for (; borrow && i < m; ++i) {
1346 borrow = x[i] - borrow;
1347 x[i] = borrow & MASK;
1348 borrow >>= SHIFT;
1349 borrow &= 1;
1350 }
1351 return borrow;
1352}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001353
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001354/* Multiply by a single digit, ignoring the sign. */
1355
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001356static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001357mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001358{
1359 return muladd1(a, n, (digit)0);
1360}
1361
1362/* Multiply by a single digit and add a single digit, ignoring the sign. */
1363
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001364static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001365muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001366{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001367 Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001368 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001369 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001370 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001371
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001372 if (z == NULL)
1373 return NULL;
1374 for (i = 0; i < size_a; ++i) {
1375 carry += (twodigits)a->ob_digit[i] * n;
Guido van Rossum2095d241997-04-09 19:41:24 +00001376 z->ob_digit[i] = (digit) (carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001377 carry >>= SHIFT;
1378 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001379 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001380 return long_normalize(z);
1381}
1382
Tim Peters212e6142001-07-14 12:23:19 +00001383/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1384 in pout, and returning the remainder. pin and pout point at the LSD.
1385 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001386 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001387 immutable. */
1388
1389static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001390inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001391{
1392 twodigits rem = 0;
1393
1394 assert(n > 0 && n <= MASK);
1395 pin += size;
1396 pout += size;
1397 while (--size >= 0) {
1398 digit hi;
1399 rem = (rem << SHIFT) + *--pin;
1400 *--pout = hi = (digit)(rem / n);
1401 rem -= hi * n;
1402 }
1403 return (digit)rem;
1404}
1405
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001406/* Divide a long integer by a digit, returning both the quotient
1407 (as function result) and the remainder (through *prem).
1408 The sign of a is ignored; n should not be zero. */
1409
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001410static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001411divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001412{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001413 const Py_ssize_t size = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001414 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001415
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001416 assert(n > 0 && n <= MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001417 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001418 if (z == NULL)
1419 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001420 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001421 return long_normalize(z);
1422}
1423
1424/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001425 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001426 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001427
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001428PyObject *
1429_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001430{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001431 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001432 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001433 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001434 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001435 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001436 int bits;
1437 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001438
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001439 if (a == NULL || !PyLong_Check(a)) {
1440 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001441 return NULL;
1442 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001443 assert(base >= 2 && base <= 36);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001444 size_a = ABS(a->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001445
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001446 /* Compute a rough upper bound for the length of the string */
1447 i = base;
1448 bits = 0;
1449 while (i > 1) {
1450 ++bits;
1451 i >>= 1;
1452 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001453 i = 5;
1454 j = size_a*SHIFT + bits-1;
1455 sz = i + j / bits;
1456 if (j / SHIFT < size_a || sz < i) {
1457 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001458 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001459 return NULL;
1460 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001461 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001462 if (str == NULL)
1463 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001464 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001465 *p = '\0';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001466 if (a->ob_size < 0)
1467 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001468
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001469 if (a->ob_size == 0) {
1470 *--p = '0';
1471 }
1472 else if ((base & (base - 1)) == 0) {
1473 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001474 twodigits accum = 0;
1475 int accumbits = 0; /* # of bits in accum */
1476 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001477 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001478 while ((i >>= 1) > 1)
1479 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001480
1481 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001482 accum |= (twodigits)a->ob_digit[i] << accumbits;
Tim Peters586b2e32001-07-15 09:11:14 +00001483 accumbits += SHIFT;
1484 assert(accumbits >= basebits);
1485 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001486 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001487 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001488 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001489 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001490 accumbits -= basebits;
1491 accum >>= basebits;
1492 } while (i < size_a-1 ? accumbits >= basebits :
1493 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001494 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001495 }
1496 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001497 /* Not 0, and base not a power of 2. Divide repeatedly by
1498 base, but for speed use the highest power of base that
1499 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001500 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001501 digit *pin = a->ob_digit;
1502 PyLongObject *scratch;
1503 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001504 digit powbase = base; /* powbase == base ** power */
1505 int power = 1;
1506 for (;;) {
1507 unsigned long newpow = powbase * (unsigned long)base;
1508 if (newpow >> SHIFT) /* doesn't fit in a digit */
1509 break;
1510 powbase = (digit)newpow;
1511 ++power;
1512 }
Tim Peters212e6142001-07-14 12:23:19 +00001513
1514 /* Get a scratch area for repeated division. */
1515 scratch = _PyLong_New(size);
1516 if (scratch == NULL) {
1517 Py_DECREF(str);
1518 return NULL;
1519 }
1520
1521 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001522 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001523 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001524 digit rem = inplace_divrem1(scratch->ob_digit,
1525 pin, size, powbase);
1526 pin = scratch->ob_digit; /* no need to use a again */
1527 if (pin[size - 1] == 0)
1528 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001529 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001530 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001531 Py_DECREF(str);
1532 return NULL;
1533 })
Tim Peters212e6142001-07-14 12:23:19 +00001534
1535 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001536 assert(ntostore > 0);
1537 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001538 digit nextrem = (digit)(rem / base);
1539 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001540 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001541 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001542 *--p = c;
1543 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001544 --ntostore;
1545 /* Termination is a bit delicate: must not
1546 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001547 remaining quotient and rem are both 0. */
1548 } while (ntostore && (size || rem));
1549 } while (size != 0);
1550 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001551 }
1552
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001553 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001554 *--p = 'x';
1555 *--p = '0';
1556 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001557 else if (base == 8) {
1558 *--p = 'o';
1559 *--p = '0';
1560 }
1561 else if (base == 2) {
1562 *--p = 'b';
1563 *--p = '0';
1564 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001565 else if (base != 10) {
1566 *--p = '#';
1567 *--p = '0' + base%10;
1568 if (base > 10)
1569 *--p = '0' + base/10;
1570 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001571 if (sign)
1572 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001573 if (p != PyUnicode_AS_UNICODE(str)) {
1574 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001575 assert(p > q);
1576 do {
1577 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001578 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001579 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1580 Py_DECREF(str);
1581 return NULL;
1582 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001583 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001584 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001585}
1586
Thomas Wouters477c8d52006-05-27 19:21:47 +00001587/* Table of digit values for 8-bit string -> integer conversion.
1588 * '0' maps to 0, ..., '9' maps to 9.
1589 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1590 * All other indices map to 37.
1591 * Note that when converting a base B string, a char c is a legitimate
1592 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1593 */
1594int _PyLong_DigitValue[256] = {
1595 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1596 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1597 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1598 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1599 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1600 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1601 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1602 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1603 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1604 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1605 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1606 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1607 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1608 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1609 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1610 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1611};
1612
1613/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001614 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1615 * non-digit (which may be *str!). A normalized long is returned.
1616 * The point to this routine is that it takes time linear in the number of
1617 * string characters.
1618 */
1619static PyLongObject *
1620long_from_binary_base(char **str, int base)
1621{
1622 char *p = *str;
1623 char *start = p;
1624 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001625 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001626 PyLongObject *z;
1627 twodigits accum;
1628 int bits_in_accum;
1629 digit *pdigit;
1630
1631 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1632 n = base;
1633 for (bits_per_char = -1; n; ++bits_per_char)
1634 n >>= 1;
1635 /* n <- total # of bits needed, while setting p to end-of-string */
1636 n = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001637 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001638 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001639 *str = p;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001640 /* n <- # of Python digits needed, = ceiling(n/SHIFT). */
1641 n = (p - start) * bits_per_char + SHIFT - 1;
1642 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001643 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001644 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001645 return NULL;
1646 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001647 n = n / SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001648 z = _PyLong_New(n);
1649 if (z == NULL)
1650 return NULL;
1651 /* Read string from right, and fill in long from left; i.e.,
1652 * from least to most significant in both.
1653 */
1654 accum = 0;
1655 bits_in_accum = 0;
1656 pdigit = z->ob_digit;
1657 while (--p >= start) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001658 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001659 assert(k >= 0 && k < base);
1660 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001661 bits_in_accum += bits_per_char;
1662 if (bits_in_accum >= SHIFT) {
1663 *pdigit++ = (digit)(accum & MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001664 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001665 accum >>= SHIFT;
1666 bits_in_accum -= SHIFT;
1667 assert(bits_in_accum < SHIFT);
1668 }
1669 }
1670 if (bits_in_accum) {
1671 assert(bits_in_accum <= SHIFT);
1672 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001673 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001674 }
1675 while (pdigit - z->ob_digit < n)
1676 *pdigit++ = 0;
1677 return long_normalize(z);
1678}
1679
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001680PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001681PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001682{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001683 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001684 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001685 PyLongObject *z = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001686 PyObject *strobj, *strrepr;
1687 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001688
Guido van Rossum472c04f1996-12-05 21:57:21 +00001689 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001690 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001691 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001692 return NULL;
1693 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001694 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001695 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001696 if (*str == '+')
1697 ++str;
1698 else if (*str == '-') {
1699 ++str;
1700 sign = -1;
1701 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001702 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001703 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001704 if (base == 0) {
1705 if (str[0] != '0')
1706 base = 10;
1707 else if (str[1] == 'x' || str[1] == 'X')
1708 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001709 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001710 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001711 else if (str[1] == 'b' || str[1] == 'B')
1712 base = 2;
1713 else {
1714 /* "old" (C-style) octal literal, now invalid.
1715 it might still be zero though */
1716 error_if_nonzero = 1;
1717 base = 10;
1718 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001719 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001720 if (str[0] == '0' &&
1721 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1722 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1723 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001724 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001725
Guido van Rossume6762971998-06-22 03:54:46 +00001726 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001727 if ((base & (base - 1)) == 0)
1728 z = long_from_binary_base(&str, base);
1729 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001730/***
1731Binary bases can be converted in time linear in the number of digits, because
1732Python's representation base is binary. Other bases (including decimal!) use
1733the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001734
Thomas Wouters477c8d52006-05-27 19:21:47 +00001735First some math: the largest integer that can be expressed in N base-B digits
1736is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1737case number of Python digits needed to hold it is the smallest integer n s.t.
1738
1739 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1740 BASE**n >= B**N [taking logs to base BASE]
1741 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1742
1743The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1744this quickly. A Python long with that much space is reserved near the start,
1745and the result is computed into it.
1746
1747The input string is actually treated as being in base base**i (i.e., i digits
1748are processed at a time), where two more static arrays hold:
1749
1750 convwidth_base[base] = the largest integer i such that base**i <= BASE
1751 convmultmax_base[base] = base ** convwidth_base[base]
1752
1753The first of these is the largest i such that i consecutive input digits
1754must fit in a single Python digit. The second is effectively the input
1755base we're really using.
1756
1757Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1758convmultmax_base[base], the result is "simply"
1759
1760 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1761
1762where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001763
1764Error analysis: as above, the number of Python digits `n` needed is worst-
1765case
1766
1767 n >= N * log(B)/log(BASE)
1768
1769where `N` is the number of input digits in base `B`. This is computed via
1770
1771 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1772
1773below. Two numeric concerns are how much space this can waste, and whether
1774the computed result can be too small. To be concrete, assume BASE = 2**15,
1775which is the default (and it's unlikely anyone changes that).
1776
1777Waste isn't a problem: provided the first input digit isn't 0, the difference
1778between the worst-case input with N digits and the smallest input with N
1779digits is about a factor of B, but B is small compared to BASE so at most
1780one allocated Python digit can remain unused on that count. If
1781N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1782and adding 1 returns a result 1 larger than necessary. However, that can't
1783happen: whenever B is a power of 2, long_from_binary_base() is called
1784instead, and it's impossible for B**i to be an integer power of 2**15 when
1785B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1786an exact integer when B is not a power of 2, since B**i has a prime factor
1787other than 2 in that case, but (2**15)**j's only prime factor is 2).
1788
1789The computed result can be too small if the true value of N*log(B)/log(BASE)
1790is a little bit larger than an exact integer, but due to roundoff errors (in
1791computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1792yields a numeric result a little less than that integer. Unfortunately, "how
1793close can a transcendental function get to an integer over some range?"
1794questions are generally theoretically intractable. Computer analysis via
1795continued fractions is practical: expand log(B)/log(BASE) via continued
1796fractions, giving a sequence i/j of "the best" rational approximations. Then
1797j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1798we can get very close to being in trouble, but very rarely. For example,
179976573 is a denominator in one of the continued-fraction approximations to
1800log(10)/log(2**15), and indeed:
1801
1802 >>> log(10)/log(2**15)*76573
1803 16958.000000654003
1804
1805is very close to an integer. If we were working with IEEE single-precision,
1806rounding errors could kill us. Finding worst cases in IEEE double-precision
1807requires better-than-double-precision log() functions, and Tim didn't bother.
1808Instead the code checks to see whether the allocated space is enough as each
1809new Python digit is added, and copies the whole thing to a larger long if not.
1810This should happen extremely rarely, and in fact I don't have a test case
1811that triggers it(!). Instead the code was tested by artificially allocating
1812just 1 digit at the start, so that the copying code was exercised for every
1813digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001814***/
1815 register twodigits c; /* current input character */
1816 Py_ssize_t size_z;
1817 int i;
1818 int convwidth;
1819 twodigits convmultmax, convmult;
1820 digit *pz, *pzstop;
1821 char* scan;
1822
1823 static double log_base_BASE[37] = {0.0e0,};
1824 static int convwidth_base[37] = {0,};
1825 static twodigits convmultmax_base[37] = {0,};
1826
1827 if (log_base_BASE[base] == 0.0) {
1828 twodigits convmax = base;
1829 int i = 1;
1830
1831 log_base_BASE[base] = log((double)base) /
1832 log((double)BASE);
1833 for (;;) {
1834 twodigits next = convmax * base;
1835 if (next > BASE)
1836 break;
1837 convmax = next;
1838 ++i;
1839 }
1840 convmultmax_base[base] = convmax;
1841 assert(i > 0);
1842 convwidth_base[base] = i;
1843 }
1844
1845 /* Find length of the string of numeric characters. */
1846 scan = str;
1847 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1848 ++scan;
1849
1850 /* Create a long object that can contain the largest possible
1851 * integer with this base and length. Note that there's no
1852 * need to initialize z->ob_digit -- no slot is read up before
1853 * being stored into.
1854 */
1855 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001856 /* Uncomment next line to test exceedingly rare copy code */
1857 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001858 assert(size_z > 0);
1859 z = _PyLong_New(size_z);
1860 if (z == NULL)
1861 return NULL;
1862 z->ob_size = 0;
1863
1864 /* `convwidth` consecutive input digits are treated as a single
1865 * digit in base `convmultmax`.
1866 */
1867 convwidth = convwidth_base[base];
1868 convmultmax = convmultmax_base[base];
1869
1870 /* Work ;-) */
1871 while (str < scan) {
1872 /* grab up to convwidth digits from the input string */
1873 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1874 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1875 c = (twodigits)(c * base +
1876 _PyLong_DigitValue[Py_CHARMASK(*str)]);
1877 assert(c < BASE);
1878 }
1879
1880 convmult = convmultmax;
1881 /* Calculate the shift only if we couldn't get
1882 * convwidth digits.
1883 */
1884 if (i != convwidth) {
1885 convmult = base;
1886 for ( ; i > 1; --i)
1887 convmult *= base;
1888 }
1889
1890 /* Multiply z by convmult, and add c. */
1891 pz = z->ob_digit;
1892 pzstop = pz + z->ob_size;
1893 for (; pz < pzstop; ++pz) {
1894 c += (twodigits)*pz * convmult;
1895 *pz = (digit)(c & MASK);
1896 c >>= SHIFT;
1897 }
1898 /* carry off the current end? */
1899 if (c) {
1900 assert(c < BASE);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001901 if (z->ob_size < size_z) {
1902 *pz = (digit)c;
1903 ++z->ob_size;
1904 }
1905 else {
1906 PyLongObject *tmp;
1907 /* Extremely rare. Get more space. */
1908 assert(z->ob_size == size_z);
1909 tmp = _PyLong_New(size_z + 1);
1910 if (tmp == NULL) {
1911 Py_DECREF(z);
1912 return NULL;
1913 }
1914 memcpy(tmp->ob_digit,
1915 z->ob_digit,
1916 sizeof(digit) * size_z);
1917 Py_DECREF(z);
1918 z = tmp;
1919 z->ob_digit[size_z] = (digit)c;
1920 ++size_z;
1921 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001922 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001923 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001924 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001925 if (z == NULL)
1926 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001927 if (error_if_nonzero) {
1928 /* reset the base to 0, else the exception message
1929 doesn't make too much sense */
1930 base = 0;
1931 if (z->ob_size != 0)
1932 goto onError;
1933 /* there might still be other problems, therefore base
1934 remains zero here for the same reason */
1935 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001936 if (str == start)
1937 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001938 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001939 z->ob_size = -(z->ob_size);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001940 if (*str == 'L' || *str == 'l')
1941 str++;
1942 while (*str && isspace(Py_CHARMASK(*str)))
1943 str++;
1944 if (*str != '\0')
1945 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001946 if (pend)
1947 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001948 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001949
1950 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001951 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001952 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1953 strobj = PyString_FromStringAndSize(orig_str, slen);
1954 if (strobj == NULL)
1955 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001956 strrepr = PyObject_ReprStr8(strobj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001957 Py_DECREF(strobj);
1958 if (strrepr == NULL)
1959 return NULL;
1960 PyErr_Format(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001961 "invalid literal for int() with base %d: %s",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001962 base, PyString_AS_STRING(strrepr));
1963 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001964 return NULL;
1965}
1966
1967PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001968PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001969{
Walter Dörwald07e14762002-11-06 16:15:14 +00001970 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001971 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001972
Walter Dörwald07e14762002-11-06 16:15:14 +00001973 if (buffer == NULL)
1974 return NULL;
1975
1976 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1977 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001978 return NULL;
1979 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001980 result = PyLong_FromString(buffer, NULL, base);
1981 PyMem_FREE(buffer);
1982 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001983}
1984
Tim Peters9f688bf2000-07-07 15:53:28 +00001985/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001986static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001987 (PyLongObject *, PyLongObject *, PyLongObject **);
1988static PyObject *long_pos(PyLongObject *);
1989static int long_divrem(PyLongObject *, PyLongObject *,
1990 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001991
1992/* Long division with remainder, top-level routine */
1993
Guido van Rossume32e0141992-01-19 16:31:05 +00001994static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001995long_divrem(PyLongObject *a, PyLongObject *b,
1996 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001997{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001998 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001999 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002000
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002001 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002002 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002003 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002004 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002005 }
2006 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002007 (size_a == size_b &&
2008 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002009 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002010 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002011 if (*pdiv == NULL)
2012 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002013 Py_INCREF(a);
2014 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002015 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002016 }
2017 if (size_b == 1) {
2018 digit rem = 0;
2019 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002020 if (z == NULL)
2021 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002022 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002023 if (*prem == NULL) {
2024 Py_DECREF(z);
2025 return -1;
2026 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002027 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002028 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002029 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002030 if (z == NULL)
2031 return -1;
2032 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002033 /* Set the signs.
2034 The quotient z has the sign of a*b;
2035 the remainder r has the sign of a,
2036 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00002037 if ((a->ob_size < 0) != (b->ob_size < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002038 NEGATE(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002039 if (a->ob_size < 0 && (*prem)->ob_size != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002040 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002041 *pdiv = z;
2042 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002043}
2044
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002045/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002046
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002047static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002048x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002049{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002050 Py_ssize_t size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size);
Guido van Rossum2095d241997-04-09 19:41:24 +00002051 digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002052 PyLongObject *v = mul1(v1, d);
2053 PyLongObject *w = mul1(w1, d);
2054 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002055 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002056
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002057 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002058 Py_XDECREF(v);
2059 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002060 return NULL;
2061 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002062
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002063 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002064 assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002065 assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002066
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002067 size_v = ABS(v->ob_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002068 k = size_v - size_w;
2069 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002070
Thomas Wouters477c8d52006-05-27 19:21:47 +00002071 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002072 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2073 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002074 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002075 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002076
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002077 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002078 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002080 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002081 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002082 if (vj == w->ob_digit[size_w-1])
2083 q = MASK;
2084 else
2085 q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
2086 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002087
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002088 while (w->ob_digit[size_w-2]*q >
2089 ((
2090 ((twodigits)vj << SHIFT)
2091 + v->ob_digit[j-1]
2092 - q*w->ob_digit[size_w-1]
2093 ) << SHIFT)
2094 + v->ob_digit[j-2])
2095 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002096
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002097 for (i = 0; i < size_w && i+k < size_v; ++i) {
2098 twodigits z = w->ob_digit[i] * q;
Guido van Rossum2095d241997-04-09 19:41:24 +00002099 digit zz = (digit) (z >> SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002100 carry += v->ob_digit[i+k] - z
2101 + ((twodigits)zz << SHIFT);
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00002102 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002103 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
2104 carry, SHIFT);
2105 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002106 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002107
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002108 if (i+k < size_v) {
2109 carry += v->ob_digit[i+k];
2110 v->ob_digit[i+k] = 0;
2111 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002112
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002113 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002114 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002115 else {
2116 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002117 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002118 carry = 0;
2119 for (i = 0; i < size_w && i+k < size_v; ++i) {
2120 carry += v->ob_digit[i+k] + w->ob_digit[i];
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00002121 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002122 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2123 BASE_TWODIGITS_TYPE,
2124 carry, SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002125 }
2126 }
2127 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002128
Guido van Rossumc206c761995-01-10 15:23:19 +00002129 if (a == NULL)
2130 *prem = NULL;
2131 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002132 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002133 *prem = divrem1(v, d, &d);
2134 /* d receives the (unused) remainder */
2135 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002136 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002137 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002138 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002139 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002140 Py_DECREF(v);
2141 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002142 return a;
2143}
2144
2145/* Methods */
2146
2147static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002148long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002149{
Guido van Rossum9475a232001-10-05 20:51:39 +00002150 v->ob_type->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002151}
2152
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002153static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002154long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002155{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002156 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002157}
2158
2159static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002160long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002161{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002162 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002163
Guido van Rossumc6913e71991-11-19 20:26:46 +00002164 if (a->ob_size != b->ob_size) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002165 if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002166 sign = 0;
2167 else
2168 sign = a->ob_size - b->ob_size;
2169 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002170 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002171 Py_ssize_t i = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002172 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2173 ;
2174 if (i < 0)
2175 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002176 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002177 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002178 if (a->ob_size < 0)
2179 sign = -sign;
2180 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002181 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002182 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002183}
2184
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002185static PyObject *
2186long_richcompare(PyObject *self, PyObject *other, int op)
2187{
2188 PyLongObject *a, *b;
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002189 PyObject *result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002190 CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b);
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002191 result = Py_CmpToRich(op, long_compare(a, b));
2192 Py_DECREF(a);
2193 Py_DECREF(b);
2194 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002195}
2196
Guido van Rossum9bfef441993-03-29 10:43:31 +00002197static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002198long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002199{
2200 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002201 Py_ssize_t i;
2202 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002203
2204 /* This is designed so that Python ints and longs with the
2205 same value hash to the same value, otherwise comparisons
2206 of mapping keys will turn out weird */
2207 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00002208 switch(i) {
2209 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2210 case 0: return 0;
2211 case 1: return v->ob_digit[0];
2212 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002213 sign = 1;
2214 x = 0;
2215 if (i < 0) {
2216 sign = -1;
2217 i = -(i);
2218 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002219#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002220 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002221 /* Force a native long #-bits (32 or 64) circular shift */
2222 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002223 x += v->ob_digit[i];
2224 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002225#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002226 x = x * sign;
2227 if (x == -1)
2228 x = -2;
2229 return x;
2230}
2231
2232
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002233/* Add the absolute values of two long integers. */
2234
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002235static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002236x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002237{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002238 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002239 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002240 int i;
2241 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002242
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002243 /* Ensure a is the larger of the two: */
2244 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002245 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002246 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002247 size_a = size_b;
2248 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002249 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002250 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002251 if (z == NULL)
2252 return NULL;
2253 for (i = 0; i < size_b; ++i) {
2254 carry += a->ob_digit[i] + b->ob_digit[i];
2255 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002256 carry >>= SHIFT;
2257 }
2258 for (; i < size_a; ++i) {
2259 carry += a->ob_digit[i];
2260 z->ob_digit[i] = carry & MASK;
2261 carry >>= SHIFT;
2262 }
2263 z->ob_digit[i] = carry;
2264 return long_normalize(z);
2265}
2266
2267/* Subtract the absolute values of two integers. */
2268
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002269static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002270x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002271{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002272 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002273 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002274 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002275 int sign = 1;
2276 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002277
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002278 /* Ensure a is the larger of the two: */
2279 if (size_a < size_b) {
2280 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002281 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002282 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002283 size_a = size_b;
2284 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002285 }
2286 else if (size_a == size_b) {
2287 /* Find highest digit where a and b differ: */
2288 i = size_a;
2289 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2290 ;
2291 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002292 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002293 if (a->ob_digit[i] < b->ob_digit[i]) {
2294 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002295 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002296 }
2297 size_a = size_b = i+1;
2298 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002299 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002300 if (z == NULL)
2301 return NULL;
2302 for (i = 0; i < size_b; ++i) {
2303 /* The following assumes unsigned arithmetic
2304 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002305 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002306 z->ob_digit[i] = borrow & MASK;
2307 borrow >>= SHIFT;
2308 borrow &= 1; /* Keep only one sign bit */
2309 }
2310 for (; i < size_a; ++i) {
2311 borrow = a->ob_digit[i] - borrow;
2312 z->ob_digit[i] = borrow & MASK;
2313 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002314 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002315 }
2316 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002317 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002318 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002319 return long_normalize(z);
2320}
2321
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002322static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002323long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002324{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002325 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002326
Neil Schemenauerba872e22001-01-04 01:46:03 +00002327 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2328
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002329 if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) {
2330 PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) +
2331 MEDIUM_VALUE(b));
2332 Py_DECREF(a);
2333 Py_DECREF(b);
2334 return result;
2335 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002336 if (a->ob_size < 0) {
2337 if (b->ob_size < 0) {
2338 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002339 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002340 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002341 }
2342 else
2343 z = x_sub(b, a);
2344 }
2345 else {
2346 if (b->ob_size < 0)
2347 z = x_sub(a, b);
2348 else
2349 z = x_add(a, b);
2350 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002351 Py_DECREF(a);
2352 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002353 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002354}
2355
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002356static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002357long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002358{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002359 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002360
Neil Schemenauerba872e22001-01-04 01:46:03 +00002361 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2362
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002363 if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) {
2364 PyObject* r;
2365 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2366 Py_DECREF(a);
2367 Py_DECREF(b);
2368 return r;
2369 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002370 if (a->ob_size < 0) {
2371 if (b->ob_size < 0)
2372 z = x_sub(a, b);
2373 else
2374 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002375 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002376 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002377 }
2378 else {
2379 if (b->ob_size < 0)
2380 z = x_add(a, b);
2381 else
2382 z = x_sub(a, b);
2383 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002384 Py_DECREF(a);
2385 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002386 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002387}
2388
Tim Peters5af4e6c2002-08-12 02:31:19 +00002389/* Grade school multiplication, ignoring the signs.
2390 * Returns the absolute value of the product, or NULL if error.
2391 */
2392static PyLongObject *
2393x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002394{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002395 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002396 Py_ssize_t size_a = ABS(a->ob_size);
2397 Py_ssize_t size_b = ABS(b->ob_size);
2398 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002399
Tim Peters5af4e6c2002-08-12 02:31:19 +00002400 z = _PyLong_New(size_a + size_b);
2401 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002402 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002403
2404 memset(z->ob_digit, 0, z->ob_size * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002405 if (a == b) {
2406 /* Efficient squaring per HAC, Algorithm 14.16:
2407 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2408 * Gives slightly less than a 2x speedup when a == b,
2409 * via exploiting that each entry in the multiplication
2410 * pyramid appears twice (except for the size_a squares).
2411 */
2412 for (i = 0; i < size_a; ++i) {
2413 twodigits carry;
2414 twodigits f = a->ob_digit[i];
2415 digit *pz = z->ob_digit + (i << 1);
2416 digit *pa = a->ob_digit + i + 1;
2417 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002418
Tim Peters0973b992004-08-29 22:16:50 +00002419 SIGCHECK({
2420 Py_DECREF(z);
2421 return NULL;
2422 })
2423
2424 carry = *pz + f * f;
2425 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002426 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002427 assert(carry <= MASK);
2428
2429 /* Now f is added in twice in each column of the
2430 * pyramid it appears. Same as adding f<<1 once.
2431 */
2432 f <<= 1;
2433 while (pa < paend) {
2434 carry += *pz + *pa++ * f;
2435 *pz++ = (digit)(carry & MASK);
2436 carry >>= SHIFT;
2437 assert(carry <= (MASK << 1));
2438 }
2439 if (carry) {
2440 carry += *pz;
2441 *pz++ = (digit)(carry & MASK);
2442 carry >>= SHIFT;
2443 }
2444 if (carry)
2445 *pz += (digit)(carry & MASK);
2446 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002447 }
Tim Peters0973b992004-08-29 22:16:50 +00002448 }
2449 else { /* a is not the same as b -- gradeschool long mult */
2450 for (i = 0; i < size_a; ++i) {
2451 twodigits carry = 0;
2452 twodigits f = a->ob_digit[i];
2453 digit *pz = z->ob_digit + i;
2454 digit *pb = b->ob_digit;
2455 digit *pbend = b->ob_digit + size_b;
2456
2457 SIGCHECK({
2458 Py_DECREF(z);
2459 return NULL;
2460 })
2461
2462 while (pb < pbend) {
2463 carry += *pz + *pb++ * f;
2464 *pz++ = (digit)(carry & MASK);
2465 carry >>= SHIFT;
2466 assert(carry <= MASK);
2467 }
2468 if (carry)
2469 *pz += (digit)(carry & MASK);
2470 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002471 }
2472 }
Tim Peters44121a62002-08-12 06:17:58 +00002473 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002474}
2475
2476/* A helper for Karatsuba multiplication (k_mul).
2477 Takes a long "n" and an integer "size" representing the place to
2478 split, and sets low and high such that abs(n) == (high << size) + low,
2479 viewing the shift as being by digits. The sign bit is ignored, and
2480 the return values are >= 0.
2481 Returns 0 on success, -1 on failure.
2482*/
2483static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002484kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002485{
2486 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002487 Py_ssize_t size_lo, size_hi;
2488 const Py_ssize_t size_n = ABS(n->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002489
2490 size_lo = MIN(size_n, size);
2491 size_hi = size_n - size_lo;
2492
2493 if ((hi = _PyLong_New(size_hi)) == NULL)
2494 return -1;
2495 if ((lo = _PyLong_New(size_lo)) == NULL) {
2496 Py_DECREF(hi);
2497 return -1;
2498 }
2499
2500 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2501 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2502
2503 *high = long_normalize(hi);
2504 *low = long_normalize(lo);
2505 return 0;
2506}
2507
Tim Peters60004642002-08-12 22:01:34 +00002508static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2509
Tim Peters5af4e6c2002-08-12 02:31:19 +00002510/* Karatsuba multiplication. Ignores the input signs, and returns the
2511 * absolute value of the product (or NULL if error).
2512 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2513 */
2514static PyLongObject *
2515k_mul(PyLongObject *a, PyLongObject *b)
2516{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002517 Py_ssize_t asize = ABS(a->ob_size);
2518 Py_ssize_t bsize = ABS(b->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002519 PyLongObject *ah = NULL;
2520 PyLongObject *al = NULL;
2521 PyLongObject *bh = NULL;
2522 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002523 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002524 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002525 Py_ssize_t shift; /* the number of digits we split off */
2526 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002527
Tim Peters5af4e6c2002-08-12 02:31:19 +00002528 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2529 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2530 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002531 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002532 * By picking X to be a power of 2, "*X" is just shifting, and it's
2533 * been reduced to 3 multiplies on numbers half the size.
2534 */
2535
Tim Petersfc07e562002-08-12 02:54:10 +00002536 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002537 * is largest.
2538 */
Tim Peters738eda72002-08-12 15:08:20 +00002539 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002540 t1 = a;
2541 a = b;
2542 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002543
2544 i = asize;
2545 asize = bsize;
2546 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002547 }
2548
2549 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002550 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2551 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002552 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002553 return _PyLong_New(0);
2554 else
2555 return x_mul(a, b);
2556 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002557
Tim Peters60004642002-08-12 22:01:34 +00002558 /* If a is small compared to b, splitting on b gives a degenerate
2559 * case with ah==0, and Karatsuba may be (even much) less efficient
2560 * than "grade school" then. However, we can still win, by viewing
2561 * b as a string of "big digits", each of width a->ob_size. That
2562 * leads to a sequence of balanced calls to k_mul.
2563 */
2564 if (2 * asize <= bsize)
2565 return k_lopsided_mul(a, b);
2566
Tim Petersd6974a52002-08-13 20:37:51 +00002567 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002568 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002569 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Tim Petersd6974a52002-08-13 20:37:51 +00002570 assert(ah->ob_size > 0); /* the split isn't degenerate */
2571
Tim Peters0973b992004-08-29 22:16:50 +00002572 if (a == b) {
2573 bh = ah;
2574 bl = al;
2575 Py_INCREF(bh);
2576 Py_INCREF(bl);
2577 }
2578 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002579
Tim Petersd64c1de2002-08-12 17:36:03 +00002580 /* The plan:
2581 * 1. Allocate result space (asize + bsize digits: that's always
2582 * enough).
2583 * 2. Compute ah*bh, and copy into result at 2*shift.
2584 * 3. Compute al*bl, and copy into result at 0. Note that this
2585 * can't overlap with #2.
2586 * 4. Subtract al*bl from the result, starting at shift. This may
2587 * underflow (borrow out of the high digit), but we don't care:
2588 * we're effectively doing unsigned arithmetic mod
2589 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2590 * borrows and carries out of the high digit can be ignored.
2591 * 5. Subtract ah*bh from the result, starting at shift.
2592 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2593 * at shift.
2594 */
2595
2596 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002597 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002598 if (ret == NULL) goto fail;
2599#ifdef Py_DEBUG
2600 /* Fill with trash, to catch reference to uninitialized digits. */
2601 memset(ret->ob_digit, 0xDF, ret->ob_size * sizeof(digit));
2602#endif
Tim Peters44121a62002-08-12 06:17:58 +00002603
Tim Petersd64c1de2002-08-12 17:36:03 +00002604 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002605 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2606 assert(t1->ob_size >= 0);
2607 assert(2*shift + t1->ob_size <= ret->ob_size);
2608 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2609 t1->ob_size * sizeof(digit));
2610
2611 /* Zero-out the digits higher than the ah*bh copy. */
2612 i = ret->ob_size - 2*shift - t1->ob_size;
Tim Peters44121a62002-08-12 06:17:58 +00002613 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002614 memset(ret->ob_digit + 2*shift + t1->ob_size, 0,
Tim Peters44121a62002-08-12 06:17:58 +00002615 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002616
Tim Petersd64c1de2002-08-12 17:36:03 +00002617 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002618 if ((t2 = k_mul(al, bl)) == NULL) {
2619 Py_DECREF(t1);
2620 goto fail;
2621 }
2622 assert(t2->ob_size >= 0);
2623 assert(t2->ob_size <= 2*shift); /* no overlap with high digits */
2624 memcpy(ret->ob_digit, t2->ob_digit, t2->ob_size * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002625
2626 /* Zero out remaining digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002627 i = 2*shift - t2->ob_size; /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002628 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002629 memset(ret->ob_digit + t2->ob_size, 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002630
Tim Petersd64c1de2002-08-12 17:36:03 +00002631 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2632 * because it's fresher in cache.
2633 */
Tim Peters738eda72002-08-12 15:08:20 +00002634 i = ret->ob_size - shift; /* # digits after shift */
Tim Petersd64c1de2002-08-12 17:36:03 +00002635 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, t2->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002636 Py_DECREF(t2);
2637
Tim Petersd64c1de2002-08-12 17:36:03 +00002638 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, t1->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002639 Py_DECREF(t1);
2640
Tim Petersd64c1de2002-08-12 17:36:03 +00002641 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002642 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2643 Py_DECREF(ah);
2644 Py_DECREF(al);
2645 ah = al = NULL;
2646
Tim Peters0973b992004-08-29 22:16:50 +00002647 if (a == b) {
2648 t2 = t1;
2649 Py_INCREF(t2);
2650 }
2651 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002652 Py_DECREF(t1);
2653 goto fail;
2654 }
2655 Py_DECREF(bh);
2656 Py_DECREF(bl);
2657 bh = bl = NULL;
2658
Tim Peters738eda72002-08-12 15:08:20 +00002659 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002660 Py_DECREF(t1);
2661 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002662 if (t3 == NULL) goto fail;
Tim Peters547607c2002-08-12 19:43:49 +00002663 assert(t3->ob_size >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002664
Tim Petersd6974a52002-08-13 20:37:51 +00002665 /* Add t3. It's not obvious why we can't run out of room here.
2666 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002667 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002668 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, t3->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002669 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002670
Tim Peters5af4e6c2002-08-12 02:31:19 +00002671 return long_normalize(ret);
2672
2673 fail:
2674 Py_XDECREF(ret);
2675 Py_XDECREF(ah);
2676 Py_XDECREF(al);
2677 Py_XDECREF(bh);
2678 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002679 return NULL;
2680}
2681
Tim Petersd6974a52002-08-13 20:37:51 +00002682/* (*) Why adding t3 can't "run out of room" above.
2683
Tim Petersab86c2b2002-08-15 20:06:00 +00002684Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2685to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002686
Tim Petersab86c2b2002-08-15 20:06:00 +000026871. For any integer i, i = c(i/2) + f(i/2). In particular,
2688 bsize = c(bsize/2) + f(bsize/2).
26892. shift = f(bsize/2)
26903. asize <= bsize
26914. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2692 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002693
Tim Petersab86c2b2002-08-15 20:06:00 +00002694We allocated asize + bsize result digits, and add t3 into them at an offset
2695of shift. This leaves asize+bsize-shift allocated digit positions for t3
2696to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2697asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002698
Tim Petersab86c2b2002-08-15 20:06:00 +00002699bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2700at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002701
Tim Petersab86c2b2002-08-15 20:06:00 +00002702If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2703digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2704most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002705
Tim Petersab86c2b2002-08-15 20:06:00 +00002706The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002707
Tim Petersab86c2b2002-08-15 20:06:00 +00002708 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002709
Tim Petersab86c2b2002-08-15 20:06:00 +00002710and we have asize + c(bsize/2) available digit positions. We need to show
2711this is always enough. An instance of c(bsize/2) cancels out in both, so
2712the question reduces to whether asize digits is enough to hold
2713(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2714then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2715asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2716digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2717asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002718c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2719is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2720bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002721
Tim Peters48d52c02002-08-14 17:07:32 +00002722Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2723clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2724ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002725*/
2726
Tim Peters60004642002-08-12 22:01:34 +00002727/* b has at least twice the digits of a, and a is big enough that Karatsuba
2728 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2729 * of slices, each with a->ob_size digits, and multiply the slices by a,
2730 * one at a time. This gives k_mul balanced inputs to work with, and is
2731 * also cache-friendly (we compute one double-width slice of the result
2732 * at a time, then move on, never bactracking except for the helpful
2733 * single-width slice overlap between successive partial sums).
2734 */
2735static PyLongObject *
2736k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2737{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002738 const Py_ssize_t asize = ABS(a->ob_size);
2739 Py_ssize_t bsize = ABS(b->ob_size);
2740 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002741 PyLongObject *ret;
2742 PyLongObject *bslice = NULL;
2743
2744 assert(asize > KARATSUBA_CUTOFF);
2745 assert(2 * asize <= bsize);
2746
2747 /* Allocate result space, and zero it out. */
2748 ret = _PyLong_New(asize + bsize);
2749 if (ret == NULL)
2750 return NULL;
2751 memset(ret->ob_digit, 0, ret->ob_size * sizeof(digit));
2752
2753 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002754 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002755 if (bslice == NULL)
2756 goto fail;
2757
2758 nbdone = 0;
2759 while (bsize > 0) {
2760 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002761 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002762
2763 /* Multiply the next slice of b by a. */
2764 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2765 nbtouse * sizeof(digit));
2766 bslice->ob_size = nbtouse;
2767 product = k_mul(a, bslice);
2768 if (product == NULL)
2769 goto fail;
2770
2771 /* Add into result. */
2772 (void)v_iadd(ret->ob_digit + nbdone, ret->ob_size - nbdone,
2773 product->ob_digit, product->ob_size);
2774 Py_DECREF(product);
2775
2776 bsize -= nbtouse;
2777 nbdone += nbtouse;
2778 }
2779
2780 Py_DECREF(bslice);
2781 return long_normalize(ret);
2782
2783 fail:
2784 Py_DECREF(ret);
2785 Py_XDECREF(bslice);
2786 return NULL;
2787}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002788
2789static PyObject *
2790long_mul(PyLongObject *v, PyLongObject *w)
2791{
2792 PyLongObject *a, *b, *z;
2793
2794 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002795 Py_INCREF(Py_NotImplemented);
2796 return Py_NotImplemented;
2797 }
2798
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002799 if (ABS(v->ob_size) <= 1 && ABS(w->ob_size) <= 1) {
2800 PyObject *r;
2801 r = PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w));
2802 Py_DECREF(a);
2803 Py_DECREF(b);
2804 return r;
2805 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002806
Tim Petersd64c1de2002-08-12 17:36:03 +00002807 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002808 /* Negate if exactly one of the inputs is negative. */
2809 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002810 NEGATE(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002811 Py_DECREF(a);
2812 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002813 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002814}
2815
Guido van Rossume32e0141992-01-19 16:31:05 +00002816/* The / and % operators are now defined in terms of divmod().
2817 The expression a mod b has the value a - b*floor(a/b).
2818 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002819 |a| by |b|, with the sign of a. This is also expressed
2820 as a - b*trunc(a/b), if trunc truncates towards zero.
2821 Some examples:
2822 a b a rem b a mod b
2823 13 10 3 3
2824 -13 10 -3 7
2825 13 -10 3 -7
2826 -13 -10 -3 -3
2827 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002828 have different signs. We then subtract one from the 'div'
2829 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002830
Tim Peters47e52ee2004-08-30 02:44:38 +00002831/* Compute
2832 * *pdiv, *pmod = divmod(v, w)
2833 * NULL can be passed for pdiv or pmod, in which case that part of
2834 * the result is simply thrown away. The caller owns a reference to
2835 * each of these it requests (does not pass NULL for).
2836 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002837static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002838l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002839 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002840{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002841 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002842
Guido van Rossume32e0141992-01-19 16:31:05 +00002843 if (long_divrem(v, w, &div, &mod) < 0)
2844 return -1;
Guido van Rossum472c04f1996-12-05 21:57:21 +00002845 if ((mod->ob_size < 0 && w->ob_size > 0) ||
2846 (mod->ob_size > 0 && w->ob_size < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002847 PyLongObject *temp;
2848 PyLongObject *one;
2849 temp = (PyLongObject *) long_add(mod, w);
2850 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002851 mod = temp;
2852 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002853 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002854 return -1;
2855 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002856 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002857 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002858 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2859 Py_DECREF(mod);
2860 Py_DECREF(div);
2861 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002862 return -1;
2863 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002864 Py_DECREF(one);
2865 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002866 div = temp;
2867 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002868 if (pdiv != NULL)
2869 *pdiv = div;
2870 else
2871 Py_DECREF(div);
2872
2873 if (pmod != NULL)
2874 *pmod = mod;
2875 else
2876 Py_DECREF(mod);
2877
Guido van Rossume32e0141992-01-19 16:31:05 +00002878 return 0;
2879}
2880
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002881static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002882long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002883{
Tim Peters47e52ee2004-08-30 02:44:38 +00002884 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002885
2886 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002887 if (l_divmod(a, b, &div, NULL) < 0)
2888 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002889 Py_DECREF(a);
2890 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002891 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002892}
2893
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002894static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002895long_true_divide(PyObject *v, PyObject *w)
2896{
Tim Peterse2a60002001-09-04 06:17:36 +00002897 PyLongObject *a, *b;
2898 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002899 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002900
2901 CONVERT_BINOP(v, w, &a, &b);
2902 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2903 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002904 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2905 Py_DECREF(a);
2906 Py_DECREF(b);
2907 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002908 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002909 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2910 but should really be set correctly after sucessful calls to
2911 _PyLong_AsScaledDouble() */
2912 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002913
2914 if (bd == 0.0) {
2915 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002916 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002917 return NULL;
2918 }
2919
2920 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2921 ad /= bd; /* overflow/underflow impossible here */
2922 aexp -= bexp;
2923 if (aexp > INT_MAX / SHIFT)
2924 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002925 else if (aexp < -(INT_MAX / SHIFT))
2926 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002927 errno = 0;
2928 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002929 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002930 goto overflow;
2931 return PyFloat_FromDouble(ad);
2932
2933overflow:
2934 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002935 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002936 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002937
Tim Peters20dab9f2001-09-04 05:31:47 +00002938}
2939
2940static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002941long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002942{
Tim Peters47e52ee2004-08-30 02:44:38 +00002943 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002944
2945 CONVERT_BINOP(v, w, &a, &b);
2946
Tim Peters47e52ee2004-08-30 02:44:38 +00002947 if (l_divmod(a, b, NULL, &mod) < 0)
2948 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002949 Py_DECREF(a);
2950 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002951 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002952}
2953
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002954static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002955long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002956{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002957 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002958 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002959
2960 CONVERT_BINOP(v, w, &a, &b);
2961
2962 if (l_divmod(a, b, &div, &mod) < 0) {
2963 Py_DECREF(a);
2964 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002965 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002966 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002967 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002968 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002969 PyTuple_SetItem(z, 0, (PyObject *) div);
2970 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002971 }
2972 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002973 Py_DECREF(div);
2974 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002975 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002976 Py_DECREF(a);
2977 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002978 return z;
2979}
2980
Tim Peters47e52ee2004-08-30 02:44:38 +00002981/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002982static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002983long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002984{
Tim Peters47e52ee2004-08-30 02:44:38 +00002985 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2986 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002987
Tim Peters47e52ee2004-08-30 02:44:38 +00002988 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002989 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002990 PyLongObject *temp = NULL;
2991
2992 /* 5-ary values. If the exponent is large enough, table is
2993 * precomputed so that table[i] == a**i % c for i in range(32).
2994 */
2995 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2996 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2997
2998 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002999 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003000 if (PyLong_Check(x)) {
3001 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003002 Py_INCREF(x);
3003 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003004 else if (x == Py_None)
3005 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003006 else {
3007 Py_DECREF(a);
3008 Py_DECREF(b);
3009 Py_INCREF(Py_NotImplemented);
3010 return Py_NotImplemented;
3011 }
Tim Peters4c483c42001-09-05 06:24:58 +00003012
Tim Peters47e52ee2004-08-30 02:44:38 +00003013 if (b->ob_size < 0) { /* if exponent is negative */
3014 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003015 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003016 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003017 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003018 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003019 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003020 /* else return a float. This works because we know
3021 that this calls float_pow() which converts its
3022 arguments to double. */
3023 Py_DECREF(a);
3024 Py_DECREF(b);
3025 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003026 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003027 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003028
3029 if (c) {
3030 /* if modulus == 0:
3031 raise ValueError() */
3032 if (c->ob_size == 0) {
3033 PyErr_SetString(PyExc_ValueError,
3034 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003035 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003036 }
3037
3038 /* if modulus < 0:
3039 negativeOutput = True
3040 modulus = -modulus */
3041 if (c->ob_size < 0) {
3042 negativeOutput = 1;
3043 temp = (PyLongObject *)_PyLong_Copy(c);
3044 if (temp == NULL)
3045 goto Error;
3046 Py_DECREF(c);
3047 c = temp;
3048 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003049 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003050 }
3051
3052 /* if modulus == 1:
3053 return 0 */
3054 if ((c->ob_size == 1) && (c->ob_digit[0] == 1)) {
3055 z = (PyLongObject *)PyLong_FromLong(0L);
3056 goto Done;
3057 }
3058
3059 /* if base < 0:
3060 base = base % modulus
3061 Having the base positive just makes things easier. */
3062 if (a->ob_size < 0) {
3063 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003064 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003065 Py_DECREF(a);
3066 a = temp;
3067 temp = NULL;
3068 }
3069 }
3070
3071 /* At this point a, b, and c are guaranteed non-negative UNLESS
3072 c is NULL, in which case a may be negative. */
3073
3074 z = (PyLongObject *)PyLong_FromLong(1L);
3075 if (z == NULL)
3076 goto Error;
3077
3078 /* Perform a modular reduction, X = X % c, but leave X alone if c
3079 * is NULL.
3080 */
3081#define REDUCE(X) \
3082 if (c != NULL) { \
3083 if (l_divmod(X, c, NULL, &temp) < 0) \
3084 goto Error; \
3085 Py_XDECREF(X); \
3086 X = temp; \
3087 temp = NULL; \
3088 }
3089
3090 /* Multiply two values, then reduce the result:
3091 result = X*Y % c. If c is NULL, skip the mod. */
3092#define MULT(X, Y, result) \
3093{ \
3094 temp = (PyLongObject *)long_mul(X, Y); \
3095 if (temp == NULL) \
3096 goto Error; \
3097 Py_XDECREF(result); \
3098 result = temp; \
3099 temp = NULL; \
3100 REDUCE(result) \
3101}
3102
3103 if (b->ob_size <= FIVEARY_CUTOFF) {
3104 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3105 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3106 for (i = b->ob_size - 1; i >= 0; --i) {
3107 digit bi = b->ob_digit[i];
3108
3109 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
3110 MULT(z, z, z)
3111 if (bi & j)
3112 MULT(z, a, z)
3113 }
3114 }
3115 }
3116 else {
3117 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3118 Py_INCREF(z); /* still holds 1L */
3119 table[0] = z;
3120 for (i = 1; i < 32; ++i)
3121 MULT(table[i-1], a, table[i])
3122
3123 for (i = b->ob_size - 1; i >= 0; --i) {
3124 const digit bi = b->ob_digit[i];
3125
3126 for (j = SHIFT - 5; j >= 0; j -= 5) {
3127 const int index = (bi >> j) & 0x1f;
3128 for (k = 0; k < 5; ++k)
3129 MULT(z, z, z)
3130 if (index)
3131 MULT(z, table[index], z)
3132 }
3133 }
3134 }
3135
3136 if (negativeOutput && (z->ob_size != 0)) {
3137 temp = (PyLongObject *)long_sub(z, c);
3138 if (temp == NULL)
3139 goto Error;
3140 Py_DECREF(z);
3141 z = temp;
3142 temp = NULL;
3143 }
3144 goto Done;
3145
3146 Error:
3147 if (z != NULL) {
3148 Py_DECREF(z);
3149 z = NULL;
3150 }
3151 /* fall through */
3152 Done:
Tim Peters47e52ee2004-08-30 02:44:38 +00003153 if (b->ob_size > FIVEARY_CUTOFF) {
3154 for (i = 0; i < 32; ++i)
3155 Py_XDECREF(table[i]);
3156 }
Tim Petersde7990b2005-07-17 23:45:23 +00003157 Py_DECREF(a);
3158 Py_DECREF(b);
3159 Py_XDECREF(c);
3160 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003161 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003162}
3163
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003164static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003165long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003166{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003167 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003168 PyLongObject *x;
3169 PyLongObject *w;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003170 if (ABS(v->ob_size) <=1)
3171 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003172 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003173 if (w == NULL)
3174 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003175 x = (PyLongObject *) long_add(v, w);
3176 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003177 if (x == NULL)
3178 return NULL;
Tim Peters40c397d2001-09-11 23:24:22 +00003179 x->ob_size = -(x->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003180 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003181}
3182
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003183static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003184long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003185{
Tim Peters69c2de32001-09-11 22:31:33 +00003186 if (PyLong_CheckExact(v)) {
3187 Py_INCREF(v);
3188 return (PyObject *)v;
3189 }
3190 else
3191 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003192}
3193
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003194static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003195long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003196{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003197 PyLongObject *z;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003198 if (ABS(v->ob_size) <= 1)
3199 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003200 z = (PyLongObject *)_PyLong_Copy(v);
3201 if (z != NULL)
3202 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003203 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003204}
3205
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003206static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003207long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003208{
3209 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003210 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003211 else
3212 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003213}
3214
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003215static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003216long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003217{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003218 return ABS(v->ob_size) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003219}
3220
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003221static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003222long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003223{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003224 PyLongObject *a, *b;
3225 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003226 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003227 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003228 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003229
Neil Schemenauerba872e22001-01-04 01:46:03 +00003230 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3231
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003232 if (a->ob_size < 0) {
3233 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003234 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003235 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003236 if (a1 == NULL)
3237 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003238 a2 = (PyLongObject *) long_rshift(a1, b);
3239 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003240 if (a2 == NULL)
3241 goto rshift_error;
3242 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003243 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003244 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003245 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003246
Neil Schemenauerba872e22001-01-04 01:46:03 +00003247 shiftby = PyLong_AsLong((PyObject *)b);
3248 if (shiftby == -1L && PyErr_Occurred())
3249 goto rshift_error;
3250 if (shiftby < 0) {
3251 PyErr_SetString(PyExc_ValueError,
3252 "negative shift count");
3253 goto rshift_error;
3254 }
3255 wordshift = shiftby / SHIFT;
3256 newsize = ABS(a->ob_size) - wordshift;
3257 if (newsize <= 0) {
3258 z = _PyLong_New(0);
3259 Py_DECREF(a);
3260 Py_DECREF(b);
3261 return (PyObject *)z;
3262 }
3263 loshift = shiftby % SHIFT;
3264 hishift = SHIFT - loshift;
3265 lomask = ((digit)1 << hishift) - 1;
3266 himask = MASK ^ lomask;
3267 z = _PyLong_New(newsize);
3268 if (z == NULL)
3269 goto rshift_error;
3270 if (a->ob_size < 0)
3271 z->ob_size = -(z->ob_size);
3272 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3273 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3274 if (i+1 < newsize)
3275 z->ob_digit[i] |=
3276 (a->ob_digit[j+1] << hishift) & himask;
3277 }
3278 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003279 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003280rshift_error:
3281 Py_DECREF(a);
3282 Py_DECREF(b);
3283 return (PyObject *) z;
3284
Guido van Rossumc6913e71991-11-19 20:26:46 +00003285}
3286
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003287static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003288long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003289{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003290 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003291 PyLongObject *a, *b;
3292 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003293 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003294 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003295 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003296
Neil Schemenauerba872e22001-01-04 01:46:03 +00003297 CONVERT_BINOP(v, w, &a, &b);
3298
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003299 shiftby = PyLong_AsLong((PyObject *)b);
3300 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003301 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003302 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003303 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003304 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003305 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003306 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003307 PyErr_SetString(PyExc_ValueError,
3308 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003309 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003310 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003311 /* wordshift, remshift = divmod(shiftby, SHIFT) */
3312 wordshift = (int)shiftby / SHIFT;
3313 remshift = (int)shiftby - wordshift * SHIFT;
3314
3315 oldsize = ABS(a->ob_size);
3316 newsize = oldsize + wordshift;
3317 if (remshift)
3318 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003319 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003320 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003321 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003322 if (a->ob_size < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003323 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003324 for (i = 0; i < wordshift; i++)
3325 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003326 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003327 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003328 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003329 z->ob_digit[i] = (digit)(accum & MASK);
3330 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003331 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003332 if (remshift)
3333 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003334 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003335 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003336 z = long_normalize(z);
3337lshift_error:
3338 Py_DECREF(a);
3339 Py_DECREF(b);
3340 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003341}
3342
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003343
3344/* Bitwise and/xor/or operations */
3345
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003346static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003347long_bitwise(PyLongObject *a,
3348 int op, /* '&', '|', '^' */
3349 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003350{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003351 digit maska, maskb; /* 0 or MASK */
3352 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003353 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003354 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003355 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003356 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003357 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003358
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003359 if (a->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003360 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003361 if (a == NULL)
3362 return NULL;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003363 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003364 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003365 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003366 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003367 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003368 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003369 if (b->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003370 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003371 if (b == NULL) {
3372 Py_DECREF(a);
3373 return NULL;
3374 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003375 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003376 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003377 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003378 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003379 maskb = 0;
3380 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003381
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003382 negz = 0;
3383 switch (op) {
3384 case '^':
3385 if (maska != maskb) {
3386 maska ^= MASK;
3387 negz = -1;
3388 }
3389 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003390 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003391 if (maska && maskb) {
3392 op = '|';
3393 maska ^= MASK;
3394 maskb ^= MASK;
3395 negz = -1;
3396 }
3397 break;
3398 case '|':
3399 if (maska || maskb) {
3400 op = '&';
3401 maska ^= MASK;
3402 maskb ^= MASK;
3403 negz = -1;
3404 }
3405 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003406 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003407
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003408 /* JRH: The original logic here was to allocate the result value (z)
3409 as the longer of the two operands. However, there are some cases
3410 where the result is guaranteed to be shorter than that: AND of two
3411 positives, OR of two negatives: use the shorter number. AND with
3412 mixed signs: use the positive number. OR with mixed signs: use the
3413 negative number. After the transformations above, op will be '&'
3414 iff one of these cases applies, and mask will be non-0 for operands
3415 whose length should be ignored.
3416 */
3417
3418 size_a = a->ob_size;
3419 size_b = b->ob_size;
3420 size_z = op == '&'
3421 ? (maska
3422 ? size_b
3423 : (maskb ? size_a : MIN(size_a, size_b)))
3424 : MAX(size_a, size_b);
3425 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003426 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003427 Py_DECREF(a);
3428 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003429 return NULL;
3430 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003431
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003432 for (i = 0; i < size_z; ++i) {
3433 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3434 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3435 switch (op) {
3436 case '&': z->ob_digit[i] = diga & digb; break;
3437 case '|': z->ob_digit[i] = diga | digb; break;
3438 case '^': z->ob_digit[i] = diga ^ digb; break;
3439 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003440 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003441
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003442 Py_DECREF(a);
3443 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003444 z = long_normalize(z);
3445 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003446 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003447 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003448 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003449 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003450}
3451
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003452static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003453long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003454{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003455 PyLongObject *a, *b;
3456 PyObject *c;
3457 CONVERT_BINOP(v, w, &a, &b);
3458 c = long_bitwise(a, '&', b);
3459 Py_DECREF(a);
3460 Py_DECREF(b);
3461 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003462}
3463
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003464static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003465long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003466{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003467 PyLongObject *a, *b;
3468 PyObject *c;
3469 CONVERT_BINOP(v, w, &a, &b);
3470 c = long_bitwise(a, '^', b);
3471 Py_DECREF(a);
3472 Py_DECREF(b);
3473 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003474}
3475
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003476static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003477long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003478{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003479 PyLongObject *a, *b;
3480 PyObject *c;
3481 CONVERT_BINOP(v, w, &a, &b);
3482 c = long_bitwise(a, '|', b);
3483 Py_DECREF(a);
3484 Py_DECREF(b);
3485 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003486}
3487
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003488static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003489long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003490{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003491 if (PyLong_CheckExact(v))
3492 Py_INCREF(v);
3493 else
3494 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003495 return v;
3496}
3497
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003498static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003499long_int(PyObject *v)
3500{
Guido van Rossumddefaf32007-01-14 03:31:43 +00003501 return long_long(v);
Walter Dörwaldf1715402002-11-19 20:49:15 +00003502}
3503
3504static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003505long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003506{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003507 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003508 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003509 if (result == -1.0 && PyErr_Occurred())
3510 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003511 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003512}
3513
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003514static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003515long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003516
Tim Peters6d6c1a32001-08-02 04:15:00 +00003517static PyObject *
3518long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3519{
3520 PyObject *x = NULL;
3521 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003522 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003523
Guido van Rossumbef14172001-08-29 15:47:46 +00003524 if (type != &PyLong_Type)
3525 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003526 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527 &x, &base))
3528 return NULL;
3529 if (x == NULL)
3530 return PyLong_FromLong(0L);
3531 if (base == -909)
3532 return PyNumber_Long(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003533 else if (PyString_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003534 /* Since PyLong_FromString doesn't have a length parameter,
3535 * check here for possible NULs in the string. */
Guido van Rossum4581ae52007-05-22 21:56:47 +00003536 char *string;
3537 int size;
3538 if (PyBytes_Check(x)) {
3539 string = PyBytes_AS_STRING(x);
3540 size = PyBytes_GET_SIZE(x);
3541 }
3542 else {
3543 string = PyString_AS_STRING(x);
3544 size = PyString_GET_SIZE(x);
3545 }
3546 if (strlen(string) != size) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003547 /* create a repr() of the input string,
3548 * just like PyLong_FromString does. */
3549 PyObject *srepr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00003550 srepr = PyObject_ReprStr8(x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003551 if (srepr == NULL)
3552 return NULL;
3553 PyErr_Format(PyExc_ValueError,
3554 "invalid literal for int() with base %d: %s",
3555 base, PyString_AS_STRING(srepr));
3556 Py_DECREF(srepr);
3557 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003558 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003559 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003560 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003561 else if (PyUnicode_Check(x))
3562 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3563 PyUnicode_GET_SIZE(x),
3564 base);
3565 else {
3566 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003567 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003568 return NULL;
3569 }
3570}
3571
Guido van Rossumbef14172001-08-29 15:47:46 +00003572/* Wimpy, slow approach to tp_new calls for subtypes of long:
3573 first create a regular long from whatever arguments we got,
3574 then allocate a subtype instance and initialize it from
3575 the regular long. The regular long is then thrown away.
3576*/
3577static PyObject *
3578long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3579{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003580 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003581 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003582
3583 assert(PyType_IsSubtype(type, &PyLong_Type));
3584 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3585 if (tmp == NULL)
3586 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003587 assert(PyLong_CheckExact(tmp));
Guido van Rossumbef14172001-08-29 15:47:46 +00003588 n = tmp->ob_size;
3589 if (n < 0)
3590 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003591 newobj = (PyLongObject *)type->tp_alloc(type, n);
3592 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003593 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003594 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003595 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003596 assert(PyLong_Check(newobj));
3597 newobj->ob_size = tmp->ob_size;
Guido van Rossumbef14172001-08-29 15:47:46 +00003598 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003599 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003600 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003601 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003602}
3603
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003604static PyObject *
3605long_getnewargs(PyLongObject *v)
3606{
3607 return Py_BuildValue("(N)", _PyLong_Copy(v));
3608}
3609
3610static PyMethodDef long_methods[] = {
3611 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3612 {NULL, NULL} /* sentinel */
3613};
3614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003615PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003616"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003617\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003618Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003619point argument will be truncated towards zero (this does not include a\n\
3620string representation of a floating point number!) When converting a\n\
3621string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003622converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003624static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003625 (binaryfunc) long_add, /*nb_add*/
3626 (binaryfunc) long_sub, /*nb_subtract*/
3627 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003628 long_mod, /*nb_remainder*/
3629 long_divmod, /*nb_divmod*/
3630 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003631 (unaryfunc) long_neg, /*nb_negative*/
3632 (unaryfunc) long_pos, /*tp_positive*/
3633 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003634 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003635 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003636 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003637 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003638 long_and, /*nb_and*/
3639 long_xor, /*nb_xor*/
3640 long_or, /*nb_or*/
Neal Norwitzca810462006-08-29 07:57:59 +00003641 0, /*nb_coerce*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003642 long_int, /*nb_int*/
3643 long_long, /*nb_long*/
3644 long_float, /*nb_float*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003645 0, /*nb_oct*/ /* not used */
3646 0, /*nb_hex*/ /* not used */
Guido van Rossum4668b002001-08-08 05:00:18 +00003647 0, /* nb_inplace_add */
3648 0, /* nb_inplace_subtract */
3649 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003650 0, /* nb_inplace_remainder */
3651 0, /* nb_inplace_power */
3652 0, /* nb_inplace_lshift */
3653 0, /* nb_inplace_rshift */
3654 0, /* nb_inplace_and */
3655 0, /* nb_inplace_xor */
3656 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003657 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003658 long_true_divide, /* nb_true_divide */
3659 0, /* nb_inplace_floor_divide */
3660 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003661 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003662};
3663
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003664PyTypeObject PyLong_Type = {
3665 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003666 0, /* ob_size */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003667 "int", /* tp_name */
3668 /* See _PyLong_New for why this isn't
3669 sizeof(PyLongObject) - sizeof(digit) */
3670 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003671 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003672 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673 0, /* tp_print */
3674 0, /* tp_getattr */
3675 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003676 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003677 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003678 &long_as_number, /* tp_as_number */
3679 0, /* tp_as_sequence */
3680 0, /* tp_as_mapping */
3681 (hashfunc)long_hash, /* tp_hash */
3682 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003683 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003684 PyObject_GenericGetAttr, /* tp_getattro */
3685 0, /* tp_setattro */
3686 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003687 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3688 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003689 long_doc, /* tp_doc */
3690 0, /* tp_traverse */
3691 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003692 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693 0, /* tp_weaklistoffset */
3694 0, /* tp_iter */
3695 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003696 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003697 0, /* tp_members */
3698 0, /* tp_getset */
3699 0, /* tp_base */
3700 0, /* tp_dict */
3701 0, /* tp_descr_get */
3702 0, /* tp_descr_set */
3703 0, /* tp_dictoffset */
3704 0, /* tp_init */
3705 0, /* tp_alloc */
3706 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003707 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003708};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003709
3710int
3711_PyLong_Init(void)
3712{
3713#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3714 int ival;
3715 PyLongObject *v = small_ints;
3716 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3717 PyObject_INIT(v, &PyLong_Type);
3718 v->ob_size = -1;
3719 v->ob_digit[0] = -ival;
3720 }
3721 for (; ival < NSMALLPOSINTS; ival++, v++) {
3722 PyObject_INIT(v, &PyLong_Type);
3723 v->ob_size = ival ? 1 : 0;
3724 v->ob_digit[0] = ival;
3725 }
3726#endif
3727 return 1;
3728}
3729
3730void
3731PyLong_Fini(void)
3732{
3733#if 0
3734 int i;
3735 /* This is currently not needed; the small integers
3736 are statically allocated */
3737#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3738 PyIntObject **q;
3739
3740 i = NSMALLNEGINTS + NSMALLPOSINTS;
3741 q = small_ints;
3742 while (--i >= 0) {
3743 Py_XDECREF(*q);
3744 *q++ = NULL;
3745 }
3746#endif
3747#endif
3748}