blob: 1f497c4141f6ba6f779014f47a5fb3e4d1114960 [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;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001433 PyObject *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;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001436 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001437 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 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001462 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001463 if (str == NULL)
1464 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001465 p = PyUnicode_AS_UNICODE(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;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001489 assert(p > PyUnicode_AS_UNICODE(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);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001541 assert(p > PyUnicode_AS_UNICODE(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;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001570 if (p != PyUnicode_AS_UNICODE(str)) {
1571 Py_UNICODE *q = PyUnicode_AS_UNICODE(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--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001576 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1577 Py_DECREF(str);
1578 return NULL;
1579 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001580 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001581 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001582}
1583
Thomas Wouters477c8d52006-05-27 19:21:47 +00001584/* Table of digit values for 8-bit string -> integer conversion.
1585 * '0' maps to 0, ..., '9' maps to 9.
1586 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1587 * All other indices map to 37.
1588 * Note that when converting a base B string, a char c is a legitimate
1589 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1590 */
1591int _PyLong_DigitValue[256] = {
1592 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1593 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1594 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1595 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 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, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1599 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1607 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1608};
1609
1610/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001611 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1612 * non-digit (which may be *str!). A normalized long is returned.
1613 * The point to this routine is that it takes time linear in the number of
1614 * string characters.
1615 */
1616static PyLongObject *
1617long_from_binary_base(char **str, int base)
1618{
1619 char *p = *str;
1620 char *start = p;
1621 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001622 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001623 PyLongObject *z;
1624 twodigits accum;
1625 int bits_in_accum;
1626 digit *pdigit;
1627
1628 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1629 n = base;
1630 for (bits_per_char = -1; n; ++bits_per_char)
1631 n >>= 1;
1632 /* n <- total # of bits needed, while setting p to end-of-string */
1633 n = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001634 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001635 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001636 *str = p;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001637 /* n <- # of Python digits needed, = ceiling(n/SHIFT). */
1638 n = (p - start) * bits_per_char + SHIFT - 1;
1639 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001640 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001641 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001642 return NULL;
1643 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001644 n = n / SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001645 z = _PyLong_New(n);
1646 if (z == NULL)
1647 return NULL;
1648 /* Read string from right, and fill in long from left; i.e.,
1649 * from least to most significant in both.
1650 */
1651 accum = 0;
1652 bits_in_accum = 0;
1653 pdigit = z->ob_digit;
1654 while (--p >= start) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001655 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001656 assert(k >= 0 && k < base);
1657 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001658 bits_in_accum += bits_per_char;
1659 if (bits_in_accum >= SHIFT) {
1660 *pdigit++ = (digit)(accum & MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001661 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001662 accum >>= SHIFT;
1663 bits_in_accum -= SHIFT;
1664 assert(bits_in_accum < SHIFT);
1665 }
1666 }
1667 if (bits_in_accum) {
1668 assert(bits_in_accum <= SHIFT);
1669 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001670 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001671 }
1672 while (pdigit - z->ob_digit < n)
1673 *pdigit++ = 0;
1674 return long_normalize(z);
1675}
1676
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001677PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001678PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001679{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001680 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001681 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001682 PyLongObject *z;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001683 PyObject *strobj, *strrepr;
1684 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001685
Guido van Rossum472c04f1996-12-05 21:57:21 +00001686 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001687 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001688 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001689 return NULL;
1690 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001691 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001692 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001693 if (*str == '+')
1694 ++str;
1695 else if (*str == '-') {
1696 ++str;
1697 sign = -1;
1698 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001699 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001700 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001701 if (base == 0) {
1702 if (str[0] != '0')
1703 base = 10;
1704 else if (str[1] == 'x' || str[1] == 'X')
1705 base = 16;
1706 else
1707 base = 8;
1708 }
1709 if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
1710 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001711
Guido van Rossume6762971998-06-22 03:54:46 +00001712 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001713 if ((base & (base - 1)) == 0)
1714 z = long_from_binary_base(&str, base);
1715 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001716/***
1717Binary bases can be converted in time linear in the number of digits, because
1718Python's representation base is binary. Other bases (including decimal!) use
1719the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001720
Thomas Wouters477c8d52006-05-27 19:21:47 +00001721First some math: the largest integer that can be expressed in N base-B digits
1722is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1723case number of Python digits needed to hold it is the smallest integer n s.t.
1724
1725 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1726 BASE**n >= B**N [taking logs to base BASE]
1727 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1728
1729The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1730this quickly. A Python long with that much space is reserved near the start,
1731and the result is computed into it.
1732
1733The input string is actually treated as being in base base**i (i.e., i digits
1734are processed at a time), where two more static arrays hold:
1735
1736 convwidth_base[base] = the largest integer i such that base**i <= BASE
1737 convmultmax_base[base] = base ** convwidth_base[base]
1738
1739The first of these is the largest i such that i consecutive input digits
1740must fit in a single Python digit. The second is effectively the input
1741base we're really using.
1742
1743Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1744convmultmax_base[base], the result is "simply"
1745
1746 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1747
1748where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001749
1750Error analysis: as above, the number of Python digits `n` needed is worst-
1751case
1752
1753 n >= N * log(B)/log(BASE)
1754
1755where `N` is the number of input digits in base `B`. This is computed via
1756
1757 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1758
1759below. Two numeric concerns are how much space this can waste, and whether
1760the computed result can be too small. To be concrete, assume BASE = 2**15,
1761which is the default (and it's unlikely anyone changes that).
1762
1763Waste isn't a problem: provided the first input digit isn't 0, the difference
1764between the worst-case input with N digits and the smallest input with N
1765digits is about a factor of B, but B is small compared to BASE so at most
1766one allocated Python digit can remain unused on that count. If
1767N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1768and adding 1 returns a result 1 larger than necessary. However, that can't
1769happen: whenever B is a power of 2, long_from_binary_base() is called
1770instead, and it's impossible for B**i to be an integer power of 2**15 when
1771B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1772an exact integer when B is not a power of 2, since B**i has a prime factor
1773other than 2 in that case, but (2**15)**j's only prime factor is 2).
1774
1775The computed result can be too small if the true value of N*log(B)/log(BASE)
1776is a little bit larger than an exact integer, but due to roundoff errors (in
1777computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1778yields a numeric result a little less than that integer. Unfortunately, "how
1779close can a transcendental function get to an integer over some range?"
1780questions are generally theoretically intractable. Computer analysis via
1781continued fractions is practical: expand log(B)/log(BASE) via continued
1782fractions, giving a sequence i/j of "the best" rational approximations. Then
1783j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1784we can get very close to being in trouble, but very rarely. For example,
178576573 is a denominator in one of the continued-fraction approximations to
1786log(10)/log(2**15), and indeed:
1787
1788 >>> log(10)/log(2**15)*76573
1789 16958.000000654003
1790
1791is very close to an integer. If we were working with IEEE single-precision,
1792rounding errors could kill us. Finding worst cases in IEEE double-precision
1793requires better-than-double-precision log() functions, and Tim didn't bother.
1794Instead the code checks to see whether the allocated space is enough as each
1795new Python digit is added, and copies the whole thing to a larger long if not.
1796This should happen extremely rarely, and in fact I don't have a test case
1797that triggers it(!). Instead the code was tested by artificially allocating
1798just 1 digit at the start, so that the copying code was exercised for every
1799digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001800***/
1801 register twodigits c; /* current input character */
1802 Py_ssize_t size_z;
1803 int i;
1804 int convwidth;
1805 twodigits convmultmax, convmult;
1806 digit *pz, *pzstop;
1807 char* scan;
1808
1809 static double log_base_BASE[37] = {0.0e0,};
1810 static int convwidth_base[37] = {0,};
1811 static twodigits convmultmax_base[37] = {0,};
1812
1813 if (log_base_BASE[base] == 0.0) {
1814 twodigits convmax = base;
1815 int i = 1;
1816
1817 log_base_BASE[base] = log((double)base) /
1818 log((double)BASE);
1819 for (;;) {
1820 twodigits next = convmax * base;
1821 if (next > BASE)
1822 break;
1823 convmax = next;
1824 ++i;
1825 }
1826 convmultmax_base[base] = convmax;
1827 assert(i > 0);
1828 convwidth_base[base] = i;
1829 }
1830
1831 /* Find length of the string of numeric characters. */
1832 scan = str;
1833 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1834 ++scan;
1835
1836 /* Create a long object that can contain the largest possible
1837 * integer with this base and length. Note that there's no
1838 * need to initialize z->ob_digit -- no slot is read up before
1839 * being stored into.
1840 */
1841 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001842 /* Uncomment next line to test exceedingly rare copy code */
1843 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001844 assert(size_z > 0);
1845 z = _PyLong_New(size_z);
1846 if (z == NULL)
1847 return NULL;
1848 z->ob_size = 0;
1849
1850 /* `convwidth` consecutive input digits are treated as a single
1851 * digit in base `convmultmax`.
1852 */
1853 convwidth = convwidth_base[base];
1854 convmultmax = convmultmax_base[base];
1855
1856 /* Work ;-) */
1857 while (str < scan) {
1858 /* grab up to convwidth digits from the input string */
1859 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1860 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1861 c = (twodigits)(c * base +
1862 _PyLong_DigitValue[Py_CHARMASK(*str)]);
1863 assert(c < BASE);
1864 }
1865
1866 convmult = convmultmax;
1867 /* Calculate the shift only if we couldn't get
1868 * convwidth digits.
1869 */
1870 if (i != convwidth) {
1871 convmult = base;
1872 for ( ; i > 1; --i)
1873 convmult *= base;
1874 }
1875
1876 /* Multiply z by convmult, and add c. */
1877 pz = z->ob_digit;
1878 pzstop = pz + z->ob_size;
1879 for (; pz < pzstop; ++pz) {
1880 c += (twodigits)*pz * convmult;
1881 *pz = (digit)(c & MASK);
1882 c >>= SHIFT;
1883 }
1884 /* carry off the current end? */
1885 if (c) {
1886 assert(c < BASE);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001887 if (z->ob_size < size_z) {
1888 *pz = (digit)c;
1889 ++z->ob_size;
1890 }
1891 else {
1892 PyLongObject *tmp;
1893 /* Extremely rare. Get more space. */
1894 assert(z->ob_size == size_z);
1895 tmp = _PyLong_New(size_z + 1);
1896 if (tmp == NULL) {
1897 Py_DECREF(z);
1898 return NULL;
1899 }
1900 memcpy(tmp->ob_digit,
1901 z->ob_digit,
1902 sizeof(digit) * size_z);
1903 Py_DECREF(z);
1904 z = tmp;
1905 z->ob_digit[size_z] = (digit)c;
1906 ++size_z;
1907 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001908 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001909 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001910 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001911 if (z == NULL)
1912 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001913 if (str == start)
1914 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001915 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001916 z->ob_size = -(z->ob_size);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001917 if (*str == 'L' || *str == 'l')
1918 str++;
1919 while (*str && isspace(Py_CHARMASK(*str)))
1920 str++;
1921 if (*str != '\0')
1922 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001923 if (pend)
1924 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001925 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001926
1927 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001928 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001929 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1930 strobj = PyString_FromStringAndSize(orig_str, slen);
1931 if (strobj == NULL)
1932 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001933 strrepr = PyObject_ReprStr8(strobj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001934 Py_DECREF(strobj);
1935 if (strrepr == NULL)
1936 return NULL;
1937 PyErr_Format(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001938 "invalid literal for int() with base %d: %s",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001939 base, PyString_AS_STRING(strrepr));
1940 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001941 return NULL;
1942}
1943
1944PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001945PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001946{
Walter Dörwald07e14762002-11-06 16:15:14 +00001947 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001948 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001949
Walter Dörwald07e14762002-11-06 16:15:14 +00001950 if (buffer == NULL)
1951 return NULL;
1952
1953 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1954 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001955 return NULL;
1956 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001957 result = PyLong_FromString(buffer, NULL, base);
1958 PyMem_FREE(buffer);
1959 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001960}
1961
Tim Peters9f688bf2000-07-07 15:53:28 +00001962/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001963static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001964 (PyLongObject *, PyLongObject *, PyLongObject **);
1965static PyObject *long_pos(PyLongObject *);
1966static int long_divrem(PyLongObject *, PyLongObject *,
1967 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001968
1969/* Long division with remainder, top-level routine */
1970
Guido van Rossume32e0141992-01-19 16:31:05 +00001971static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001972long_divrem(PyLongObject *a, PyLongObject *b,
1973 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001974{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001975 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001976 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001977
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001978 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001979 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001980 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001981 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001982 }
1983 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001984 (size_a == size_b &&
1985 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001986 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00001987 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001988 if (*pdiv == NULL)
1989 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001990 Py_INCREF(a);
1991 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001992 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001993 }
1994 if (size_b == 1) {
1995 digit rem = 0;
1996 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001997 if (z == NULL)
1998 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001999 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002000 if (*prem == NULL) {
2001 Py_DECREF(z);
2002 return -1;
2003 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002004 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002005 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002006 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002007 if (z == NULL)
2008 return -1;
2009 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002010 /* Set the signs.
2011 The quotient z has the sign of a*b;
2012 the remainder r has the sign of a,
2013 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00002014 if ((a->ob_size < 0) != (b->ob_size < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002015 NEGATE(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002016 if (a->ob_size < 0 && (*prem)->ob_size != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002017 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002018 *pdiv = z;
2019 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002020}
2021
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002022/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002023
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002024static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002025x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002026{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002027 Py_ssize_t size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size);
Guido van Rossum2095d241997-04-09 19:41:24 +00002028 digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002029 PyLongObject *v = mul1(v1, d);
2030 PyLongObject *w = mul1(w1, d);
2031 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002032 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002033
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002034 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002035 Py_XDECREF(v);
2036 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002037 return NULL;
2038 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002039
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002040 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002041 assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002042 assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002043
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002044 size_v = ABS(v->ob_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002045 k = size_v - size_w;
2046 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002047
Thomas Wouters477c8d52006-05-27 19:21:47 +00002048 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002049 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2050 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002051 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002052 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002053
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002054 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002055 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002056 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002057 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002058 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002059 if (vj == w->ob_digit[size_w-1])
2060 q = MASK;
2061 else
2062 q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
2063 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002064
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002065 while (w->ob_digit[size_w-2]*q >
2066 ((
2067 ((twodigits)vj << SHIFT)
2068 + v->ob_digit[j-1]
2069 - q*w->ob_digit[size_w-1]
2070 ) << SHIFT)
2071 + v->ob_digit[j-2])
2072 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002073
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002074 for (i = 0; i < size_w && i+k < size_v; ++i) {
2075 twodigits z = w->ob_digit[i] * q;
Guido van Rossum2095d241997-04-09 19:41:24 +00002076 digit zz = (digit) (z >> SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002077 carry += v->ob_digit[i+k] - z
2078 + ((twodigits)zz << SHIFT);
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00002079 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002080 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
2081 carry, SHIFT);
2082 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002083 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002084
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002085 if (i+k < size_v) {
2086 carry += v->ob_digit[i+k];
2087 v->ob_digit[i+k] = 0;
2088 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002089
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002091 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002092 else {
2093 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002094 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002095 carry = 0;
2096 for (i = 0; i < size_w && i+k < size_v; ++i) {
2097 carry += v->ob_digit[i+k] + w->ob_digit[i];
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00002098 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002099 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2100 BASE_TWODIGITS_TYPE,
2101 carry, SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002102 }
2103 }
2104 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002105
Guido van Rossumc206c761995-01-10 15:23:19 +00002106 if (a == NULL)
2107 *prem = NULL;
2108 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002109 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002110 *prem = divrem1(v, d, &d);
2111 /* d receives the (unused) remainder */
2112 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002113 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002114 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002115 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002116 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002117 Py_DECREF(v);
2118 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002119 return a;
2120}
2121
2122/* Methods */
2123
2124static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002125long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002126{
Guido van Rossum9475a232001-10-05 20:51:39 +00002127 v->ob_type->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002128}
2129
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002130static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002131long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002132{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00002133 return long_format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002134}
2135
2136static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002137long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002138{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002139 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002140
Guido van Rossumc6913e71991-11-19 20:26:46 +00002141 if (a->ob_size != b->ob_size) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002142 if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002143 sign = 0;
2144 else
2145 sign = a->ob_size - b->ob_size;
2146 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002147 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002148 Py_ssize_t i = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002149 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2150 ;
2151 if (i < 0)
2152 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002153 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002154 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002155 if (a->ob_size < 0)
2156 sign = -sign;
2157 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002158 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002159 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002160}
2161
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002162static PyObject *
2163long_richcompare(PyObject *self, PyObject *other, int op)
2164{
2165 PyLongObject *a, *b;
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002166 PyObject *result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002167 CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b);
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002168 result = Py_CmpToRich(op, long_compare(a, b));
2169 Py_DECREF(a);
2170 Py_DECREF(b);
2171 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002172}
2173
Guido van Rossum9bfef441993-03-29 10:43:31 +00002174static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002175long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002176{
2177 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002178 Py_ssize_t i;
2179 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002180
2181 /* This is designed so that Python ints and longs with the
2182 same value hash to the same value, otherwise comparisons
2183 of mapping keys will turn out weird */
2184 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00002185 switch(i) {
2186 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2187 case 0: return 0;
2188 case 1: return v->ob_digit[0];
2189 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002190 sign = 1;
2191 x = 0;
2192 if (i < 0) {
2193 sign = -1;
2194 i = -(i);
2195 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002196#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002197 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002198 /* Force a native long #-bits (32 or 64) circular shift */
2199 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002200 x += v->ob_digit[i];
2201 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002202#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002203 x = x * sign;
2204 if (x == -1)
2205 x = -2;
2206 return x;
2207}
2208
2209
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002210/* Add the absolute values of two long integers. */
2211
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002212static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002213x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002214{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002215 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002216 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002217 int i;
2218 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002219
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002220 /* Ensure a is the larger of the two: */
2221 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002222 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002223 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002224 size_a = size_b;
2225 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002226 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002227 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002228 if (z == NULL)
2229 return NULL;
2230 for (i = 0; i < size_b; ++i) {
2231 carry += a->ob_digit[i] + b->ob_digit[i];
2232 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002233 carry >>= SHIFT;
2234 }
2235 for (; i < size_a; ++i) {
2236 carry += a->ob_digit[i];
2237 z->ob_digit[i] = carry & MASK;
2238 carry >>= SHIFT;
2239 }
2240 z->ob_digit[i] = carry;
2241 return long_normalize(z);
2242}
2243
2244/* Subtract the absolute values of two integers. */
2245
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002246static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002247x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002248{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002249 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002250 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002251 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002252 int sign = 1;
2253 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002254
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002255 /* Ensure a is the larger of the two: */
2256 if (size_a < size_b) {
2257 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002258 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002259 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002260 size_a = size_b;
2261 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002262 }
2263 else if (size_a == size_b) {
2264 /* Find highest digit where a and b differ: */
2265 i = size_a;
2266 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2267 ;
2268 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002269 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002270 if (a->ob_digit[i] < b->ob_digit[i]) {
2271 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002272 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002273 }
2274 size_a = size_b = i+1;
2275 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002276 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002277 if (z == NULL)
2278 return NULL;
2279 for (i = 0; i < size_b; ++i) {
2280 /* The following assumes unsigned arithmetic
2281 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002282 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002283 z->ob_digit[i] = borrow & MASK;
2284 borrow >>= SHIFT;
2285 borrow &= 1; /* Keep only one sign bit */
2286 }
2287 for (; i < size_a; ++i) {
2288 borrow = a->ob_digit[i] - borrow;
2289 z->ob_digit[i] = borrow & MASK;
2290 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002291 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002292 }
2293 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002294 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002295 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002296 return long_normalize(z);
2297}
2298
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002299static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002300long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002301{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002302 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002303
Neil Schemenauerba872e22001-01-04 01:46:03 +00002304 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2305
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002306 if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) {
2307 PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) +
2308 MEDIUM_VALUE(b));
2309 Py_DECREF(a);
2310 Py_DECREF(b);
2311 return result;
2312 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002313 if (a->ob_size < 0) {
2314 if (b->ob_size < 0) {
2315 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002316 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002317 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002318 }
2319 else
2320 z = x_sub(b, a);
2321 }
2322 else {
2323 if (b->ob_size < 0)
2324 z = x_sub(a, b);
2325 else
2326 z = x_add(a, b);
2327 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002328 Py_DECREF(a);
2329 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002330 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002331}
2332
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002333static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002334long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002335{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002336 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002337
Neil Schemenauerba872e22001-01-04 01:46:03 +00002338 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2339
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002340 if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) {
2341 PyObject* r;
2342 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2343 Py_DECREF(a);
2344 Py_DECREF(b);
2345 return r;
2346 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002347 if (a->ob_size < 0) {
2348 if (b->ob_size < 0)
2349 z = x_sub(a, b);
2350 else
2351 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002352 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002353 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002354 }
2355 else {
2356 if (b->ob_size < 0)
2357 z = x_add(a, b);
2358 else
2359 z = x_sub(a, b);
2360 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002361 Py_DECREF(a);
2362 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002363 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002364}
2365
Tim Peters5af4e6c2002-08-12 02:31:19 +00002366/* Grade school multiplication, ignoring the signs.
2367 * Returns the absolute value of the product, or NULL if error.
2368 */
2369static PyLongObject *
2370x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002371{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002372 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002373 Py_ssize_t size_a = ABS(a->ob_size);
2374 Py_ssize_t size_b = ABS(b->ob_size);
2375 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002376
Tim Peters5af4e6c2002-08-12 02:31:19 +00002377 z = _PyLong_New(size_a + size_b);
2378 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002379 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002380
2381 memset(z->ob_digit, 0, z->ob_size * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002382 if (a == b) {
2383 /* Efficient squaring per HAC, Algorithm 14.16:
2384 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2385 * Gives slightly less than a 2x speedup when a == b,
2386 * via exploiting that each entry in the multiplication
2387 * pyramid appears twice (except for the size_a squares).
2388 */
2389 for (i = 0; i < size_a; ++i) {
2390 twodigits carry;
2391 twodigits f = a->ob_digit[i];
2392 digit *pz = z->ob_digit + (i << 1);
2393 digit *pa = a->ob_digit + i + 1;
2394 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002395
Tim Peters0973b992004-08-29 22:16:50 +00002396 SIGCHECK({
2397 Py_DECREF(z);
2398 return NULL;
2399 })
2400
2401 carry = *pz + f * f;
2402 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002403 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002404 assert(carry <= MASK);
2405
2406 /* Now f is added in twice in each column of the
2407 * pyramid it appears. Same as adding f<<1 once.
2408 */
2409 f <<= 1;
2410 while (pa < paend) {
2411 carry += *pz + *pa++ * f;
2412 *pz++ = (digit)(carry & MASK);
2413 carry >>= SHIFT;
2414 assert(carry <= (MASK << 1));
2415 }
2416 if (carry) {
2417 carry += *pz;
2418 *pz++ = (digit)(carry & MASK);
2419 carry >>= SHIFT;
2420 }
2421 if (carry)
2422 *pz += (digit)(carry & MASK);
2423 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002424 }
Tim Peters0973b992004-08-29 22:16:50 +00002425 }
2426 else { /* a is not the same as b -- gradeschool long mult */
2427 for (i = 0; i < size_a; ++i) {
2428 twodigits carry = 0;
2429 twodigits f = a->ob_digit[i];
2430 digit *pz = z->ob_digit + i;
2431 digit *pb = b->ob_digit;
2432 digit *pbend = b->ob_digit + size_b;
2433
2434 SIGCHECK({
2435 Py_DECREF(z);
2436 return NULL;
2437 })
2438
2439 while (pb < pbend) {
2440 carry += *pz + *pb++ * f;
2441 *pz++ = (digit)(carry & MASK);
2442 carry >>= SHIFT;
2443 assert(carry <= MASK);
2444 }
2445 if (carry)
2446 *pz += (digit)(carry & MASK);
2447 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002448 }
2449 }
Tim Peters44121a62002-08-12 06:17:58 +00002450 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002451}
2452
2453/* A helper for Karatsuba multiplication (k_mul).
2454 Takes a long "n" and an integer "size" representing the place to
2455 split, and sets low and high such that abs(n) == (high << size) + low,
2456 viewing the shift as being by digits. The sign bit is ignored, and
2457 the return values are >= 0.
2458 Returns 0 on success, -1 on failure.
2459*/
2460static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002461kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002462{
2463 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002464 Py_ssize_t size_lo, size_hi;
2465 const Py_ssize_t size_n = ABS(n->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002466
2467 size_lo = MIN(size_n, size);
2468 size_hi = size_n - size_lo;
2469
2470 if ((hi = _PyLong_New(size_hi)) == NULL)
2471 return -1;
2472 if ((lo = _PyLong_New(size_lo)) == NULL) {
2473 Py_DECREF(hi);
2474 return -1;
2475 }
2476
2477 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2478 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2479
2480 *high = long_normalize(hi);
2481 *low = long_normalize(lo);
2482 return 0;
2483}
2484
Tim Peters60004642002-08-12 22:01:34 +00002485static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2486
Tim Peters5af4e6c2002-08-12 02:31:19 +00002487/* Karatsuba multiplication. Ignores the input signs, and returns the
2488 * absolute value of the product (or NULL if error).
2489 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2490 */
2491static PyLongObject *
2492k_mul(PyLongObject *a, PyLongObject *b)
2493{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002494 Py_ssize_t asize = ABS(a->ob_size);
2495 Py_ssize_t bsize = ABS(b->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002496 PyLongObject *ah = NULL;
2497 PyLongObject *al = NULL;
2498 PyLongObject *bh = NULL;
2499 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002500 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002501 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002502 Py_ssize_t shift; /* the number of digits we split off */
2503 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002504
Tim Peters5af4e6c2002-08-12 02:31:19 +00002505 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2506 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2507 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002508 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002509 * By picking X to be a power of 2, "*X" is just shifting, and it's
2510 * been reduced to 3 multiplies on numbers half the size.
2511 */
2512
Tim Petersfc07e562002-08-12 02:54:10 +00002513 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002514 * is largest.
2515 */
Tim Peters738eda72002-08-12 15:08:20 +00002516 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002517 t1 = a;
2518 a = b;
2519 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002520
2521 i = asize;
2522 asize = bsize;
2523 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002524 }
2525
2526 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002527 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2528 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002529 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002530 return _PyLong_New(0);
2531 else
2532 return x_mul(a, b);
2533 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002534
Tim Peters60004642002-08-12 22:01:34 +00002535 /* If a is small compared to b, splitting on b gives a degenerate
2536 * case with ah==0, and Karatsuba may be (even much) less efficient
2537 * than "grade school" then. However, we can still win, by viewing
2538 * b as a string of "big digits", each of width a->ob_size. That
2539 * leads to a sequence of balanced calls to k_mul.
2540 */
2541 if (2 * asize <= bsize)
2542 return k_lopsided_mul(a, b);
2543
Tim Petersd6974a52002-08-13 20:37:51 +00002544 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002545 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002546 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Tim Petersd6974a52002-08-13 20:37:51 +00002547 assert(ah->ob_size > 0); /* the split isn't degenerate */
2548
Tim Peters0973b992004-08-29 22:16:50 +00002549 if (a == b) {
2550 bh = ah;
2551 bl = al;
2552 Py_INCREF(bh);
2553 Py_INCREF(bl);
2554 }
2555 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002556
Tim Petersd64c1de2002-08-12 17:36:03 +00002557 /* The plan:
2558 * 1. Allocate result space (asize + bsize digits: that's always
2559 * enough).
2560 * 2. Compute ah*bh, and copy into result at 2*shift.
2561 * 3. Compute al*bl, and copy into result at 0. Note that this
2562 * can't overlap with #2.
2563 * 4. Subtract al*bl from the result, starting at shift. This may
2564 * underflow (borrow out of the high digit), but we don't care:
2565 * we're effectively doing unsigned arithmetic mod
2566 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2567 * borrows and carries out of the high digit can be ignored.
2568 * 5. Subtract ah*bh from the result, starting at shift.
2569 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2570 * at shift.
2571 */
2572
2573 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002574 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002575 if (ret == NULL) goto fail;
2576#ifdef Py_DEBUG
2577 /* Fill with trash, to catch reference to uninitialized digits. */
2578 memset(ret->ob_digit, 0xDF, ret->ob_size * sizeof(digit));
2579#endif
Tim Peters44121a62002-08-12 06:17:58 +00002580
Tim Petersd64c1de2002-08-12 17:36:03 +00002581 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002582 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2583 assert(t1->ob_size >= 0);
2584 assert(2*shift + t1->ob_size <= ret->ob_size);
2585 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2586 t1->ob_size * sizeof(digit));
2587
2588 /* Zero-out the digits higher than the ah*bh copy. */
2589 i = ret->ob_size - 2*shift - t1->ob_size;
Tim Peters44121a62002-08-12 06:17:58 +00002590 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002591 memset(ret->ob_digit + 2*shift + t1->ob_size, 0,
Tim Peters44121a62002-08-12 06:17:58 +00002592 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002593
Tim Petersd64c1de2002-08-12 17:36:03 +00002594 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002595 if ((t2 = k_mul(al, bl)) == NULL) {
2596 Py_DECREF(t1);
2597 goto fail;
2598 }
2599 assert(t2->ob_size >= 0);
2600 assert(t2->ob_size <= 2*shift); /* no overlap with high digits */
2601 memcpy(ret->ob_digit, t2->ob_digit, t2->ob_size * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002602
2603 /* Zero out remaining digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002604 i = 2*shift - t2->ob_size; /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002605 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002606 memset(ret->ob_digit + t2->ob_size, 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002607
Tim Petersd64c1de2002-08-12 17:36:03 +00002608 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2609 * because it's fresher in cache.
2610 */
Tim Peters738eda72002-08-12 15:08:20 +00002611 i = ret->ob_size - shift; /* # digits after shift */
Tim Petersd64c1de2002-08-12 17:36:03 +00002612 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, t2->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002613 Py_DECREF(t2);
2614
Tim Petersd64c1de2002-08-12 17:36:03 +00002615 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, t1->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002616 Py_DECREF(t1);
2617
Tim Petersd64c1de2002-08-12 17:36:03 +00002618 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002619 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2620 Py_DECREF(ah);
2621 Py_DECREF(al);
2622 ah = al = NULL;
2623
Tim Peters0973b992004-08-29 22:16:50 +00002624 if (a == b) {
2625 t2 = t1;
2626 Py_INCREF(t2);
2627 }
2628 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002629 Py_DECREF(t1);
2630 goto fail;
2631 }
2632 Py_DECREF(bh);
2633 Py_DECREF(bl);
2634 bh = bl = NULL;
2635
Tim Peters738eda72002-08-12 15:08:20 +00002636 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002637 Py_DECREF(t1);
2638 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002639 if (t3 == NULL) goto fail;
Tim Peters547607c2002-08-12 19:43:49 +00002640 assert(t3->ob_size >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002641
Tim Petersd6974a52002-08-13 20:37:51 +00002642 /* Add t3. It's not obvious why we can't run out of room here.
2643 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002644 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002645 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, t3->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002646 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002647
Tim Peters5af4e6c2002-08-12 02:31:19 +00002648 return long_normalize(ret);
2649
2650 fail:
2651 Py_XDECREF(ret);
2652 Py_XDECREF(ah);
2653 Py_XDECREF(al);
2654 Py_XDECREF(bh);
2655 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002656 return NULL;
2657}
2658
Tim Petersd6974a52002-08-13 20:37:51 +00002659/* (*) Why adding t3 can't "run out of room" above.
2660
Tim Petersab86c2b2002-08-15 20:06:00 +00002661Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2662to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002663
Tim Petersab86c2b2002-08-15 20:06:00 +000026641. For any integer i, i = c(i/2) + f(i/2). In particular,
2665 bsize = c(bsize/2) + f(bsize/2).
26662. shift = f(bsize/2)
26673. asize <= bsize
26684. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2669 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002670
Tim Petersab86c2b2002-08-15 20:06:00 +00002671We allocated asize + bsize result digits, and add t3 into them at an offset
2672of shift. This leaves asize+bsize-shift allocated digit positions for t3
2673to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2674asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002675
Tim Petersab86c2b2002-08-15 20:06:00 +00002676bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2677at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002678
Tim Petersab86c2b2002-08-15 20:06:00 +00002679If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2680digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2681most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002682
Tim Petersab86c2b2002-08-15 20:06:00 +00002683The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002684
Tim Petersab86c2b2002-08-15 20:06:00 +00002685 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002686
Tim Petersab86c2b2002-08-15 20:06:00 +00002687and we have asize + c(bsize/2) available digit positions. We need to show
2688this is always enough. An instance of c(bsize/2) cancels out in both, so
2689the question reduces to whether asize digits is enough to hold
2690(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2691then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2692asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2693digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2694asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002695c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2696is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2697bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002698
Tim Peters48d52c02002-08-14 17:07:32 +00002699Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2700clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2701ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002702*/
2703
Tim Peters60004642002-08-12 22:01:34 +00002704/* b has at least twice the digits of a, and a is big enough that Karatsuba
2705 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2706 * of slices, each with a->ob_size digits, and multiply the slices by a,
2707 * one at a time. This gives k_mul balanced inputs to work with, and is
2708 * also cache-friendly (we compute one double-width slice of the result
2709 * at a time, then move on, never bactracking except for the helpful
2710 * single-width slice overlap between successive partial sums).
2711 */
2712static PyLongObject *
2713k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2714{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002715 const Py_ssize_t asize = ABS(a->ob_size);
2716 Py_ssize_t bsize = ABS(b->ob_size);
2717 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002718 PyLongObject *ret;
2719 PyLongObject *bslice = NULL;
2720
2721 assert(asize > KARATSUBA_CUTOFF);
2722 assert(2 * asize <= bsize);
2723
2724 /* Allocate result space, and zero it out. */
2725 ret = _PyLong_New(asize + bsize);
2726 if (ret == NULL)
2727 return NULL;
2728 memset(ret->ob_digit, 0, ret->ob_size * sizeof(digit));
2729
2730 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002731 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002732 if (bslice == NULL)
2733 goto fail;
2734
2735 nbdone = 0;
2736 while (bsize > 0) {
2737 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002738 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002739
2740 /* Multiply the next slice of b by a. */
2741 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2742 nbtouse * sizeof(digit));
2743 bslice->ob_size = nbtouse;
2744 product = k_mul(a, bslice);
2745 if (product == NULL)
2746 goto fail;
2747
2748 /* Add into result. */
2749 (void)v_iadd(ret->ob_digit + nbdone, ret->ob_size - nbdone,
2750 product->ob_digit, product->ob_size);
2751 Py_DECREF(product);
2752
2753 bsize -= nbtouse;
2754 nbdone += nbtouse;
2755 }
2756
2757 Py_DECREF(bslice);
2758 return long_normalize(ret);
2759
2760 fail:
2761 Py_DECREF(ret);
2762 Py_XDECREF(bslice);
2763 return NULL;
2764}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002765
2766static PyObject *
2767long_mul(PyLongObject *v, PyLongObject *w)
2768{
2769 PyLongObject *a, *b, *z;
2770
2771 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002772 Py_INCREF(Py_NotImplemented);
2773 return Py_NotImplemented;
2774 }
2775
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002776 if (ABS(v->ob_size) <= 1 && ABS(w->ob_size) <= 1) {
2777 PyObject *r;
2778 r = PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w));
2779 Py_DECREF(a);
2780 Py_DECREF(b);
2781 return r;
2782 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002783
Tim Petersd64c1de2002-08-12 17:36:03 +00002784 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002785 /* Negate if exactly one of the inputs is negative. */
2786 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002787 NEGATE(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002788 Py_DECREF(a);
2789 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002790 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002791}
2792
Guido van Rossume32e0141992-01-19 16:31:05 +00002793/* The / and % operators are now defined in terms of divmod().
2794 The expression a mod b has the value a - b*floor(a/b).
2795 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002796 |a| by |b|, with the sign of a. This is also expressed
2797 as a - b*trunc(a/b), if trunc truncates towards zero.
2798 Some examples:
2799 a b a rem b a mod b
2800 13 10 3 3
2801 -13 10 -3 7
2802 13 -10 3 -7
2803 -13 -10 -3 -3
2804 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002805 have different signs. We then subtract one from the 'div'
2806 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002807
Tim Peters47e52ee2004-08-30 02:44:38 +00002808/* Compute
2809 * *pdiv, *pmod = divmod(v, w)
2810 * NULL can be passed for pdiv or pmod, in which case that part of
2811 * the result is simply thrown away. The caller owns a reference to
2812 * each of these it requests (does not pass NULL for).
2813 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002814static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002815l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002816 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002817{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002818 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002819
Guido van Rossume32e0141992-01-19 16:31:05 +00002820 if (long_divrem(v, w, &div, &mod) < 0)
2821 return -1;
Guido van Rossum472c04f1996-12-05 21:57:21 +00002822 if ((mod->ob_size < 0 && w->ob_size > 0) ||
2823 (mod->ob_size > 0 && w->ob_size < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002824 PyLongObject *temp;
2825 PyLongObject *one;
2826 temp = (PyLongObject *) long_add(mod, w);
2827 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002828 mod = temp;
2829 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002830 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002831 return -1;
2832 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002833 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002834 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002835 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2836 Py_DECREF(mod);
2837 Py_DECREF(div);
2838 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002839 return -1;
2840 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002841 Py_DECREF(one);
2842 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002843 div = temp;
2844 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002845 if (pdiv != NULL)
2846 *pdiv = div;
2847 else
2848 Py_DECREF(div);
2849
2850 if (pmod != NULL)
2851 *pmod = mod;
2852 else
2853 Py_DECREF(mod);
2854
Guido van Rossume32e0141992-01-19 16:31:05 +00002855 return 0;
2856}
2857
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002858static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002859long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002860{
Tim Peters47e52ee2004-08-30 02:44:38 +00002861 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002862
2863 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002864 if (l_divmod(a, b, &div, NULL) < 0)
2865 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002866 Py_DECREF(a);
2867 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002868 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002869}
2870
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002871static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002872long_true_divide(PyObject *v, PyObject *w)
2873{
Tim Peterse2a60002001-09-04 06:17:36 +00002874 PyLongObject *a, *b;
2875 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002876 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002877
2878 CONVERT_BINOP(v, w, &a, &b);
2879 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2880 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002881 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2882 Py_DECREF(a);
2883 Py_DECREF(b);
2884 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002885 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002886 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2887 but should really be set correctly after sucessful calls to
2888 _PyLong_AsScaledDouble() */
2889 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002890
2891 if (bd == 0.0) {
2892 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002893 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002894 return NULL;
2895 }
2896
2897 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2898 ad /= bd; /* overflow/underflow impossible here */
2899 aexp -= bexp;
2900 if (aexp > INT_MAX / SHIFT)
2901 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002902 else if (aexp < -(INT_MAX / SHIFT))
2903 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002904 errno = 0;
2905 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002906 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002907 goto overflow;
2908 return PyFloat_FromDouble(ad);
2909
2910overflow:
2911 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002912 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002913 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002914
Tim Peters20dab9f2001-09-04 05:31:47 +00002915}
2916
2917static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002918long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002919{
Tim Peters47e52ee2004-08-30 02:44:38 +00002920 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002921
2922 CONVERT_BINOP(v, w, &a, &b);
2923
Tim Peters47e52ee2004-08-30 02:44:38 +00002924 if (l_divmod(a, b, NULL, &mod) < 0)
2925 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002926 Py_DECREF(a);
2927 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002928 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002929}
2930
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002931static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002932long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002933{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002934 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002935 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002936
2937 CONVERT_BINOP(v, w, &a, &b);
2938
2939 if (l_divmod(a, b, &div, &mod) < 0) {
2940 Py_DECREF(a);
2941 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002942 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002943 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002944 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002945 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002946 PyTuple_SetItem(z, 0, (PyObject *) div);
2947 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002948 }
2949 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002950 Py_DECREF(div);
2951 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002952 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002953 Py_DECREF(a);
2954 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002955 return z;
2956}
2957
Tim Peters47e52ee2004-08-30 02:44:38 +00002958/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002959static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002960long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002961{
Tim Peters47e52ee2004-08-30 02:44:38 +00002962 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2963 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002964
Tim Peters47e52ee2004-08-30 02:44:38 +00002965 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002966 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002967 PyLongObject *temp = NULL;
2968
2969 /* 5-ary values. If the exponent is large enough, table is
2970 * precomputed so that table[i] == a**i % c for i in range(32).
2971 */
2972 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2973 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2974
2975 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002976 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002977 if (PyLong_Check(x)) {
2978 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002979 Py_INCREF(x);
2980 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002981 else if (x == Py_None)
2982 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002983 else {
2984 Py_DECREF(a);
2985 Py_DECREF(b);
2986 Py_INCREF(Py_NotImplemented);
2987 return Py_NotImplemented;
2988 }
Tim Peters4c483c42001-09-05 06:24:58 +00002989
Tim Peters47e52ee2004-08-30 02:44:38 +00002990 if (b->ob_size < 0) { /* if exponent is negative */
2991 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002992 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002993 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002994 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002995 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002996 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002997 /* else return a float. This works because we know
2998 that this calls float_pow() which converts its
2999 arguments to double. */
3000 Py_DECREF(a);
3001 Py_DECREF(b);
3002 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003003 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003004 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003005
3006 if (c) {
3007 /* if modulus == 0:
3008 raise ValueError() */
3009 if (c->ob_size == 0) {
3010 PyErr_SetString(PyExc_ValueError,
3011 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003012 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003013 }
3014
3015 /* if modulus < 0:
3016 negativeOutput = True
3017 modulus = -modulus */
3018 if (c->ob_size < 0) {
3019 negativeOutput = 1;
3020 temp = (PyLongObject *)_PyLong_Copy(c);
3021 if (temp == NULL)
3022 goto Error;
3023 Py_DECREF(c);
3024 c = temp;
3025 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003026 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003027 }
3028
3029 /* if modulus == 1:
3030 return 0 */
3031 if ((c->ob_size == 1) && (c->ob_digit[0] == 1)) {
3032 z = (PyLongObject *)PyLong_FromLong(0L);
3033 goto Done;
3034 }
3035
3036 /* if base < 0:
3037 base = base % modulus
3038 Having the base positive just makes things easier. */
3039 if (a->ob_size < 0) {
3040 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003041 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003042 Py_DECREF(a);
3043 a = temp;
3044 temp = NULL;
3045 }
3046 }
3047
3048 /* At this point a, b, and c are guaranteed non-negative UNLESS
3049 c is NULL, in which case a may be negative. */
3050
3051 z = (PyLongObject *)PyLong_FromLong(1L);
3052 if (z == NULL)
3053 goto Error;
3054
3055 /* Perform a modular reduction, X = X % c, but leave X alone if c
3056 * is NULL.
3057 */
3058#define REDUCE(X) \
3059 if (c != NULL) { \
3060 if (l_divmod(X, c, NULL, &temp) < 0) \
3061 goto Error; \
3062 Py_XDECREF(X); \
3063 X = temp; \
3064 temp = NULL; \
3065 }
3066
3067 /* Multiply two values, then reduce the result:
3068 result = X*Y % c. If c is NULL, skip the mod. */
3069#define MULT(X, Y, result) \
3070{ \
3071 temp = (PyLongObject *)long_mul(X, Y); \
3072 if (temp == NULL) \
3073 goto Error; \
3074 Py_XDECREF(result); \
3075 result = temp; \
3076 temp = NULL; \
3077 REDUCE(result) \
3078}
3079
3080 if (b->ob_size <= FIVEARY_CUTOFF) {
3081 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3082 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3083 for (i = b->ob_size - 1; i >= 0; --i) {
3084 digit bi = b->ob_digit[i];
3085
3086 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
3087 MULT(z, z, z)
3088 if (bi & j)
3089 MULT(z, a, z)
3090 }
3091 }
3092 }
3093 else {
3094 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3095 Py_INCREF(z); /* still holds 1L */
3096 table[0] = z;
3097 for (i = 1; i < 32; ++i)
3098 MULT(table[i-1], a, table[i])
3099
3100 for (i = b->ob_size - 1; i >= 0; --i) {
3101 const digit bi = b->ob_digit[i];
3102
3103 for (j = SHIFT - 5; j >= 0; j -= 5) {
3104 const int index = (bi >> j) & 0x1f;
3105 for (k = 0; k < 5; ++k)
3106 MULT(z, z, z)
3107 if (index)
3108 MULT(z, table[index], z)
3109 }
3110 }
3111 }
3112
3113 if (negativeOutput && (z->ob_size != 0)) {
3114 temp = (PyLongObject *)long_sub(z, c);
3115 if (temp == NULL)
3116 goto Error;
3117 Py_DECREF(z);
3118 z = temp;
3119 temp = NULL;
3120 }
3121 goto Done;
3122
3123 Error:
3124 if (z != NULL) {
3125 Py_DECREF(z);
3126 z = NULL;
3127 }
3128 /* fall through */
3129 Done:
Tim Peters47e52ee2004-08-30 02:44:38 +00003130 if (b->ob_size > FIVEARY_CUTOFF) {
3131 for (i = 0; i < 32; ++i)
3132 Py_XDECREF(table[i]);
3133 }
Tim Petersde7990b2005-07-17 23:45:23 +00003134 Py_DECREF(a);
3135 Py_DECREF(b);
3136 Py_XDECREF(c);
3137 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003138 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003139}
3140
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003141static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003142long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003143{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003144 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003145 PyLongObject *x;
3146 PyLongObject *w;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003147 if (ABS(v->ob_size) <=1)
3148 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003149 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003150 if (w == NULL)
3151 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003152 x = (PyLongObject *) long_add(v, w);
3153 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003154 if (x == NULL)
3155 return NULL;
Tim Peters40c397d2001-09-11 23:24:22 +00003156 x->ob_size = -(x->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003157 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003158}
3159
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003160static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003161long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003162{
Tim Peters69c2de32001-09-11 22:31:33 +00003163 if (PyLong_CheckExact(v)) {
3164 Py_INCREF(v);
3165 return (PyObject *)v;
3166 }
3167 else
3168 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003169}
3170
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003171static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003172long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003173{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003174 PyLongObject *z;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003175 if (ABS(v->ob_size) <= 1)
3176 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003177 z = (PyLongObject *)_PyLong_Copy(v);
3178 if (z != NULL)
3179 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003180 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003181}
3182
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003183static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003184long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003185{
3186 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003187 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003188 else
3189 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003190}
3191
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003192static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003193long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003194{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003195 return ABS(v->ob_size) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003196}
3197
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003198static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003199long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003200{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003201 PyLongObject *a, *b;
3202 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003203 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003204 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003205 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003206
Neil Schemenauerba872e22001-01-04 01:46:03 +00003207 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3208
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003209 if (a->ob_size < 0) {
3210 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003211 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003212 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003213 if (a1 == NULL)
3214 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003215 a2 = (PyLongObject *) long_rshift(a1, b);
3216 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003217 if (a2 == NULL)
3218 goto rshift_error;
3219 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003220 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003221 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003222 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003223
Neil Schemenauerba872e22001-01-04 01:46:03 +00003224 shiftby = PyLong_AsLong((PyObject *)b);
3225 if (shiftby == -1L && PyErr_Occurred())
3226 goto rshift_error;
3227 if (shiftby < 0) {
3228 PyErr_SetString(PyExc_ValueError,
3229 "negative shift count");
3230 goto rshift_error;
3231 }
3232 wordshift = shiftby / SHIFT;
3233 newsize = ABS(a->ob_size) - wordshift;
3234 if (newsize <= 0) {
3235 z = _PyLong_New(0);
3236 Py_DECREF(a);
3237 Py_DECREF(b);
3238 return (PyObject *)z;
3239 }
3240 loshift = shiftby % SHIFT;
3241 hishift = SHIFT - loshift;
3242 lomask = ((digit)1 << hishift) - 1;
3243 himask = MASK ^ lomask;
3244 z = _PyLong_New(newsize);
3245 if (z == NULL)
3246 goto rshift_error;
3247 if (a->ob_size < 0)
3248 z->ob_size = -(z->ob_size);
3249 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3250 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3251 if (i+1 < newsize)
3252 z->ob_digit[i] |=
3253 (a->ob_digit[j+1] << hishift) & himask;
3254 }
3255 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003256 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003257rshift_error:
3258 Py_DECREF(a);
3259 Py_DECREF(b);
3260 return (PyObject *) z;
3261
Guido van Rossumc6913e71991-11-19 20:26:46 +00003262}
3263
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003264static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003265long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003266{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003267 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003268 PyLongObject *a, *b;
3269 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003270 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003271 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003272 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003273
Neil Schemenauerba872e22001-01-04 01:46:03 +00003274 CONVERT_BINOP(v, w, &a, &b);
3275
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003276 shiftby = PyLong_AsLong((PyObject *)b);
3277 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003278 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003279 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003280 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003281 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003282 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003283 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003284 PyErr_SetString(PyExc_ValueError,
3285 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003286 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003287 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003288 /* wordshift, remshift = divmod(shiftby, SHIFT) */
3289 wordshift = (int)shiftby / SHIFT;
3290 remshift = (int)shiftby - wordshift * SHIFT;
3291
3292 oldsize = ABS(a->ob_size);
3293 newsize = oldsize + wordshift;
3294 if (remshift)
3295 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003296 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003297 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003298 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003299 if (a->ob_size < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003300 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003301 for (i = 0; i < wordshift; i++)
3302 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003303 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003304 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003305 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003306 z->ob_digit[i] = (digit)(accum & MASK);
3307 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003308 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003309 if (remshift)
3310 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003311 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003312 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003313 z = long_normalize(z);
3314lshift_error:
3315 Py_DECREF(a);
3316 Py_DECREF(b);
3317 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003318}
3319
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003320
3321/* Bitwise and/xor/or operations */
3322
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003323static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003324long_bitwise(PyLongObject *a,
3325 int op, /* '&', '|', '^' */
3326 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003327{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003328 digit maska, maskb; /* 0 or MASK */
3329 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003330 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003331 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003332 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003333 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003334 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003335
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003336 if (a->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003337 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003338 if (a == NULL)
3339 return NULL;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003340 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003341 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003342 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003343 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003344 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003345 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003346 if (b->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003347 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003348 if (b == NULL) {
3349 Py_DECREF(a);
3350 return NULL;
3351 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003352 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003353 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003354 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003355 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003356 maskb = 0;
3357 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003358
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003359 negz = 0;
3360 switch (op) {
3361 case '^':
3362 if (maska != maskb) {
3363 maska ^= MASK;
3364 negz = -1;
3365 }
3366 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003367 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003368 if (maska && maskb) {
3369 op = '|';
3370 maska ^= MASK;
3371 maskb ^= MASK;
3372 negz = -1;
3373 }
3374 break;
3375 case '|':
3376 if (maska || maskb) {
3377 op = '&';
3378 maska ^= MASK;
3379 maskb ^= MASK;
3380 negz = -1;
3381 }
3382 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003383 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003384
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003385 /* JRH: The original logic here was to allocate the result value (z)
3386 as the longer of the two operands. However, there are some cases
3387 where the result is guaranteed to be shorter than that: AND of two
3388 positives, OR of two negatives: use the shorter number. AND with
3389 mixed signs: use the positive number. OR with mixed signs: use the
3390 negative number. After the transformations above, op will be '&'
3391 iff one of these cases applies, and mask will be non-0 for operands
3392 whose length should be ignored.
3393 */
3394
3395 size_a = a->ob_size;
3396 size_b = b->ob_size;
3397 size_z = op == '&'
3398 ? (maska
3399 ? size_b
3400 : (maskb ? size_a : MIN(size_a, size_b)))
3401 : MAX(size_a, size_b);
3402 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003403 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003404 Py_DECREF(a);
3405 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003406 return NULL;
3407 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003408
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003409 for (i = 0; i < size_z; ++i) {
3410 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3411 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3412 switch (op) {
3413 case '&': z->ob_digit[i] = diga & digb; break;
3414 case '|': z->ob_digit[i] = diga | digb; break;
3415 case '^': z->ob_digit[i] = diga ^ digb; break;
3416 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003417 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003418
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003419 Py_DECREF(a);
3420 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003421 z = long_normalize(z);
3422 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003423 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003424 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003425 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003426 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003427}
3428
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003429static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003430long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003431{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003432 PyLongObject *a, *b;
3433 PyObject *c;
3434 CONVERT_BINOP(v, w, &a, &b);
3435 c = long_bitwise(a, '&', b);
3436 Py_DECREF(a);
3437 Py_DECREF(b);
3438 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003439}
3440
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003441static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003442long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003443{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003444 PyLongObject *a, *b;
3445 PyObject *c;
3446 CONVERT_BINOP(v, w, &a, &b);
3447 c = long_bitwise(a, '^', b);
3448 Py_DECREF(a);
3449 Py_DECREF(b);
3450 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003451}
3452
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003453static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003454long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003455{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003456 PyLongObject *a, *b;
3457 PyObject *c;
3458 CONVERT_BINOP(v, w, &a, &b);
3459 c = long_bitwise(a, '|', b);
3460 Py_DECREF(a);
3461 Py_DECREF(b);
3462 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003463}
3464
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003465static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003466long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003467{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003468 if (PyLong_CheckExact(v))
3469 Py_INCREF(v);
3470 else
3471 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003472 return v;
3473}
3474
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003475static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003476long_int(PyObject *v)
3477{
Guido van Rossumddefaf32007-01-14 03:31:43 +00003478 return long_long(v);
Walter Dörwaldf1715402002-11-19 20:49:15 +00003479}
3480
3481static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003482long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003483{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003484 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003485 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003486 if (result == -1.0 && PyErr_Occurred())
3487 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003488 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003489}
3490
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003491static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003492long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003493{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00003494 return long_format(v, 8);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003495}
3496
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003497static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003498long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003499{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00003500 return long_format(v, 16);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003501}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003502
3503static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003504long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003505
Tim Peters6d6c1a32001-08-02 04:15:00 +00003506static PyObject *
3507long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3508{
3509 PyObject *x = NULL;
3510 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003511 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003512
Guido van Rossumbef14172001-08-29 15:47:46 +00003513 if (type != &PyLong_Type)
3514 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003515 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003516 &x, &base))
3517 return NULL;
3518 if (x == NULL)
3519 return PyLong_FromLong(0L);
3520 if (base == -909)
3521 return PyNumber_Long(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003522 else if (PyString_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003523 /* Since PyLong_FromString doesn't have a length parameter,
3524 * check here for possible NULs in the string. */
Guido van Rossum4581ae52007-05-22 21:56:47 +00003525 char *string;
3526 int size;
3527 if (PyBytes_Check(x)) {
3528 string = PyBytes_AS_STRING(x);
3529 size = PyBytes_GET_SIZE(x);
3530 }
3531 else {
3532 string = PyString_AS_STRING(x);
3533 size = PyString_GET_SIZE(x);
3534 }
3535 if (strlen(string) != size) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003536 /* create a repr() of the input string,
3537 * just like PyLong_FromString does. */
3538 PyObject *srepr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00003539 srepr = PyObject_ReprStr8(x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003540 if (srepr == NULL)
3541 return NULL;
3542 PyErr_Format(PyExc_ValueError,
3543 "invalid literal for int() with base %d: %s",
3544 base, PyString_AS_STRING(srepr));
3545 Py_DECREF(srepr);
3546 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003547 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003548 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003549 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003550 else if (PyUnicode_Check(x))
3551 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3552 PyUnicode_GET_SIZE(x),
3553 base);
3554 else {
3555 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003556 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003557 return NULL;
3558 }
3559}
3560
Guido van Rossumbef14172001-08-29 15:47:46 +00003561/* Wimpy, slow approach to tp_new calls for subtypes of long:
3562 first create a regular long from whatever arguments we got,
3563 then allocate a subtype instance and initialize it from
3564 the regular long. The regular long is then thrown away.
3565*/
3566static PyObject *
3567long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3568{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003569 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003570 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003571
3572 assert(PyType_IsSubtype(type, &PyLong_Type));
3573 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3574 if (tmp == NULL)
3575 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003576 assert(PyLong_CheckExact(tmp));
Guido van Rossumbef14172001-08-29 15:47:46 +00003577 n = tmp->ob_size;
3578 if (n < 0)
3579 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003580 newobj = (PyLongObject *)type->tp_alloc(type, n);
3581 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003582 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003583 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003584 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003585 assert(PyLong_Check(newobj));
3586 newobj->ob_size = tmp->ob_size;
Guido van Rossumbef14172001-08-29 15:47:46 +00003587 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003588 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003589 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003590 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003591}
3592
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003593static PyObject *
3594long_getnewargs(PyLongObject *v)
3595{
3596 return Py_BuildValue("(N)", _PyLong_Copy(v));
3597}
3598
3599static PyMethodDef long_methods[] = {
3600 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3601 {NULL, NULL} /* sentinel */
3602};
3603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003604PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003605"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003606\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003607Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608point argument will be truncated towards zero (this does not include a\n\
3609string representation of a floating point number!) When converting a\n\
3610string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003611converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003612
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003613static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003614 (binaryfunc) long_add, /*nb_add*/
3615 (binaryfunc) long_sub, /*nb_subtract*/
3616 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003617 long_mod, /*nb_remainder*/
3618 long_divmod, /*nb_divmod*/
3619 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003620 (unaryfunc) long_neg, /*nb_negative*/
3621 (unaryfunc) long_pos, /*tp_positive*/
3622 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003623 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003624 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003625 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003626 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003627 long_and, /*nb_and*/
3628 long_xor, /*nb_xor*/
3629 long_or, /*nb_or*/
Neal Norwitzca810462006-08-29 07:57:59 +00003630 0, /*nb_coerce*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003631 long_int, /*nb_int*/
3632 long_long, /*nb_long*/
3633 long_float, /*nb_float*/
3634 long_oct, /*nb_oct*/
3635 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003636 0, /* nb_inplace_add */
3637 0, /* nb_inplace_subtract */
3638 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003639 0, /* nb_inplace_remainder */
3640 0, /* nb_inplace_power */
3641 0, /* nb_inplace_lshift */
3642 0, /* nb_inplace_rshift */
3643 0, /* nb_inplace_and */
3644 0, /* nb_inplace_xor */
3645 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003646 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003647 long_true_divide, /* nb_true_divide */
3648 0, /* nb_inplace_floor_divide */
3649 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003650 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003651};
3652
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003653PyTypeObject PyLong_Type = {
3654 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003655 0, /* ob_size */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003656 "int", /* tp_name */
3657 /* See _PyLong_New for why this isn't
3658 sizeof(PyLongObject) - sizeof(digit) */
3659 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003660 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003661 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003662 0, /* tp_print */
3663 0, /* tp_getattr */
3664 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003665 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003666 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003667 &long_as_number, /* tp_as_number */
3668 0, /* tp_as_sequence */
3669 0, /* tp_as_mapping */
3670 (hashfunc)long_hash, /* tp_hash */
3671 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003672 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673 PyObject_GenericGetAttr, /* tp_getattro */
3674 0, /* tp_setattro */
3675 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003676 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3677 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003678 long_doc, /* tp_doc */
3679 0, /* tp_traverse */
3680 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003681 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682 0, /* tp_weaklistoffset */
3683 0, /* tp_iter */
3684 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003685 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003686 0, /* tp_members */
3687 0, /* tp_getset */
3688 0, /* tp_base */
3689 0, /* tp_dict */
3690 0, /* tp_descr_get */
3691 0, /* tp_descr_set */
3692 0, /* tp_dictoffset */
3693 0, /* tp_init */
3694 0, /* tp_alloc */
3695 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003696 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003697};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003698
3699int
3700_PyLong_Init(void)
3701{
3702#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3703 int ival;
3704 PyLongObject *v = small_ints;
3705 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3706 PyObject_INIT(v, &PyLong_Type);
3707 v->ob_size = -1;
3708 v->ob_digit[0] = -ival;
3709 }
3710 for (; ival < NSMALLPOSINTS; ival++, v++) {
3711 PyObject_INIT(v, &PyLong_Type);
3712 v->ob_size = ival ? 1 : 0;
3713 v->ob_digit[0] = ival;
3714 }
3715#endif
3716 return 1;
3717}
3718
3719void
3720PyLong_Fini(void)
3721{
3722#if 0
3723 int i;
3724 /* This is currently not needed; the small integers
3725 are statically allocated */
3726#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3727 PyIntObject **q;
3728
3729 i = NSMALLNEGINTS + NSMALLPOSINTS;
3730 q = small_ints;
3731 while (--i >= 0) {
3732 Py_XDECREF(*q);
3733 *q++ = NULL;
3734 }
3735#endif
3736#endif
3737}