blob: 3b4a6756a09b6181274284c2e8981d7abef300e7 [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
27static inline PyObject *
28get_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 Rossumd2dbecb2006-08-18 16:29:54 +000083static PyObject *long_format(PyObject *aa, int base);
Guido van Rossume32e0141992-01-19 16:31:05 +000084
Guido van Rossumc0b618a1997-05-02 03:12:38 +000085#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000086 if (--_Py_Ticker < 0) { \
87 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +000088 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000089 }
90
Guido van Rossumedcc38a1991-05-05 20:09:44 +000091/* Normalize (remove leading zeros from) a long int object.
92 Doesn't attempt to free the storage--in most cases, due to the nature
93 of the algorithms used, this could save at most be one word anyway. */
94
Guido van Rossumc0b618a1997-05-02 03:12:38 +000095static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000096long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000097{
Martin v. Löwis18e16552006-02-15 17:27:45 +000098 Py_ssize_t j = ABS(v->ob_size);
99 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000100
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000101 while (i > 0 && v->ob_digit[i-1] == 0)
102 --i;
103 if (i != j)
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000104 v->ob_size = (v->ob_size < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000105 return v;
106}
107
108/* Allocate a new long int object with size digits.
109 Return NULL and set exception if we run out of memory. */
110
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000112_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000113{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000114 PyLongObject *result;
115 /* Can't use sizeof(PyLongObject) here, since the
116 compiler takes padding at the end into account.
117 As the consequence, this would waste 2 bytes on
118 a 32-bit system, and 6 bytes on a 64-bit system.
119 This computation would be incorrect on systems
120 which have padding before the digits; with 16-bit
121 digits this should not happen. */
122 result = PyObject_MALLOC(sizeof(PyVarObject) +
123 size*sizeof(digit));
124 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000125 PyErr_NoMemory();
126 return NULL;
127 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000128 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000129}
130
Tim Peters64b5ce32001-09-10 20:52:51 +0000131PyObject *
132_PyLong_Copy(PyLongObject *src)
133{
134 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000135 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000136
137 assert(src != NULL);
138 i = src->ob_size;
139 if (i < 0)
140 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000141 if (i < 2) {
142 int ival = src->ob_digit[0];
143 if (src->ob_size < 0)
144 ival = -ival;
145 CHECK_SMALL_INT(ival);
146 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000147 result = _PyLong_New(i);
148 if (result != NULL) {
Tim Peters5329cdb2002-03-02 04:18:04 +0000149 result->ob_size = src->ob_size;
Tim Peters64b5ce32001-09-10 20:52:51 +0000150 while (--i >= 0)
151 result->ob_digit[i] = src->ob_digit[i];
152 }
153 return (PyObject *)result;
154}
155
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000156/* Create a new long int object from a C long int */
157
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000159PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000160{
Tim Petersce9de2f2001-06-14 04:56:19 +0000161 PyLongObject *v;
162 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
163 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000164 int sign = 1;
165
166 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000167
168 if (ival < 0) {
169 ival = -ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000170 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000171 }
172
Guido van Rossumddefaf32007-01-14 03:31:43 +0000173 /* Fast path for single-digits ints */
174 if (!(ival>>SHIFT)) {
175 v = _PyLong_New(1);
176 if (v) {
177 v->ob_size = sign;
178 v->ob_digit[0] = ival;
179 }
180 return (PyObject*)v;
181 }
182
183 /* 2 digits */
184 if (!(ival >> 2*SHIFT)) {
185 v = _PyLong_New(2);
186 if (v) {
187 v->ob_size = 2*sign;
188 v->ob_digit[0] = (digit)ival & MASK;
189 v->ob_digit[1] = ival >> SHIFT;
190 }
191 return (PyObject*)v;
192 }
193
194 /* Larger numbers: loop to determine number of digits */
Tim Petersce9de2f2001-06-14 04:56:19 +0000195 t = (unsigned long)ival;
196 while (t) {
197 ++ndigits;
198 t >>= SHIFT;
199 }
200 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000201 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000202 digit *p = v->ob_digit;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000203 v->ob_size = ndigits*sign;
Tim Petersce9de2f2001-06-14 04:56:19 +0000204 t = (unsigned long)ival;
205 while (t) {
206 *p++ = (digit)(t & MASK);
Guido van Rossum472c04f1996-12-05 21:57:21 +0000207 t >>= SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000208 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000209 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000210 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000211}
212
Guido van Rossum53756b11997-01-03 17:14:46 +0000213/* Create a new long int object from a C unsigned long int */
214
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000215PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000216PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000217{
Tim Petersce9de2f2001-06-14 04:56:19 +0000218 PyLongObject *v;
219 unsigned long t;
220 int ndigits = 0;
221
Guido van Rossumddefaf32007-01-14 03:31:43 +0000222 if (ival < BASE)
223 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000224 /* Count the number of Python digits. */
225 t = (unsigned long)ival;
226 while (t) {
227 ++ndigits;
228 t >>= SHIFT;
229 }
230 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000231 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000232 digit *p = v->ob_digit;
233 v->ob_size = ndigits;
234 while (ival) {
235 *p++ = (digit)(ival & MASK);
236 ival >>= SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000237 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000238 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000239 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000240}
241
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000242/* Create a new long int object from a C double */
243
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000245PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000246{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000247 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000248 double frac;
249 int i, ndig, expo, neg;
250 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000251 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000252 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000253 "cannot convert float infinity to int");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000254 return NULL;
255 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000256 CHECK_SMALL_INT((int)dval);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000257 if (dval < 0.0) {
258 neg = 1;
259 dval = -dval;
260 }
261 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
262 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000263 return PyLong_FromLong(0L);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000264 ndig = (expo-1) / SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000265 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000266 if (v == NULL)
267 return NULL;
268 frac = ldexp(frac, (expo-1) % SHIFT + 1);
269 for (i = ndig; --i >= 0; ) {
270 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000271 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000272 frac = frac - (double)bits;
273 frac = ldexp(frac, SHIFT);
274 }
275 if (neg)
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000276 v->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000277 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000278}
279
Thomas Wouters89f507f2006-12-13 04:49:30 +0000280/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
281 * anything about what happens when a signed integer operation overflows,
282 * and some compilers think they're doing you a favor by being "clever"
283 * then. The bit pattern for the largest postive signed long is
284 * (unsigned long)LONG_MAX, and for the smallest negative signed long
285 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
286 * However, some other compilers warn about applying unary minus to an
287 * unsigned operand. Hence the weird "0-".
288 */
289#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
290#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
291
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000292/* Get a C long int from a long int object.
293 Returns -1 and sets an error condition if overflow occurs. */
294
295long
Tim Peters9f688bf2000-07-07 15:53:28 +0000296PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000297{
Guido van Rossumf7531811998-05-26 14:33:37 +0000298 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000300 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000301 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000302 Py_ssize_t i;
303 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000304 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000305
Guido van Rossumddefaf32007-01-14 03:31:43 +0000306 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000308 return -1;
309 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000310
311 if (!PyLong_Check(vv)) {
312 PyNumberMethods *nb;
313 if ((nb = vv->ob_type->tp_as_number) == NULL ||
314 nb->nb_int == NULL) {
315 PyErr_SetString(PyExc_TypeError, "an integer is required");
316 return -1;
317 }
318 vv = (*nb->nb_int) (vv);
319 if (vv == NULL)
320 return -1;
321 do_decref = 1;
322 if (!PyLong_Check(vv)) {
323 Py_DECREF(vv);
324 PyErr_SetString(PyExc_TypeError,
325 "nb_int should return int object");
326 return -1;
327 }
328 }
329
Georg Brandl61c31b02007-02-26 14:46:30 +0000330 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000331 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000332 i = v->ob_size;
Guido van Rossumf7531811998-05-26 14:33:37 +0000333
Georg Brandl61c31b02007-02-26 14:46:30 +0000334 switch (i) {
335 case -1:
336 res = -v->ob_digit[0];
337 break;
338 case 0:
339 res = 0;
340 break;
341 case 1:
342 res = v->ob_digit[0];
343 break;
344 default:
345 sign = 1;
346 x = 0;
347 if (i < 0) {
348 sign = -1;
349 i = -(i);
350 }
351 while (--i >= 0) {
352 prev = x;
353 x = (x << SHIFT) + v->ob_digit[i];
354 if ((x >> SHIFT) != prev) {
355 PyErr_SetString(PyExc_OverflowError,
356 "Python int too large to convert to C long");
357 goto exit;
358 }
359 }
360 /* Haven't lost any bits, but casting to long requires extra care
361 * (see comment above).
362 */
363 if (x <= (unsigned long)LONG_MAX) {
364 res = (long)x * sign;
365 }
366 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
367 res = LONG_MIN;
368 }
369 else {
370 PyErr_SetString(PyExc_OverflowError,
371 "Python int too large to convert to C long");
372 }
373 }
374 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000375 if (do_decref) {
376 Py_DECREF(vv);
377 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000378 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000379}
380
Guido van Rossumddefaf32007-01-14 03:31:43 +0000381int
382_PyLong_FitsInLong(PyObject *vv)
383{
384 int size;
385 if (!PyLong_CheckExact(vv)) {
386 PyErr_BadInternalCall();
387 return 0;
388 }
389 /* conservative estimate */
390 size = ((PyLongObject*)vv)->ob_size;
391 return -2 <= size && size <= 2;
392}
393
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000394/* Get a Py_ssize_t from a long int object.
395 Returns -1 and sets an error condition if overflow occurs. */
396
397Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000398PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000399 register PyLongObject *v;
400 size_t x, prev;
401 Py_ssize_t i;
402 int sign;
403
404 if (vv == NULL || !PyLong_Check(vv)) {
405 PyErr_BadInternalCall();
406 return -1;
407 }
408 v = (PyLongObject *)vv;
409 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000410 switch (i) {
411 case -1: return -v->ob_digit[0];
412 case 0: return 0;
413 case 1: return v->ob_digit[0];
414 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000415 sign = 1;
416 x = 0;
417 if (i < 0) {
418 sign = -1;
419 i = -(i);
420 }
421 while (--i >= 0) {
422 prev = x;
423 x = (x << SHIFT) + v->ob_digit[i];
424 if ((x >> SHIFT) != prev)
425 goto overflow;
426 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000427 /* Haven't lost any bits, but casting to a signed type requires
428 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000429 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000430 if (x <= (size_t)PY_SSIZE_T_MAX) {
431 return (Py_ssize_t)x * sign;
432 }
433 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
434 return PY_SSIZE_T_MIN;
435 }
436 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000437
438 overflow:
439 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000440 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000441 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000442}
443
Guido van Rossumd8c80482002-08-13 00:24:58 +0000444/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000445 Returns -1 and sets an error condition if overflow occurs. */
446
447unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000448PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000449{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000450 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000451 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000452 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000453
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000454 if (vv == NULL || !PyLong_Check(vv)) {
455 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000456 return (unsigned long) -1;
457 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000458 v = (PyLongObject *)vv;
Guido van Rossum53756b11997-01-03 17:14:46 +0000459 i = v->ob_size;
460 x = 0;
461 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000462 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000463 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000464 return (unsigned long) -1;
465 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000466 switch (i) {
467 case 0: return 0;
468 case 1: return v->ob_digit[0];
469 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000470 while (--i >= 0) {
471 prev = x;
472 x = (x << SHIFT) + v->ob_digit[i];
473 if ((x >> SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000474 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000475 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000476 return (unsigned long) -1;
477 }
478 }
479 return x;
480}
481
482/* Get a C unsigned long int from a long int object.
483 Returns -1 and sets an error condition if overflow occurs. */
484
485size_t
486PyLong_AsSize_t(PyObject *vv)
487{
488 register PyLongObject *v;
489 size_t x, prev;
490 Py_ssize_t i;
491
492 if (vv == NULL || !PyLong_Check(vv)) {
493 PyErr_BadInternalCall();
494 return (unsigned long) -1;
495 }
496 v = (PyLongObject *)vv;
497 i = v->ob_size;
498 x = 0;
499 if (i < 0) {
500 PyErr_SetString(PyExc_OverflowError,
501 "can't convert negative value to size_t");
502 return (size_t) -1;
503 }
504 switch (i) {
505 case 0: return 0;
506 case 1: return v->ob_digit[0];
507 }
508 while (--i >= 0) {
509 prev = x;
510 x = (x << SHIFT) + v->ob_digit[i];
511 if ((x >> SHIFT) != prev) {
512 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000513 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000514 return (unsigned long) -1;
515 }
516 }
517 return x;
518}
519
Thomas Hellera4ea6032003-04-17 18:55:45 +0000520/* Get a C unsigned long int from a long int object, ignoring the high bits.
521 Returns -1 and sets an error condition if an error occurs. */
522
Guido van Rossumddefaf32007-01-14 03:31:43 +0000523static unsigned long
524_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000525{
526 register PyLongObject *v;
527 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000528 Py_ssize_t i;
529 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000530
531 if (vv == NULL || !PyLong_Check(vv)) {
532 PyErr_BadInternalCall();
533 return (unsigned long) -1;
534 }
535 v = (PyLongObject *)vv;
536 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000537 switch (i) {
538 case 0: return 0;
539 case 1: return v->ob_digit[0];
540 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000541 sign = 1;
542 x = 0;
543 if (i < 0) {
544 sign = -1;
545 i = -i;
546 }
547 while (--i >= 0) {
548 x = (x << SHIFT) + v->ob_digit[i];
549 }
550 return x * sign;
551}
552
Guido van Rossumddefaf32007-01-14 03:31:43 +0000553unsigned long
554PyLong_AsUnsignedLongMask(register PyObject *op)
555{
556 PyNumberMethods *nb;
557 PyLongObject *lo;
558 unsigned long val;
559
560 if (op && PyLong_Check(op))
561 return _PyLong_AsUnsignedLongMask(op);
562
563 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
564 nb->nb_int == NULL) {
565 PyErr_SetString(PyExc_TypeError, "an integer is required");
566 return (unsigned long)-1;
567 }
568
569 lo = (PyLongObject*) (*nb->nb_int) (op);
570 if (lo == NULL)
571 return (unsigned long)-1;
572 if (PyLong_Check(lo)) {
573 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
574 Py_DECREF(lo);
575 if (PyErr_Occurred())
576 return (unsigned long)-1;
577 return val;
578 }
579 else
580 {
581 Py_DECREF(lo);
582 PyErr_SetString(PyExc_TypeError,
583 "nb_int should return int object");
584 return (unsigned long)-1;
585 }
586}
587
Tim Peters5b8132f2003-01-31 15:52:05 +0000588int
589_PyLong_Sign(PyObject *vv)
590{
591 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000592
593 assert(v != NULL);
594 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000595
Tim Petersee1a53c2003-02-02 02:57:53 +0000596 return v->ob_size == 0 ? 0 : (v->ob_size < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000597}
598
Tim Petersbaefd9e2003-01-28 20:37:45 +0000599size_t
600_PyLong_NumBits(PyObject *vv)
601{
602 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000603 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000604 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000605
606 assert(v != NULL);
607 assert(PyLong_Check(v));
Guido van Rossum004a65c2003-02-03 15:28:19 +0000608 ndigits = ABS(v->ob_size);
Tim Petersbaefd9e2003-01-28 20:37:45 +0000609 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
610 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000611 digit msd = v->ob_digit[ndigits - 1];
612
Tim Peters5b8132f2003-01-31 15:52:05 +0000613 result = (ndigits - 1) * SHIFT;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000614 if (result / SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000615 goto Overflow;
616 do {
617 ++result;
618 if (result == 0)
619 goto Overflow;
620 msd >>= 1;
621 } while (msd);
622 }
623 return result;
624
625Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000626 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000627 "to express in a platform size_t");
628 return (size_t)-1;
629}
630
Tim Peters2a9b3672001-06-11 21:23:58 +0000631PyObject *
632_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
633 int little_endian, int is_signed)
634{
635 const unsigned char* pstartbyte;/* LSB of bytes */
636 int incr; /* direction to move pstartbyte */
637 const unsigned char* pendbyte; /* MSB of bytes */
638 size_t numsignificantbytes; /* number of bytes that matter */
639 size_t ndigits; /* number of Python long digits */
640 PyLongObject* v; /* result */
641 int idigit = 0; /* next free index in v->ob_digit */
642
643 if (n == 0)
644 return PyLong_FromLong(0L);
645
646 if (little_endian) {
647 pstartbyte = bytes;
648 pendbyte = bytes + n - 1;
649 incr = 1;
650 }
651 else {
652 pstartbyte = bytes + n - 1;
653 pendbyte = bytes;
654 incr = -1;
655 }
656
657 if (is_signed)
658 is_signed = *pendbyte >= 0x80;
659
660 /* Compute numsignificantbytes. This consists of finding the most
661 significant byte. Leading 0 bytes are insignficant if the number
662 is positive, and leading 0xff bytes if negative. */
663 {
664 size_t i;
665 const unsigned char* p = pendbyte;
666 const int pincr = -incr; /* search MSB to LSB */
667 const unsigned char insignficant = is_signed ? 0xff : 0x00;
668
669 for (i = 0; i < n; ++i, p += pincr) {
670 if (*p != insignficant)
671 break;
672 }
673 numsignificantbytes = n - i;
674 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
675 actually has 2 significant bytes. OTOH, 0xff0001 ==
676 -0x00ffff, so we wouldn't *need* to bump it there; but we
677 do for 0xffff = -0x0001. To be safe without bothering to
678 check every case, bump it regardless. */
679 if (is_signed && numsignificantbytes < n)
680 ++numsignificantbytes;
681 }
682
683 /* How many Python long digits do we need? We have
684 8*numsignificantbytes bits, and each Python long digit has SHIFT
685 bits, so it's the ceiling of the quotient. */
686 ndigits = (numsignificantbytes * 8 + SHIFT - 1) / SHIFT;
687 if (ndigits > (size_t)INT_MAX)
688 return PyErr_NoMemory();
689 v = _PyLong_New((int)ndigits);
690 if (v == NULL)
691 return NULL;
692
693 /* Copy the bits over. The tricky parts are computing 2's-comp on
694 the fly for signed numbers, and dealing with the mismatch between
695 8-bit bytes and (probably) 15-bit Python digits.*/
696 {
697 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000698 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000699 twodigits accum = 0; /* sliding register */
700 unsigned int accumbits = 0; /* number of bits in accum */
701 const unsigned char* p = pstartbyte;
702
703 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000704 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000705 /* Compute correction for 2's comp, if needed. */
706 if (is_signed) {
707 thisbyte = (0xff ^ thisbyte) + carry;
708 carry = thisbyte >> 8;
709 thisbyte &= 0xff;
710 }
711 /* Because we're going LSB to MSB, thisbyte is
712 more significant than what's already in accum,
713 so needs to be prepended to accum. */
714 accum |= thisbyte << accumbits;
715 accumbits += 8;
716 if (accumbits >= SHIFT) {
717 /* There's enough to fill a Python digit. */
718 assert(idigit < (int)ndigits);
719 v->ob_digit[idigit] = (digit)(accum & MASK);
720 ++idigit;
721 accum >>= SHIFT;
722 accumbits -= SHIFT;
723 assert(accumbits < SHIFT);
724 }
725 }
726 assert(accumbits < SHIFT);
727 if (accumbits) {
728 assert(idigit < (int)ndigits);
729 v->ob_digit[idigit] = (digit)accum;
730 ++idigit;
731 }
732 }
733
734 v->ob_size = is_signed ? -idigit : idigit;
735 return (PyObject *)long_normalize(v);
736}
737
738int
739_PyLong_AsByteArray(PyLongObject* v,
740 unsigned char* bytes, size_t n,
741 int little_endian, int is_signed)
742{
743 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000744 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000745 twodigits accum; /* sliding register */
746 unsigned int accumbits; /* # bits in accum */
747 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
748 twodigits carry; /* for computing 2's-comp */
749 size_t j; /* # bytes filled */
750 unsigned char* p; /* pointer to next byte in bytes */
751 int pincr; /* direction to move p */
752
753 assert(v != NULL && PyLong_Check(v));
754
755 if (v->ob_size < 0) {
756 ndigits = -(v->ob_size);
757 if (!is_signed) {
758 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000759 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000760 return -1;
761 }
762 do_twos_comp = 1;
763 }
764 else {
765 ndigits = v->ob_size;
766 do_twos_comp = 0;
767 }
768
769 if (little_endian) {
770 p = bytes;
771 pincr = 1;
772 }
773 else {
774 p = bytes + n - 1;
775 pincr = -1;
776 }
777
Tim Peters898cf852001-06-13 20:50:08 +0000778 /* Copy over all the Python digits.
779 It's crucial that every Python digit except for the MSD contribute
780 exactly SHIFT bits to the total, so first assert that the long is
781 normalized. */
782 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000783 j = 0;
784 accum = 0;
785 accumbits = 0;
786 carry = do_twos_comp ? 1 : 0;
787 for (i = 0; i < ndigits; ++i) {
788 twodigits thisdigit = v->ob_digit[i];
789 if (do_twos_comp) {
790 thisdigit = (thisdigit ^ MASK) + carry;
791 carry = thisdigit >> SHIFT;
792 thisdigit &= MASK;
793 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000794 /* Because we're going LSB to MSB, thisdigit is more
795 significant than what's already in accum, so needs to be
796 prepended to accum. */
797 accum |= thisdigit << accumbits;
Tim Petersede05092001-06-14 08:53:38 +0000798 accumbits += SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000799
Tim Petersede05092001-06-14 08:53:38 +0000800 /* The most-significant digit may be (probably is) at least
801 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000802 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000803 /* Count # of sign bits -- they needn't be stored,
804 * although for signed conversion we need later to
805 * make sure at least one sign bit gets stored.
806 * First shift conceptual sign bit to real sign bit.
807 */
808 stwodigits s = (stwodigits)(thisdigit <<
809 (8*sizeof(stwodigits) - SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000810 unsigned int nsignbits = 0;
Tim Petersede05092001-06-14 08:53:38 +0000811 while ((s < 0) == do_twos_comp && nsignbits < SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000812 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000813 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000814 }
Tim Petersede05092001-06-14 08:53:38 +0000815 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000816 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000817
Tim Peters2a9b3672001-06-11 21:23:58 +0000818 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000819 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000820 if (j >= n)
821 goto Overflow;
822 ++j;
823 *p = (unsigned char)(accum & 0xff);
824 p += pincr;
825 accumbits -= 8;
826 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000827 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000828 }
829
830 /* Store the straggler (if any). */
831 assert(accumbits < 8);
832 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000833 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000834 if (j >= n)
835 goto Overflow;
836 ++j;
837 if (do_twos_comp) {
838 /* Fill leading bits of the byte with sign bits
839 (appropriately pretending that the long had an
840 infinite supply of sign bits). */
841 accum |= (~(twodigits)0) << accumbits;
842 }
843 *p = (unsigned char)(accum & 0xff);
844 p += pincr;
845 }
Tim Peters05607ad2001-06-13 21:01:27 +0000846 else if (j == n && n > 0 && is_signed) {
847 /* The main loop filled the byte array exactly, so the code
848 just above didn't get to ensure there's a sign bit, and the
849 loop below wouldn't add one either. Make sure a sign bit
850 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000851 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000852 int sign_bit_set = msb >= 0x80;
853 assert(accumbits == 0);
854 if (sign_bit_set == do_twos_comp)
855 return 0;
856 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000857 goto Overflow;
858 }
Tim Peters05607ad2001-06-13 21:01:27 +0000859
860 /* Fill remaining bytes with copies of the sign bit. */
861 {
862 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
863 for ( ; j < n; ++j, p += pincr)
864 *p = signbyte;
865 }
866
Tim Peters2a9b3672001-06-11 21:23:58 +0000867 return 0;
868
869Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000870 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000871 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000872
Tim Peters2a9b3672001-06-11 21:23:58 +0000873}
874
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000875double
876_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
877{
878/* NBITS_WANTED should be > the number of bits in a double's precision,
879 but small enough so that 2**NBITS_WANTED is within the normal double
880 range. nbitsneeded is set to 1 less than that because the most-significant
881 Python digit contains at least 1 significant bit, but we don't want to
882 bother counting them (catering to the worst case cheaply).
883
884 57 is one more than VAX-D double precision; I (Tim) don't know of a double
885 format with more precision than that; it's 1 larger so that we add in at
886 least one round bit to stand in for the ignored least-significant bits.
887*/
888#define NBITS_WANTED 57
889 PyLongObject *v;
890 double x;
891 const double multiplier = (double)(1L << SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000892 Py_ssize_t i;
893 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000894 int nbitsneeded;
895
896 if (vv == NULL || !PyLong_Check(vv)) {
897 PyErr_BadInternalCall();
898 return -1;
899 }
900 v = (PyLongObject *)vv;
901 i = v->ob_size;
902 sign = 1;
903 if (i < 0) {
904 sign = -1;
905 i = -(i);
906 }
907 else if (i == 0) {
908 *exponent = 0;
909 return 0.0;
910 }
911 --i;
912 x = (double)v->ob_digit[i];
913 nbitsneeded = NBITS_WANTED - 1;
914 /* Invariant: i Python digits remain unaccounted for. */
915 while (i > 0 && nbitsneeded > 0) {
916 --i;
917 x = x * multiplier + (double)v->ob_digit[i];
918 nbitsneeded -= SHIFT;
919 }
920 /* There are i digits we didn't shift in. Pretending they're all
921 zeroes, the true value is x * 2**(i*SHIFT). */
922 *exponent = i;
923 assert(x > 0.0);
924 return x * sign;
925#undef NBITS_WANTED
926}
927
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000928/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000929
930double
Tim Peters9f688bf2000-07-07 15:53:28 +0000931PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000932{
Thomas Wouters553489a2006-02-01 21:32:04 +0000933 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000934 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000935
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000936 if (vv == NULL || !PyLong_Check(vv)) {
937 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000938 return -1;
939 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000940 x = _PyLong_AsScaledDouble(vv, &e);
941 if (x == -1.0 && PyErr_Occurred())
942 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000943 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
944 set correctly after a successful _PyLong_AsScaledDouble() call */
945 assert(e >= 0);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000946 if (e > INT_MAX / SHIFT)
947 goto overflow;
948 errno = 0;
949 x = ldexp(x, e * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000950 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000951 goto overflow;
952 return x;
953
954overflow:
955 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000956 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000957 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000958}
959
Guido van Rossum78694d91998-09-18 14:14:13 +0000960/* Create a new long (or int) object from a C pointer */
961
962PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000963PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000964{
Tim Peters70128a12001-06-16 08:48:40 +0000965#ifndef HAVE_LONG_LONG
966# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
967#endif
968#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000969# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000970#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000971 /* special-case null pointer */
972 if (!p)
Tim Peters70128a12001-06-16 08:48:40 +0000973 return PyInt_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000974 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000975
Guido van Rossum78694d91998-09-18 14:14:13 +0000976}
977
978/* Get a C pointer from a long object (or an int object in some cases) */
979
980void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000981PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000982{
983 /* This function will allow int or long objects. If vv is neither,
984 then the PyLong_AsLong*() functions will raise the exception:
985 PyExc_SystemError, "bad argument to internal function"
986 */
Tim Peters70128a12001-06-16 08:48:40 +0000987#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000988 long x;
989
Guido van Rossumddefaf32007-01-14 03:31:43 +0000990 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000991 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000992 else
993 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000994#else
Tim Peters70128a12001-06-16 08:48:40 +0000995
996#ifndef HAVE_LONG_LONG
997# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
998#endif
999#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001000# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001001#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001002 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001003
Guido van Rossumddefaf32007-01-14 03:31:43 +00001004 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001005 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001006 else
1007 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001008
1009#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001010
1011 if (x == -1 && PyErr_Occurred())
1012 return NULL;
1013 return (void *)x;
1014}
1015
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001016#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001017
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001018/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001019 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001020 */
1021
Tim Peterscf37dfc2001-06-14 18:42:50 +00001022#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001023
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001024/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001025
1026PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001027PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001028{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001029 PyLongObject *v;
1030 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1031 int ndigits = 0;
1032 int negative = 0;
1033
Guido van Rossumddefaf32007-01-14 03:31:43 +00001034 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001035 if (ival < 0) {
1036 ival = -ival;
1037 negative = 1;
1038 }
1039
1040 /* Count the number of Python digits.
1041 We used to pick 5 ("big enough for anything"), but that's a
1042 waste of time and space given that 5*15 = 75 bits are rarely
1043 needed. */
1044 t = (unsigned PY_LONG_LONG)ival;
1045 while (t) {
1046 ++ndigits;
1047 t >>= SHIFT;
1048 }
1049 v = _PyLong_New(ndigits);
1050 if (v != NULL) {
1051 digit *p = v->ob_digit;
1052 v->ob_size = negative ? -ndigits : ndigits;
1053 t = (unsigned PY_LONG_LONG)ival;
1054 while (t) {
1055 *p++ = (digit)(t & MASK);
1056 t >>= SHIFT;
1057 }
1058 }
1059 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001060}
1061
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001062/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001063
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001064PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001065PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001066{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001067 PyLongObject *v;
1068 unsigned PY_LONG_LONG t;
1069 int ndigits = 0;
1070
Guido van Rossumddefaf32007-01-14 03:31:43 +00001071 if (ival < BASE)
1072 return PyLong_FromLong(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001073 /* Count the number of Python digits. */
1074 t = (unsigned PY_LONG_LONG)ival;
1075 while (t) {
1076 ++ndigits;
1077 t >>= SHIFT;
1078 }
1079 v = _PyLong_New(ndigits);
1080 if (v != NULL) {
1081 digit *p = v->ob_digit;
1082 v->ob_size = ndigits;
1083 while (ival) {
1084 *p++ = (digit)(ival & MASK);
1085 ival >>= SHIFT;
1086 }
1087 }
1088 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001089}
1090
Martin v. Löwis18e16552006-02-15 17:27:45 +00001091/* Create a new long int object from a C Py_ssize_t. */
1092
1093PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001094PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001095{
1096 Py_ssize_t bytes = ival;
1097 int one = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001098 if (ival < BASE)
1099 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001100 return _PyLong_FromByteArray(
1101 (unsigned char *)&bytes,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001102 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001103}
1104
1105/* Create a new long int object from a C size_t. */
1106
1107PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001108PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001109{
1110 size_t bytes = ival;
1111 int one = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001112 if (ival < BASE)
1113 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114 return _PyLong_FromByteArray(
1115 (unsigned char *)&bytes,
1116 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
1117}
1118
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001119/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001120 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001121
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001122PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001123PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001124{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001125 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001126 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001127 int one = 1;
1128 int res;
1129
Tim Petersd38b1c72001-09-30 05:09:37 +00001130 if (vv == NULL) {
1131 PyErr_BadInternalCall();
1132 return -1;
1133 }
1134 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001135 PyNumberMethods *nb;
1136 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001137 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1138 nb->nb_int == NULL) {
1139 PyErr_SetString(PyExc_TypeError, "an integer is required");
1140 return -1;
1141 }
1142 io = (*nb->nb_int) (vv);
1143 if (io == NULL)
1144 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001145 if (PyLong_Check(io)) {
1146 bytes = PyLong_AsLongLong(io);
1147 Py_DECREF(io);
1148 return bytes;
1149 }
1150 Py_DECREF(io);
1151 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001152 return -1;
1153 }
1154
Guido van Rossumddefaf32007-01-14 03:31:43 +00001155 v = (PyLongObject*)vv;
1156 switch(v->ob_size) {
1157 case -1: return -v->ob_digit[0];
1158 case 0: return 0;
1159 case 1: return v->ob_digit[0];
1160 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001161 res = _PyLong_AsByteArray(
1162 (PyLongObject *)vv, (unsigned char *)&bytes,
1163 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001164
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001165 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001166 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001167 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001168 else
1169 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001170}
1171
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001172/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001173 Return -1 and set an error if overflow occurs. */
1174
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001175unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001176PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001177{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001178 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001179 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001180 int one = 1;
1181 int res;
1182
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001183 if (vv == NULL || !PyLong_Check(vv)) {
1184 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001185 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001186 }
1187
Guido van Rossumddefaf32007-01-14 03:31:43 +00001188 v = (PyLongObject*)vv;
1189 switch(v->ob_size) {
1190 case 0: return 0;
1191 case 1: return v->ob_digit[0];
1192 }
1193
Tim Petersd1a7da62001-06-13 00:35:57 +00001194 res = _PyLong_AsByteArray(
1195 (PyLongObject *)vv, (unsigned char *)&bytes,
1196 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001197
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001198 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001199 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001200 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001201 else
1202 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001203}
Tim Petersd1a7da62001-06-13 00:35:57 +00001204
Thomas Hellera4ea6032003-04-17 18:55:45 +00001205/* Get a C unsigned long int from a long int object, ignoring the high bits.
1206 Returns -1 and sets an error condition if an error occurs. */
1207
Guido van Rossumddefaf32007-01-14 03:31:43 +00001208static unsigned PY_LONG_LONG
1209_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001210{
1211 register PyLongObject *v;
1212 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001213 Py_ssize_t i;
1214 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001215
1216 if (vv == NULL || !PyLong_Check(vv)) {
1217 PyErr_BadInternalCall();
1218 return (unsigned long) -1;
1219 }
1220 v = (PyLongObject *)vv;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001221 switch(v->ob_size) {
1222 case 0: return 0;
1223 case 1: return v->ob_digit[0];
1224 }
Thomas Hellera4ea6032003-04-17 18:55:45 +00001225 i = v->ob_size;
1226 sign = 1;
1227 x = 0;
1228 if (i < 0) {
1229 sign = -1;
1230 i = -i;
1231 }
1232 while (--i >= 0) {
1233 x = (x << SHIFT) + v->ob_digit[i];
1234 }
1235 return x * sign;
1236}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001237
1238unsigned PY_LONG_LONG
1239PyLong_AsUnsignedLongLongMask(register PyObject *op)
1240{
1241 PyNumberMethods *nb;
1242 PyLongObject *lo;
1243 unsigned PY_LONG_LONG val;
1244
1245 if (op && PyLong_Check(op))
1246 return _PyLong_AsUnsignedLongLongMask(op);
1247
1248 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1249 nb->nb_int == NULL) {
1250 PyErr_SetString(PyExc_TypeError, "an integer is required");
1251 return (unsigned PY_LONG_LONG)-1;
1252 }
1253
1254 lo = (PyLongObject*) (*nb->nb_int) (op);
1255 if (lo == NULL)
1256 return (unsigned PY_LONG_LONG)-1;
1257 if (PyLong_Check(lo)) {
1258 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1259 Py_DECREF(lo);
1260 if (PyErr_Occurred())
1261 return (unsigned PY_LONG_LONG)-1;
1262 return val;
1263 }
1264 else
1265 {
1266 Py_DECREF(lo);
1267 PyErr_SetString(PyExc_TypeError,
1268 "nb_int should return int object");
1269 return (unsigned PY_LONG_LONG)-1;
1270 }
1271}
Tim Petersd1a7da62001-06-13 00:35:57 +00001272#undef IS_LITTLE_ENDIAN
1273
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001274#endif /* HAVE_LONG_LONG */
1275
Neil Schemenauerba872e22001-01-04 01:46:03 +00001276
1277static int
1278convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001279 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001280 *a = (PyLongObject *) v;
1281 Py_INCREF(v);
1282 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001283 else {
1284 return 0;
1285 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001286 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001287 *b = (PyLongObject *) w;
1288 Py_INCREF(w);
1289 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001290 else {
1291 Py_DECREF(*a);
1292 return 0;
1293 }
1294 return 1;
1295}
1296
1297#define CONVERT_BINOP(v, w, a, b) \
1298 if (!convert_binop(v, w, a, b)) { \
1299 Py_INCREF(Py_NotImplemented); \
1300 return Py_NotImplemented; \
1301 }
1302
Tim Peters877a2122002-08-12 05:09:36 +00001303/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1304 * is modified in place, by adding y to it. Carries are propagated as far as
1305 * x[m-1], and the remaining carry (0 or 1) is returned.
1306 */
1307static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001308v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001309{
1310 int i;
1311 digit carry = 0;
1312
1313 assert(m >= n);
1314 for (i = 0; i < n; ++i) {
1315 carry += x[i] + y[i];
1316 x[i] = carry & MASK;
1317 carry >>= SHIFT;
1318 assert((carry & 1) == carry);
1319 }
1320 for (; carry && i < m; ++i) {
1321 carry += x[i];
1322 x[i] = carry & MASK;
1323 carry >>= SHIFT;
1324 assert((carry & 1) == carry);
1325 }
1326 return carry;
1327}
1328
1329/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1330 * is modified in place, by subtracting y from it. Borrows are propagated as
1331 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1332 */
1333static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001334v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001335{
1336 int i;
1337 digit borrow = 0;
1338
1339 assert(m >= n);
1340 for (i = 0; i < n; ++i) {
1341 borrow = x[i] - y[i] - borrow;
1342 x[i] = borrow & MASK;
1343 borrow >>= SHIFT;
1344 borrow &= 1; /* keep only 1 sign bit */
1345 }
1346 for (; borrow && i < m; ++i) {
1347 borrow = x[i] - borrow;
1348 x[i] = borrow & MASK;
1349 borrow >>= SHIFT;
1350 borrow &= 1;
1351 }
1352 return borrow;
1353}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001354
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001355/* Multiply by a single digit, ignoring the sign. */
1356
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001357static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001358mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001359{
1360 return muladd1(a, n, (digit)0);
1361}
1362
1363/* Multiply by a single digit and add a single digit, ignoring the sign. */
1364
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001365static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001366muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001367{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001368 Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001369 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001370 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001371 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001372
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001373 if (z == NULL)
1374 return NULL;
1375 for (i = 0; i < size_a; ++i) {
1376 carry += (twodigits)a->ob_digit[i] * n;
Guido van Rossum2095d241997-04-09 19:41:24 +00001377 z->ob_digit[i] = (digit) (carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001378 carry >>= SHIFT;
1379 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001380 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001381 return long_normalize(z);
1382}
1383
Tim Peters212e6142001-07-14 12:23:19 +00001384/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1385 in pout, and returning the remainder. pin and pout point at the LSD.
1386 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1387 long_format, but that should be done with great care since longs are
1388 immutable. */
1389
1390static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001391inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001392{
1393 twodigits rem = 0;
1394
1395 assert(n > 0 && n <= MASK);
1396 pin += size;
1397 pout += size;
1398 while (--size >= 0) {
1399 digit hi;
1400 rem = (rem << SHIFT) + *--pin;
1401 *--pout = hi = (digit)(rem / n);
1402 rem -= hi * n;
1403 }
1404 return (digit)rem;
1405}
1406
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001407/* Divide a long integer by a digit, returning both the quotient
1408 (as function result) and the remainder (through *prem).
1409 The sign of a is ignored; n should not be zero. */
1410
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001411static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001412divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001413{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001414 const Py_ssize_t size = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001415 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001416
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001417 assert(n > 0 && n <= MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001418 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001419 if (z == NULL)
1420 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001421 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001422 return long_normalize(z);
1423}
1424
1425/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001426 Return a string object.
Fred Drake121ee271999-12-23 15:41:28 +00001427 If base is 8 or 16, add the proper prefix '0' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001428
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001429static PyObject *
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00001430long_format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001431{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001432 register PyLongObject *a = (PyLongObject *)aa;
1433 PyStringObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001434 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001435 Py_ssize_t size_a;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001436 char *p;
1437 int bits;
1438 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001439
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001440 if (a == NULL || !PyLong_Check(a)) {
1441 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001442 return NULL;
1443 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001444 assert(base >= 2 && base <= 36);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001445 size_a = ABS(a->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001446
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001447 /* Compute a rough upper bound for the length of the string */
1448 i = base;
1449 bits = 0;
1450 while (i > 1) {
1451 ++bits;
1452 i >>= 1;
1453 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001454 i = 5;
1455 j = size_a*SHIFT + bits-1;
1456 sz = i + j / bits;
1457 if (j / SHIFT < size_a || sz < i) {
1458 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001459 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001460 return NULL;
1461 }
1462 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001463 if (str == NULL)
1464 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001465 p = PyString_AS_STRING(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001466 *p = '\0';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001467 if (a->ob_size < 0)
1468 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001469
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001470 if (a->ob_size == 0) {
1471 *--p = '0';
1472 }
1473 else if ((base & (base - 1)) == 0) {
1474 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001475 twodigits accum = 0;
1476 int accumbits = 0; /* # of bits in accum */
1477 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001478 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001479 while ((i >>= 1) > 1)
1480 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001481
1482 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001483 accum |= (twodigits)a->ob_digit[i] << accumbits;
Tim Peters586b2e32001-07-15 09:11:14 +00001484 accumbits += SHIFT;
1485 assert(accumbits >= basebits);
1486 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001487 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001488 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001489 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001490 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001491 accumbits -= basebits;
1492 accum >>= basebits;
1493 } while (i < size_a-1 ? accumbits >= basebits :
1494 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001495 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001496 }
1497 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001498 /* Not 0, and base not a power of 2. Divide repeatedly by
1499 base, but for speed use the highest power of base that
1500 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001501 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001502 digit *pin = a->ob_digit;
1503 PyLongObject *scratch;
1504 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001505 digit powbase = base; /* powbase == base ** power */
1506 int power = 1;
1507 for (;;) {
1508 unsigned long newpow = powbase * (unsigned long)base;
1509 if (newpow >> SHIFT) /* doesn't fit in a digit */
1510 break;
1511 powbase = (digit)newpow;
1512 ++power;
1513 }
Tim Peters212e6142001-07-14 12:23:19 +00001514
1515 /* Get a scratch area for repeated division. */
1516 scratch = _PyLong_New(size);
1517 if (scratch == NULL) {
1518 Py_DECREF(str);
1519 return NULL;
1520 }
1521
1522 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001523 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001524 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001525 digit rem = inplace_divrem1(scratch->ob_digit,
1526 pin, size, powbase);
1527 pin = scratch->ob_digit; /* no need to use a again */
1528 if (pin[size - 1] == 0)
1529 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001530 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001531 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001532 Py_DECREF(str);
1533 return NULL;
1534 })
Tim Peters212e6142001-07-14 12:23:19 +00001535
1536 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001537 assert(ntostore > 0);
1538 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001539 digit nextrem = (digit)(rem / base);
1540 char c = (char)(rem - nextrem * base);
1541 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001542 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001543 *--p = c;
1544 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001545 --ntostore;
1546 /* Termination is a bit delicate: must not
1547 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001548 remaining quotient and rem are both 0. */
1549 } while (ntostore && (size || rem));
1550 } while (size != 0);
1551 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001552 }
1553
Guido van Rossum2c475421992-08-14 15:13:07 +00001554 if (base == 8) {
1555 if (size_a != 0)
1556 *--p = '0';
1557 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001558 else if (base == 16) {
1559 *--p = 'x';
1560 *--p = '0';
1561 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001562 else if (base != 10) {
1563 *--p = '#';
1564 *--p = '0' + base%10;
1565 if (base > 10)
1566 *--p = '0' + base/10;
1567 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001568 if (sign)
1569 *--p = sign;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001570 if (p != PyString_AS_STRING(str)) {
1571 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001572 assert(p > q);
1573 do {
1574 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001575 q--;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001576 _PyString_Resize((PyObject **)&str,
Thomas Wouters89f507f2006-12-13 04:49:30 +00001577 (Py_ssize_t) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001578 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001579 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001580}
1581
Thomas Wouters477c8d52006-05-27 19:21:47 +00001582/* Table of digit values for 8-bit string -> integer conversion.
1583 * '0' maps to 0, ..., '9' maps to 9.
1584 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1585 * All other indices map to 37.
1586 * Note that when converting a base B string, a char c is a legitimate
1587 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1588 */
1589int _PyLong_DigitValue[256] = {
1590 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1591 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1592 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1593 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1594 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1595 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1596 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1597 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1598 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1599 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1600 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1601 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1602 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 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};
1607
1608/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001609 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1610 * non-digit (which may be *str!). A normalized long is returned.
1611 * The point to this routine is that it takes time linear in the number of
1612 * string characters.
1613 */
1614static PyLongObject *
1615long_from_binary_base(char **str, int base)
1616{
1617 char *p = *str;
1618 char *start = p;
1619 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001620 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001621 PyLongObject *z;
1622 twodigits accum;
1623 int bits_in_accum;
1624 digit *pdigit;
1625
1626 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1627 n = base;
1628 for (bits_per_char = -1; n; ++bits_per_char)
1629 n >>= 1;
1630 /* n <- total # of bits needed, while setting p to end-of-string */
1631 n = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001632 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001633 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001634 *str = p;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001635 /* n <- # of Python digits needed, = ceiling(n/SHIFT). */
1636 n = (p - start) * bits_per_char + SHIFT - 1;
1637 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001638 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001639 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001640 return NULL;
1641 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001642 n = n / SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001643 z = _PyLong_New(n);
1644 if (z == NULL)
1645 return NULL;
1646 /* Read string from right, and fill in long from left; i.e.,
1647 * from least to most significant in both.
1648 */
1649 accum = 0;
1650 bits_in_accum = 0;
1651 pdigit = z->ob_digit;
1652 while (--p >= start) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001653 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001654 assert(k >= 0 && k < base);
1655 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001656 bits_in_accum += bits_per_char;
1657 if (bits_in_accum >= SHIFT) {
1658 *pdigit++ = (digit)(accum & MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001659 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001660 accum >>= SHIFT;
1661 bits_in_accum -= SHIFT;
1662 assert(bits_in_accum < SHIFT);
1663 }
1664 }
1665 if (bits_in_accum) {
1666 assert(bits_in_accum <= SHIFT);
1667 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001668 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001669 }
1670 while (pdigit - z->ob_digit < n)
1671 *pdigit++ = 0;
1672 return long_normalize(z);
1673}
1674
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001675PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001676PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001677{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001678 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001679 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001680 PyLongObject *z;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001681 PyObject *strobj, *strrepr;
1682 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001683
Guido van Rossum472c04f1996-12-05 21:57:21 +00001684 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001685 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001686 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001687 return NULL;
1688 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001689 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001690 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001691 if (*str == '+')
1692 ++str;
1693 else if (*str == '-') {
1694 ++str;
1695 sign = -1;
1696 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001697 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001698 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001699 if (base == 0) {
1700 if (str[0] != '0')
1701 base = 10;
1702 else if (str[1] == 'x' || str[1] == 'X')
1703 base = 16;
1704 else
1705 base = 8;
1706 }
1707 if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
1708 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001709
Guido van Rossume6762971998-06-22 03:54:46 +00001710 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001711 if ((base & (base - 1)) == 0)
1712 z = long_from_binary_base(&str, base);
1713 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001714/***
1715Binary bases can be converted in time linear in the number of digits, because
1716Python's representation base is binary. Other bases (including decimal!) use
1717the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001718
Thomas Wouters477c8d52006-05-27 19:21:47 +00001719First some math: the largest integer that can be expressed in N base-B digits
1720is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1721case number of Python digits needed to hold it is the smallest integer n s.t.
1722
1723 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1724 BASE**n >= B**N [taking logs to base BASE]
1725 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1726
1727The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1728this quickly. A Python long with that much space is reserved near the start,
1729and the result is computed into it.
1730
1731The input string is actually treated as being in base base**i (i.e., i digits
1732are processed at a time), where two more static arrays hold:
1733
1734 convwidth_base[base] = the largest integer i such that base**i <= BASE
1735 convmultmax_base[base] = base ** convwidth_base[base]
1736
1737The first of these is the largest i such that i consecutive input digits
1738must fit in a single Python digit. The second is effectively the input
1739base we're really using.
1740
1741Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1742convmultmax_base[base], the result is "simply"
1743
1744 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1745
1746where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001747
1748Error analysis: as above, the number of Python digits `n` needed is worst-
1749case
1750
1751 n >= N * log(B)/log(BASE)
1752
1753where `N` is the number of input digits in base `B`. This is computed via
1754
1755 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1756
1757below. Two numeric concerns are how much space this can waste, and whether
1758the computed result can be too small. To be concrete, assume BASE = 2**15,
1759which is the default (and it's unlikely anyone changes that).
1760
1761Waste isn't a problem: provided the first input digit isn't 0, the difference
1762between the worst-case input with N digits and the smallest input with N
1763digits is about a factor of B, but B is small compared to BASE so at most
1764one allocated Python digit can remain unused on that count. If
1765N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1766and adding 1 returns a result 1 larger than necessary. However, that can't
1767happen: whenever B is a power of 2, long_from_binary_base() is called
1768instead, and it's impossible for B**i to be an integer power of 2**15 when
1769B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1770an exact integer when B is not a power of 2, since B**i has a prime factor
1771other than 2 in that case, but (2**15)**j's only prime factor is 2).
1772
1773The computed result can be too small if the true value of N*log(B)/log(BASE)
1774is a little bit larger than an exact integer, but due to roundoff errors (in
1775computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1776yields a numeric result a little less than that integer. Unfortunately, "how
1777close can a transcendental function get to an integer over some range?"
1778questions are generally theoretically intractable. Computer analysis via
1779continued fractions is practical: expand log(B)/log(BASE) via continued
1780fractions, giving a sequence i/j of "the best" rational approximations. Then
1781j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1782we can get very close to being in trouble, but very rarely. For example,
178376573 is a denominator in one of the continued-fraction approximations to
1784log(10)/log(2**15), and indeed:
1785
1786 >>> log(10)/log(2**15)*76573
1787 16958.000000654003
1788
1789is very close to an integer. If we were working with IEEE single-precision,
1790rounding errors could kill us. Finding worst cases in IEEE double-precision
1791requires better-than-double-precision log() functions, and Tim didn't bother.
1792Instead the code checks to see whether the allocated space is enough as each
1793new Python digit is added, and copies the whole thing to a larger long if not.
1794This should happen extremely rarely, and in fact I don't have a test case
1795that triggers it(!). Instead the code was tested by artificially allocating
1796just 1 digit at the start, so that the copying code was exercised for every
1797digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001798***/
1799 register twodigits c; /* current input character */
1800 Py_ssize_t size_z;
1801 int i;
1802 int convwidth;
1803 twodigits convmultmax, convmult;
1804 digit *pz, *pzstop;
1805 char* scan;
1806
1807 static double log_base_BASE[37] = {0.0e0,};
1808 static int convwidth_base[37] = {0,};
1809 static twodigits convmultmax_base[37] = {0,};
1810
1811 if (log_base_BASE[base] == 0.0) {
1812 twodigits convmax = base;
1813 int i = 1;
1814
1815 log_base_BASE[base] = log((double)base) /
1816 log((double)BASE);
1817 for (;;) {
1818 twodigits next = convmax * base;
1819 if (next > BASE)
1820 break;
1821 convmax = next;
1822 ++i;
1823 }
1824 convmultmax_base[base] = convmax;
1825 assert(i > 0);
1826 convwidth_base[base] = i;
1827 }
1828
1829 /* Find length of the string of numeric characters. */
1830 scan = str;
1831 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1832 ++scan;
1833
1834 /* Create a long object that can contain the largest possible
1835 * integer with this base and length. Note that there's no
1836 * need to initialize z->ob_digit -- no slot is read up before
1837 * being stored into.
1838 */
1839 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001840 /* Uncomment next line to test exceedingly rare copy code */
1841 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001842 assert(size_z > 0);
1843 z = _PyLong_New(size_z);
1844 if (z == NULL)
1845 return NULL;
1846 z->ob_size = 0;
1847
1848 /* `convwidth` consecutive input digits are treated as a single
1849 * digit in base `convmultmax`.
1850 */
1851 convwidth = convwidth_base[base];
1852 convmultmax = convmultmax_base[base];
1853
1854 /* Work ;-) */
1855 while (str < scan) {
1856 /* grab up to convwidth digits from the input string */
1857 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1858 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1859 c = (twodigits)(c * base +
1860 _PyLong_DigitValue[Py_CHARMASK(*str)]);
1861 assert(c < BASE);
1862 }
1863
1864 convmult = convmultmax;
1865 /* Calculate the shift only if we couldn't get
1866 * convwidth digits.
1867 */
1868 if (i != convwidth) {
1869 convmult = base;
1870 for ( ; i > 1; --i)
1871 convmult *= base;
1872 }
1873
1874 /* Multiply z by convmult, and add c. */
1875 pz = z->ob_digit;
1876 pzstop = pz + z->ob_size;
1877 for (; pz < pzstop; ++pz) {
1878 c += (twodigits)*pz * convmult;
1879 *pz = (digit)(c & MASK);
1880 c >>= SHIFT;
1881 }
1882 /* carry off the current end? */
1883 if (c) {
1884 assert(c < BASE);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001885 if (z->ob_size < size_z) {
1886 *pz = (digit)c;
1887 ++z->ob_size;
1888 }
1889 else {
1890 PyLongObject *tmp;
1891 /* Extremely rare. Get more space. */
1892 assert(z->ob_size == size_z);
1893 tmp = _PyLong_New(size_z + 1);
1894 if (tmp == NULL) {
1895 Py_DECREF(z);
1896 return NULL;
1897 }
1898 memcpy(tmp->ob_digit,
1899 z->ob_digit,
1900 sizeof(digit) * size_z);
1901 Py_DECREF(z);
1902 z = tmp;
1903 z->ob_digit[size_z] = (digit)c;
1904 ++size_z;
1905 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001906 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001907 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001908 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001909 if (z == NULL)
1910 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001911 if (str == start)
1912 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001913 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001914 z->ob_size = -(z->ob_size);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001915 if (*str == 'L' || *str == 'l')
1916 str++;
1917 while (*str && isspace(Py_CHARMASK(*str)))
1918 str++;
1919 if (*str != '\0')
1920 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001921 if (pend)
1922 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001923 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001924
1925 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001926 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001927 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1928 strobj = PyString_FromStringAndSize(orig_str, slen);
1929 if (strobj == NULL)
1930 return NULL;
1931 strrepr = PyObject_Repr(strobj);
1932 Py_DECREF(strobj);
1933 if (strrepr == NULL)
1934 return NULL;
1935 PyErr_Format(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001936 "invalid literal for int() with base %d: %s",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001937 base, PyString_AS_STRING(strrepr));
1938 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001939 return NULL;
1940}
1941
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001942#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001943PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001944PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001945{
Walter Dörwald07e14762002-11-06 16:15:14 +00001946 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001947 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001948
Walter Dörwald07e14762002-11-06 16:15:14 +00001949 if (buffer == NULL)
1950 return NULL;
1951
1952 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1953 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001954 return NULL;
1955 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001956 result = PyLong_FromString(buffer, NULL, base);
1957 PyMem_FREE(buffer);
1958 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001959}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001960#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001961
Tim Peters9f688bf2000-07-07 15:53:28 +00001962/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001963static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001964 (PyLongObject *, PyLongObject *, PyLongObject **);
1965static PyObject *long_pos(PyLongObject *);
1966static int long_divrem(PyLongObject *, PyLongObject *,
1967 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001968
1969/* Long division with remainder, top-level routine */
1970
Guido van Rossume32e0141992-01-19 16:31:05 +00001971static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001972long_divrem(PyLongObject *a, PyLongObject *b,
1973 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001974{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001975 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001976 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001977
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001978 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001979 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001980 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001981 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001982 }
1983 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001984 (size_a == size_b &&
1985 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001986 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00001987 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001988 Py_INCREF(a);
1989 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001990 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001991 }
1992 if (size_b == 1) {
1993 digit rem = 0;
1994 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001995 if (z == NULL)
1996 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001997 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001998 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001999 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002000 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002001 if (z == NULL)
2002 return -1;
2003 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002004 /* Set the signs.
2005 The quotient z has the sign of a*b;
2006 the remainder r has the sign of a,
2007 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00002008 if ((a->ob_size < 0) != (b->ob_size < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002009 NEGATE(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002010 if (a->ob_size < 0 && (*prem)->ob_size != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002011 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002012 *pdiv = z;
2013 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002014}
2015
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002016/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002017
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002018static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002019x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002020{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002021 Py_ssize_t size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size);
Guido van Rossum2095d241997-04-09 19:41:24 +00002022 digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002023 PyLongObject *v = mul1(v1, d);
2024 PyLongObject *w = mul1(w1, d);
2025 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002026 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002027
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002028 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002029 Py_XDECREF(v);
2030 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002031 return NULL;
2032 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002033
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002034 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002035 assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002036 assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002037
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002038 size_v = ABS(v->ob_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002039 k = size_v - size_w;
2040 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002041
Thomas Wouters477c8d52006-05-27 19:21:47 +00002042 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002043 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2044 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002045 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002046 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002047
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002048 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002049 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002050 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002051 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002052 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002053 if (vj == w->ob_digit[size_w-1])
2054 q = MASK;
2055 else
2056 q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
2057 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002058
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002059 while (w->ob_digit[size_w-2]*q >
2060 ((
2061 ((twodigits)vj << SHIFT)
2062 + v->ob_digit[j-1]
2063 - q*w->ob_digit[size_w-1]
2064 ) << SHIFT)
2065 + v->ob_digit[j-2])
2066 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002067
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002068 for (i = 0; i < size_w && i+k < size_v; ++i) {
2069 twodigits z = w->ob_digit[i] * q;
Guido van Rossum2095d241997-04-09 19:41:24 +00002070 digit zz = (digit) (z >> SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002071 carry += v->ob_digit[i+k] - z
2072 + ((twodigits)zz << SHIFT);
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00002073 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002074 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
2075 carry, SHIFT);
2076 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002077 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002078
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079 if (i+k < size_v) {
2080 carry += v->ob_digit[i+k];
2081 v->ob_digit[i+k] = 0;
2082 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002083
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002084 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002085 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002086 else {
2087 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002088 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002089 carry = 0;
2090 for (i = 0; i < size_w && i+k < size_v; ++i) {
2091 carry += v->ob_digit[i+k] + w->ob_digit[i];
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00002092 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002093 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2094 BASE_TWODIGITS_TYPE,
2095 carry, SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002096 }
2097 }
2098 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002099
Guido van Rossumc206c761995-01-10 15:23:19 +00002100 if (a == NULL)
2101 *prem = NULL;
2102 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002103 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002104 *prem = divrem1(v, d, &d);
2105 /* d receives the (unused) remainder */
2106 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002107 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002108 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002109 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002110 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002111 Py_DECREF(v);
2112 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002113 return a;
2114}
2115
2116/* Methods */
2117
2118static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002119long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002120{
Guido van Rossum9475a232001-10-05 20:51:39 +00002121 v->ob_type->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002122}
2123
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002124static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002125long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002126{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00002127 return long_format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002128}
2129
2130static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002131long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002132{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002133 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002134
Guido van Rossumc6913e71991-11-19 20:26:46 +00002135 if (a->ob_size != b->ob_size) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002136 if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002137 sign = 0;
2138 else
2139 sign = a->ob_size - b->ob_size;
2140 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002141 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002142 Py_ssize_t i = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002143 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2144 ;
2145 if (i < 0)
2146 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002147 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002148 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002149 if (a->ob_size < 0)
2150 sign = -sign;
2151 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002152 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002153 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002154}
2155
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002156static PyObject *
2157long_richcompare(PyObject *self, PyObject *other, int op)
2158{
2159 PyLongObject *a, *b;
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002160 PyObject *result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002161 CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b);
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002162 result = Py_CmpToRich(op, long_compare(a, b));
2163 Py_DECREF(a);
2164 Py_DECREF(b);
2165 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002166}
2167
Guido van Rossum9bfef441993-03-29 10:43:31 +00002168static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002169long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002170{
2171 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002172 Py_ssize_t i;
2173 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002174
2175 /* This is designed so that Python ints and longs with the
2176 same value hash to the same value, otherwise comparisons
2177 of mapping keys will turn out weird */
2178 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00002179 switch(i) {
2180 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2181 case 0: return 0;
2182 case 1: return v->ob_digit[0];
2183 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002184 sign = 1;
2185 x = 0;
2186 if (i < 0) {
2187 sign = -1;
2188 i = -(i);
2189 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002190#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002191 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002192 /* Force a native long #-bits (32 or 64) circular shift */
2193 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002194 x += v->ob_digit[i];
2195 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002196#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002197 x = x * sign;
2198 if (x == -1)
2199 x = -2;
2200 return x;
2201}
2202
2203
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002204/* Add the absolute values of two long integers. */
2205
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002206static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002207x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002208{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002209 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002210 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002211 int i;
2212 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002213
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002214 /* Ensure a is the larger of the two: */
2215 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002216 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002217 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002218 size_a = size_b;
2219 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002220 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002221 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002222 if (z == NULL)
2223 return NULL;
2224 for (i = 0; i < size_b; ++i) {
2225 carry += a->ob_digit[i] + b->ob_digit[i];
2226 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002227 carry >>= SHIFT;
2228 }
2229 for (; i < size_a; ++i) {
2230 carry += a->ob_digit[i];
2231 z->ob_digit[i] = carry & MASK;
2232 carry >>= SHIFT;
2233 }
2234 z->ob_digit[i] = carry;
2235 return long_normalize(z);
2236}
2237
2238/* Subtract the absolute values of two integers. */
2239
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002240static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002241x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002242{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002243 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002244 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002245 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002246 int sign = 1;
2247 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002248
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002249 /* Ensure a is the larger of the two: */
2250 if (size_a < size_b) {
2251 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002252 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002253 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002254 size_a = size_b;
2255 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002256 }
2257 else if (size_a == size_b) {
2258 /* Find highest digit where a and b differ: */
2259 i = size_a;
2260 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2261 ;
2262 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002263 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002264 if (a->ob_digit[i] < b->ob_digit[i]) {
2265 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002266 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002267 }
2268 size_a = size_b = i+1;
2269 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002270 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002271 if (z == NULL)
2272 return NULL;
2273 for (i = 0; i < size_b; ++i) {
2274 /* The following assumes unsigned arithmetic
2275 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002276 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002277 z->ob_digit[i] = borrow & MASK;
2278 borrow >>= SHIFT;
2279 borrow &= 1; /* Keep only one sign bit */
2280 }
2281 for (; i < size_a; ++i) {
2282 borrow = a->ob_digit[i] - borrow;
2283 z->ob_digit[i] = borrow & MASK;
2284 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002285 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002286 }
2287 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002288 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002289 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002290 return long_normalize(z);
2291}
2292
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002293static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002294long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002295{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002296 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002297
Neil Schemenauerba872e22001-01-04 01:46:03 +00002298 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2299
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002300 if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) {
2301 PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) +
2302 MEDIUM_VALUE(b));
2303 Py_DECREF(a);
2304 Py_DECREF(b);
2305 return result;
2306 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002307 if (a->ob_size < 0) {
2308 if (b->ob_size < 0) {
2309 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002310 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002311 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002312 }
2313 else
2314 z = x_sub(b, a);
2315 }
2316 else {
2317 if (b->ob_size < 0)
2318 z = x_sub(a, b);
2319 else
2320 z = x_add(a, b);
2321 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002322 Py_DECREF(a);
2323 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002324 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002325}
2326
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002327static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002328long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002329{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002330 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002331
Neil Schemenauerba872e22001-01-04 01:46:03 +00002332 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2333
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002334 if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) {
2335 PyObject* r;
2336 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2337 Py_DECREF(a);
2338 Py_DECREF(b);
2339 return r;
2340 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002341 if (a->ob_size < 0) {
2342 if (b->ob_size < 0)
2343 z = x_sub(a, b);
2344 else
2345 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002346 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002347 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002348 }
2349 else {
2350 if (b->ob_size < 0)
2351 z = x_add(a, b);
2352 else
2353 z = x_sub(a, b);
2354 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002355 Py_DECREF(a);
2356 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002357 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002358}
2359
Tim Peters5af4e6c2002-08-12 02:31:19 +00002360/* Grade school multiplication, ignoring the signs.
2361 * Returns the absolute value of the product, or NULL if error.
2362 */
2363static PyLongObject *
2364x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002365{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002366 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002367 Py_ssize_t size_a = ABS(a->ob_size);
2368 Py_ssize_t size_b = ABS(b->ob_size);
2369 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002370
Tim Peters5af4e6c2002-08-12 02:31:19 +00002371 z = _PyLong_New(size_a + size_b);
2372 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002373 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002374
2375 memset(z->ob_digit, 0, z->ob_size * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002376 if (a == b) {
2377 /* Efficient squaring per HAC, Algorithm 14.16:
2378 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2379 * Gives slightly less than a 2x speedup when a == b,
2380 * via exploiting that each entry in the multiplication
2381 * pyramid appears twice (except for the size_a squares).
2382 */
2383 for (i = 0; i < size_a; ++i) {
2384 twodigits carry;
2385 twodigits f = a->ob_digit[i];
2386 digit *pz = z->ob_digit + (i << 1);
2387 digit *pa = a->ob_digit + i + 1;
2388 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002389
Tim Peters0973b992004-08-29 22:16:50 +00002390 SIGCHECK({
2391 Py_DECREF(z);
2392 return NULL;
2393 })
2394
2395 carry = *pz + f * f;
2396 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002397 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002398 assert(carry <= MASK);
2399
2400 /* Now f is added in twice in each column of the
2401 * pyramid it appears. Same as adding f<<1 once.
2402 */
2403 f <<= 1;
2404 while (pa < paend) {
2405 carry += *pz + *pa++ * f;
2406 *pz++ = (digit)(carry & MASK);
2407 carry >>= SHIFT;
2408 assert(carry <= (MASK << 1));
2409 }
2410 if (carry) {
2411 carry += *pz;
2412 *pz++ = (digit)(carry & MASK);
2413 carry >>= SHIFT;
2414 }
2415 if (carry)
2416 *pz += (digit)(carry & MASK);
2417 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002418 }
Tim Peters0973b992004-08-29 22:16:50 +00002419 }
2420 else { /* a is not the same as b -- gradeschool long mult */
2421 for (i = 0; i < size_a; ++i) {
2422 twodigits carry = 0;
2423 twodigits f = a->ob_digit[i];
2424 digit *pz = z->ob_digit + i;
2425 digit *pb = b->ob_digit;
2426 digit *pbend = b->ob_digit + size_b;
2427
2428 SIGCHECK({
2429 Py_DECREF(z);
2430 return NULL;
2431 })
2432
2433 while (pb < pbend) {
2434 carry += *pz + *pb++ * f;
2435 *pz++ = (digit)(carry & MASK);
2436 carry >>= SHIFT;
2437 assert(carry <= MASK);
2438 }
2439 if (carry)
2440 *pz += (digit)(carry & MASK);
2441 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002442 }
2443 }
Tim Peters44121a62002-08-12 06:17:58 +00002444 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002445}
2446
2447/* A helper for Karatsuba multiplication (k_mul).
2448 Takes a long "n" and an integer "size" representing the place to
2449 split, and sets low and high such that abs(n) == (high << size) + low,
2450 viewing the shift as being by digits. The sign bit is ignored, and
2451 the return values are >= 0.
2452 Returns 0 on success, -1 on failure.
2453*/
2454static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002455kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002456{
2457 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002458 Py_ssize_t size_lo, size_hi;
2459 const Py_ssize_t size_n = ABS(n->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002460
2461 size_lo = MIN(size_n, size);
2462 size_hi = size_n - size_lo;
2463
2464 if ((hi = _PyLong_New(size_hi)) == NULL)
2465 return -1;
2466 if ((lo = _PyLong_New(size_lo)) == NULL) {
2467 Py_DECREF(hi);
2468 return -1;
2469 }
2470
2471 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2472 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2473
2474 *high = long_normalize(hi);
2475 *low = long_normalize(lo);
2476 return 0;
2477}
2478
Tim Peters60004642002-08-12 22:01:34 +00002479static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2480
Tim Peters5af4e6c2002-08-12 02:31:19 +00002481/* Karatsuba multiplication. Ignores the input signs, and returns the
2482 * absolute value of the product (or NULL if error).
2483 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2484 */
2485static PyLongObject *
2486k_mul(PyLongObject *a, PyLongObject *b)
2487{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002488 Py_ssize_t asize = ABS(a->ob_size);
2489 Py_ssize_t bsize = ABS(b->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002490 PyLongObject *ah = NULL;
2491 PyLongObject *al = NULL;
2492 PyLongObject *bh = NULL;
2493 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002494 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002495 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002496 Py_ssize_t shift; /* the number of digits we split off */
2497 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002498
Tim Peters5af4e6c2002-08-12 02:31:19 +00002499 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2500 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2501 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002502 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002503 * By picking X to be a power of 2, "*X" is just shifting, and it's
2504 * been reduced to 3 multiplies on numbers half the size.
2505 */
2506
Tim Petersfc07e562002-08-12 02:54:10 +00002507 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002508 * is largest.
2509 */
Tim Peters738eda72002-08-12 15:08:20 +00002510 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002511 t1 = a;
2512 a = b;
2513 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002514
2515 i = asize;
2516 asize = bsize;
2517 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002518 }
2519
2520 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002521 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2522 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002523 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002524 return _PyLong_New(0);
2525 else
2526 return x_mul(a, b);
2527 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002528
Tim Peters60004642002-08-12 22:01:34 +00002529 /* If a is small compared to b, splitting on b gives a degenerate
2530 * case with ah==0, and Karatsuba may be (even much) less efficient
2531 * than "grade school" then. However, we can still win, by viewing
2532 * b as a string of "big digits", each of width a->ob_size. That
2533 * leads to a sequence of balanced calls to k_mul.
2534 */
2535 if (2 * asize <= bsize)
2536 return k_lopsided_mul(a, b);
2537
Tim Petersd6974a52002-08-13 20:37:51 +00002538 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002539 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002540 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Tim Petersd6974a52002-08-13 20:37:51 +00002541 assert(ah->ob_size > 0); /* the split isn't degenerate */
2542
Tim Peters0973b992004-08-29 22:16:50 +00002543 if (a == b) {
2544 bh = ah;
2545 bl = al;
2546 Py_INCREF(bh);
2547 Py_INCREF(bl);
2548 }
2549 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002550
Tim Petersd64c1de2002-08-12 17:36:03 +00002551 /* The plan:
2552 * 1. Allocate result space (asize + bsize digits: that's always
2553 * enough).
2554 * 2. Compute ah*bh, and copy into result at 2*shift.
2555 * 3. Compute al*bl, and copy into result at 0. Note that this
2556 * can't overlap with #2.
2557 * 4. Subtract al*bl from the result, starting at shift. This may
2558 * underflow (borrow out of the high digit), but we don't care:
2559 * we're effectively doing unsigned arithmetic mod
2560 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2561 * borrows and carries out of the high digit can be ignored.
2562 * 5. Subtract ah*bh from the result, starting at shift.
2563 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2564 * at shift.
2565 */
2566
2567 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002568 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002569 if (ret == NULL) goto fail;
2570#ifdef Py_DEBUG
2571 /* Fill with trash, to catch reference to uninitialized digits. */
2572 memset(ret->ob_digit, 0xDF, ret->ob_size * sizeof(digit));
2573#endif
Tim Peters44121a62002-08-12 06:17:58 +00002574
Tim Petersd64c1de2002-08-12 17:36:03 +00002575 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002576 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2577 assert(t1->ob_size >= 0);
2578 assert(2*shift + t1->ob_size <= ret->ob_size);
2579 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2580 t1->ob_size * sizeof(digit));
2581
2582 /* Zero-out the digits higher than the ah*bh copy. */
2583 i = ret->ob_size - 2*shift - t1->ob_size;
Tim Peters44121a62002-08-12 06:17:58 +00002584 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002585 memset(ret->ob_digit + 2*shift + t1->ob_size, 0,
Tim Peters44121a62002-08-12 06:17:58 +00002586 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002587
Tim Petersd64c1de2002-08-12 17:36:03 +00002588 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002589 if ((t2 = k_mul(al, bl)) == NULL) {
2590 Py_DECREF(t1);
2591 goto fail;
2592 }
2593 assert(t2->ob_size >= 0);
2594 assert(t2->ob_size <= 2*shift); /* no overlap with high digits */
2595 memcpy(ret->ob_digit, t2->ob_digit, t2->ob_size * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002596
2597 /* Zero out remaining digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002598 i = 2*shift - t2->ob_size; /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002599 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002600 memset(ret->ob_digit + t2->ob_size, 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002601
Tim Petersd64c1de2002-08-12 17:36:03 +00002602 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2603 * because it's fresher in cache.
2604 */
Tim Peters738eda72002-08-12 15:08:20 +00002605 i = ret->ob_size - shift; /* # digits after shift */
Tim Petersd64c1de2002-08-12 17:36:03 +00002606 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, t2->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002607 Py_DECREF(t2);
2608
Tim Petersd64c1de2002-08-12 17:36:03 +00002609 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, t1->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002610 Py_DECREF(t1);
2611
Tim Petersd64c1de2002-08-12 17:36:03 +00002612 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002613 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2614 Py_DECREF(ah);
2615 Py_DECREF(al);
2616 ah = al = NULL;
2617
Tim Peters0973b992004-08-29 22:16:50 +00002618 if (a == b) {
2619 t2 = t1;
2620 Py_INCREF(t2);
2621 }
2622 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002623 Py_DECREF(t1);
2624 goto fail;
2625 }
2626 Py_DECREF(bh);
2627 Py_DECREF(bl);
2628 bh = bl = NULL;
2629
Tim Peters738eda72002-08-12 15:08:20 +00002630 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002631 Py_DECREF(t1);
2632 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002633 if (t3 == NULL) goto fail;
Tim Peters547607c2002-08-12 19:43:49 +00002634 assert(t3->ob_size >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002635
Tim Petersd6974a52002-08-13 20:37:51 +00002636 /* Add t3. It's not obvious why we can't run out of room here.
2637 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002638 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002639 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, t3->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002640 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002641
Tim Peters5af4e6c2002-08-12 02:31:19 +00002642 return long_normalize(ret);
2643
2644 fail:
2645 Py_XDECREF(ret);
2646 Py_XDECREF(ah);
2647 Py_XDECREF(al);
2648 Py_XDECREF(bh);
2649 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002650 return NULL;
2651}
2652
Tim Petersd6974a52002-08-13 20:37:51 +00002653/* (*) Why adding t3 can't "run out of room" above.
2654
Tim Petersab86c2b2002-08-15 20:06:00 +00002655Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2656to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002657
Tim Petersab86c2b2002-08-15 20:06:00 +000026581. For any integer i, i = c(i/2) + f(i/2). In particular,
2659 bsize = c(bsize/2) + f(bsize/2).
26602. shift = f(bsize/2)
26613. asize <= bsize
26624. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2663 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002664
Tim Petersab86c2b2002-08-15 20:06:00 +00002665We allocated asize + bsize result digits, and add t3 into them at an offset
2666of shift. This leaves asize+bsize-shift allocated digit positions for t3
2667to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2668asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002669
Tim Petersab86c2b2002-08-15 20:06:00 +00002670bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2671at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002672
Tim Petersab86c2b2002-08-15 20:06:00 +00002673If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2674digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2675most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002676
Tim Petersab86c2b2002-08-15 20:06:00 +00002677The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002678
Tim Petersab86c2b2002-08-15 20:06:00 +00002679 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002680
Tim Petersab86c2b2002-08-15 20:06:00 +00002681and we have asize + c(bsize/2) available digit positions. We need to show
2682this is always enough. An instance of c(bsize/2) cancels out in both, so
2683the question reduces to whether asize digits is enough to hold
2684(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2685then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2686asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2687digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2688asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002689c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2690is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2691bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002692
Tim Peters48d52c02002-08-14 17:07:32 +00002693Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2694clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2695ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002696*/
2697
Tim Peters60004642002-08-12 22:01:34 +00002698/* b has at least twice the digits of a, and a is big enough that Karatsuba
2699 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2700 * of slices, each with a->ob_size digits, and multiply the slices by a,
2701 * one at a time. This gives k_mul balanced inputs to work with, and is
2702 * also cache-friendly (we compute one double-width slice of the result
2703 * at a time, then move on, never bactracking except for the helpful
2704 * single-width slice overlap between successive partial sums).
2705 */
2706static PyLongObject *
2707k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2708{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002709 const Py_ssize_t asize = ABS(a->ob_size);
2710 Py_ssize_t bsize = ABS(b->ob_size);
2711 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002712 PyLongObject *ret;
2713 PyLongObject *bslice = NULL;
2714
2715 assert(asize > KARATSUBA_CUTOFF);
2716 assert(2 * asize <= bsize);
2717
2718 /* Allocate result space, and zero it out. */
2719 ret = _PyLong_New(asize + bsize);
2720 if (ret == NULL)
2721 return NULL;
2722 memset(ret->ob_digit, 0, ret->ob_size * sizeof(digit));
2723
2724 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002725 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002726 if (bslice == NULL)
2727 goto fail;
2728
2729 nbdone = 0;
2730 while (bsize > 0) {
2731 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002732 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002733
2734 /* Multiply the next slice of b by a. */
2735 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2736 nbtouse * sizeof(digit));
2737 bslice->ob_size = nbtouse;
2738 product = k_mul(a, bslice);
2739 if (product == NULL)
2740 goto fail;
2741
2742 /* Add into result. */
2743 (void)v_iadd(ret->ob_digit + nbdone, ret->ob_size - nbdone,
2744 product->ob_digit, product->ob_size);
2745 Py_DECREF(product);
2746
2747 bsize -= nbtouse;
2748 nbdone += nbtouse;
2749 }
2750
2751 Py_DECREF(bslice);
2752 return long_normalize(ret);
2753
2754 fail:
2755 Py_DECREF(ret);
2756 Py_XDECREF(bslice);
2757 return NULL;
2758}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002759
2760static PyObject *
2761long_mul(PyLongObject *v, PyLongObject *w)
2762{
2763 PyLongObject *a, *b, *z;
2764
2765 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002766 Py_INCREF(Py_NotImplemented);
2767 return Py_NotImplemented;
2768 }
2769
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002770 if (ABS(v->ob_size) <= 1 && ABS(w->ob_size) <= 1) {
2771 PyObject *r;
2772 r = PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w));
2773 Py_DECREF(a);
2774 Py_DECREF(b);
2775 return r;
2776 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002777
Tim Petersd64c1de2002-08-12 17:36:03 +00002778 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002779 /* Negate if exactly one of the inputs is negative. */
2780 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002781 NEGATE(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002782 Py_DECREF(a);
2783 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002784 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002785}
2786
Guido van Rossume32e0141992-01-19 16:31:05 +00002787/* The / and % operators are now defined in terms of divmod().
2788 The expression a mod b has the value a - b*floor(a/b).
2789 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002790 |a| by |b|, with the sign of a. This is also expressed
2791 as a - b*trunc(a/b), if trunc truncates towards zero.
2792 Some examples:
2793 a b a rem b a mod b
2794 13 10 3 3
2795 -13 10 -3 7
2796 13 -10 3 -7
2797 -13 -10 -3 -3
2798 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002799 have different signs. We then subtract one from the 'div'
2800 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002801
Tim Peters47e52ee2004-08-30 02:44:38 +00002802/* Compute
2803 * *pdiv, *pmod = divmod(v, w)
2804 * NULL can be passed for pdiv or pmod, in which case that part of
2805 * the result is simply thrown away. The caller owns a reference to
2806 * each of these it requests (does not pass NULL for).
2807 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002808static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002809l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002810 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002811{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002812 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002813
Guido van Rossume32e0141992-01-19 16:31:05 +00002814 if (long_divrem(v, w, &div, &mod) < 0)
2815 return -1;
Guido van Rossum472c04f1996-12-05 21:57:21 +00002816 if ((mod->ob_size < 0 && w->ob_size > 0) ||
2817 (mod->ob_size > 0 && w->ob_size < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002818 PyLongObject *temp;
2819 PyLongObject *one;
2820 temp = (PyLongObject *) long_add(mod, w);
2821 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002822 mod = temp;
2823 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002824 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002825 return -1;
2826 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002827 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002828 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002829 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2830 Py_DECREF(mod);
2831 Py_DECREF(div);
2832 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002833 return -1;
2834 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002835 Py_DECREF(one);
2836 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002837 div = temp;
2838 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002839 if (pdiv != NULL)
2840 *pdiv = div;
2841 else
2842 Py_DECREF(div);
2843
2844 if (pmod != NULL)
2845 *pmod = mod;
2846 else
2847 Py_DECREF(mod);
2848
Guido van Rossume32e0141992-01-19 16:31:05 +00002849 return 0;
2850}
2851
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002852static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002853long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002854{
Tim Peters47e52ee2004-08-30 02:44:38 +00002855 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002856
2857 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002858 if (l_divmod(a, b, &div, NULL) < 0)
2859 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002860 Py_DECREF(a);
2861 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002862 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002863}
2864
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002865static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002866long_true_divide(PyObject *v, PyObject *w)
2867{
Tim Peterse2a60002001-09-04 06:17:36 +00002868 PyLongObject *a, *b;
2869 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002870 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002871
2872 CONVERT_BINOP(v, w, &a, &b);
2873 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2874 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002875 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2876 Py_DECREF(a);
2877 Py_DECREF(b);
2878 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002879 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002880 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2881 but should really be set correctly after sucessful calls to
2882 _PyLong_AsScaledDouble() */
2883 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002884
2885 if (bd == 0.0) {
2886 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002887 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002888 return NULL;
2889 }
2890
2891 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2892 ad /= bd; /* overflow/underflow impossible here */
2893 aexp -= bexp;
2894 if (aexp > INT_MAX / SHIFT)
2895 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002896 else if (aexp < -(INT_MAX / SHIFT))
2897 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002898 errno = 0;
2899 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002900 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002901 goto overflow;
2902 return PyFloat_FromDouble(ad);
2903
2904overflow:
2905 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002906 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002907 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002908
Tim Peters20dab9f2001-09-04 05:31:47 +00002909}
2910
2911static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002912long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002913{
Tim Peters47e52ee2004-08-30 02:44:38 +00002914 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002915
2916 CONVERT_BINOP(v, w, &a, &b);
2917
Tim Peters47e52ee2004-08-30 02:44:38 +00002918 if (l_divmod(a, b, NULL, &mod) < 0)
2919 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002920 Py_DECREF(a);
2921 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002922 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002923}
2924
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002925static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002926long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002927{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002928 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002929 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002930
2931 CONVERT_BINOP(v, w, &a, &b);
2932
2933 if (l_divmod(a, b, &div, &mod) < 0) {
2934 Py_DECREF(a);
2935 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002936 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002937 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002938 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002939 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002940 PyTuple_SetItem(z, 0, (PyObject *) div);
2941 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002942 }
2943 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002944 Py_DECREF(div);
2945 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002946 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002947 Py_DECREF(a);
2948 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002949 return z;
2950}
2951
Tim Peters47e52ee2004-08-30 02:44:38 +00002952/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002953static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002954long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002955{
Tim Peters47e52ee2004-08-30 02:44:38 +00002956 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2957 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002958
Tim Peters47e52ee2004-08-30 02:44:38 +00002959 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002960 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002961 PyLongObject *temp = NULL;
2962
2963 /* 5-ary values. If the exponent is large enough, table is
2964 * precomputed so that table[i] == a**i % c for i in range(32).
2965 */
2966 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2967 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2968
2969 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002970 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002971 if (PyLong_Check(x)) {
2972 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002973 Py_INCREF(x);
2974 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002975 else if (x == Py_None)
2976 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002977 else {
2978 Py_DECREF(a);
2979 Py_DECREF(b);
2980 Py_INCREF(Py_NotImplemented);
2981 return Py_NotImplemented;
2982 }
Tim Peters4c483c42001-09-05 06:24:58 +00002983
Tim Peters47e52ee2004-08-30 02:44:38 +00002984 if (b->ob_size < 0) { /* if exponent is negative */
2985 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002986 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002987 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002988 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002989 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002990 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002991 /* else return a float. This works because we know
2992 that this calls float_pow() which converts its
2993 arguments to double. */
2994 Py_DECREF(a);
2995 Py_DECREF(b);
2996 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002997 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002998 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002999
3000 if (c) {
3001 /* if modulus == 0:
3002 raise ValueError() */
3003 if (c->ob_size == 0) {
3004 PyErr_SetString(PyExc_ValueError,
3005 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003006 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003007 }
3008
3009 /* if modulus < 0:
3010 negativeOutput = True
3011 modulus = -modulus */
3012 if (c->ob_size < 0) {
3013 negativeOutput = 1;
3014 temp = (PyLongObject *)_PyLong_Copy(c);
3015 if (temp == NULL)
3016 goto Error;
3017 Py_DECREF(c);
3018 c = temp;
3019 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003020 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003021 }
3022
3023 /* if modulus == 1:
3024 return 0 */
3025 if ((c->ob_size == 1) && (c->ob_digit[0] == 1)) {
3026 z = (PyLongObject *)PyLong_FromLong(0L);
3027 goto Done;
3028 }
3029
3030 /* if base < 0:
3031 base = base % modulus
3032 Having the base positive just makes things easier. */
3033 if (a->ob_size < 0) {
3034 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003035 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003036 Py_DECREF(a);
3037 a = temp;
3038 temp = NULL;
3039 }
3040 }
3041
3042 /* At this point a, b, and c are guaranteed non-negative UNLESS
3043 c is NULL, in which case a may be negative. */
3044
3045 z = (PyLongObject *)PyLong_FromLong(1L);
3046 if (z == NULL)
3047 goto Error;
3048
3049 /* Perform a modular reduction, X = X % c, but leave X alone if c
3050 * is NULL.
3051 */
3052#define REDUCE(X) \
3053 if (c != NULL) { \
3054 if (l_divmod(X, c, NULL, &temp) < 0) \
3055 goto Error; \
3056 Py_XDECREF(X); \
3057 X = temp; \
3058 temp = NULL; \
3059 }
3060
3061 /* Multiply two values, then reduce the result:
3062 result = X*Y % c. If c is NULL, skip the mod. */
3063#define MULT(X, Y, result) \
3064{ \
3065 temp = (PyLongObject *)long_mul(X, Y); \
3066 if (temp == NULL) \
3067 goto Error; \
3068 Py_XDECREF(result); \
3069 result = temp; \
3070 temp = NULL; \
3071 REDUCE(result) \
3072}
3073
3074 if (b->ob_size <= FIVEARY_CUTOFF) {
3075 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3076 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3077 for (i = b->ob_size - 1; i >= 0; --i) {
3078 digit bi = b->ob_digit[i];
3079
3080 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
3081 MULT(z, z, z)
3082 if (bi & j)
3083 MULT(z, a, z)
3084 }
3085 }
3086 }
3087 else {
3088 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3089 Py_INCREF(z); /* still holds 1L */
3090 table[0] = z;
3091 for (i = 1; i < 32; ++i)
3092 MULT(table[i-1], a, table[i])
3093
3094 for (i = b->ob_size - 1; i >= 0; --i) {
3095 const digit bi = b->ob_digit[i];
3096
3097 for (j = SHIFT - 5; j >= 0; j -= 5) {
3098 const int index = (bi >> j) & 0x1f;
3099 for (k = 0; k < 5; ++k)
3100 MULT(z, z, z)
3101 if (index)
3102 MULT(z, table[index], z)
3103 }
3104 }
3105 }
3106
3107 if (negativeOutput && (z->ob_size != 0)) {
3108 temp = (PyLongObject *)long_sub(z, c);
3109 if (temp == NULL)
3110 goto Error;
3111 Py_DECREF(z);
3112 z = temp;
3113 temp = NULL;
3114 }
3115 goto Done;
3116
3117 Error:
3118 if (z != NULL) {
3119 Py_DECREF(z);
3120 z = NULL;
3121 }
3122 /* fall through */
3123 Done:
Tim Peters47e52ee2004-08-30 02:44:38 +00003124 if (b->ob_size > FIVEARY_CUTOFF) {
3125 for (i = 0; i < 32; ++i)
3126 Py_XDECREF(table[i]);
3127 }
Tim Petersde7990b2005-07-17 23:45:23 +00003128 Py_DECREF(a);
3129 Py_DECREF(b);
3130 Py_XDECREF(c);
3131 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003132 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003133}
3134
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003135static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003136long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003137{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003138 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003139 PyLongObject *x;
3140 PyLongObject *w;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003141 if (ABS(v->ob_size) <=1)
3142 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003143 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003144 if (w == NULL)
3145 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003146 x = (PyLongObject *) long_add(v, w);
3147 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003148 if (x == NULL)
3149 return NULL;
Tim Peters40c397d2001-09-11 23:24:22 +00003150 x->ob_size = -(x->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003151 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003152}
3153
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003154static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003155long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003156{
Tim Peters69c2de32001-09-11 22:31:33 +00003157 if (PyLong_CheckExact(v)) {
3158 Py_INCREF(v);
3159 return (PyObject *)v;
3160 }
3161 else
3162 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003163}
3164
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003165static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003166long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003167{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003168 PyLongObject *z;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003169 if (ABS(v->ob_size) <= 1)
3170 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003171 z = (PyLongObject *)_PyLong_Copy(v);
3172 if (z != NULL)
3173 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003174 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003175}
3176
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003177static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003178long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003179{
3180 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003181 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003182 else
3183 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003184}
3185
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003186static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003187long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003188{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003189 return ABS(v->ob_size) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003190}
3191
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003192static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003193long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003194{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003195 PyLongObject *a, *b;
3196 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003197 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003198 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003199 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003200
Neil Schemenauerba872e22001-01-04 01:46:03 +00003201 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3202
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003203 if (a->ob_size < 0) {
3204 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003205 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003206 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003207 if (a1 == NULL)
3208 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003209 a2 = (PyLongObject *) long_rshift(a1, b);
3210 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003211 if (a2 == NULL)
3212 goto rshift_error;
3213 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003214 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003215 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003216 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003217
Neil Schemenauerba872e22001-01-04 01:46:03 +00003218 shiftby = PyLong_AsLong((PyObject *)b);
3219 if (shiftby == -1L && PyErr_Occurred())
3220 goto rshift_error;
3221 if (shiftby < 0) {
3222 PyErr_SetString(PyExc_ValueError,
3223 "negative shift count");
3224 goto rshift_error;
3225 }
3226 wordshift = shiftby / SHIFT;
3227 newsize = ABS(a->ob_size) - wordshift;
3228 if (newsize <= 0) {
3229 z = _PyLong_New(0);
3230 Py_DECREF(a);
3231 Py_DECREF(b);
3232 return (PyObject *)z;
3233 }
3234 loshift = shiftby % SHIFT;
3235 hishift = SHIFT - loshift;
3236 lomask = ((digit)1 << hishift) - 1;
3237 himask = MASK ^ lomask;
3238 z = _PyLong_New(newsize);
3239 if (z == NULL)
3240 goto rshift_error;
3241 if (a->ob_size < 0)
3242 z->ob_size = -(z->ob_size);
3243 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3244 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3245 if (i+1 < newsize)
3246 z->ob_digit[i] |=
3247 (a->ob_digit[j+1] << hishift) & himask;
3248 }
3249 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003250 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003251rshift_error:
3252 Py_DECREF(a);
3253 Py_DECREF(b);
3254 return (PyObject *) z;
3255
Guido van Rossumc6913e71991-11-19 20:26:46 +00003256}
3257
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003258static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003259long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003260{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003261 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003262 PyLongObject *a, *b;
3263 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003264 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003265 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003266 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003267
Neil Schemenauerba872e22001-01-04 01:46:03 +00003268 CONVERT_BINOP(v, w, &a, &b);
3269
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003270 shiftby = PyLong_AsLong((PyObject *)b);
3271 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003272 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003273 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003274 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003275 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003276 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003277 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003278 PyErr_SetString(PyExc_ValueError,
3279 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003280 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003281 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003282 /* wordshift, remshift = divmod(shiftby, SHIFT) */
3283 wordshift = (int)shiftby / SHIFT;
3284 remshift = (int)shiftby - wordshift * SHIFT;
3285
3286 oldsize = ABS(a->ob_size);
3287 newsize = oldsize + wordshift;
3288 if (remshift)
3289 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003290 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003291 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003292 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003293 if (a->ob_size < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003294 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003295 for (i = 0; i < wordshift; i++)
3296 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003297 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003298 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003299 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003300 z->ob_digit[i] = (digit)(accum & MASK);
3301 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003302 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003303 if (remshift)
3304 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003305 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003306 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003307 z = long_normalize(z);
3308lshift_error:
3309 Py_DECREF(a);
3310 Py_DECREF(b);
3311 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003312}
3313
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003314
3315/* Bitwise and/xor/or operations */
3316
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003317static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003318long_bitwise(PyLongObject *a,
3319 int op, /* '&', '|', '^' */
3320 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003321{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003322 digit maska, maskb; /* 0 or MASK */
3323 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003324 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003325 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003326 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003327 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003328 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003329
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003330 if (a->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003331 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003332 if (a == NULL)
3333 return NULL;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003334 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003335 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003336 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003337 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003338 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003339 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003340 if (b->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003341 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003342 if (b == NULL) {
3343 Py_DECREF(a);
3344 return NULL;
3345 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003346 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003347 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003348 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003349 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003350 maskb = 0;
3351 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003352
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003353 negz = 0;
3354 switch (op) {
3355 case '^':
3356 if (maska != maskb) {
3357 maska ^= MASK;
3358 negz = -1;
3359 }
3360 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003361 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003362 if (maska && maskb) {
3363 op = '|';
3364 maska ^= MASK;
3365 maskb ^= MASK;
3366 negz = -1;
3367 }
3368 break;
3369 case '|':
3370 if (maska || maskb) {
3371 op = '&';
3372 maska ^= MASK;
3373 maskb ^= MASK;
3374 negz = -1;
3375 }
3376 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003377 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003378
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003379 /* JRH: The original logic here was to allocate the result value (z)
3380 as the longer of the two operands. However, there are some cases
3381 where the result is guaranteed to be shorter than that: AND of two
3382 positives, OR of two negatives: use the shorter number. AND with
3383 mixed signs: use the positive number. OR with mixed signs: use the
3384 negative number. After the transformations above, op will be '&'
3385 iff one of these cases applies, and mask will be non-0 for operands
3386 whose length should be ignored.
3387 */
3388
3389 size_a = a->ob_size;
3390 size_b = b->ob_size;
3391 size_z = op == '&'
3392 ? (maska
3393 ? size_b
3394 : (maskb ? size_a : MIN(size_a, size_b)))
3395 : MAX(size_a, size_b);
3396 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003397 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003398 Py_DECREF(a);
3399 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003400 return NULL;
3401 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003402
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003403 for (i = 0; i < size_z; ++i) {
3404 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3405 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3406 switch (op) {
3407 case '&': z->ob_digit[i] = diga & digb; break;
3408 case '|': z->ob_digit[i] = diga | digb; break;
3409 case '^': z->ob_digit[i] = diga ^ digb; break;
3410 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003411 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003412
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003413 Py_DECREF(a);
3414 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003415 z = long_normalize(z);
3416 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003417 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003418 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003419 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003420 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003421}
3422
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003423static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003424long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003425{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003426 PyLongObject *a, *b;
3427 PyObject *c;
3428 CONVERT_BINOP(v, w, &a, &b);
3429 c = long_bitwise(a, '&', b);
3430 Py_DECREF(a);
3431 Py_DECREF(b);
3432 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003433}
3434
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003435static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003436long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003437{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003438 PyLongObject *a, *b;
3439 PyObject *c;
3440 CONVERT_BINOP(v, w, &a, &b);
3441 c = long_bitwise(a, '^', b);
3442 Py_DECREF(a);
3443 Py_DECREF(b);
3444 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003445}
3446
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003447static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003448long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003449{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003450 PyLongObject *a, *b;
3451 PyObject *c;
3452 CONVERT_BINOP(v, w, &a, &b);
3453 c = long_bitwise(a, '|', b);
3454 Py_DECREF(a);
3455 Py_DECREF(b);
3456 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003457}
3458
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003459static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003460long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003461{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003462 if (PyLong_CheckExact(v))
3463 Py_INCREF(v);
3464 else
3465 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003466 return v;
3467}
3468
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003469static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003470long_int(PyObject *v)
3471{
Guido van Rossumddefaf32007-01-14 03:31:43 +00003472 return long_long(v);
Walter Dörwaldf1715402002-11-19 20:49:15 +00003473}
3474
3475static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003476long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003477{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003478 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003479 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003480 if (result == -1.0 && PyErr_Occurred())
3481 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003482 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003483}
3484
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003485static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003486long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003487{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00003488 return long_format(v, 8);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003489}
3490
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003491static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003492long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003493{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00003494 return long_format(v, 16);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003495}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003496
3497static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003498long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003499
Tim Peters6d6c1a32001-08-02 04:15:00 +00003500static PyObject *
3501long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3502{
3503 PyObject *x = NULL;
3504 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003505 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003506
Guido van Rossumbef14172001-08-29 15:47:46 +00003507 if (type != &PyLong_Type)
3508 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003509 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003510 &x, &base))
3511 return NULL;
3512 if (x == NULL)
3513 return PyLong_FromLong(0L);
3514 if (base == -909)
3515 return PyNumber_Long(x);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003516 else if (PyString_Check(x)) {
3517 char *s = PyString_AS_STRING(x);
3518 char *end;
3519 PyObject *r = PyLong_FromString(s, &end, base);
3520 if (r != NULL && end != s + PyString_GET_SIZE(x)) {
3521 PyErr_SetString(PyExc_ValueError,
3522 "null byte in argument for int()");
3523 Py_DECREF(r);
3524 r = NULL;
3525 }
3526 return r;
3527 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003528#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003529 else if (PyUnicode_Check(x))
3530 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3531 PyUnicode_GET_SIZE(x),
3532 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003533#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003534 else {
3535 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003536 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537 return NULL;
3538 }
3539}
3540
Guido van Rossumbef14172001-08-29 15:47:46 +00003541/* Wimpy, slow approach to tp_new calls for subtypes of long:
3542 first create a regular long from whatever arguments we got,
3543 then allocate a subtype instance and initialize it from
3544 the regular long. The regular long is then thrown away.
3545*/
3546static PyObject *
3547long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3548{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003549 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003550 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003551
3552 assert(PyType_IsSubtype(type, &PyLong_Type));
3553 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3554 if (tmp == NULL)
3555 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003556 assert(PyLong_CheckExact(tmp));
Guido van Rossumbef14172001-08-29 15:47:46 +00003557 n = tmp->ob_size;
3558 if (n < 0)
3559 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003560 newobj = (PyLongObject *)type->tp_alloc(type, n);
3561 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003562 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003563 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003564 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003565 assert(PyLong_Check(newobj));
3566 newobj->ob_size = tmp->ob_size;
Guido van Rossumbef14172001-08-29 15:47:46 +00003567 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003568 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003569 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003570 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003571}
3572
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003573static PyObject *
3574long_getnewargs(PyLongObject *v)
3575{
3576 return Py_BuildValue("(N)", _PyLong_Copy(v));
3577}
3578
3579static PyMethodDef long_methods[] = {
3580 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3581 {NULL, NULL} /* sentinel */
3582};
3583
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003584PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003585"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003586\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003587Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003588point argument will be truncated towards zero (this does not include a\n\
3589string representation of a floating point number!) When converting a\n\
3590string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003591converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003592
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003593static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003594 (binaryfunc) long_add, /*nb_add*/
3595 (binaryfunc) long_sub, /*nb_subtract*/
3596 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003597 long_mod, /*nb_remainder*/
3598 long_divmod, /*nb_divmod*/
3599 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003600 (unaryfunc) long_neg, /*nb_negative*/
3601 (unaryfunc) long_pos, /*tp_positive*/
3602 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003603 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003604 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003605 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003606 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003607 long_and, /*nb_and*/
3608 long_xor, /*nb_xor*/
3609 long_or, /*nb_or*/
Neal Norwitzca810462006-08-29 07:57:59 +00003610 0, /*nb_coerce*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003611 long_int, /*nb_int*/
3612 long_long, /*nb_long*/
3613 long_float, /*nb_float*/
3614 long_oct, /*nb_oct*/
3615 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003616 0, /* nb_inplace_add */
3617 0, /* nb_inplace_subtract */
3618 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003619 0, /* nb_inplace_remainder */
3620 0, /* nb_inplace_power */
3621 0, /* nb_inplace_lshift */
3622 0, /* nb_inplace_rshift */
3623 0, /* nb_inplace_and */
3624 0, /* nb_inplace_xor */
3625 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003626 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003627 long_true_divide, /* nb_true_divide */
3628 0, /* nb_inplace_floor_divide */
3629 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003630 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003631};
3632
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003633PyTypeObject PyLong_Type = {
3634 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003635 0, /* ob_size */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003636 "int", /* tp_name */
3637 /* See _PyLong_New for why this isn't
3638 sizeof(PyLongObject) - sizeof(digit) */
3639 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003640 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003641 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003642 0, /* tp_print */
3643 0, /* tp_getattr */
3644 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003645 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003646 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003647 &long_as_number, /* tp_as_number */
3648 0, /* tp_as_sequence */
3649 0, /* tp_as_mapping */
3650 (hashfunc)long_hash, /* tp_hash */
3651 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003652 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003653 PyObject_GenericGetAttr, /* tp_getattro */
3654 0, /* tp_setattro */
3655 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003656 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3657 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003658 long_doc, /* tp_doc */
3659 0, /* tp_traverse */
3660 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003661 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003662 0, /* tp_weaklistoffset */
3663 0, /* tp_iter */
3664 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003665 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003666 0, /* tp_members */
3667 0, /* tp_getset */
3668 0, /* tp_base */
3669 0, /* tp_dict */
3670 0, /* tp_descr_get */
3671 0, /* tp_descr_set */
3672 0, /* tp_dictoffset */
3673 0, /* tp_init */
3674 0, /* tp_alloc */
3675 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003676 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003677};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003678
3679int
3680_PyLong_Init(void)
3681{
3682#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3683 int ival;
3684 PyLongObject *v = small_ints;
3685 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3686 PyObject_INIT(v, &PyLong_Type);
3687 v->ob_size = -1;
3688 v->ob_digit[0] = -ival;
3689 }
3690 for (; ival < NSMALLPOSINTS; ival++, v++) {
3691 PyObject_INIT(v, &PyLong_Type);
3692 v->ob_size = ival ? 1 : 0;
3693 v->ob_digit[0] = ival;
3694 }
3695#endif
3696 return 1;
3697}
3698
3699void
3700PyLong_Fini(void)
3701{
3702#if 0
3703 int i;
3704 /* This is currently not needed; the small integers
3705 are statically allocated */
3706#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3707 PyIntObject **q;
3708
3709 i = NSMALLNEGINTS + NSMALLPOSINTS;
3710 q = small_ints;
3711 while (--i >= 0) {
3712 Py_XDECREF(*q);
3713 *q++ = NULL;
3714 }
3715#endif
3716#endif
3717}