blob: 61e5bed5212747762fcbe6a320b9432fb9bd13a2 [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
1942PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001943PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001944{
Walter Dörwald07e14762002-11-06 16:15:14 +00001945 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001946 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001947
Walter Dörwald07e14762002-11-06 16:15:14 +00001948 if (buffer == NULL)
1949 return NULL;
1950
1951 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1952 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001953 return NULL;
1954 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001955 result = PyLong_FromString(buffer, NULL, base);
1956 PyMem_FREE(buffer);
1957 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001958}
1959
Tim Peters9f688bf2000-07-07 15:53:28 +00001960/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001961static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001962 (PyLongObject *, PyLongObject *, PyLongObject **);
1963static PyObject *long_pos(PyLongObject *);
1964static int long_divrem(PyLongObject *, PyLongObject *,
1965 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001966
1967/* Long division with remainder, top-level routine */
1968
Guido van Rossume32e0141992-01-19 16:31:05 +00001969static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001970long_divrem(PyLongObject *a, PyLongObject *b,
1971 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001972{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001973 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001974 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001975
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001976 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001977 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001978 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001979 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001980 }
1981 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001982 (size_a == size_b &&
1983 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001984 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00001985 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001986 if (*pdiv == NULL)
1987 return -1;
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 Rossumd8faa362007-04-27 19:54:29 +00001998 if (*prem == NULL) {
1999 Py_DECREF(z);
2000 return -1;
2001 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002002 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002003 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002004 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002005 if (z == NULL)
2006 return -1;
2007 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002008 /* Set the signs.
2009 The quotient z has the sign of a*b;
2010 the remainder r has the sign of a,
2011 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00002012 if ((a->ob_size < 0) != (b->ob_size < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002013 NEGATE(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002014 if (a->ob_size < 0 && (*prem)->ob_size != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002015 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002016 *pdiv = z;
2017 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002018}
2019
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002020/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002021
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002022static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002023x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002024{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002025 Py_ssize_t size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size);
Guido van Rossum2095d241997-04-09 19:41:24 +00002026 digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002027 PyLongObject *v = mul1(v1, d);
2028 PyLongObject *w = mul1(w1, d);
2029 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002030 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002031
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002032 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002033 Py_XDECREF(v);
2034 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002035 return NULL;
2036 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002037
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002038 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002039 assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002040 assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002041
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002042 size_v = ABS(v->ob_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002043 k = size_v - size_w;
2044 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002045
Thomas Wouters477c8d52006-05-27 19:21:47 +00002046 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002047 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2048 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002049 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002050 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002051
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002052 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002053 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002054 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002055 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002056 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002057 if (vj == w->ob_digit[size_w-1])
2058 q = MASK;
2059 else
2060 q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
2061 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002062
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002063 while (w->ob_digit[size_w-2]*q >
2064 ((
2065 ((twodigits)vj << SHIFT)
2066 + v->ob_digit[j-1]
2067 - q*w->ob_digit[size_w-1]
2068 ) << SHIFT)
2069 + v->ob_digit[j-2])
2070 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002071
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002072 for (i = 0; i < size_w && i+k < size_v; ++i) {
2073 twodigits z = w->ob_digit[i] * q;
Guido van Rossum2095d241997-04-09 19:41:24 +00002074 digit zz = (digit) (z >> SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002075 carry += v->ob_digit[i+k] - z
2076 + ((twodigits)zz << SHIFT);
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00002077 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002078 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
2079 carry, SHIFT);
2080 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002081 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002082
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002083 if (i+k < size_v) {
2084 carry += v->ob_digit[i+k];
2085 v->ob_digit[i+k] = 0;
2086 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002087
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002088 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002089 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090 else {
2091 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002092 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002093 carry = 0;
2094 for (i = 0; i < size_w && i+k < size_v; ++i) {
2095 carry += v->ob_digit[i+k] + w->ob_digit[i];
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00002096 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002097 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2098 BASE_TWODIGITS_TYPE,
2099 carry, SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002100 }
2101 }
2102 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002103
Guido van Rossumc206c761995-01-10 15:23:19 +00002104 if (a == NULL)
2105 *prem = NULL;
2106 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002107 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002108 *prem = divrem1(v, d, &d);
2109 /* d receives the (unused) remainder */
2110 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002111 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002112 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002113 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002114 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002115 Py_DECREF(v);
2116 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002117 return a;
2118}
2119
2120/* Methods */
2121
2122static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002123long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002124{
Guido van Rossum9475a232001-10-05 20:51:39 +00002125 v->ob_type->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002126}
2127
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002128static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002129long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002130{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00002131 return long_format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002132}
2133
2134static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002135long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002136{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002137 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002138
Guido van Rossumc6913e71991-11-19 20:26:46 +00002139 if (a->ob_size != b->ob_size) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002140 if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002141 sign = 0;
2142 else
2143 sign = a->ob_size - b->ob_size;
2144 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002145 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002146 Py_ssize_t i = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002147 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2148 ;
2149 if (i < 0)
2150 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002151 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002152 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002153 if (a->ob_size < 0)
2154 sign = -sign;
2155 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002156 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002157 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002158}
2159
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002160static PyObject *
2161long_richcompare(PyObject *self, PyObject *other, int op)
2162{
2163 PyLongObject *a, *b;
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002164 PyObject *result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002165 CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b);
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002166 result = Py_CmpToRich(op, long_compare(a, b));
2167 Py_DECREF(a);
2168 Py_DECREF(b);
2169 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002170}
2171
Guido van Rossum9bfef441993-03-29 10:43:31 +00002172static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002173long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002174{
2175 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002176 Py_ssize_t i;
2177 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002178
2179 /* This is designed so that Python ints and longs with the
2180 same value hash to the same value, otherwise comparisons
2181 of mapping keys will turn out weird */
2182 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00002183 switch(i) {
2184 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2185 case 0: return 0;
2186 case 1: return v->ob_digit[0];
2187 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002188 sign = 1;
2189 x = 0;
2190 if (i < 0) {
2191 sign = -1;
2192 i = -(i);
2193 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002194#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002195 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002196 /* Force a native long #-bits (32 or 64) circular shift */
2197 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002198 x += v->ob_digit[i];
2199 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002200#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002201 x = x * sign;
2202 if (x == -1)
2203 x = -2;
2204 return x;
2205}
2206
2207
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002208/* Add the absolute values of two long integers. */
2209
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002210static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002211x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002212{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002213 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002214 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002215 int i;
2216 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002217
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002218 /* Ensure a is the larger of the two: */
2219 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002220 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002221 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002222 size_a = size_b;
2223 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002224 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002225 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002226 if (z == NULL)
2227 return NULL;
2228 for (i = 0; i < size_b; ++i) {
2229 carry += a->ob_digit[i] + b->ob_digit[i];
2230 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002231 carry >>= SHIFT;
2232 }
2233 for (; i < size_a; ++i) {
2234 carry += a->ob_digit[i];
2235 z->ob_digit[i] = carry & MASK;
2236 carry >>= SHIFT;
2237 }
2238 z->ob_digit[i] = carry;
2239 return long_normalize(z);
2240}
2241
2242/* Subtract the absolute values of two integers. */
2243
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002244static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002245x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002246{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002247 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002248 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002249 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002250 int sign = 1;
2251 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002252
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002253 /* Ensure a is the larger of the two: */
2254 if (size_a < size_b) {
2255 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002256 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002257 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002258 size_a = size_b;
2259 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002260 }
2261 else if (size_a == size_b) {
2262 /* Find highest digit where a and b differ: */
2263 i = size_a;
2264 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2265 ;
2266 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002267 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002268 if (a->ob_digit[i] < b->ob_digit[i]) {
2269 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002270 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002271 }
2272 size_a = size_b = i+1;
2273 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002274 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002275 if (z == NULL)
2276 return NULL;
2277 for (i = 0; i < size_b; ++i) {
2278 /* The following assumes unsigned arithmetic
2279 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002280 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002281 z->ob_digit[i] = borrow & MASK;
2282 borrow >>= SHIFT;
2283 borrow &= 1; /* Keep only one sign bit */
2284 }
2285 for (; i < size_a; ++i) {
2286 borrow = a->ob_digit[i] - borrow;
2287 z->ob_digit[i] = borrow & MASK;
2288 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002289 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002290 }
2291 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002292 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002293 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002294 return long_normalize(z);
2295}
2296
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002297static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002298long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002299{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002300 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002301
Neil Schemenauerba872e22001-01-04 01:46:03 +00002302 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2303
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002304 if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) {
2305 PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) +
2306 MEDIUM_VALUE(b));
2307 Py_DECREF(a);
2308 Py_DECREF(b);
2309 return result;
2310 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002311 if (a->ob_size < 0) {
2312 if (b->ob_size < 0) {
2313 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002314 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002315 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002316 }
2317 else
2318 z = x_sub(b, a);
2319 }
2320 else {
2321 if (b->ob_size < 0)
2322 z = x_sub(a, b);
2323 else
2324 z = x_add(a, b);
2325 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002326 Py_DECREF(a);
2327 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002328 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002329}
2330
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002331static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002332long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002333{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002334 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002335
Neil Schemenauerba872e22001-01-04 01:46:03 +00002336 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2337
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002338 if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) {
2339 PyObject* r;
2340 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2341 Py_DECREF(a);
2342 Py_DECREF(b);
2343 return r;
2344 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002345 if (a->ob_size < 0) {
2346 if (b->ob_size < 0)
2347 z = x_sub(a, b);
2348 else
2349 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002350 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002351 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002352 }
2353 else {
2354 if (b->ob_size < 0)
2355 z = x_add(a, b);
2356 else
2357 z = x_sub(a, b);
2358 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002359 Py_DECREF(a);
2360 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002361 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002362}
2363
Tim Peters5af4e6c2002-08-12 02:31:19 +00002364/* Grade school multiplication, ignoring the signs.
2365 * Returns the absolute value of the product, or NULL if error.
2366 */
2367static PyLongObject *
2368x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002369{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002370 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002371 Py_ssize_t size_a = ABS(a->ob_size);
2372 Py_ssize_t size_b = ABS(b->ob_size);
2373 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002374
Tim Peters5af4e6c2002-08-12 02:31:19 +00002375 z = _PyLong_New(size_a + size_b);
2376 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002377 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002378
2379 memset(z->ob_digit, 0, z->ob_size * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002380 if (a == b) {
2381 /* Efficient squaring per HAC, Algorithm 14.16:
2382 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2383 * Gives slightly less than a 2x speedup when a == b,
2384 * via exploiting that each entry in the multiplication
2385 * pyramid appears twice (except for the size_a squares).
2386 */
2387 for (i = 0; i < size_a; ++i) {
2388 twodigits carry;
2389 twodigits f = a->ob_digit[i];
2390 digit *pz = z->ob_digit + (i << 1);
2391 digit *pa = a->ob_digit + i + 1;
2392 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002393
Tim Peters0973b992004-08-29 22:16:50 +00002394 SIGCHECK({
2395 Py_DECREF(z);
2396 return NULL;
2397 })
2398
2399 carry = *pz + f * f;
2400 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002401 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002402 assert(carry <= MASK);
2403
2404 /* Now f is added in twice in each column of the
2405 * pyramid it appears. Same as adding f<<1 once.
2406 */
2407 f <<= 1;
2408 while (pa < paend) {
2409 carry += *pz + *pa++ * f;
2410 *pz++ = (digit)(carry & MASK);
2411 carry >>= SHIFT;
2412 assert(carry <= (MASK << 1));
2413 }
2414 if (carry) {
2415 carry += *pz;
2416 *pz++ = (digit)(carry & MASK);
2417 carry >>= SHIFT;
2418 }
2419 if (carry)
2420 *pz += (digit)(carry & MASK);
2421 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002422 }
Tim Peters0973b992004-08-29 22:16:50 +00002423 }
2424 else { /* a is not the same as b -- gradeschool long mult */
2425 for (i = 0; i < size_a; ++i) {
2426 twodigits carry = 0;
2427 twodigits f = a->ob_digit[i];
2428 digit *pz = z->ob_digit + i;
2429 digit *pb = b->ob_digit;
2430 digit *pbend = b->ob_digit + size_b;
2431
2432 SIGCHECK({
2433 Py_DECREF(z);
2434 return NULL;
2435 })
2436
2437 while (pb < pbend) {
2438 carry += *pz + *pb++ * f;
2439 *pz++ = (digit)(carry & MASK);
2440 carry >>= SHIFT;
2441 assert(carry <= MASK);
2442 }
2443 if (carry)
2444 *pz += (digit)(carry & MASK);
2445 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002446 }
2447 }
Tim Peters44121a62002-08-12 06:17:58 +00002448 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002449}
2450
2451/* A helper for Karatsuba multiplication (k_mul).
2452 Takes a long "n" and an integer "size" representing the place to
2453 split, and sets low and high such that abs(n) == (high << size) + low,
2454 viewing the shift as being by digits. The sign bit is ignored, and
2455 the return values are >= 0.
2456 Returns 0 on success, -1 on failure.
2457*/
2458static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002459kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002460{
2461 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002462 Py_ssize_t size_lo, size_hi;
2463 const Py_ssize_t size_n = ABS(n->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002464
2465 size_lo = MIN(size_n, size);
2466 size_hi = size_n - size_lo;
2467
2468 if ((hi = _PyLong_New(size_hi)) == NULL)
2469 return -1;
2470 if ((lo = _PyLong_New(size_lo)) == NULL) {
2471 Py_DECREF(hi);
2472 return -1;
2473 }
2474
2475 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2476 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2477
2478 *high = long_normalize(hi);
2479 *low = long_normalize(lo);
2480 return 0;
2481}
2482
Tim Peters60004642002-08-12 22:01:34 +00002483static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2484
Tim Peters5af4e6c2002-08-12 02:31:19 +00002485/* Karatsuba multiplication. Ignores the input signs, and returns the
2486 * absolute value of the product (or NULL if error).
2487 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2488 */
2489static PyLongObject *
2490k_mul(PyLongObject *a, PyLongObject *b)
2491{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002492 Py_ssize_t asize = ABS(a->ob_size);
2493 Py_ssize_t bsize = ABS(b->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002494 PyLongObject *ah = NULL;
2495 PyLongObject *al = NULL;
2496 PyLongObject *bh = NULL;
2497 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002498 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002499 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002500 Py_ssize_t shift; /* the number of digits we split off */
2501 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002502
Tim Peters5af4e6c2002-08-12 02:31:19 +00002503 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2504 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2505 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002506 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002507 * By picking X to be a power of 2, "*X" is just shifting, and it's
2508 * been reduced to 3 multiplies on numbers half the size.
2509 */
2510
Tim Petersfc07e562002-08-12 02:54:10 +00002511 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002512 * is largest.
2513 */
Tim Peters738eda72002-08-12 15:08:20 +00002514 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002515 t1 = a;
2516 a = b;
2517 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002518
2519 i = asize;
2520 asize = bsize;
2521 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002522 }
2523
2524 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002525 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2526 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002527 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002528 return _PyLong_New(0);
2529 else
2530 return x_mul(a, b);
2531 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002532
Tim Peters60004642002-08-12 22:01:34 +00002533 /* If a is small compared to b, splitting on b gives a degenerate
2534 * case with ah==0, and Karatsuba may be (even much) less efficient
2535 * than "grade school" then. However, we can still win, by viewing
2536 * b as a string of "big digits", each of width a->ob_size. That
2537 * leads to a sequence of balanced calls to k_mul.
2538 */
2539 if (2 * asize <= bsize)
2540 return k_lopsided_mul(a, b);
2541
Tim Petersd6974a52002-08-13 20:37:51 +00002542 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002543 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002544 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Tim Petersd6974a52002-08-13 20:37:51 +00002545 assert(ah->ob_size > 0); /* the split isn't degenerate */
2546
Tim Peters0973b992004-08-29 22:16:50 +00002547 if (a == b) {
2548 bh = ah;
2549 bl = al;
2550 Py_INCREF(bh);
2551 Py_INCREF(bl);
2552 }
2553 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002554
Tim Petersd64c1de2002-08-12 17:36:03 +00002555 /* The plan:
2556 * 1. Allocate result space (asize + bsize digits: that's always
2557 * enough).
2558 * 2. Compute ah*bh, and copy into result at 2*shift.
2559 * 3. Compute al*bl, and copy into result at 0. Note that this
2560 * can't overlap with #2.
2561 * 4. Subtract al*bl from the result, starting at shift. This may
2562 * underflow (borrow out of the high digit), but we don't care:
2563 * we're effectively doing unsigned arithmetic mod
2564 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2565 * borrows and carries out of the high digit can be ignored.
2566 * 5. Subtract ah*bh from the result, starting at shift.
2567 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2568 * at shift.
2569 */
2570
2571 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002572 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002573 if (ret == NULL) goto fail;
2574#ifdef Py_DEBUG
2575 /* Fill with trash, to catch reference to uninitialized digits. */
2576 memset(ret->ob_digit, 0xDF, ret->ob_size * sizeof(digit));
2577#endif
Tim Peters44121a62002-08-12 06:17:58 +00002578
Tim Petersd64c1de2002-08-12 17:36:03 +00002579 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002580 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2581 assert(t1->ob_size >= 0);
2582 assert(2*shift + t1->ob_size <= ret->ob_size);
2583 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2584 t1->ob_size * sizeof(digit));
2585
2586 /* Zero-out the digits higher than the ah*bh copy. */
2587 i = ret->ob_size - 2*shift - t1->ob_size;
Tim Peters44121a62002-08-12 06:17:58 +00002588 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002589 memset(ret->ob_digit + 2*shift + t1->ob_size, 0,
Tim Peters44121a62002-08-12 06:17:58 +00002590 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002591
Tim Petersd64c1de2002-08-12 17:36:03 +00002592 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002593 if ((t2 = k_mul(al, bl)) == NULL) {
2594 Py_DECREF(t1);
2595 goto fail;
2596 }
2597 assert(t2->ob_size >= 0);
2598 assert(t2->ob_size <= 2*shift); /* no overlap with high digits */
2599 memcpy(ret->ob_digit, t2->ob_digit, t2->ob_size * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002600
2601 /* Zero out remaining digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002602 i = 2*shift - t2->ob_size; /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002603 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002604 memset(ret->ob_digit + t2->ob_size, 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002605
Tim Petersd64c1de2002-08-12 17:36:03 +00002606 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2607 * because it's fresher in cache.
2608 */
Tim Peters738eda72002-08-12 15:08:20 +00002609 i = ret->ob_size - shift; /* # digits after shift */
Tim Petersd64c1de2002-08-12 17:36:03 +00002610 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, t2->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002611 Py_DECREF(t2);
2612
Tim Petersd64c1de2002-08-12 17:36:03 +00002613 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, t1->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002614 Py_DECREF(t1);
2615
Tim Petersd64c1de2002-08-12 17:36:03 +00002616 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002617 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2618 Py_DECREF(ah);
2619 Py_DECREF(al);
2620 ah = al = NULL;
2621
Tim Peters0973b992004-08-29 22:16:50 +00002622 if (a == b) {
2623 t2 = t1;
2624 Py_INCREF(t2);
2625 }
2626 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002627 Py_DECREF(t1);
2628 goto fail;
2629 }
2630 Py_DECREF(bh);
2631 Py_DECREF(bl);
2632 bh = bl = NULL;
2633
Tim Peters738eda72002-08-12 15:08:20 +00002634 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002635 Py_DECREF(t1);
2636 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002637 if (t3 == NULL) goto fail;
Tim Peters547607c2002-08-12 19:43:49 +00002638 assert(t3->ob_size >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002639
Tim Petersd6974a52002-08-13 20:37:51 +00002640 /* Add t3. It's not obvious why we can't run out of room here.
2641 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002642 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002643 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, t3->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002644 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002645
Tim Peters5af4e6c2002-08-12 02:31:19 +00002646 return long_normalize(ret);
2647
2648 fail:
2649 Py_XDECREF(ret);
2650 Py_XDECREF(ah);
2651 Py_XDECREF(al);
2652 Py_XDECREF(bh);
2653 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002654 return NULL;
2655}
2656
Tim Petersd6974a52002-08-13 20:37:51 +00002657/* (*) Why adding t3 can't "run out of room" above.
2658
Tim Petersab86c2b2002-08-15 20:06:00 +00002659Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2660to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002661
Tim Petersab86c2b2002-08-15 20:06:00 +000026621. For any integer i, i = c(i/2) + f(i/2). In particular,
2663 bsize = c(bsize/2) + f(bsize/2).
26642. shift = f(bsize/2)
26653. asize <= bsize
26664. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2667 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002668
Tim Petersab86c2b2002-08-15 20:06:00 +00002669We allocated asize + bsize result digits, and add t3 into them at an offset
2670of shift. This leaves asize+bsize-shift allocated digit positions for t3
2671to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2672asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002673
Tim Petersab86c2b2002-08-15 20:06:00 +00002674bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2675at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002676
Tim Petersab86c2b2002-08-15 20:06:00 +00002677If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2678digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2679most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002680
Tim Petersab86c2b2002-08-15 20:06:00 +00002681The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002682
Tim Petersab86c2b2002-08-15 20:06:00 +00002683 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002684
Tim Petersab86c2b2002-08-15 20:06:00 +00002685and we have asize + c(bsize/2) available digit positions. We need to show
2686this is always enough. An instance of c(bsize/2) cancels out in both, so
2687the question reduces to whether asize digits is enough to hold
2688(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2689then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2690asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2691digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2692asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002693c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2694is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2695bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002696
Tim Peters48d52c02002-08-14 17:07:32 +00002697Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2698clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2699ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002700*/
2701
Tim Peters60004642002-08-12 22:01:34 +00002702/* b has at least twice the digits of a, and a is big enough that Karatsuba
2703 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2704 * of slices, each with a->ob_size digits, and multiply the slices by a,
2705 * one at a time. This gives k_mul balanced inputs to work with, and is
2706 * also cache-friendly (we compute one double-width slice of the result
2707 * at a time, then move on, never bactracking except for the helpful
2708 * single-width slice overlap between successive partial sums).
2709 */
2710static PyLongObject *
2711k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2712{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002713 const Py_ssize_t asize = ABS(a->ob_size);
2714 Py_ssize_t bsize = ABS(b->ob_size);
2715 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002716 PyLongObject *ret;
2717 PyLongObject *bslice = NULL;
2718
2719 assert(asize > KARATSUBA_CUTOFF);
2720 assert(2 * asize <= bsize);
2721
2722 /* Allocate result space, and zero it out. */
2723 ret = _PyLong_New(asize + bsize);
2724 if (ret == NULL)
2725 return NULL;
2726 memset(ret->ob_digit, 0, ret->ob_size * sizeof(digit));
2727
2728 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002729 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002730 if (bslice == NULL)
2731 goto fail;
2732
2733 nbdone = 0;
2734 while (bsize > 0) {
2735 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002736 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002737
2738 /* Multiply the next slice of b by a. */
2739 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2740 nbtouse * sizeof(digit));
2741 bslice->ob_size = nbtouse;
2742 product = k_mul(a, bslice);
2743 if (product == NULL)
2744 goto fail;
2745
2746 /* Add into result. */
2747 (void)v_iadd(ret->ob_digit + nbdone, ret->ob_size - nbdone,
2748 product->ob_digit, product->ob_size);
2749 Py_DECREF(product);
2750
2751 bsize -= nbtouse;
2752 nbdone += nbtouse;
2753 }
2754
2755 Py_DECREF(bslice);
2756 return long_normalize(ret);
2757
2758 fail:
2759 Py_DECREF(ret);
2760 Py_XDECREF(bslice);
2761 return NULL;
2762}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002763
2764static PyObject *
2765long_mul(PyLongObject *v, PyLongObject *w)
2766{
2767 PyLongObject *a, *b, *z;
2768
2769 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002770 Py_INCREF(Py_NotImplemented);
2771 return Py_NotImplemented;
2772 }
2773
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002774 if (ABS(v->ob_size) <= 1 && ABS(w->ob_size) <= 1) {
2775 PyObject *r;
2776 r = PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w));
2777 Py_DECREF(a);
2778 Py_DECREF(b);
2779 return r;
2780 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002781
Tim Petersd64c1de2002-08-12 17:36:03 +00002782 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002783 /* Negate if exactly one of the inputs is negative. */
2784 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002785 NEGATE(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002786 Py_DECREF(a);
2787 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002788 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002789}
2790
Guido van Rossume32e0141992-01-19 16:31:05 +00002791/* The / and % operators are now defined in terms of divmod().
2792 The expression a mod b has the value a - b*floor(a/b).
2793 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002794 |a| by |b|, with the sign of a. This is also expressed
2795 as a - b*trunc(a/b), if trunc truncates towards zero.
2796 Some examples:
2797 a b a rem b a mod b
2798 13 10 3 3
2799 -13 10 -3 7
2800 13 -10 3 -7
2801 -13 -10 -3 -3
2802 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002803 have different signs. We then subtract one from the 'div'
2804 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002805
Tim Peters47e52ee2004-08-30 02:44:38 +00002806/* Compute
2807 * *pdiv, *pmod = divmod(v, w)
2808 * NULL can be passed for pdiv or pmod, in which case that part of
2809 * the result is simply thrown away. The caller owns a reference to
2810 * each of these it requests (does not pass NULL for).
2811 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002812static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002813l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002814 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002815{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002816 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002817
Guido van Rossume32e0141992-01-19 16:31:05 +00002818 if (long_divrem(v, w, &div, &mod) < 0)
2819 return -1;
Guido van Rossum472c04f1996-12-05 21:57:21 +00002820 if ((mod->ob_size < 0 && w->ob_size > 0) ||
2821 (mod->ob_size > 0 && w->ob_size < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002822 PyLongObject *temp;
2823 PyLongObject *one;
2824 temp = (PyLongObject *) long_add(mod, w);
2825 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002826 mod = temp;
2827 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002828 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002829 return -1;
2830 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002831 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002832 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002833 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2834 Py_DECREF(mod);
2835 Py_DECREF(div);
2836 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002837 return -1;
2838 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002839 Py_DECREF(one);
2840 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002841 div = temp;
2842 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002843 if (pdiv != NULL)
2844 *pdiv = div;
2845 else
2846 Py_DECREF(div);
2847
2848 if (pmod != NULL)
2849 *pmod = mod;
2850 else
2851 Py_DECREF(mod);
2852
Guido van Rossume32e0141992-01-19 16:31:05 +00002853 return 0;
2854}
2855
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002856static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002857long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002858{
Tim Peters47e52ee2004-08-30 02:44:38 +00002859 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002860
2861 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002862 if (l_divmod(a, b, &div, NULL) < 0)
2863 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002864 Py_DECREF(a);
2865 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002866 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002867}
2868
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002869static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002870long_true_divide(PyObject *v, PyObject *w)
2871{
Tim Peterse2a60002001-09-04 06:17:36 +00002872 PyLongObject *a, *b;
2873 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002874 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002875
2876 CONVERT_BINOP(v, w, &a, &b);
2877 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2878 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002879 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2880 Py_DECREF(a);
2881 Py_DECREF(b);
2882 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002883 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002884 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2885 but should really be set correctly after sucessful calls to
2886 _PyLong_AsScaledDouble() */
2887 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002888
2889 if (bd == 0.0) {
2890 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002891 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002892 return NULL;
2893 }
2894
2895 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2896 ad /= bd; /* overflow/underflow impossible here */
2897 aexp -= bexp;
2898 if (aexp > INT_MAX / SHIFT)
2899 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002900 else if (aexp < -(INT_MAX / SHIFT))
2901 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002902 errno = 0;
2903 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002904 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002905 goto overflow;
2906 return PyFloat_FromDouble(ad);
2907
2908overflow:
2909 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002910 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002911 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002912
Tim Peters20dab9f2001-09-04 05:31:47 +00002913}
2914
2915static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002916long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002917{
Tim Peters47e52ee2004-08-30 02:44:38 +00002918 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002919
2920 CONVERT_BINOP(v, w, &a, &b);
2921
Tim Peters47e52ee2004-08-30 02:44:38 +00002922 if (l_divmod(a, b, NULL, &mod) < 0)
2923 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002924 Py_DECREF(a);
2925 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002926 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002927}
2928
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002929static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002930long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002931{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002932 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002933 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002934
2935 CONVERT_BINOP(v, w, &a, &b);
2936
2937 if (l_divmod(a, b, &div, &mod) < 0) {
2938 Py_DECREF(a);
2939 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002940 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002941 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002942 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002943 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002944 PyTuple_SetItem(z, 0, (PyObject *) div);
2945 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002946 }
2947 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002948 Py_DECREF(div);
2949 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002950 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002951 Py_DECREF(a);
2952 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002953 return z;
2954}
2955
Tim Peters47e52ee2004-08-30 02:44:38 +00002956/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002957static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002958long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002959{
Tim Peters47e52ee2004-08-30 02:44:38 +00002960 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2961 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002962
Tim Peters47e52ee2004-08-30 02:44:38 +00002963 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002964 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002965 PyLongObject *temp = NULL;
2966
2967 /* 5-ary values. If the exponent is large enough, table is
2968 * precomputed so that table[i] == a**i % c for i in range(32).
2969 */
2970 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2971 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2972
2973 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002974 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002975 if (PyLong_Check(x)) {
2976 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002977 Py_INCREF(x);
2978 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002979 else if (x == Py_None)
2980 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002981 else {
2982 Py_DECREF(a);
2983 Py_DECREF(b);
2984 Py_INCREF(Py_NotImplemented);
2985 return Py_NotImplemented;
2986 }
Tim Peters4c483c42001-09-05 06:24:58 +00002987
Tim Peters47e52ee2004-08-30 02:44:38 +00002988 if (b->ob_size < 0) { /* if exponent is negative */
2989 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002990 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002991 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002992 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002993 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002994 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002995 /* else return a float. This works because we know
2996 that this calls float_pow() which converts its
2997 arguments to double. */
2998 Py_DECREF(a);
2999 Py_DECREF(b);
3000 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003001 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003002 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003003
3004 if (c) {
3005 /* if modulus == 0:
3006 raise ValueError() */
3007 if (c->ob_size == 0) {
3008 PyErr_SetString(PyExc_ValueError,
3009 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003010 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003011 }
3012
3013 /* if modulus < 0:
3014 negativeOutput = True
3015 modulus = -modulus */
3016 if (c->ob_size < 0) {
3017 negativeOutput = 1;
3018 temp = (PyLongObject *)_PyLong_Copy(c);
3019 if (temp == NULL)
3020 goto Error;
3021 Py_DECREF(c);
3022 c = temp;
3023 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003024 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003025 }
3026
3027 /* if modulus == 1:
3028 return 0 */
3029 if ((c->ob_size == 1) && (c->ob_digit[0] == 1)) {
3030 z = (PyLongObject *)PyLong_FromLong(0L);
3031 goto Done;
3032 }
3033
3034 /* if base < 0:
3035 base = base % modulus
3036 Having the base positive just makes things easier. */
3037 if (a->ob_size < 0) {
3038 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003039 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003040 Py_DECREF(a);
3041 a = temp;
3042 temp = NULL;
3043 }
3044 }
3045
3046 /* At this point a, b, and c are guaranteed non-negative UNLESS
3047 c is NULL, in which case a may be negative. */
3048
3049 z = (PyLongObject *)PyLong_FromLong(1L);
3050 if (z == NULL)
3051 goto Error;
3052
3053 /* Perform a modular reduction, X = X % c, but leave X alone if c
3054 * is NULL.
3055 */
3056#define REDUCE(X) \
3057 if (c != NULL) { \
3058 if (l_divmod(X, c, NULL, &temp) < 0) \
3059 goto Error; \
3060 Py_XDECREF(X); \
3061 X = temp; \
3062 temp = NULL; \
3063 }
3064
3065 /* Multiply two values, then reduce the result:
3066 result = X*Y % c. If c is NULL, skip the mod. */
3067#define MULT(X, Y, result) \
3068{ \
3069 temp = (PyLongObject *)long_mul(X, Y); \
3070 if (temp == NULL) \
3071 goto Error; \
3072 Py_XDECREF(result); \
3073 result = temp; \
3074 temp = NULL; \
3075 REDUCE(result) \
3076}
3077
3078 if (b->ob_size <= FIVEARY_CUTOFF) {
3079 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3080 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3081 for (i = b->ob_size - 1; i >= 0; --i) {
3082 digit bi = b->ob_digit[i];
3083
3084 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
3085 MULT(z, z, z)
3086 if (bi & j)
3087 MULT(z, a, z)
3088 }
3089 }
3090 }
3091 else {
3092 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3093 Py_INCREF(z); /* still holds 1L */
3094 table[0] = z;
3095 for (i = 1; i < 32; ++i)
3096 MULT(table[i-1], a, table[i])
3097
3098 for (i = b->ob_size - 1; i >= 0; --i) {
3099 const digit bi = b->ob_digit[i];
3100
3101 for (j = SHIFT - 5; j >= 0; j -= 5) {
3102 const int index = (bi >> j) & 0x1f;
3103 for (k = 0; k < 5; ++k)
3104 MULT(z, z, z)
3105 if (index)
3106 MULT(z, table[index], z)
3107 }
3108 }
3109 }
3110
3111 if (negativeOutput && (z->ob_size != 0)) {
3112 temp = (PyLongObject *)long_sub(z, c);
3113 if (temp == NULL)
3114 goto Error;
3115 Py_DECREF(z);
3116 z = temp;
3117 temp = NULL;
3118 }
3119 goto Done;
3120
3121 Error:
3122 if (z != NULL) {
3123 Py_DECREF(z);
3124 z = NULL;
3125 }
3126 /* fall through */
3127 Done:
Tim Peters47e52ee2004-08-30 02:44:38 +00003128 if (b->ob_size > FIVEARY_CUTOFF) {
3129 for (i = 0; i < 32; ++i)
3130 Py_XDECREF(table[i]);
3131 }
Tim Petersde7990b2005-07-17 23:45:23 +00003132 Py_DECREF(a);
3133 Py_DECREF(b);
3134 Py_XDECREF(c);
3135 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003136 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003137}
3138
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003139static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003140long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003141{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003142 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003143 PyLongObject *x;
3144 PyLongObject *w;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003145 if (ABS(v->ob_size) <=1)
3146 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003147 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003148 if (w == NULL)
3149 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003150 x = (PyLongObject *) long_add(v, w);
3151 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003152 if (x == NULL)
3153 return NULL;
Tim Peters40c397d2001-09-11 23:24:22 +00003154 x->ob_size = -(x->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003155 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003156}
3157
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003158static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003159long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003160{
Tim Peters69c2de32001-09-11 22:31:33 +00003161 if (PyLong_CheckExact(v)) {
3162 Py_INCREF(v);
3163 return (PyObject *)v;
3164 }
3165 else
3166 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003167}
3168
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003169static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003170long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003171{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003172 PyLongObject *z;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003173 if (ABS(v->ob_size) <= 1)
3174 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003175 z = (PyLongObject *)_PyLong_Copy(v);
3176 if (z != NULL)
3177 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003178 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003179}
3180
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003181static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003182long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003183{
3184 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003185 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003186 else
3187 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003188}
3189
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003190static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003191long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003192{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003193 return ABS(v->ob_size) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003194}
3195
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003196static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003197long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003198{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003199 PyLongObject *a, *b;
3200 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003201 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003202 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003203 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003204
Neil Schemenauerba872e22001-01-04 01:46:03 +00003205 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3206
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003207 if (a->ob_size < 0) {
3208 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003209 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003210 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003211 if (a1 == NULL)
3212 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003213 a2 = (PyLongObject *) long_rshift(a1, b);
3214 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003215 if (a2 == NULL)
3216 goto rshift_error;
3217 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003218 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003219 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003220 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003221
Neil Schemenauerba872e22001-01-04 01:46:03 +00003222 shiftby = PyLong_AsLong((PyObject *)b);
3223 if (shiftby == -1L && PyErr_Occurred())
3224 goto rshift_error;
3225 if (shiftby < 0) {
3226 PyErr_SetString(PyExc_ValueError,
3227 "negative shift count");
3228 goto rshift_error;
3229 }
3230 wordshift = shiftby / SHIFT;
3231 newsize = ABS(a->ob_size) - wordshift;
3232 if (newsize <= 0) {
3233 z = _PyLong_New(0);
3234 Py_DECREF(a);
3235 Py_DECREF(b);
3236 return (PyObject *)z;
3237 }
3238 loshift = shiftby % SHIFT;
3239 hishift = SHIFT - loshift;
3240 lomask = ((digit)1 << hishift) - 1;
3241 himask = MASK ^ lomask;
3242 z = _PyLong_New(newsize);
3243 if (z == NULL)
3244 goto rshift_error;
3245 if (a->ob_size < 0)
3246 z->ob_size = -(z->ob_size);
3247 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3248 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3249 if (i+1 < newsize)
3250 z->ob_digit[i] |=
3251 (a->ob_digit[j+1] << hishift) & himask;
3252 }
3253 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003254 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003255rshift_error:
3256 Py_DECREF(a);
3257 Py_DECREF(b);
3258 return (PyObject *) z;
3259
Guido van Rossumc6913e71991-11-19 20:26:46 +00003260}
3261
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003262static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003263long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003264{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003265 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003266 PyLongObject *a, *b;
3267 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003268 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003269 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003270 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003271
Neil Schemenauerba872e22001-01-04 01:46:03 +00003272 CONVERT_BINOP(v, w, &a, &b);
3273
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003274 shiftby = PyLong_AsLong((PyObject *)b);
3275 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003276 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003277 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003278 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003279 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003280 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003281 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003282 PyErr_SetString(PyExc_ValueError,
3283 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003284 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003285 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003286 /* wordshift, remshift = divmod(shiftby, SHIFT) */
3287 wordshift = (int)shiftby / SHIFT;
3288 remshift = (int)shiftby - wordshift * SHIFT;
3289
3290 oldsize = ABS(a->ob_size);
3291 newsize = oldsize + wordshift;
3292 if (remshift)
3293 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003294 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003295 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003296 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003297 if (a->ob_size < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003298 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003299 for (i = 0; i < wordshift; i++)
3300 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003301 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003302 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003303 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003304 z->ob_digit[i] = (digit)(accum & MASK);
3305 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003306 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003307 if (remshift)
3308 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003309 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003310 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003311 z = long_normalize(z);
3312lshift_error:
3313 Py_DECREF(a);
3314 Py_DECREF(b);
3315 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003316}
3317
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003318
3319/* Bitwise and/xor/or operations */
3320
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003321static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003322long_bitwise(PyLongObject *a,
3323 int op, /* '&', '|', '^' */
3324 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003325{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003326 digit maska, maskb; /* 0 or MASK */
3327 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003328 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003329 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003330 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003331 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003332 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003333
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003334 if (a->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003335 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003336 if (a == NULL)
3337 return NULL;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003338 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003339 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003340 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003341 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003342 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003343 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003344 if (b->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003345 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003346 if (b == NULL) {
3347 Py_DECREF(a);
3348 return NULL;
3349 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003350 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003351 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003352 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003353 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003354 maskb = 0;
3355 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003356
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003357 negz = 0;
3358 switch (op) {
3359 case '^':
3360 if (maska != maskb) {
3361 maska ^= MASK;
3362 negz = -1;
3363 }
3364 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003365 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003366 if (maska && maskb) {
3367 op = '|';
3368 maska ^= MASK;
3369 maskb ^= MASK;
3370 negz = -1;
3371 }
3372 break;
3373 case '|':
3374 if (maska || maskb) {
3375 op = '&';
3376 maska ^= MASK;
3377 maskb ^= MASK;
3378 negz = -1;
3379 }
3380 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003381 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003382
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003383 /* JRH: The original logic here was to allocate the result value (z)
3384 as the longer of the two operands. However, there are some cases
3385 where the result is guaranteed to be shorter than that: AND of two
3386 positives, OR of two negatives: use the shorter number. AND with
3387 mixed signs: use the positive number. OR with mixed signs: use the
3388 negative number. After the transformations above, op will be '&'
3389 iff one of these cases applies, and mask will be non-0 for operands
3390 whose length should be ignored.
3391 */
3392
3393 size_a = a->ob_size;
3394 size_b = b->ob_size;
3395 size_z = op == '&'
3396 ? (maska
3397 ? size_b
3398 : (maskb ? size_a : MIN(size_a, size_b)))
3399 : MAX(size_a, size_b);
3400 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003401 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003402 Py_DECREF(a);
3403 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003404 return NULL;
3405 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003406
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003407 for (i = 0; i < size_z; ++i) {
3408 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3409 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3410 switch (op) {
3411 case '&': z->ob_digit[i] = diga & digb; break;
3412 case '|': z->ob_digit[i] = diga | digb; break;
3413 case '^': z->ob_digit[i] = diga ^ digb; break;
3414 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003415 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003416
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003417 Py_DECREF(a);
3418 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003419 z = long_normalize(z);
3420 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003421 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003422 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003423 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003424 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003425}
3426
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003427static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003428long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003429{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003430 PyLongObject *a, *b;
3431 PyObject *c;
3432 CONVERT_BINOP(v, w, &a, &b);
3433 c = long_bitwise(a, '&', b);
3434 Py_DECREF(a);
3435 Py_DECREF(b);
3436 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003437}
3438
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003439static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003440long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003441{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003442 PyLongObject *a, *b;
3443 PyObject *c;
3444 CONVERT_BINOP(v, w, &a, &b);
3445 c = long_bitwise(a, '^', b);
3446 Py_DECREF(a);
3447 Py_DECREF(b);
3448 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003449}
3450
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003451static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003452long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003453{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003454 PyLongObject *a, *b;
3455 PyObject *c;
3456 CONVERT_BINOP(v, w, &a, &b);
3457 c = long_bitwise(a, '|', b);
3458 Py_DECREF(a);
3459 Py_DECREF(b);
3460 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003461}
3462
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003463static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003464long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003465{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003466 if (PyLong_CheckExact(v))
3467 Py_INCREF(v);
3468 else
3469 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003470 return v;
3471}
3472
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003473static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003474long_int(PyObject *v)
3475{
Guido van Rossumddefaf32007-01-14 03:31:43 +00003476 return long_long(v);
Walter Dörwaldf1715402002-11-19 20:49:15 +00003477}
3478
3479static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003480long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003481{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003482 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003483 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003484 if (result == -1.0 && PyErr_Occurred())
3485 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003486 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003487}
3488
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003489static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003490long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003491{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00003492 return long_format(v, 8);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003493}
3494
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003495static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003496long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003497{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00003498 return long_format(v, 16);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003499}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003500
3501static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003502long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003503
Tim Peters6d6c1a32001-08-02 04:15:00 +00003504static PyObject *
3505long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3506{
3507 PyObject *x = NULL;
3508 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003509 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003510
Guido van Rossumbef14172001-08-29 15:47:46 +00003511 if (type != &PyLong_Type)
3512 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003513 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003514 &x, &base))
3515 return NULL;
3516 if (x == NULL)
3517 return PyLong_FromLong(0L);
3518 if (base == -909)
3519 return PyNumber_Long(x);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003520 else if (PyString_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003521 /* Since PyLong_FromString doesn't have a length parameter,
3522 * check here for possible NULs in the string. */
3523 char *string = PyString_AS_STRING(x);
3524 if (strlen(string) != PyString_Size(x)) {
3525 /* create a repr() of the input string,
3526 * just like PyLong_FromString does. */
3527 PyObject *srepr;
3528 srepr = PyObject_Repr(x);
3529 if (srepr == NULL)
3530 return NULL;
3531 PyErr_Format(PyExc_ValueError,
3532 "invalid literal for int() with base %d: %s",
3533 base, PyString_AS_STRING(srepr));
3534 Py_DECREF(srepr);
3535 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003536 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00003537 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003538 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003539 else if (PyUnicode_Check(x))
3540 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3541 PyUnicode_GET_SIZE(x),
3542 base);
3543 else {
3544 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003545 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003546 return NULL;
3547 }
3548}
3549
Guido van Rossumbef14172001-08-29 15:47:46 +00003550/* Wimpy, slow approach to tp_new calls for subtypes of long:
3551 first create a regular long from whatever arguments we got,
3552 then allocate a subtype instance and initialize it from
3553 the regular long. The regular long is then thrown away.
3554*/
3555static PyObject *
3556long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3557{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003558 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003559 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003560
3561 assert(PyType_IsSubtype(type, &PyLong_Type));
3562 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3563 if (tmp == NULL)
3564 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003565 assert(PyLong_CheckExact(tmp));
Guido van Rossumbef14172001-08-29 15:47:46 +00003566 n = tmp->ob_size;
3567 if (n < 0)
3568 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003569 newobj = (PyLongObject *)type->tp_alloc(type, n);
3570 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003571 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003572 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003573 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003574 assert(PyLong_Check(newobj));
3575 newobj->ob_size = tmp->ob_size;
Guido van Rossumbef14172001-08-29 15:47:46 +00003576 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003577 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003578 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003579 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003580}
3581
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003582static PyObject *
3583long_getnewargs(PyLongObject *v)
3584{
3585 return Py_BuildValue("(N)", _PyLong_Copy(v));
3586}
3587
3588static PyMethodDef long_methods[] = {
3589 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3590 {NULL, NULL} /* sentinel */
3591};
3592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003593PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003594"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003595\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003596Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003597point argument will be truncated towards zero (this does not include a\n\
3598string representation of a floating point number!) When converting a\n\
3599string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003600converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003601
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003602static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003603 (binaryfunc) long_add, /*nb_add*/
3604 (binaryfunc) long_sub, /*nb_subtract*/
3605 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003606 long_mod, /*nb_remainder*/
3607 long_divmod, /*nb_divmod*/
3608 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003609 (unaryfunc) long_neg, /*nb_negative*/
3610 (unaryfunc) long_pos, /*tp_positive*/
3611 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003612 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003613 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003614 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003615 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003616 long_and, /*nb_and*/
3617 long_xor, /*nb_xor*/
3618 long_or, /*nb_or*/
Neal Norwitzca810462006-08-29 07:57:59 +00003619 0, /*nb_coerce*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003620 long_int, /*nb_int*/
3621 long_long, /*nb_long*/
3622 long_float, /*nb_float*/
3623 long_oct, /*nb_oct*/
3624 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003625 0, /* nb_inplace_add */
3626 0, /* nb_inplace_subtract */
3627 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003628 0, /* nb_inplace_remainder */
3629 0, /* nb_inplace_power */
3630 0, /* nb_inplace_lshift */
3631 0, /* nb_inplace_rshift */
3632 0, /* nb_inplace_and */
3633 0, /* nb_inplace_xor */
3634 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003635 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003636 long_true_divide, /* nb_true_divide */
3637 0, /* nb_inplace_floor_divide */
3638 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003639 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003640};
3641
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003642PyTypeObject PyLong_Type = {
3643 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003644 0, /* ob_size */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003645 "int", /* tp_name */
3646 /* See _PyLong_New for why this isn't
3647 sizeof(PyLongObject) - sizeof(digit) */
3648 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003649 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003650 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003651 0, /* tp_print */
3652 0, /* tp_getattr */
3653 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003654 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003655 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003656 &long_as_number, /* tp_as_number */
3657 0, /* tp_as_sequence */
3658 0, /* tp_as_mapping */
3659 (hashfunc)long_hash, /* tp_hash */
3660 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003661 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003662 PyObject_GenericGetAttr, /* tp_getattro */
3663 0, /* tp_setattro */
3664 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003665 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3666 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003667 long_doc, /* tp_doc */
3668 0, /* tp_traverse */
3669 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003670 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003671 0, /* tp_weaklistoffset */
3672 0, /* tp_iter */
3673 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003674 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003675 0, /* tp_members */
3676 0, /* tp_getset */
3677 0, /* tp_base */
3678 0, /* tp_dict */
3679 0, /* tp_descr_get */
3680 0, /* tp_descr_set */
3681 0, /* tp_dictoffset */
3682 0, /* tp_init */
3683 0, /* tp_alloc */
3684 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003685 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003686};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003687
3688int
3689_PyLong_Init(void)
3690{
3691#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3692 int ival;
3693 PyLongObject *v = small_ints;
3694 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3695 PyObject_INIT(v, &PyLong_Type);
3696 v->ob_size = -1;
3697 v->ob_digit[0] = -ival;
3698 }
3699 for (; ival < NSMALLPOSINTS; ival++, v++) {
3700 PyObject_INIT(v, &PyLong_Type);
3701 v->ob_size = ival ? 1 : 0;
3702 v->ob_digit[0] = ival;
3703 }
3704#endif
3705 return 1;
3706}
3707
3708void
3709PyLong_Fini(void)
3710{
3711#if 0
3712 int i;
3713 /* This is currently not needed; the small integers
3714 are statically allocated */
3715#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3716 PyIntObject **q;
3717
3718 i = NSMALLNEGINTS + NSMALLPOSINTS;
3719 q = small_ints;
3720 while (--i >= 0) {
3721 Py_XDECREF(*q);
3722 *q++ = NULL;
3723 }
3724#endif
3725#endif
3726}