blob: 22d4741bcdcb762e1bc328eeba7e1c28fe8b877e [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;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000301 Py_ssize_t i;
302 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000303 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000304
Guido van Rossumddefaf32007-01-14 03:31:43 +0000305 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000306 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000307 return -1;
308 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000309
310 if (!PyLong_Check(vv)) {
311 PyNumberMethods *nb;
312 if ((nb = vv->ob_type->tp_as_number) == NULL ||
313 nb->nb_int == NULL) {
314 PyErr_SetString(PyExc_TypeError, "an integer is required");
315 return -1;
316 }
317 vv = (*nb->nb_int) (vv);
318 if (vv == NULL)
319 return -1;
320 do_decref = 1;
321 if (!PyLong_Check(vv)) {
322 Py_DECREF(vv);
323 PyErr_SetString(PyExc_TypeError,
324 "nb_int should return int object");
325 return -1;
326 }
327 }
328
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000330 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000331 switch (i) {
332 case -1: return -v->ob_digit[0];
333 case 0: return 0;
334 case 1: return v->ob_digit[0];
335 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000336 sign = 1;
337 x = 0;
338 if (i < 0) {
339 sign = -1;
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000340 i = -(i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000341 }
342 while (--i >= 0) {
343 prev = x;
344 x = (x << SHIFT) + v->ob_digit[i];
Guido van Rossumf7531811998-05-26 14:33:37 +0000345 if ((x >> SHIFT) != prev)
346 goto overflow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000347 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000348 if (do_decref) {
349 Py_DECREF(vv);
350 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000351 /* Haven't lost any bits, but casting to long requires extra care
352 * (see comment above).
353 */
354 if (x <= (unsigned long)LONG_MAX) {
355 return (long)x * sign;
356 }
357 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
358 return LONG_MIN;
359 }
360 /* else overflow */
Guido van Rossumf7531811998-05-26 14:33:37 +0000361
362 overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000363 if (do_decref) {
364 Py_DECREF(vv);
365 }
Guido van Rossumf7531811998-05-26 14:33:37 +0000366 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000367 "Python int too large to convert to C long");
Guido van Rossumf7531811998-05-26 14:33:37 +0000368 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000369}
370
Guido van Rossumddefaf32007-01-14 03:31:43 +0000371int
372_PyLong_FitsInLong(PyObject *vv)
373{
374 int size;
375 if (!PyLong_CheckExact(vv)) {
376 PyErr_BadInternalCall();
377 return 0;
378 }
379 /* conservative estimate */
380 size = ((PyLongObject*)vv)->ob_size;
381 return -2 <= size && size <= 2;
382}
383
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000384/* Get a Py_ssize_t from a long int object.
385 Returns -1 and sets an error condition if overflow occurs. */
386
387Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000388PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000389 register PyLongObject *v;
390 size_t x, prev;
391 Py_ssize_t i;
392 int sign;
393
394 if (vv == NULL || !PyLong_Check(vv)) {
395 PyErr_BadInternalCall();
396 return -1;
397 }
398 v = (PyLongObject *)vv;
399 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000400 switch (i) {
401 case -1: return -v->ob_digit[0];
402 case 0: return 0;
403 case 1: return v->ob_digit[0];
404 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000405 sign = 1;
406 x = 0;
407 if (i < 0) {
408 sign = -1;
409 i = -(i);
410 }
411 while (--i >= 0) {
412 prev = x;
413 x = (x << SHIFT) + v->ob_digit[i];
414 if ((x >> SHIFT) != prev)
415 goto overflow;
416 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000417 /* Haven't lost any bits, but casting to a signed type requires
418 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000419 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000420 if (x <= (size_t)PY_SSIZE_T_MAX) {
421 return (Py_ssize_t)x * sign;
422 }
423 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
424 return PY_SSIZE_T_MIN;
425 }
426 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000427
428 overflow:
429 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000430 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000431 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000432}
433
Guido van Rossumd8c80482002-08-13 00:24:58 +0000434/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000435 Returns -1 and sets an error condition if overflow occurs. */
436
437unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000438PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000439{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000440 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000441 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000442 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000443
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000444 if (vv == NULL || !PyLong_Check(vv)) {
445 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000446 return (unsigned long) -1;
447 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000448 v = (PyLongObject *)vv;
Guido van Rossum53756b11997-01-03 17:14:46 +0000449 i = v->ob_size;
450 x = 0;
451 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000453 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000454 return (unsigned long) -1;
455 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000456 switch (i) {
457 case 0: return 0;
458 case 1: return v->ob_digit[0];
459 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000460 while (--i >= 0) {
461 prev = x;
462 x = (x << SHIFT) + v->ob_digit[i];
463 if ((x >> SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000464 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000465 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000466 return (unsigned long) -1;
467 }
468 }
469 return x;
470}
471
472/* Get a C unsigned long int from a long int object.
473 Returns -1 and sets an error condition if overflow occurs. */
474
475size_t
476PyLong_AsSize_t(PyObject *vv)
477{
478 register PyLongObject *v;
479 size_t x, prev;
480 Py_ssize_t i;
481
482 if (vv == NULL || !PyLong_Check(vv)) {
483 PyErr_BadInternalCall();
484 return (unsigned long) -1;
485 }
486 v = (PyLongObject *)vv;
487 i = v->ob_size;
488 x = 0;
489 if (i < 0) {
490 PyErr_SetString(PyExc_OverflowError,
491 "can't convert negative value to size_t");
492 return (size_t) -1;
493 }
494 switch (i) {
495 case 0: return 0;
496 case 1: return v->ob_digit[0];
497 }
498 while (--i >= 0) {
499 prev = x;
500 x = (x << SHIFT) + v->ob_digit[i];
501 if ((x >> SHIFT) != prev) {
502 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000503 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000504 return (unsigned long) -1;
505 }
506 }
507 return x;
508}
509
Thomas Hellera4ea6032003-04-17 18:55:45 +0000510/* Get a C unsigned long int from a long int object, ignoring the high bits.
511 Returns -1 and sets an error condition if an error occurs. */
512
Guido van Rossumddefaf32007-01-14 03:31:43 +0000513static unsigned long
514_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000515{
516 register PyLongObject *v;
517 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000518 Py_ssize_t i;
519 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000520
521 if (vv == NULL || !PyLong_Check(vv)) {
522 PyErr_BadInternalCall();
523 return (unsigned long) -1;
524 }
525 v = (PyLongObject *)vv;
526 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000527 switch (i) {
528 case 0: return 0;
529 case 1: return v->ob_digit[0];
530 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000531 sign = 1;
532 x = 0;
533 if (i < 0) {
534 sign = -1;
535 i = -i;
536 }
537 while (--i >= 0) {
538 x = (x << SHIFT) + v->ob_digit[i];
539 }
540 return x * sign;
541}
542
Guido van Rossumddefaf32007-01-14 03:31:43 +0000543unsigned long
544PyLong_AsUnsignedLongMask(register PyObject *op)
545{
546 PyNumberMethods *nb;
547 PyLongObject *lo;
548 unsigned long val;
549
550 if (op && PyLong_Check(op))
551 return _PyLong_AsUnsignedLongMask(op);
552
553 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
554 nb->nb_int == NULL) {
555 PyErr_SetString(PyExc_TypeError, "an integer is required");
556 return (unsigned long)-1;
557 }
558
559 lo = (PyLongObject*) (*nb->nb_int) (op);
560 if (lo == NULL)
561 return (unsigned long)-1;
562 if (PyLong_Check(lo)) {
563 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
564 Py_DECREF(lo);
565 if (PyErr_Occurred())
566 return (unsigned long)-1;
567 return val;
568 }
569 else
570 {
571 Py_DECREF(lo);
572 PyErr_SetString(PyExc_TypeError,
573 "nb_int should return int object");
574 return (unsigned long)-1;
575 }
576}
577
Tim Peters5b8132f2003-01-31 15:52:05 +0000578int
579_PyLong_Sign(PyObject *vv)
580{
581 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000582
583 assert(v != NULL);
584 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000585
Tim Petersee1a53c2003-02-02 02:57:53 +0000586 return v->ob_size == 0 ? 0 : (v->ob_size < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000587}
588
Tim Petersbaefd9e2003-01-28 20:37:45 +0000589size_t
590_PyLong_NumBits(PyObject *vv)
591{
592 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000593 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000594 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000595
596 assert(v != NULL);
597 assert(PyLong_Check(v));
Guido van Rossum004a65c2003-02-03 15:28:19 +0000598 ndigits = ABS(v->ob_size);
Tim Petersbaefd9e2003-01-28 20:37:45 +0000599 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
600 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000601 digit msd = v->ob_digit[ndigits - 1];
602
Tim Peters5b8132f2003-01-31 15:52:05 +0000603 result = (ndigits - 1) * SHIFT;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000604 if (result / SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000605 goto Overflow;
606 do {
607 ++result;
608 if (result == 0)
609 goto Overflow;
610 msd >>= 1;
611 } while (msd);
612 }
613 return result;
614
615Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000616 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000617 "to express in a platform size_t");
618 return (size_t)-1;
619}
620
Tim Peters2a9b3672001-06-11 21:23:58 +0000621PyObject *
622_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
623 int little_endian, int is_signed)
624{
625 const unsigned char* pstartbyte;/* LSB of bytes */
626 int incr; /* direction to move pstartbyte */
627 const unsigned char* pendbyte; /* MSB of bytes */
628 size_t numsignificantbytes; /* number of bytes that matter */
629 size_t ndigits; /* number of Python long digits */
630 PyLongObject* v; /* result */
631 int idigit = 0; /* next free index in v->ob_digit */
632
633 if (n == 0)
634 return PyLong_FromLong(0L);
635
636 if (little_endian) {
637 pstartbyte = bytes;
638 pendbyte = bytes + n - 1;
639 incr = 1;
640 }
641 else {
642 pstartbyte = bytes + n - 1;
643 pendbyte = bytes;
644 incr = -1;
645 }
646
647 if (is_signed)
648 is_signed = *pendbyte >= 0x80;
649
650 /* Compute numsignificantbytes. This consists of finding the most
651 significant byte. Leading 0 bytes are insignficant if the number
652 is positive, and leading 0xff bytes if negative. */
653 {
654 size_t i;
655 const unsigned char* p = pendbyte;
656 const int pincr = -incr; /* search MSB to LSB */
657 const unsigned char insignficant = is_signed ? 0xff : 0x00;
658
659 for (i = 0; i < n; ++i, p += pincr) {
660 if (*p != insignficant)
661 break;
662 }
663 numsignificantbytes = n - i;
664 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
665 actually has 2 significant bytes. OTOH, 0xff0001 ==
666 -0x00ffff, so we wouldn't *need* to bump it there; but we
667 do for 0xffff = -0x0001. To be safe without bothering to
668 check every case, bump it regardless. */
669 if (is_signed && numsignificantbytes < n)
670 ++numsignificantbytes;
671 }
672
673 /* How many Python long digits do we need? We have
674 8*numsignificantbytes bits, and each Python long digit has SHIFT
675 bits, so it's the ceiling of the quotient. */
676 ndigits = (numsignificantbytes * 8 + SHIFT - 1) / SHIFT;
677 if (ndigits > (size_t)INT_MAX)
678 return PyErr_NoMemory();
679 v = _PyLong_New((int)ndigits);
680 if (v == NULL)
681 return NULL;
682
683 /* Copy the bits over. The tricky parts are computing 2's-comp on
684 the fly for signed numbers, and dealing with the mismatch between
685 8-bit bytes and (probably) 15-bit Python digits.*/
686 {
687 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000688 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000689 twodigits accum = 0; /* sliding register */
690 unsigned int accumbits = 0; /* number of bits in accum */
691 const unsigned char* p = pstartbyte;
692
693 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000694 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000695 /* Compute correction for 2's comp, if needed. */
696 if (is_signed) {
697 thisbyte = (0xff ^ thisbyte) + carry;
698 carry = thisbyte >> 8;
699 thisbyte &= 0xff;
700 }
701 /* Because we're going LSB to MSB, thisbyte is
702 more significant than what's already in accum,
703 so needs to be prepended to accum. */
704 accum |= thisbyte << accumbits;
705 accumbits += 8;
706 if (accumbits >= SHIFT) {
707 /* There's enough to fill a Python digit. */
708 assert(idigit < (int)ndigits);
709 v->ob_digit[idigit] = (digit)(accum & MASK);
710 ++idigit;
711 accum >>= SHIFT;
712 accumbits -= SHIFT;
713 assert(accumbits < SHIFT);
714 }
715 }
716 assert(accumbits < SHIFT);
717 if (accumbits) {
718 assert(idigit < (int)ndigits);
719 v->ob_digit[idigit] = (digit)accum;
720 ++idigit;
721 }
722 }
723
724 v->ob_size = is_signed ? -idigit : idigit;
725 return (PyObject *)long_normalize(v);
726}
727
728int
729_PyLong_AsByteArray(PyLongObject* v,
730 unsigned char* bytes, size_t n,
731 int little_endian, int is_signed)
732{
733 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000734 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000735 twodigits accum; /* sliding register */
736 unsigned int accumbits; /* # bits in accum */
737 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
738 twodigits carry; /* for computing 2's-comp */
739 size_t j; /* # bytes filled */
740 unsigned char* p; /* pointer to next byte in bytes */
741 int pincr; /* direction to move p */
742
743 assert(v != NULL && PyLong_Check(v));
744
745 if (v->ob_size < 0) {
746 ndigits = -(v->ob_size);
747 if (!is_signed) {
748 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000749 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000750 return -1;
751 }
752 do_twos_comp = 1;
753 }
754 else {
755 ndigits = v->ob_size;
756 do_twos_comp = 0;
757 }
758
759 if (little_endian) {
760 p = bytes;
761 pincr = 1;
762 }
763 else {
764 p = bytes + n - 1;
765 pincr = -1;
766 }
767
Tim Peters898cf852001-06-13 20:50:08 +0000768 /* Copy over all the Python digits.
769 It's crucial that every Python digit except for the MSD contribute
770 exactly SHIFT bits to the total, so first assert that the long is
771 normalized. */
772 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000773 j = 0;
774 accum = 0;
775 accumbits = 0;
776 carry = do_twos_comp ? 1 : 0;
777 for (i = 0; i < ndigits; ++i) {
778 twodigits thisdigit = v->ob_digit[i];
779 if (do_twos_comp) {
780 thisdigit = (thisdigit ^ MASK) + carry;
781 carry = thisdigit >> SHIFT;
782 thisdigit &= MASK;
783 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000784 /* Because we're going LSB to MSB, thisdigit is more
785 significant than what's already in accum, so needs to be
786 prepended to accum. */
787 accum |= thisdigit << accumbits;
Tim Petersede05092001-06-14 08:53:38 +0000788 accumbits += SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000789
Tim Petersede05092001-06-14 08:53:38 +0000790 /* The most-significant digit may be (probably is) at least
791 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000792 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000793 /* Count # of sign bits -- they needn't be stored,
794 * although for signed conversion we need later to
795 * make sure at least one sign bit gets stored.
796 * First shift conceptual sign bit to real sign bit.
797 */
798 stwodigits s = (stwodigits)(thisdigit <<
799 (8*sizeof(stwodigits) - SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000800 unsigned int nsignbits = 0;
Tim Petersede05092001-06-14 08:53:38 +0000801 while ((s < 0) == do_twos_comp && nsignbits < SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000802 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000803 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000804 }
Tim Petersede05092001-06-14 08:53:38 +0000805 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000806 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000807
Tim Peters2a9b3672001-06-11 21:23:58 +0000808 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000809 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000810 if (j >= n)
811 goto Overflow;
812 ++j;
813 *p = (unsigned char)(accum & 0xff);
814 p += pincr;
815 accumbits -= 8;
816 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000817 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000818 }
819
820 /* Store the straggler (if any). */
821 assert(accumbits < 8);
822 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000823 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000824 if (j >= n)
825 goto Overflow;
826 ++j;
827 if (do_twos_comp) {
828 /* Fill leading bits of the byte with sign bits
829 (appropriately pretending that the long had an
830 infinite supply of sign bits). */
831 accum |= (~(twodigits)0) << accumbits;
832 }
833 *p = (unsigned char)(accum & 0xff);
834 p += pincr;
835 }
Tim Peters05607ad2001-06-13 21:01:27 +0000836 else if (j == n && n > 0 && is_signed) {
837 /* The main loop filled the byte array exactly, so the code
838 just above didn't get to ensure there's a sign bit, and the
839 loop below wouldn't add one either. Make sure a sign bit
840 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000841 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000842 int sign_bit_set = msb >= 0x80;
843 assert(accumbits == 0);
844 if (sign_bit_set == do_twos_comp)
845 return 0;
846 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000847 goto Overflow;
848 }
Tim Peters05607ad2001-06-13 21:01:27 +0000849
850 /* Fill remaining bytes with copies of the sign bit. */
851 {
852 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
853 for ( ; j < n; ++j, p += pincr)
854 *p = signbyte;
855 }
856
Tim Peters2a9b3672001-06-11 21:23:58 +0000857 return 0;
858
859Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000860 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000861 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000862
Tim Peters2a9b3672001-06-11 21:23:58 +0000863}
864
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000865double
866_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
867{
868/* NBITS_WANTED should be > the number of bits in a double's precision,
869 but small enough so that 2**NBITS_WANTED is within the normal double
870 range. nbitsneeded is set to 1 less than that because the most-significant
871 Python digit contains at least 1 significant bit, but we don't want to
872 bother counting them (catering to the worst case cheaply).
873
874 57 is one more than VAX-D double precision; I (Tim) don't know of a double
875 format with more precision than that; it's 1 larger so that we add in at
876 least one round bit to stand in for the ignored least-significant bits.
877*/
878#define NBITS_WANTED 57
879 PyLongObject *v;
880 double x;
881 const double multiplier = (double)(1L << SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000882 Py_ssize_t i;
883 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000884 int nbitsneeded;
885
886 if (vv == NULL || !PyLong_Check(vv)) {
887 PyErr_BadInternalCall();
888 return -1;
889 }
890 v = (PyLongObject *)vv;
891 i = v->ob_size;
892 sign = 1;
893 if (i < 0) {
894 sign = -1;
895 i = -(i);
896 }
897 else if (i == 0) {
898 *exponent = 0;
899 return 0.0;
900 }
901 --i;
902 x = (double)v->ob_digit[i];
903 nbitsneeded = NBITS_WANTED - 1;
904 /* Invariant: i Python digits remain unaccounted for. */
905 while (i > 0 && nbitsneeded > 0) {
906 --i;
907 x = x * multiplier + (double)v->ob_digit[i];
908 nbitsneeded -= SHIFT;
909 }
910 /* There are i digits we didn't shift in. Pretending they're all
911 zeroes, the true value is x * 2**(i*SHIFT). */
912 *exponent = i;
913 assert(x > 0.0);
914 return x * sign;
915#undef NBITS_WANTED
916}
917
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000918/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000919
920double
Tim Peters9f688bf2000-07-07 15:53:28 +0000921PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000922{
Thomas Wouters553489a2006-02-01 21:32:04 +0000923 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000924 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000925
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000926 if (vv == NULL || !PyLong_Check(vv)) {
927 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000928 return -1;
929 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000930 x = _PyLong_AsScaledDouble(vv, &e);
931 if (x == -1.0 && PyErr_Occurred())
932 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000933 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
934 set correctly after a successful _PyLong_AsScaledDouble() call */
935 assert(e >= 0);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000936 if (e > INT_MAX / SHIFT)
937 goto overflow;
938 errno = 0;
939 x = ldexp(x, e * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000940 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000941 goto overflow;
942 return x;
943
944overflow:
945 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000946 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000947 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000948}
949
Guido van Rossum78694d91998-09-18 14:14:13 +0000950/* Create a new long (or int) object from a C pointer */
951
952PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000953PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000954{
Tim Peters70128a12001-06-16 08:48:40 +0000955#ifndef HAVE_LONG_LONG
956# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
957#endif
958#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000959# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000960#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000961 /* special-case null pointer */
962 if (!p)
Tim Peters70128a12001-06-16 08:48:40 +0000963 return PyInt_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000964 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000965
Guido van Rossum78694d91998-09-18 14:14:13 +0000966}
967
968/* Get a C pointer from a long object (or an int object in some cases) */
969
970void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000971PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000972{
973 /* This function will allow int or long objects. If vv is neither,
974 then the PyLong_AsLong*() functions will raise the exception:
975 PyExc_SystemError, "bad argument to internal function"
976 */
Tim Peters70128a12001-06-16 08:48:40 +0000977#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000978 long x;
979
Guido van Rossumddefaf32007-01-14 03:31:43 +0000980 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000981 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000982 else
983 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000984#else
Tim Peters70128a12001-06-16 08:48:40 +0000985
986#ifndef HAVE_LONG_LONG
987# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
988#endif
989#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000990# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000991#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000992 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000993
Guido van Rossumddefaf32007-01-14 03:31:43 +0000994 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000995 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000996 else
997 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000998
999#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001000
1001 if (x == -1 && PyErr_Occurred())
1002 return NULL;
1003 return (void *)x;
1004}
1005
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001006#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001007
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001008/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001009 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001010 */
1011
Tim Peterscf37dfc2001-06-14 18:42:50 +00001012#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001013
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001014/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001015
1016PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001017PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001018{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001019 PyLongObject *v;
1020 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1021 int ndigits = 0;
1022 int negative = 0;
1023
Guido van Rossumddefaf32007-01-14 03:31:43 +00001024 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001025 if (ival < 0) {
1026 ival = -ival;
1027 negative = 1;
1028 }
1029
1030 /* Count the number of Python digits.
1031 We used to pick 5 ("big enough for anything"), but that's a
1032 waste of time and space given that 5*15 = 75 bits are rarely
1033 needed. */
1034 t = (unsigned PY_LONG_LONG)ival;
1035 while (t) {
1036 ++ndigits;
1037 t >>= SHIFT;
1038 }
1039 v = _PyLong_New(ndigits);
1040 if (v != NULL) {
1041 digit *p = v->ob_digit;
1042 v->ob_size = negative ? -ndigits : ndigits;
1043 t = (unsigned PY_LONG_LONG)ival;
1044 while (t) {
1045 *p++ = (digit)(t & MASK);
1046 t >>= SHIFT;
1047 }
1048 }
1049 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001050}
1051
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001052/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001053
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001054PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001055PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001056{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001057 PyLongObject *v;
1058 unsigned PY_LONG_LONG t;
1059 int ndigits = 0;
1060
Guido van Rossumddefaf32007-01-14 03:31:43 +00001061 if (ival < BASE)
1062 return PyLong_FromLong(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001063 /* Count the number of Python digits. */
1064 t = (unsigned PY_LONG_LONG)ival;
1065 while (t) {
1066 ++ndigits;
1067 t >>= SHIFT;
1068 }
1069 v = _PyLong_New(ndigits);
1070 if (v != NULL) {
1071 digit *p = v->ob_digit;
1072 v->ob_size = ndigits;
1073 while (ival) {
1074 *p++ = (digit)(ival & MASK);
1075 ival >>= SHIFT;
1076 }
1077 }
1078 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001079}
1080
Martin v. Löwis18e16552006-02-15 17:27:45 +00001081/* Create a new long int object from a C Py_ssize_t. */
1082
1083PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001084PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001085{
1086 Py_ssize_t bytes = ival;
1087 int one = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001088 if (ival < BASE)
1089 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001090 return _PyLong_FromByteArray(
1091 (unsigned char *)&bytes,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001092 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001093}
1094
1095/* Create a new long int object from a C size_t. */
1096
1097PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001098PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001099{
1100 size_t bytes = ival;
1101 int one = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001102 if (ival < BASE)
1103 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001104 return _PyLong_FromByteArray(
1105 (unsigned char *)&bytes,
1106 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
1107}
1108
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001109/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001110 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001111
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001112PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001113PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001114{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001115 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001116 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001117 int one = 1;
1118 int res;
1119
Tim Petersd38b1c72001-09-30 05:09:37 +00001120 if (vv == NULL) {
1121 PyErr_BadInternalCall();
1122 return -1;
1123 }
1124 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001125 PyNumberMethods *nb;
1126 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001127 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1128 nb->nb_int == NULL) {
1129 PyErr_SetString(PyExc_TypeError, "an integer is required");
1130 return -1;
1131 }
1132 io = (*nb->nb_int) (vv);
1133 if (io == NULL)
1134 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001135 if (PyLong_Check(io)) {
1136 bytes = PyLong_AsLongLong(io);
1137 Py_DECREF(io);
1138 return bytes;
1139 }
1140 Py_DECREF(io);
1141 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001142 return -1;
1143 }
1144
Guido van Rossumddefaf32007-01-14 03:31:43 +00001145 v = (PyLongObject*)vv;
1146 switch(v->ob_size) {
1147 case -1: return -v->ob_digit[0];
1148 case 0: return 0;
1149 case 1: return v->ob_digit[0];
1150 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001151 res = _PyLong_AsByteArray(
1152 (PyLongObject *)vv, (unsigned char *)&bytes,
1153 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001154
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001155 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001156 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001157 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001158 else
1159 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001160}
1161
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001162/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001163 Return -1 and set an error if overflow occurs. */
1164
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001165unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001166PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001167{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001168 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001169 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001170 int one = 1;
1171 int res;
1172
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001173 if (vv == NULL || !PyLong_Check(vv)) {
1174 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001175 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001176 }
1177
Guido van Rossumddefaf32007-01-14 03:31:43 +00001178 v = (PyLongObject*)vv;
1179 switch(v->ob_size) {
1180 case 0: return 0;
1181 case 1: return v->ob_digit[0];
1182 }
1183
Tim Petersd1a7da62001-06-13 00:35:57 +00001184 res = _PyLong_AsByteArray(
1185 (PyLongObject *)vv, (unsigned char *)&bytes,
1186 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001187
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001188 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001189 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001190 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001191 else
1192 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001193}
Tim Petersd1a7da62001-06-13 00:35:57 +00001194
Thomas Hellera4ea6032003-04-17 18:55:45 +00001195/* Get a C unsigned long int from a long int object, ignoring the high bits.
1196 Returns -1 and sets an error condition if an error occurs. */
1197
Guido van Rossumddefaf32007-01-14 03:31:43 +00001198static unsigned PY_LONG_LONG
1199_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001200{
1201 register PyLongObject *v;
1202 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001203 Py_ssize_t i;
1204 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001205
1206 if (vv == NULL || !PyLong_Check(vv)) {
1207 PyErr_BadInternalCall();
1208 return (unsigned long) -1;
1209 }
1210 v = (PyLongObject *)vv;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001211 switch(v->ob_size) {
1212 case 0: return 0;
1213 case 1: return v->ob_digit[0];
1214 }
Thomas Hellera4ea6032003-04-17 18:55:45 +00001215 i = v->ob_size;
1216 sign = 1;
1217 x = 0;
1218 if (i < 0) {
1219 sign = -1;
1220 i = -i;
1221 }
1222 while (--i >= 0) {
1223 x = (x << SHIFT) + v->ob_digit[i];
1224 }
1225 return x * sign;
1226}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001227
1228unsigned PY_LONG_LONG
1229PyLong_AsUnsignedLongLongMask(register PyObject *op)
1230{
1231 PyNumberMethods *nb;
1232 PyLongObject *lo;
1233 unsigned PY_LONG_LONG val;
1234
1235 if (op && PyLong_Check(op))
1236 return _PyLong_AsUnsignedLongLongMask(op);
1237
1238 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1239 nb->nb_int == NULL) {
1240 PyErr_SetString(PyExc_TypeError, "an integer is required");
1241 return (unsigned PY_LONG_LONG)-1;
1242 }
1243
1244 lo = (PyLongObject*) (*nb->nb_int) (op);
1245 if (lo == NULL)
1246 return (unsigned PY_LONG_LONG)-1;
1247 if (PyLong_Check(lo)) {
1248 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1249 Py_DECREF(lo);
1250 if (PyErr_Occurred())
1251 return (unsigned PY_LONG_LONG)-1;
1252 return val;
1253 }
1254 else
1255 {
1256 Py_DECREF(lo);
1257 PyErr_SetString(PyExc_TypeError,
1258 "nb_int should return int object");
1259 return (unsigned PY_LONG_LONG)-1;
1260 }
1261}
Tim Petersd1a7da62001-06-13 00:35:57 +00001262#undef IS_LITTLE_ENDIAN
1263
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001264#endif /* HAVE_LONG_LONG */
1265
Neil Schemenauerba872e22001-01-04 01:46:03 +00001266
1267static int
1268convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001269 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001270 *a = (PyLongObject *) v;
1271 Py_INCREF(v);
1272 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001273 else {
1274 return 0;
1275 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001276 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001277 *b = (PyLongObject *) w;
1278 Py_INCREF(w);
1279 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001280 else {
1281 Py_DECREF(*a);
1282 return 0;
1283 }
1284 return 1;
1285}
1286
1287#define CONVERT_BINOP(v, w, a, b) \
1288 if (!convert_binop(v, w, a, b)) { \
1289 Py_INCREF(Py_NotImplemented); \
1290 return Py_NotImplemented; \
1291 }
1292
Tim Peters877a2122002-08-12 05:09:36 +00001293/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1294 * is modified in place, by adding y to it. Carries are propagated as far as
1295 * x[m-1], and the remaining carry (0 or 1) is returned.
1296 */
1297static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001298v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001299{
1300 int i;
1301 digit carry = 0;
1302
1303 assert(m >= n);
1304 for (i = 0; i < n; ++i) {
1305 carry += x[i] + y[i];
1306 x[i] = carry & MASK;
1307 carry >>= SHIFT;
1308 assert((carry & 1) == carry);
1309 }
1310 for (; carry && i < m; ++i) {
1311 carry += x[i];
1312 x[i] = carry & MASK;
1313 carry >>= SHIFT;
1314 assert((carry & 1) == carry);
1315 }
1316 return carry;
1317}
1318
1319/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1320 * is modified in place, by subtracting y from it. Borrows are propagated as
1321 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1322 */
1323static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001324v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001325{
1326 int i;
1327 digit borrow = 0;
1328
1329 assert(m >= n);
1330 for (i = 0; i < n; ++i) {
1331 borrow = x[i] - y[i] - borrow;
1332 x[i] = borrow & MASK;
1333 borrow >>= SHIFT;
1334 borrow &= 1; /* keep only 1 sign bit */
1335 }
1336 for (; borrow && i < m; ++i) {
1337 borrow = x[i] - borrow;
1338 x[i] = borrow & MASK;
1339 borrow >>= SHIFT;
1340 borrow &= 1;
1341 }
1342 return borrow;
1343}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001344
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001345/* Multiply by a single digit, ignoring the sign. */
1346
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001347static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001348mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001349{
1350 return muladd1(a, n, (digit)0);
1351}
1352
1353/* Multiply by a single digit and add a single digit, ignoring the sign. */
1354
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001355static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001356muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001357{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001358 Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001359 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001360 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001361 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001362
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001363 if (z == NULL)
1364 return NULL;
1365 for (i = 0; i < size_a; ++i) {
1366 carry += (twodigits)a->ob_digit[i] * n;
Guido van Rossum2095d241997-04-09 19:41:24 +00001367 z->ob_digit[i] = (digit) (carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001368 carry >>= SHIFT;
1369 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001370 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001371 return long_normalize(z);
1372}
1373
Tim Peters212e6142001-07-14 12:23:19 +00001374/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1375 in pout, and returning the remainder. pin and pout point at the LSD.
1376 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1377 long_format, but that should be done with great care since longs are
1378 immutable. */
1379
1380static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001381inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001382{
1383 twodigits rem = 0;
1384
1385 assert(n > 0 && n <= MASK);
1386 pin += size;
1387 pout += size;
1388 while (--size >= 0) {
1389 digit hi;
1390 rem = (rem << SHIFT) + *--pin;
1391 *--pout = hi = (digit)(rem / n);
1392 rem -= hi * n;
1393 }
1394 return (digit)rem;
1395}
1396
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001397/* Divide a long integer by a digit, returning both the quotient
1398 (as function result) and the remainder (through *prem).
1399 The sign of a is ignored; n should not be zero. */
1400
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001401static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001402divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001403{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001404 const Py_ssize_t size = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001405 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001406
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001407 assert(n > 0 && n <= MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001408 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001409 if (z == NULL)
1410 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001411 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001412 return long_normalize(z);
1413}
1414
1415/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001416 Return a string object.
Fred Drake121ee271999-12-23 15:41:28 +00001417 If base is 8 or 16, add the proper prefix '0' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001418
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001419static PyObject *
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00001420long_format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001421{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001422 register PyLongObject *a = (PyLongObject *)aa;
1423 PyStringObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001424 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001425 Py_ssize_t size_a;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001426 char *p;
1427 int bits;
1428 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001429
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001430 if (a == NULL || !PyLong_Check(a)) {
1431 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001432 return NULL;
1433 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001434 assert(base >= 2 && base <= 36);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001435 size_a = ABS(a->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001436
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001437 /* Compute a rough upper bound for the length of the string */
1438 i = base;
1439 bits = 0;
1440 while (i > 1) {
1441 ++bits;
1442 i >>= 1;
1443 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001444 i = 5;
1445 j = size_a*SHIFT + bits-1;
1446 sz = i + j / bits;
1447 if (j / SHIFT < size_a || sz < i) {
1448 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001449 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001450 return NULL;
1451 }
1452 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001453 if (str == NULL)
1454 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001455 p = PyString_AS_STRING(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001456 *p = '\0';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001457 if (a->ob_size < 0)
1458 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001459
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001460 if (a->ob_size == 0) {
1461 *--p = '0';
1462 }
1463 else if ((base & (base - 1)) == 0) {
1464 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001465 twodigits accum = 0;
1466 int accumbits = 0; /* # of bits in accum */
1467 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001468 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001469 while ((i >>= 1) > 1)
1470 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001471
1472 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001473 accum |= (twodigits)a->ob_digit[i] << accumbits;
Tim Peters586b2e32001-07-15 09:11:14 +00001474 accumbits += SHIFT;
1475 assert(accumbits >= basebits);
1476 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001477 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001478 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001479 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001480 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001481 accumbits -= basebits;
1482 accum >>= basebits;
1483 } while (i < size_a-1 ? accumbits >= basebits :
1484 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001485 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001486 }
1487 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001488 /* Not 0, and base not a power of 2. Divide repeatedly by
1489 base, but for speed use the highest power of base that
1490 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001491 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001492 digit *pin = a->ob_digit;
1493 PyLongObject *scratch;
1494 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001495 digit powbase = base; /* powbase == base ** power */
1496 int power = 1;
1497 for (;;) {
1498 unsigned long newpow = powbase * (unsigned long)base;
1499 if (newpow >> SHIFT) /* doesn't fit in a digit */
1500 break;
1501 powbase = (digit)newpow;
1502 ++power;
1503 }
Tim Peters212e6142001-07-14 12:23:19 +00001504
1505 /* Get a scratch area for repeated division. */
1506 scratch = _PyLong_New(size);
1507 if (scratch == NULL) {
1508 Py_DECREF(str);
1509 return NULL;
1510 }
1511
1512 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001513 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001514 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001515 digit rem = inplace_divrem1(scratch->ob_digit,
1516 pin, size, powbase);
1517 pin = scratch->ob_digit; /* no need to use a again */
1518 if (pin[size - 1] == 0)
1519 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001520 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001521 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001522 Py_DECREF(str);
1523 return NULL;
1524 })
Tim Peters212e6142001-07-14 12:23:19 +00001525
1526 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001527 assert(ntostore > 0);
1528 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001529 digit nextrem = (digit)(rem / base);
1530 char c = (char)(rem - nextrem * base);
1531 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001532 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001533 *--p = c;
1534 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001535 --ntostore;
1536 /* Termination is a bit delicate: must not
1537 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001538 remaining quotient and rem are both 0. */
1539 } while (ntostore && (size || rem));
1540 } while (size != 0);
1541 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001542 }
1543
Guido van Rossum2c475421992-08-14 15:13:07 +00001544 if (base == 8) {
1545 if (size_a != 0)
1546 *--p = '0';
1547 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001548 else if (base == 16) {
1549 *--p = 'x';
1550 *--p = '0';
1551 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001552 else if (base != 10) {
1553 *--p = '#';
1554 *--p = '0' + base%10;
1555 if (base > 10)
1556 *--p = '0' + base/10;
1557 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001558 if (sign)
1559 *--p = sign;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001560 if (p != PyString_AS_STRING(str)) {
1561 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001562 assert(p > q);
1563 do {
1564 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001565 q--;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001566 _PyString_Resize((PyObject **)&str,
Thomas Wouters89f507f2006-12-13 04:49:30 +00001567 (Py_ssize_t) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001568 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001569 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001570}
1571
Thomas Wouters477c8d52006-05-27 19:21:47 +00001572/* Table of digit values for 8-bit string -> integer conversion.
1573 * '0' maps to 0, ..., '9' maps to 9.
1574 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1575 * All other indices map to 37.
1576 * Note that when converting a base B string, a char c is a legitimate
1577 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1578 */
1579int _PyLong_DigitValue[256] = {
1580 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1581 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1582 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1583 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1584 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1585 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1586 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1587 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1588 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1589 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1590 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1591 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1592 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 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1596};
1597
1598/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001599 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1600 * non-digit (which may be *str!). A normalized long is returned.
1601 * The point to this routine is that it takes time linear in the number of
1602 * string characters.
1603 */
1604static PyLongObject *
1605long_from_binary_base(char **str, int base)
1606{
1607 char *p = *str;
1608 char *start = p;
1609 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001610 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001611 PyLongObject *z;
1612 twodigits accum;
1613 int bits_in_accum;
1614 digit *pdigit;
1615
1616 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1617 n = base;
1618 for (bits_per_char = -1; n; ++bits_per_char)
1619 n >>= 1;
1620 /* n <- total # of bits needed, while setting p to end-of-string */
1621 n = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001622 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001623 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001624 *str = p;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001625 /* n <- # of Python digits needed, = ceiling(n/SHIFT). */
1626 n = (p - start) * bits_per_char + SHIFT - 1;
1627 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001628 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001629 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001630 return NULL;
1631 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001632 n = n / SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001633 z = _PyLong_New(n);
1634 if (z == NULL)
1635 return NULL;
1636 /* Read string from right, and fill in long from left; i.e.,
1637 * from least to most significant in both.
1638 */
1639 accum = 0;
1640 bits_in_accum = 0;
1641 pdigit = z->ob_digit;
1642 while (--p >= start) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001643 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001644 assert(k >= 0 && k < base);
1645 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001646 bits_in_accum += bits_per_char;
1647 if (bits_in_accum >= SHIFT) {
1648 *pdigit++ = (digit)(accum & MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001649 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001650 accum >>= SHIFT;
1651 bits_in_accum -= SHIFT;
1652 assert(bits_in_accum < SHIFT);
1653 }
1654 }
1655 if (bits_in_accum) {
1656 assert(bits_in_accum <= SHIFT);
1657 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001658 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001659 }
1660 while (pdigit - z->ob_digit < n)
1661 *pdigit++ = 0;
1662 return long_normalize(z);
1663}
1664
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001665PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001666PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001667{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001668 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001669 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001670 PyLongObject *z;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001671 PyObject *strobj, *strrepr;
1672 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001673
Guido van Rossum472c04f1996-12-05 21:57:21 +00001674 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001675 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001676 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001677 return NULL;
1678 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001679 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001680 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001681 if (*str == '+')
1682 ++str;
1683 else if (*str == '-') {
1684 ++str;
1685 sign = -1;
1686 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001687 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001688 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001689 if (base == 0) {
1690 if (str[0] != '0')
1691 base = 10;
1692 else if (str[1] == 'x' || str[1] == 'X')
1693 base = 16;
1694 else
1695 base = 8;
1696 }
1697 if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
1698 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001699
Guido van Rossume6762971998-06-22 03:54:46 +00001700 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001701 if ((base & (base - 1)) == 0)
1702 z = long_from_binary_base(&str, base);
1703 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001704/***
1705Binary bases can be converted in time linear in the number of digits, because
1706Python's representation base is binary. Other bases (including decimal!) use
1707the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001708
Thomas Wouters477c8d52006-05-27 19:21:47 +00001709First some math: the largest integer that can be expressed in N base-B digits
1710is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1711case number of Python digits needed to hold it is the smallest integer n s.t.
1712
1713 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1714 BASE**n >= B**N [taking logs to base BASE]
1715 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1716
1717The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1718this quickly. A Python long with that much space is reserved near the start,
1719and the result is computed into it.
1720
1721The input string is actually treated as being in base base**i (i.e., i digits
1722are processed at a time), where two more static arrays hold:
1723
1724 convwidth_base[base] = the largest integer i such that base**i <= BASE
1725 convmultmax_base[base] = base ** convwidth_base[base]
1726
1727The first of these is the largest i such that i consecutive input digits
1728must fit in a single Python digit. The second is effectively the input
1729base we're really using.
1730
1731Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1732convmultmax_base[base], the result is "simply"
1733
1734 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1735
1736where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001737
1738Error analysis: as above, the number of Python digits `n` needed is worst-
1739case
1740
1741 n >= N * log(B)/log(BASE)
1742
1743where `N` is the number of input digits in base `B`. This is computed via
1744
1745 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1746
1747below. Two numeric concerns are how much space this can waste, and whether
1748the computed result can be too small. To be concrete, assume BASE = 2**15,
1749which is the default (and it's unlikely anyone changes that).
1750
1751Waste isn't a problem: provided the first input digit isn't 0, the difference
1752between the worst-case input with N digits and the smallest input with N
1753digits is about a factor of B, but B is small compared to BASE so at most
1754one allocated Python digit can remain unused on that count. If
1755N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1756and adding 1 returns a result 1 larger than necessary. However, that can't
1757happen: whenever B is a power of 2, long_from_binary_base() is called
1758instead, and it's impossible for B**i to be an integer power of 2**15 when
1759B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1760an exact integer when B is not a power of 2, since B**i has a prime factor
1761other than 2 in that case, but (2**15)**j's only prime factor is 2).
1762
1763The computed result can be too small if the true value of N*log(B)/log(BASE)
1764is a little bit larger than an exact integer, but due to roundoff errors (in
1765computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1766yields a numeric result a little less than that integer. Unfortunately, "how
1767close can a transcendental function get to an integer over some range?"
1768questions are generally theoretically intractable. Computer analysis via
1769continued fractions is practical: expand log(B)/log(BASE) via continued
1770fractions, giving a sequence i/j of "the best" rational approximations. Then
1771j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1772we can get very close to being in trouble, but very rarely. For example,
177376573 is a denominator in one of the continued-fraction approximations to
1774log(10)/log(2**15), and indeed:
1775
1776 >>> log(10)/log(2**15)*76573
1777 16958.000000654003
1778
1779is very close to an integer. If we were working with IEEE single-precision,
1780rounding errors could kill us. Finding worst cases in IEEE double-precision
1781requires better-than-double-precision log() functions, and Tim didn't bother.
1782Instead the code checks to see whether the allocated space is enough as each
1783new Python digit is added, and copies the whole thing to a larger long if not.
1784This should happen extremely rarely, and in fact I don't have a test case
1785that triggers it(!). Instead the code was tested by artificially allocating
1786just 1 digit at the start, so that the copying code was exercised for every
1787digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001788***/
1789 register twodigits c; /* current input character */
1790 Py_ssize_t size_z;
1791 int i;
1792 int convwidth;
1793 twodigits convmultmax, convmult;
1794 digit *pz, *pzstop;
1795 char* scan;
1796
1797 static double log_base_BASE[37] = {0.0e0,};
1798 static int convwidth_base[37] = {0,};
1799 static twodigits convmultmax_base[37] = {0,};
1800
1801 if (log_base_BASE[base] == 0.0) {
1802 twodigits convmax = base;
1803 int i = 1;
1804
1805 log_base_BASE[base] = log((double)base) /
1806 log((double)BASE);
1807 for (;;) {
1808 twodigits next = convmax * base;
1809 if (next > BASE)
1810 break;
1811 convmax = next;
1812 ++i;
1813 }
1814 convmultmax_base[base] = convmax;
1815 assert(i > 0);
1816 convwidth_base[base] = i;
1817 }
1818
1819 /* Find length of the string of numeric characters. */
1820 scan = str;
1821 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1822 ++scan;
1823
1824 /* Create a long object that can contain the largest possible
1825 * integer with this base and length. Note that there's no
1826 * need to initialize z->ob_digit -- no slot is read up before
1827 * being stored into.
1828 */
1829 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001830 /* Uncomment next line to test exceedingly rare copy code */
1831 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001832 assert(size_z > 0);
1833 z = _PyLong_New(size_z);
1834 if (z == NULL)
1835 return NULL;
1836 z->ob_size = 0;
1837
1838 /* `convwidth` consecutive input digits are treated as a single
1839 * digit in base `convmultmax`.
1840 */
1841 convwidth = convwidth_base[base];
1842 convmultmax = convmultmax_base[base];
1843
1844 /* Work ;-) */
1845 while (str < scan) {
1846 /* grab up to convwidth digits from the input string */
1847 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1848 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1849 c = (twodigits)(c * base +
1850 _PyLong_DigitValue[Py_CHARMASK(*str)]);
1851 assert(c < BASE);
1852 }
1853
1854 convmult = convmultmax;
1855 /* Calculate the shift only if we couldn't get
1856 * convwidth digits.
1857 */
1858 if (i != convwidth) {
1859 convmult = base;
1860 for ( ; i > 1; --i)
1861 convmult *= base;
1862 }
1863
1864 /* Multiply z by convmult, and add c. */
1865 pz = z->ob_digit;
1866 pzstop = pz + z->ob_size;
1867 for (; pz < pzstop; ++pz) {
1868 c += (twodigits)*pz * convmult;
1869 *pz = (digit)(c & MASK);
1870 c >>= SHIFT;
1871 }
1872 /* carry off the current end? */
1873 if (c) {
1874 assert(c < BASE);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001875 if (z->ob_size < size_z) {
1876 *pz = (digit)c;
1877 ++z->ob_size;
1878 }
1879 else {
1880 PyLongObject *tmp;
1881 /* Extremely rare. Get more space. */
1882 assert(z->ob_size == size_z);
1883 tmp = _PyLong_New(size_z + 1);
1884 if (tmp == NULL) {
1885 Py_DECREF(z);
1886 return NULL;
1887 }
1888 memcpy(tmp->ob_digit,
1889 z->ob_digit,
1890 sizeof(digit) * size_z);
1891 Py_DECREF(z);
1892 z = tmp;
1893 z->ob_digit[size_z] = (digit)c;
1894 ++size_z;
1895 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001896 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001897 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001898 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001899 if (z == NULL)
1900 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001901 if (str == start)
1902 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001903 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001904 z->ob_size = -(z->ob_size);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001905 if (*str == 'L' || *str == 'l')
1906 str++;
1907 while (*str && isspace(Py_CHARMASK(*str)))
1908 str++;
1909 if (*str != '\0')
1910 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001911 if (pend)
1912 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001913 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001914
1915 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001916 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001917 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1918 strobj = PyString_FromStringAndSize(orig_str, slen);
1919 if (strobj == NULL)
1920 return NULL;
1921 strrepr = PyObject_Repr(strobj);
1922 Py_DECREF(strobj);
1923 if (strrepr == NULL)
1924 return NULL;
1925 PyErr_Format(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001926 "invalid literal for int() with base %d: %s",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001927 base, PyString_AS_STRING(strrepr));
1928 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001929 return NULL;
1930}
1931
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001932#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001933PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001934PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001935{
Walter Dörwald07e14762002-11-06 16:15:14 +00001936 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001937 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001938
Walter Dörwald07e14762002-11-06 16:15:14 +00001939 if (buffer == NULL)
1940 return NULL;
1941
1942 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1943 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001944 return NULL;
1945 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001946 result = PyLong_FromString(buffer, NULL, base);
1947 PyMem_FREE(buffer);
1948 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001949}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001950#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001951
Tim Peters9f688bf2000-07-07 15:53:28 +00001952/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001953static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001954 (PyLongObject *, PyLongObject *, PyLongObject **);
1955static PyObject *long_pos(PyLongObject *);
1956static int long_divrem(PyLongObject *, PyLongObject *,
1957 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001958
1959/* Long division with remainder, top-level routine */
1960
Guido van Rossume32e0141992-01-19 16:31:05 +00001961static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001962long_divrem(PyLongObject *a, PyLongObject *b,
1963 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001964{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001965 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001966 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001967
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001968 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001969 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001970 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001971 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001972 }
1973 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001974 (size_a == size_b &&
1975 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001976 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00001977 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001978 Py_INCREF(a);
1979 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001980 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001981 }
1982 if (size_b == 1) {
1983 digit rem = 0;
1984 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001985 if (z == NULL)
1986 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001987 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001988 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001989 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001990 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001991 if (z == NULL)
1992 return -1;
1993 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001994 /* Set the signs.
1995 The quotient z has the sign of a*b;
1996 the remainder r has the sign of a,
1997 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001998 if ((a->ob_size < 0) != (b->ob_size < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00001999 NEGATE(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002000 if (a->ob_size < 0 && (*prem)->ob_size != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002001 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002002 *pdiv = z;
2003 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002004}
2005
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002006/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002007
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002008static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002009x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002010{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002011 Py_ssize_t size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size);
Guido van Rossum2095d241997-04-09 19:41:24 +00002012 digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002013 PyLongObject *v = mul1(v1, d);
2014 PyLongObject *w = mul1(w1, d);
2015 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002016 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002017
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002018 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002019 Py_XDECREF(v);
2020 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002021 return NULL;
2022 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002023
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002024 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002025 assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002026 assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002027
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002028 size_v = ABS(v->ob_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002029 k = size_v - size_w;
2030 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002031
Thomas Wouters477c8d52006-05-27 19:21:47 +00002032 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002033 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2034 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002035 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002036 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002037
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002038 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002039 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002040 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002041 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002042 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002043 if (vj == w->ob_digit[size_w-1])
2044 q = MASK;
2045 else
2046 q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
2047 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002048
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002049 while (w->ob_digit[size_w-2]*q >
2050 ((
2051 ((twodigits)vj << SHIFT)
2052 + v->ob_digit[j-1]
2053 - q*w->ob_digit[size_w-1]
2054 ) << SHIFT)
2055 + v->ob_digit[j-2])
2056 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002057
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002058 for (i = 0; i < size_w && i+k < size_v; ++i) {
2059 twodigits z = w->ob_digit[i] * q;
Guido van Rossum2095d241997-04-09 19:41:24 +00002060 digit zz = (digit) (z >> SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002061 carry += v->ob_digit[i+k] - z
2062 + ((twodigits)zz << SHIFT);
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00002063 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002064 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
2065 carry, SHIFT);
2066 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002067 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002068
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002069 if (i+k < size_v) {
2070 carry += v->ob_digit[i+k];
2071 v->ob_digit[i+k] = 0;
2072 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002073
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002074 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002075 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002076 else {
2077 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002078 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079 carry = 0;
2080 for (i = 0; i < size_w && i+k < size_v; ++i) {
2081 carry += v->ob_digit[i+k] + w->ob_digit[i];
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00002082 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002083 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2084 BASE_TWODIGITS_TYPE,
2085 carry, SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002086 }
2087 }
2088 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002089
Guido van Rossumc206c761995-01-10 15:23:19 +00002090 if (a == NULL)
2091 *prem = NULL;
2092 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002093 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002094 *prem = divrem1(v, d, &d);
2095 /* d receives the (unused) remainder */
2096 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002097 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002098 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002099 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002100 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002101 Py_DECREF(v);
2102 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002103 return a;
2104}
2105
2106/* Methods */
2107
2108static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002109long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002110{
Guido van Rossum9475a232001-10-05 20:51:39 +00002111 v->ob_type->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002112}
2113
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002114static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002115long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002116{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00002117 return long_format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002118}
2119
2120static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002121long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002122{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002123 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002124
Guido van Rossumc6913e71991-11-19 20:26:46 +00002125 if (a->ob_size != b->ob_size) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002126 if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002127 sign = 0;
2128 else
2129 sign = a->ob_size - b->ob_size;
2130 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002131 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002132 Py_ssize_t i = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002133 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2134 ;
2135 if (i < 0)
2136 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002137 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002138 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002139 if (a->ob_size < 0)
2140 sign = -sign;
2141 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002142 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002143 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002144}
2145
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002146static PyObject *
2147long_richcompare(PyObject *self, PyObject *other, int op)
2148{
2149 PyLongObject *a, *b;
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002150 PyObject *result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002151 CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b);
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002152 result = Py_CmpToRich(op, long_compare(a, b));
2153 Py_DECREF(a);
2154 Py_DECREF(b);
2155 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002156}
2157
Guido van Rossum9bfef441993-03-29 10:43:31 +00002158static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002159long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002160{
2161 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002162 Py_ssize_t i;
2163 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002164
2165 /* This is designed so that Python ints and longs with the
2166 same value hash to the same value, otherwise comparisons
2167 of mapping keys will turn out weird */
2168 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00002169 switch(i) {
2170 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2171 case 0: return 0;
2172 case 1: return v->ob_digit[0];
2173 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002174 sign = 1;
2175 x = 0;
2176 if (i < 0) {
2177 sign = -1;
2178 i = -(i);
2179 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002180#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002181 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002182 /* Force a native long #-bits (32 or 64) circular shift */
2183 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002184 x += v->ob_digit[i];
2185 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002186#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002187 x = x * sign;
2188 if (x == -1)
2189 x = -2;
2190 return x;
2191}
2192
2193
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002194/* Add the absolute values of two long integers. */
2195
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002196static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002197x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002198{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002199 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002200 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002201 int i;
2202 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002203
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002204 /* Ensure a is the larger of the two: */
2205 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002206 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002207 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002208 size_a = size_b;
2209 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002210 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002211 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002212 if (z == NULL)
2213 return NULL;
2214 for (i = 0; i < size_b; ++i) {
2215 carry += a->ob_digit[i] + b->ob_digit[i];
2216 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002217 carry >>= SHIFT;
2218 }
2219 for (; i < size_a; ++i) {
2220 carry += a->ob_digit[i];
2221 z->ob_digit[i] = carry & MASK;
2222 carry >>= SHIFT;
2223 }
2224 z->ob_digit[i] = carry;
2225 return long_normalize(z);
2226}
2227
2228/* Subtract the absolute values of two integers. */
2229
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002230static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002231x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002232{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002233 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002234 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002235 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002236 int sign = 1;
2237 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002238
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002239 /* Ensure a is the larger of the two: */
2240 if (size_a < size_b) {
2241 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002242 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002243 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002244 size_a = size_b;
2245 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002246 }
2247 else if (size_a == size_b) {
2248 /* Find highest digit where a and b differ: */
2249 i = size_a;
2250 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2251 ;
2252 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002253 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002254 if (a->ob_digit[i] < b->ob_digit[i]) {
2255 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002256 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002257 }
2258 size_a = size_b = i+1;
2259 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002260 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002261 if (z == NULL)
2262 return NULL;
2263 for (i = 0; i < size_b; ++i) {
2264 /* The following assumes unsigned arithmetic
2265 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002266 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002267 z->ob_digit[i] = borrow & MASK;
2268 borrow >>= SHIFT;
2269 borrow &= 1; /* Keep only one sign bit */
2270 }
2271 for (; i < size_a; ++i) {
2272 borrow = a->ob_digit[i] - borrow;
2273 z->ob_digit[i] = borrow & MASK;
2274 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002275 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002276 }
2277 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002278 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002279 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002280 return long_normalize(z);
2281}
2282
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002283static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002284long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002285{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002286 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002287
Neil Schemenauerba872e22001-01-04 01:46:03 +00002288 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2289
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002290 if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) {
2291 PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) +
2292 MEDIUM_VALUE(b));
2293 Py_DECREF(a);
2294 Py_DECREF(b);
2295 return result;
2296 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002297 if (a->ob_size < 0) {
2298 if (b->ob_size < 0) {
2299 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002300 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002301 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002302 }
2303 else
2304 z = x_sub(b, a);
2305 }
2306 else {
2307 if (b->ob_size < 0)
2308 z = x_sub(a, b);
2309 else
2310 z = x_add(a, b);
2311 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002312 Py_DECREF(a);
2313 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002314 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002315}
2316
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002317static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002318long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002319{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002320 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002321
Neil Schemenauerba872e22001-01-04 01:46:03 +00002322 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2323
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002324 if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) {
2325 PyObject* r;
2326 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2327 Py_DECREF(a);
2328 Py_DECREF(b);
2329 return r;
2330 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002331 if (a->ob_size < 0) {
2332 if (b->ob_size < 0)
2333 z = x_sub(a, b);
2334 else
2335 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002336 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002337 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002338 }
2339 else {
2340 if (b->ob_size < 0)
2341 z = x_add(a, b);
2342 else
2343 z = x_sub(a, b);
2344 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002345 Py_DECREF(a);
2346 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002347 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002348}
2349
Tim Peters5af4e6c2002-08-12 02:31:19 +00002350/* Grade school multiplication, ignoring the signs.
2351 * Returns the absolute value of the product, or NULL if error.
2352 */
2353static PyLongObject *
2354x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002355{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002356 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002357 Py_ssize_t size_a = ABS(a->ob_size);
2358 Py_ssize_t size_b = ABS(b->ob_size);
2359 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002360
Tim Peters5af4e6c2002-08-12 02:31:19 +00002361 z = _PyLong_New(size_a + size_b);
2362 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002363 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002364
2365 memset(z->ob_digit, 0, z->ob_size * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002366 if (a == b) {
2367 /* Efficient squaring per HAC, Algorithm 14.16:
2368 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2369 * Gives slightly less than a 2x speedup when a == b,
2370 * via exploiting that each entry in the multiplication
2371 * pyramid appears twice (except for the size_a squares).
2372 */
2373 for (i = 0; i < size_a; ++i) {
2374 twodigits carry;
2375 twodigits f = a->ob_digit[i];
2376 digit *pz = z->ob_digit + (i << 1);
2377 digit *pa = a->ob_digit + i + 1;
2378 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002379
Tim Peters0973b992004-08-29 22:16:50 +00002380 SIGCHECK({
2381 Py_DECREF(z);
2382 return NULL;
2383 })
2384
2385 carry = *pz + f * f;
2386 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002387 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002388 assert(carry <= MASK);
2389
2390 /* Now f is added in twice in each column of the
2391 * pyramid it appears. Same as adding f<<1 once.
2392 */
2393 f <<= 1;
2394 while (pa < paend) {
2395 carry += *pz + *pa++ * f;
2396 *pz++ = (digit)(carry & MASK);
2397 carry >>= SHIFT;
2398 assert(carry <= (MASK << 1));
2399 }
2400 if (carry) {
2401 carry += *pz;
2402 *pz++ = (digit)(carry & MASK);
2403 carry >>= SHIFT;
2404 }
2405 if (carry)
2406 *pz += (digit)(carry & MASK);
2407 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002408 }
Tim Peters0973b992004-08-29 22:16:50 +00002409 }
2410 else { /* a is not the same as b -- gradeschool long mult */
2411 for (i = 0; i < size_a; ++i) {
2412 twodigits carry = 0;
2413 twodigits f = a->ob_digit[i];
2414 digit *pz = z->ob_digit + i;
2415 digit *pb = b->ob_digit;
2416 digit *pbend = b->ob_digit + size_b;
2417
2418 SIGCHECK({
2419 Py_DECREF(z);
2420 return NULL;
2421 })
2422
2423 while (pb < pbend) {
2424 carry += *pz + *pb++ * f;
2425 *pz++ = (digit)(carry & MASK);
2426 carry >>= SHIFT;
2427 assert(carry <= MASK);
2428 }
2429 if (carry)
2430 *pz += (digit)(carry & MASK);
2431 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002432 }
2433 }
Tim Peters44121a62002-08-12 06:17:58 +00002434 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002435}
2436
2437/* A helper for Karatsuba multiplication (k_mul).
2438 Takes a long "n" and an integer "size" representing the place to
2439 split, and sets low and high such that abs(n) == (high << size) + low,
2440 viewing the shift as being by digits. The sign bit is ignored, and
2441 the return values are >= 0.
2442 Returns 0 on success, -1 on failure.
2443*/
2444static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002445kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002446{
2447 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002448 Py_ssize_t size_lo, size_hi;
2449 const Py_ssize_t size_n = ABS(n->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002450
2451 size_lo = MIN(size_n, size);
2452 size_hi = size_n - size_lo;
2453
2454 if ((hi = _PyLong_New(size_hi)) == NULL)
2455 return -1;
2456 if ((lo = _PyLong_New(size_lo)) == NULL) {
2457 Py_DECREF(hi);
2458 return -1;
2459 }
2460
2461 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2462 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2463
2464 *high = long_normalize(hi);
2465 *low = long_normalize(lo);
2466 return 0;
2467}
2468
Tim Peters60004642002-08-12 22:01:34 +00002469static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2470
Tim Peters5af4e6c2002-08-12 02:31:19 +00002471/* Karatsuba multiplication. Ignores the input signs, and returns the
2472 * absolute value of the product (or NULL if error).
2473 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2474 */
2475static PyLongObject *
2476k_mul(PyLongObject *a, PyLongObject *b)
2477{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002478 Py_ssize_t asize = ABS(a->ob_size);
2479 Py_ssize_t bsize = ABS(b->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002480 PyLongObject *ah = NULL;
2481 PyLongObject *al = NULL;
2482 PyLongObject *bh = NULL;
2483 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002484 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002485 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002486 Py_ssize_t shift; /* the number of digits we split off */
2487 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002488
Tim Peters5af4e6c2002-08-12 02:31:19 +00002489 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2490 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2491 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002492 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002493 * By picking X to be a power of 2, "*X" is just shifting, and it's
2494 * been reduced to 3 multiplies on numbers half the size.
2495 */
2496
Tim Petersfc07e562002-08-12 02:54:10 +00002497 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002498 * is largest.
2499 */
Tim Peters738eda72002-08-12 15:08:20 +00002500 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002501 t1 = a;
2502 a = b;
2503 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002504
2505 i = asize;
2506 asize = bsize;
2507 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002508 }
2509
2510 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002511 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2512 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002513 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002514 return _PyLong_New(0);
2515 else
2516 return x_mul(a, b);
2517 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002518
Tim Peters60004642002-08-12 22:01:34 +00002519 /* If a is small compared to b, splitting on b gives a degenerate
2520 * case with ah==0, and Karatsuba may be (even much) less efficient
2521 * than "grade school" then. However, we can still win, by viewing
2522 * b as a string of "big digits", each of width a->ob_size. That
2523 * leads to a sequence of balanced calls to k_mul.
2524 */
2525 if (2 * asize <= bsize)
2526 return k_lopsided_mul(a, b);
2527
Tim Petersd6974a52002-08-13 20:37:51 +00002528 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002529 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002530 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Tim Petersd6974a52002-08-13 20:37:51 +00002531 assert(ah->ob_size > 0); /* the split isn't degenerate */
2532
Tim Peters0973b992004-08-29 22:16:50 +00002533 if (a == b) {
2534 bh = ah;
2535 bl = al;
2536 Py_INCREF(bh);
2537 Py_INCREF(bl);
2538 }
2539 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002540
Tim Petersd64c1de2002-08-12 17:36:03 +00002541 /* The plan:
2542 * 1. Allocate result space (asize + bsize digits: that's always
2543 * enough).
2544 * 2. Compute ah*bh, and copy into result at 2*shift.
2545 * 3. Compute al*bl, and copy into result at 0. Note that this
2546 * can't overlap with #2.
2547 * 4. Subtract al*bl from the result, starting at shift. This may
2548 * underflow (borrow out of the high digit), but we don't care:
2549 * we're effectively doing unsigned arithmetic mod
2550 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2551 * borrows and carries out of the high digit can be ignored.
2552 * 5. Subtract ah*bh from the result, starting at shift.
2553 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2554 * at shift.
2555 */
2556
2557 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002558 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002559 if (ret == NULL) goto fail;
2560#ifdef Py_DEBUG
2561 /* Fill with trash, to catch reference to uninitialized digits. */
2562 memset(ret->ob_digit, 0xDF, ret->ob_size * sizeof(digit));
2563#endif
Tim Peters44121a62002-08-12 06:17:58 +00002564
Tim Petersd64c1de2002-08-12 17:36:03 +00002565 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002566 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2567 assert(t1->ob_size >= 0);
2568 assert(2*shift + t1->ob_size <= ret->ob_size);
2569 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2570 t1->ob_size * sizeof(digit));
2571
2572 /* Zero-out the digits higher than the ah*bh copy. */
2573 i = ret->ob_size - 2*shift - t1->ob_size;
Tim Peters44121a62002-08-12 06:17:58 +00002574 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002575 memset(ret->ob_digit + 2*shift + t1->ob_size, 0,
Tim Peters44121a62002-08-12 06:17:58 +00002576 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002577
Tim Petersd64c1de2002-08-12 17:36:03 +00002578 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002579 if ((t2 = k_mul(al, bl)) == NULL) {
2580 Py_DECREF(t1);
2581 goto fail;
2582 }
2583 assert(t2->ob_size >= 0);
2584 assert(t2->ob_size <= 2*shift); /* no overlap with high digits */
2585 memcpy(ret->ob_digit, t2->ob_digit, t2->ob_size * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002586
2587 /* Zero out remaining digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002588 i = 2*shift - t2->ob_size; /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002589 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002590 memset(ret->ob_digit + t2->ob_size, 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002591
Tim Petersd64c1de2002-08-12 17:36:03 +00002592 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2593 * because it's fresher in cache.
2594 */
Tim Peters738eda72002-08-12 15:08:20 +00002595 i = ret->ob_size - shift; /* # digits after shift */
Tim Petersd64c1de2002-08-12 17:36:03 +00002596 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, t2->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002597 Py_DECREF(t2);
2598
Tim Petersd64c1de2002-08-12 17:36:03 +00002599 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, t1->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002600 Py_DECREF(t1);
2601
Tim Petersd64c1de2002-08-12 17:36:03 +00002602 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002603 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2604 Py_DECREF(ah);
2605 Py_DECREF(al);
2606 ah = al = NULL;
2607
Tim Peters0973b992004-08-29 22:16:50 +00002608 if (a == b) {
2609 t2 = t1;
2610 Py_INCREF(t2);
2611 }
2612 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002613 Py_DECREF(t1);
2614 goto fail;
2615 }
2616 Py_DECREF(bh);
2617 Py_DECREF(bl);
2618 bh = bl = NULL;
2619
Tim Peters738eda72002-08-12 15:08:20 +00002620 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002621 Py_DECREF(t1);
2622 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002623 if (t3 == NULL) goto fail;
Tim Peters547607c2002-08-12 19:43:49 +00002624 assert(t3->ob_size >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002625
Tim Petersd6974a52002-08-13 20:37:51 +00002626 /* Add t3. It's not obvious why we can't run out of room here.
2627 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002628 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002629 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, t3->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002630 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002631
Tim Peters5af4e6c2002-08-12 02:31:19 +00002632 return long_normalize(ret);
2633
2634 fail:
2635 Py_XDECREF(ret);
2636 Py_XDECREF(ah);
2637 Py_XDECREF(al);
2638 Py_XDECREF(bh);
2639 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002640 return NULL;
2641}
2642
Tim Petersd6974a52002-08-13 20:37:51 +00002643/* (*) Why adding t3 can't "run out of room" above.
2644
Tim Petersab86c2b2002-08-15 20:06:00 +00002645Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2646to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002647
Tim Petersab86c2b2002-08-15 20:06:00 +000026481. For any integer i, i = c(i/2) + f(i/2). In particular,
2649 bsize = c(bsize/2) + f(bsize/2).
26502. shift = f(bsize/2)
26513. asize <= bsize
26524. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2653 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002654
Tim Petersab86c2b2002-08-15 20:06:00 +00002655We allocated asize + bsize result digits, and add t3 into them at an offset
2656of shift. This leaves asize+bsize-shift allocated digit positions for t3
2657to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2658asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002659
Tim Petersab86c2b2002-08-15 20:06:00 +00002660bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2661at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002662
Tim Petersab86c2b2002-08-15 20:06:00 +00002663If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2664digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2665most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002666
Tim Petersab86c2b2002-08-15 20:06:00 +00002667The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002668
Tim Petersab86c2b2002-08-15 20:06:00 +00002669 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002670
Tim Petersab86c2b2002-08-15 20:06:00 +00002671and we have asize + c(bsize/2) available digit positions. We need to show
2672this is always enough. An instance of c(bsize/2) cancels out in both, so
2673the question reduces to whether asize digits is enough to hold
2674(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2675then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2676asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2677digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2678asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002679c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2680is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2681bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002682
Tim Peters48d52c02002-08-14 17:07:32 +00002683Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2684clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2685ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002686*/
2687
Tim Peters60004642002-08-12 22:01:34 +00002688/* b has at least twice the digits of a, and a is big enough that Karatsuba
2689 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2690 * of slices, each with a->ob_size digits, and multiply the slices by a,
2691 * one at a time. This gives k_mul balanced inputs to work with, and is
2692 * also cache-friendly (we compute one double-width slice of the result
2693 * at a time, then move on, never bactracking except for the helpful
2694 * single-width slice overlap between successive partial sums).
2695 */
2696static PyLongObject *
2697k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2698{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002699 const Py_ssize_t asize = ABS(a->ob_size);
2700 Py_ssize_t bsize = ABS(b->ob_size);
2701 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002702 PyLongObject *ret;
2703 PyLongObject *bslice = NULL;
2704
2705 assert(asize > KARATSUBA_CUTOFF);
2706 assert(2 * asize <= bsize);
2707
2708 /* Allocate result space, and zero it out. */
2709 ret = _PyLong_New(asize + bsize);
2710 if (ret == NULL)
2711 return NULL;
2712 memset(ret->ob_digit, 0, ret->ob_size * sizeof(digit));
2713
2714 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002715 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002716 if (bslice == NULL)
2717 goto fail;
2718
2719 nbdone = 0;
2720 while (bsize > 0) {
2721 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002722 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002723
2724 /* Multiply the next slice of b by a. */
2725 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2726 nbtouse * sizeof(digit));
2727 bslice->ob_size = nbtouse;
2728 product = k_mul(a, bslice);
2729 if (product == NULL)
2730 goto fail;
2731
2732 /* Add into result. */
2733 (void)v_iadd(ret->ob_digit + nbdone, ret->ob_size - nbdone,
2734 product->ob_digit, product->ob_size);
2735 Py_DECREF(product);
2736
2737 bsize -= nbtouse;
2738 nbdone += nbtouse;
2739 }
2740
2741 Py_DECREF(bslice);
2742 return long_normalize(ret);
2743
2744 fail:
2745 Py_DECREF(ret);
2746 Py_XDECREF(bslice);
2747 return NULL;
2748}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002749
2750static PyObject *
2751long_mul(PyLongObject *v, PyLongObject *w)
2752{
2753 PyLongObject *a, *b, *z;
2754
2755 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002756 Py_INCREF(Py_NotImplemented);
2757 return Py_NotImplemented;
2758 }
2759
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002760 if (ABS(v->ob_size) <= 1 && ABS(w->ob_size) <= 1) {
2761 PyObject *r;
2762 r = PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w));
2763 Py_DECREF(a);
2764 Py_DECREF(b);
2765 return r;
2766 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002767
Tim Petersd64c1de2002-08-12 17:36:03 +00002768 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002769 /* Negate if exactly one of the inputs is negative. */
2770 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002771 NEGATE(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002772 Py_DECREF(a);
2773 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002774 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002775}
2776
Guido van Rossume32e0141992-01-19 16:31:05 +00002777/* The / and % operators are now defined in terms of divmod().
2778 The expression a mod b has the value a - b*floor(a/b).
2779 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002780 |a| by |b|, with the sign of a. This is also expressed
2781 as a - b*trunc(a/b), if trunc truncates towards zero.
2782 Some examples:
2783 a b a rem b a mod b
2784 13 10 3 3
2785 -13 10 -3 7
2786 13 -10 3 -7
2787 -13 -10 -3 -3
2788 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002789 have different signs. We then subtract one from the 'div'
2790 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002791
Tim Peters47e52ee2004-08-30 02:44:38 +00002792/* Compute
2793 * *pdiv, *pmod = divmod(v, w)
2794 * NULL can be passed for pdiv or pmod, in which case that part of
2795 * the result is simply thrown away. The caller owns a reference to
2796 * each of these it requests (does not pass NULL for).
2797 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002798static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002799l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002800 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002801{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002802 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002803
Guido van Rossume32e0141992-01-19 16:31:05 +00002804 if (long_divrem(v, w, &div, &mod) < 0)
2805 return -1;
Guido van Rossum472c04f1996-12-05 21:57:21 +00002806 if ((mod->ob_size < 0 && w->ob_size > 0) ||
2807 (mod->ob_size > 0 && w->ob_size < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002808 PyLongObject *temp;
2809 PyLongObject *one;
2810 temp = (PyLongObject *) long_add(mod, w);
2811 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002812 mod = temp;
2813 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002814 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002815 return -1;
2816 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002817 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002818 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002819 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2820 Py_DECREF(mod);
2821 Py_DECREF(div);
2822 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002823 return -1;
2824 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002825 Py_DECREF(one);
2826 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002827 div = temp;
2828 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002829 if (pdiv != NULL)
2830 *pdiv = div;
2831 else
2832 Py_DECREF(div);
2833
2834 if (pmod != NULL)
2835 *pmod = mod;
2836 else
2837 Py_DECREF(mod);
2838
Guido van Rossume32e0141992-01-19 16:31:05 +00002839 return 0;
2840}
2841
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002842static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002843long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002844{
Tim Peters47e52ee2004-08-30 02:44:38 +00002845 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002846
2847 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002848 if (l_divmod(a, b, &div, NULL) < 0)
2849 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002850 Py_DECREF(a);
2851 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002852 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002853}
2854
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002855static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002856long_true_divide(PyObject *v, PyObject *w)
2857{
Tim Peterse2a60002001-09-04 06:17:36 +00002858 PyLongObject *a, *b;
2859 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002860 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002861
2862 CONVERT_BINOP(v, w, &a, &b);
2863 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2864 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002865 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2866 Py_DECREF(a);
2867 Py_DECREF(b);
2868 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002869 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002870 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2871 but should really be set correctly after sucessful calls to
2872 _PyLong_AsScaledDouble() */
2873 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002874
2875 if (bd == 0.0) {
2876 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002877 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002878 return NULL;
2879 }
2880
2881 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2882 ad /= bd; /* overflow/underflow impossible here */
2883 aexp -= bexp;
2884 if (aexp > INT_MAX / SHIFT)
2885 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002886 else if (aexp < -(INT_MAX / SHIFT))
2887 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002888 errno = 0;
2889 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002890 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002891 goto overflow;
2892 return PyFloat_FromDouble(ad);
2893
2894overflow:
2895 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002896 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002897 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002898
Tim Peters20dab9f2001-09-04 05:31:47 +00002899}
2900
2901static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002902long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002903{
Tim Peters47e52ee2004-08-30 02:44:38 +00002904 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002905
2906 CONVERT_BINOP(v, w, &a, &b);
2907
Tim Peters47e52ee2004-08-30 02:44:38 +00002908 if (l_divmod(a, b, NULL, &mod) < 0)
2909 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002910 Py_DECREF(a);
2911 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002912 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002913}
2914
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002915static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002916long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002917{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002918 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002919 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002920
2921 CONVERT_BINOP(v, w, &a, &b);
2922
2923 if (l_divmod(a, b, &div, &mod) < 0) {
2924 Py_DECREF(a);
2925 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002926 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002927 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002928 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002929 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002930 PyTuple_SetItem(z, 0, (PyObject *) div);
2931 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002932 }
2933 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002934 Py_DECREF(div);
2935 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002936 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002937 Py_DECREF(a);
2938 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002939 return z;
2940}
2941
Tim Peters47e52ee2004-08-30 02:44:38 +00002942/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002943static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002944long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002945{
Tim Peters47e52ee2004-08-30 02:44:38 +00002946 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2947 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002948
Tim Peters47e52ee2004-08-30 02:44:38 +00002949 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002950 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002951 PyLongObject *temp = NULL;
2952
2953 /* 5-ary values. If the exponent is large enough, table is
2954 * precomputed so that table[i] == a**i % c for i in range(32).
2955 */
2956 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2957 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2958
2959 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002960 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002961 if (PyLong_Check(x)) {
2962 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002963 Py_INCREF(x);
2964 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002965 else if (x == Py_None)
2966 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002967 else {
2968 Py_DECREF(a);
2969 Py_DECREF(b);
2970 Py_INCREF(Py_NotImplemented);
2971 return Py_NotImplemented;
2972 }
Tim Peters4c483c42001-09-05 06:24:58 +00002973
Tim Peters47e52ee2004-08-30 02:44:38 +00002974 if (b->ob_size < 0) { /* if exponent is negative */
2975 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002976 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002977 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002978 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002979 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002980 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002981 /* else return a float. This works because we know
2982 that this calls float_pow() which converts its
2983 arguments to double. */
2984 Py_DECREF(a);
2985 Py_DECREF(b);
2986 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002987 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002988 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002989
2990 if (c) {
2991 /* if modulus == 0:
2992 raise ValueError() */
2993 if (c->ob_size == 0) {
2994 PyErr_SetString(PyExc_ValueError,
2995 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002996 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002997 }
2998
2999 /* if modulus < 0:
3000 negativeOutput = True
3001 modulus = -modulus */
3002 if (c->ob_size < 0) {
3003 negativeOutput = 1;
3004 temp = (PyLongObject *)_PyLong_Copy(c);
3005 if (temp == NULL)
3006 goto Error;
3007 Py_DECREF(c);
3008 c = temp;
3009 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003010 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003011 }
3012
3013 /* if modulus == 1:
3014 return 0 */
3015 if ((c->ob_size == 1) && (c->ob_digit[0] == 1)) {
3016 z = (PyLongObject *)PyLong_FromLong(0L);
3017 goto Done;
3018 }
3019
3020 /* if base < 0:
3021 base = base % modulus
3022 Having the base positive just makes things easier. */
3023 if (a->ob_size < 0) {
3024 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003025 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003026 Py_DECREF(a);
3027 a = temp;
3028 temp = NULL;
3029 }
3030 }
3031
3032 /* At this point a, b, and c are guaranteed non-negative UNLESS
3033 c is NULL, in which case a may be negative. */
3034
3035 z = (PyLongObject *)PyLong_FromLong(1L);
3036 if (z == NULL)
3037 goto Error;
3038
3039 /* Perform a modular reduction, X = X % c, but leave X alone if c
3040 * is NULL.
3041 */
3042#define REDUCE(X) \
3043 if (c != NULL) { \
3044 if (l_divmod(X, c, NULL, &temp) < 0) \
3045 goto Error; \
3046 Py_XDECREF(X); \
3047 X = temp; \
3048 temp = NULL; \
3049 }
3050
3051 /* Multiply two values, then reduce the result:
3052 result = X*Y % c. If c is NULL, skip the mod. */
3053#define MULT(X, Y, result) \
3054{ \
3055 temp = (PyLongObject *)long_mul(X, Y); \
3056 if (temp == NULL) \
3057 goto Error; \
3058 Py_XDECREF(result); \
3059 result = temp; \
3060 temp = NULL; \
3061 REDUCE(result) \
3062}
3063
3064 if (b->ob_size <= FIVEARY_CUTOFF) {
3065 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3066 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3067 for (i = b->ob_size - 1; i >= 0; --i) {
3068 digit bi = b->ob_digit[i];
3069
3070 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
3071 MULT(z, z, z)
3072 if (bi & j)
3073 MULT(z, a, z)
3074 }
3075 }
3076 }
3077 else {
3078 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3079 Py_INCREF(z); /* still holds 1L */
3080 table[0] = z;
3081 for (i = 1; i < 32; ++i)
3082 MULT(table[i-1], a, table[i])
3083
3084 for (i = b->ob_size - 1; i >= 0; --i) {
3085 const digit bi = b->ob_digit[i];
3086
3087 for (j = SHIFT - 5; j >= 0; j -= 5) {
3088 const int index = (bi >> j) & 0x1f;
3089 for (k = 0; k < 5; ++k)
3090 MULT(z, z, z)
3091 if (index)
3092 MULT(z, table[index], z)
3093 }
3094 }
3095 }
3096
3097 if (negativeOutput && (z->ob_size != 0)) {
3098 temp = (PyLongObject *)long_sub(z, c);
3099 if (temp == NULL)
3100 goto Error;
3101 Py_DECREF(z);
3102 z = temp;
3103 temp = NULL;
3104 }
3105 goto Done;
3106
3107 Error:
3108 if (z != NULL) {
3109 Py_DECREF(z);
3110 z = NULL;
3111 }
3112 /* fall through */
3113 Done:
Tim Peters47e52ee2004-08-30 02:44:38 +00003114 if (b->ob_size > FIVEARY_CUTOFF) {
3115 for (i = 0; i < 32; ++i)
3116 Py_XDECREF(table[i]);
3117 }
Tim Petersde7990b2005-07-17 23:45:23 +00003118 Py_DECREF(a);
3119 Py_DECREF(b);
3120 Py_XDECREF(c);
3121 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003122 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003123}
3124
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003125static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003126long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003127{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003128 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003129 PyLongObject *x;
3130 PyLongObject *w;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003131 if (ABS(v->ob_size) <=1)
3132 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003133 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003134 if (w == NULL)
3135 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003136 x = (PyLongObject *) long_add(v, w);
3137 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003138 if (x == NULL)
3139 return NULL;
Tim Peters40c397d2001-09-11 23:24:22 +00003140 x->ob_size = -(x->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003141 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003142}
3143
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003144static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003145long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003146{
Tim Peters69c2de32001-09-11 22:31:33 +00003147 if (PyLong_CheckExact(v)) {
3148 Py_INCREF(v);
3149 return (PyObject *)v;
3150 }
3151 else
3152 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003153}
3154
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003155static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003156long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003157{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003158 PyLongObject *z;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003159 if (ABS(v->ob_size) <= 1)
3160 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003161 z = (PyLongObject *)_PyLong_Copy(v);
3162 if (z != NULL)
3163 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003164 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003165}
3166
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003167static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003168long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003169{
3170 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003171 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003172 else
3173 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003174}
3175
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003176static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003177long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003178{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003179 return ABS(v->ob_size) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003180}
3181
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003182static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003183long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003184{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003185 PyLongObject *a, *b;
3186 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003187 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003188 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003189 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003190
Neil Schemenauerba872e22001-01-04 01:46:03 +00003191 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3192
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003193 if (a->ob_size < 0) {
3194 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003195 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003196 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003197 if (a1 == NULL)
3198 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003199 a2 = (PyLongObject *) long_rshift(a1, b);
3200 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003201 if (a2 == NULL)
3202 goto rshift_error;
3203 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003204 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003205 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003206 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003207
Neil Schemenauerba872e22001-01-04 01:46:03 +00003208 shiftby = PyLong_AsLong((PyObject *)b);
3209 if (shiftby == -1L && PyErr_Occurred())
3210 goto rshift_error;
3211 if (shiftby < 0) {
3212 PyErr_SetString(PyExc_ValueError,
3213 "negative shift count");
3214 goto rshift_error;
3215 }
3216 wordshift = shiftby / SHIFT;
3217 newsize = ABS(a->ob_size) - wordshift;
3218 if (newsize <= 0) {
3219 z = _PyLong_New(0);
3220 Py_DECREF(a);
3221 Py_DECREF(b);
3222 return (PyObject *)z;
3223 }
3224 loshift = shiftby % SHIFT;
3225 hishift = SHIFT - loshift;
3226 lomask = ((digit)1 << hishift) - 1;
3227 himask = MASK ^ lomask;
3228 z = _PyLong_New(newsize);
3229 if (z == NULL)
3230 goto rshift_error;
3231 if (a->ob_size < 0)
3232 z->ob_size = -(z->ob_size);
3233 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3234 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3235 if (i+1 < newsize)
3236 z->ob_digit[i] |=
3237 (a->ob_digit[j+1] << hishift) & himask;
3238 }
3239 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003240 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003241rshift_error:
3242 Py_DECREF(a);
3243 Py_DECREF(b);
3244 return (PyObject *) z;
3245
Guido van Rossumc6913e71991-11-19 20:26:46 +00003246}
3247
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003248static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003249long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003250{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003251 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003252 PyLongObject *a, *b;
3253 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003254 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003255 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003256 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003257
Neil Schemenauerba872e22001-01-04 01:46:03 +00003258 CONVERT_BINOP(v, w, &a, &b);
3259
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003260 shiftby = PyLong_AsLong((PyObject *)b);
3261 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003262 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003263 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003264 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003265 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003266 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003267 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003268 PyErr_SetString(PyExc_ValueError,
3269 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003270 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003271 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003272 /* wordshift, remshift = divmod(shiftby, SHIFT) */
3273 wordshift = (int)shiftby / SHIFT;
3274 remshift = (int)shiftby - wordshift * SHIFT;
3275
3276 oldsize = ABS(a->ob_size);
3277 newsize = oldsize + wordshift;
3278 if (remshift)
3279 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003280 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003281 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003282 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003283 if (a->ob_size < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003284 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003285 for (i = 0; i < wordshift; i++)
3286 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003287 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003288 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003289 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003290 z->ob_digit[i] = (digit)(accum & MASK);
3291 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003292 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003293 if (remshift)
3294 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003295 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003296 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003297 z = long_normalize(z);
3298lshift_error:
3299 Py_DECREF(a);
3300 Py_DECREF(b);
3301 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003302}
3303
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003304
3305/* Bitwise and/xor/or operations */
3306
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003307static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003308long_bitwise(PyLongObject *a,
3309 int op, /* '&', '|', '^' */
3310 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003311{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003312 digit maska, maskb; /* 0 or MASK */
3313 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003314 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003315 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003316 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003317 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003318 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003319
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003320 if (a->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003321 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003322 if (a == NULL)
3323 return NULL;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003324 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003325 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003326 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003327 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003328 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003329 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003330 if (b->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003331 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003332 if (b == NULL) {
3333 Py_DECREF(a);
3334 return NULL;
3335 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003336 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003337 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003338 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003339 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003340 maskb = 0;
3341 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003342
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003343 negz = 0;
3344 switch (op) {
3345 case '^':
3346 if (maska != maskb) {
3347 maska ^= MASK;
3348 negz = -1;
3349 }
3350 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003351 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003352 if (maska && maskb) {
3353 op = '|';
3354 maska ^= MASK;
3355 maskb ^= MASK;
3356 negz = -1;
3357 }
3358 break;
3359 case '|':
3360 if (maska || maskb) {
3361 op = '&';
3362 maska ^= MASK;
3363 maskb ^= MASK;
3364 negz = -1;
3365 }
3366 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003367 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003368
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003369 /* JRH: The original logic here was to allocate the result value (z)
3370 as the longer of the two operands. However, there are some cases
3371 where the result is guaranteed to be shorter than that: AND of two
3372 positives, OR of two negatives: use the shorter number. AND with
3373 mixed signs: use the positive number. OR with mixed signs: use the
3374 negative number. After the transformations above, op will be '&'
3375 iff one of these cases applies, and mask will be non-0 for operands
3376 whose length should be ignored.
3377 */
3378
3379 size_a = a->ob_size;
3380 size_b = b->ob_size;
3381 size_z = op == '&'
3382 ? (maska
3383 ? size_b
3384 : (maskb ? size_a : MIN(size_a, size_b)))
3385 : MAX(size_a, size_b);
3386 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003387 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003388 Py_DECREF(a);
3389 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003390 return NULL;
3391 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003392
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003393 for (i = 0; i < size_z; ++i) {
3394 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3395 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3396 switch (op) {
3397 case '&': z->ob_digit[i] = diga & digb; break;
3398 case '|': z->ob_digit[i] = diga | digb; break;
3399 case '^': z->ob_digit[i] = diga ^ digb; break;
3400 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003401 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003402
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003403 Py_DECREF(a);
3404 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003405 z = long_normalize(z);
3406 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003407 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003408 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003409 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003410 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003411}
3412
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003413static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003414long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003415{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003416 PyLongObject *a, *b;
3417 PyObject *c;
3418 CONVERT_BINOP(v, w, &a, &b);
3419 c = long_bitwise(a, '&', b);
3420 Py_DECREF(a);
3421 Py_DECREF(b);
3422 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003423}
3424
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003425static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003426long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003427{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003428 PyLongObject *a, *b;
3429 PyObject *c;
3430 CONVERT_BINOP(v, w, &a, &b);
3431 c = long_bitwise(a, '^', b);
3432 Py_DECREF(a);
3433 Py_DECREF(b);
3434 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003435}
3436
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003437static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003438long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003439{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003440 PyLongObject *a, *b;
3441 PyObject *c;
3442 CONVERT_BINOP(v, w, &a, &b);
3443 c = long_bitwise(a, '|', b);
3444 Py_DECREF(a);
3445 Py_DECREF(b);
3446 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003447}
3448
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003449static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003450long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003451{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003452 if (PyLong_CheckExact(v))
3453 Py_INCREF(v);
3454 else
3455 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003456 return v;
3457}
3458
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003459static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003460long_int(PyObject *v)
3461{
Guido van Rossumddefaf32007-01-14 03:31:43 +00003462 return long_long(v);
Walter Dörwaldf1715402002-11-19 20:49:15 +00003463}
3464
3465static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003466long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003467{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003468 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003469 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003470 if (result == -1.0 && PyErr_Occurred())
3471 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003472 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003473}
3474
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003475static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003476long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003477{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00003478 return long_format(v, 8);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003479}
3480
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003481static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003482long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003483{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00003484 return long_format(v, 16);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003485}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003486
3487static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003488long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003489
Tim Peters6d6c1a32001-08-02 04:15:00 +00003490static PyObject *
3491long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3492{
3493 PyObject *x = NULL;
3494 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003495 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003496
Guido van Rossumbef14172001-08-29 15:47:46 +00003497 if (type != &PyLong_Type)
3498 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003499 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003500 &x, &base))
3501 return NULL;
3502 if (x == NULL)
3503 return PyLong_FromLong(0L);
3504 if (base == -909)
3505 return PyNumber_Long(x);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003506 else if (PyString_Check(x)) {
3507 char *s = PyString_AS_STRING(x);
3508 char *end;
3509 PyObject *r = PyLong_FromString(s, &end, base);
3510 if (r != NULL && end != s + PyString_GET_SIZE(x)) {
3511 PyErr_SetString(PyExc_ValueError,
3512 "null byte in argument for int()");
3513 Py_DECREF(r);
3514 r = NULL;
3515 }
3516 return r;
3517 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003518#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003519 else if (PyUnicode_Check(x))
3520 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3521 PyUnicode_GET_SIZE(x),
3522 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003523#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003524 else {
3525 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003526 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527 return NULL;
3528 }
3529}
3530
Guido van Rossumbef14172001-08-29 15:47:46 +00003531/* Wimpy, slow approach to tp_new calls for subtypes of long:
3532 first create a regular long from whatever arguments we got,
3533 then allocate a subtype instance and initialize it from
3534 the regular long. The regular long is then thrown away.
3535*/
3536static PyObject *
3537long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3538{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003539 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003540 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003541
3542 assert(PyType_IsSubtype(type, &PyLong_Type));
3543 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3544 if (tmp == NULL)
3545 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003546 assert(PyLong_CheckExact(tmp));
Guido van Rossumbef14172001-08-29 15:47:46 +00003547 n = tmp->ob_size;
3548 if (n < 0)
3549 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003550 newobj = (PyLongObject *)type->tp_alloc(type, n);
3551 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003552 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003553 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003554 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003555 assert(PyLong_Check(newobj));
3556 newobj->ob_size = tmp->ob_size;
Guido van Rossumbef14172001-08-29 15:47:46 +00003557 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003558 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003559 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003560 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003561}
3562
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003563static PyObject *
3564long_getnewargs(PyLongObject *v)
3565{
3566 return Py_BuildValue("(N)", _PyLong_Copy(v));
3567}
3568
3569static PyMethodDef long_methods[] = {
3570 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3571 {NULL, NULL} /* sentinel */
3572};
3573
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003574PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003575"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003576\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003577Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003578point argument will be truncated towards zero (this does not include a\n\
3579string representation of a floating point number!) When converting a\n\
3580string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003581converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003582
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003583static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003584 (binaryfunc) long_add, /*nb_add*/
3585 (binaryfunc) long_sub, /*nb_subtract*/
3586 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003587 long_mod, /*nb_remainder*/
3588 long_divmod, /*nb_divmod*/
3589 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003590 (unaryfunc) long_neg, /*nb_negative*/
3591 (unaryfunc) long_pos, /*tp_positive*/
3592 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003593 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003594 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003595 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003596 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003597 long_and, /*nb_and*/
3598 long_xor, /*nb_xor*/
3599 long_or, /*nb_or*/
Neal Norwitzca810462006-08-29 07:57:59 +00003600 0, /*nb_coerce*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003601 long_int, /*nb_int*/
3602 long_long, /*nb_long*/
3603 long_float, /*nb_float*/
3604 long_oct, /*nb_oct*/
3605 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003606 0, /* nb_inplace_add */
3607 0, /* nb_inplace_subtract */
3608 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003609 0, /* nb_inplace_remainder */
3610 0, /* nb_inplace_power */
3611 0, /* nb_inplace_lshift */
3612 0, /* nb_inplace_rshift */
3613 0, /* nb_inplace_and */
3614 0, /* nb_inplace_xor */
3615 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003616 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003617 long_true_divide, /* nb_true_divide */
3618 0, /* nb_inplace_floor_divide */
3619 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003620 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003621};
3622
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003623PyTypeObject PyLong_Type = {
3624 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625 0, /* ob_size */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003626 "int", /* tp_name */
3627 /* See _PyLong_New for why this isn't
3628 sizeof(PyLongObject) - sizeof(digit) */
3629 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003631 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632 0, /* tp_print */
3633 0, /* tp_getattr */
3634 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003635 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003636 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637 &long_as_number, /* tp_as_number */
3638 0, /* tp_as_sequence */
3639 0, /* tp_as_mapping */
3640 (hashfunc)long_hash, /* tp_hash */
3641 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003642 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003643 PyObject_GenericGetAttr, /* tp_getattro */
3644 0, /* tp_setattro */
3645 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003646 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3647 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003648 long_doc, /* tp_doc */
3649 0, /* tp_traverse */
3650 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003651 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003652 0, /* tp_weaklistoffset */
3653 0, /* tp_iter */
3654 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003655 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003656 0, /* tp_members */
3657 0, /* tp_getset */
3658 0, /* tp_base */
3659 0, /* tp_dict */
3660 0, /* tp_descr_get */
3661 0, /* tp_descr_set */
3662 0, /* tp_dictoffset */
3663 0, /* tp_init */
3664 0, /* tp_alloc */
3665 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003666 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003667};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003668
3669int
3670_PyLong_Init(void)
3671{
3672#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3673 int ival;
3674 PyLongObject *v = small_ints;
3675 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3676 PyObject_INIT(v, &PyLong_Type);
3677 v->ob_size = -1;
3678 v->ob_digit[0] = -ival;
3679 }
3680 for (; ival < NSMALLPOSINTS; ival++, v++) {
3681 PyObject_INIT(v, &PyLong_Type);
3682 v->ob_size = ival ? 1 : 0;
3683 v->ob_digit[0] = ival;
3684 }
3685#endif
3686 return 1;
3687}
3688
3689void
3690PyLong_Fini(void)
3691{
3692#if 0
3693 int i;
3694 /* This is currently not needed; the small integers
3695 are statically allocated */
3696#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3697 PyIntObject **q;
3698
3699 i = NSMALLNEGINTS + NSMALLPOSINTS;
3700 q = small_ints;
3701 while (--i >= 0) {
3702 Py_XDECREF(*q);
3703 *q++ = NULL;
3704 }
3705#endif
3706#endif
3707}