blob: 250215ca8bacab7b913993563a9243dccf6aa160 [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;
2150 CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b);
2151 return Py_CmpToRich(op, long_compare(a, b));
2152}
2153
Guido van Rossum9bfef441993-03-29 10:43:31 +00002154static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002155long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002156{
2157 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002158 Py_ssize_t i;
2159 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002160
2161 /* This is designed so that Python ints and longs with the
2162 same value hash to the same value, otherwise comparisons
2163 of mapping keys will turn out weird */
2164 i = v->ob_size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00002165 switch(i) {
2166 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2167 case 0: return 0;
2168 case 1: return v->ob_digit[0];
2169 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002170 sign = 1;
2171 x = 0;
2172 if (i < 0) {
2173 sign = -1;
2174 i = -(i);
2175 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002176#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002177 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002178 /* Force a native long #-bits (32 or 64) circular shift */
2179 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002180 x += v->ob_digit[i];
2181 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002182#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002183 x = x * sign;
2184 if (x == -1)
2185 x = -2;
2186 return x;
2187}
2188
2189
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002190/* Add the absolute values of two long integers. */
2191
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002192static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002193x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002194{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002195 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002196 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002197 int i;
2198 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002199
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002200 /* Ensure a is the larger of the two: */
2201 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002202 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002203 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002204 size_a = size_b;
2205 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002206 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002207 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002208 if (z == NULL)
2209 return NULL;
2210 for (i = 0; i < size_b; ++i) {
2211 carry += a->ob_digit[i] + b->ob_digit[i];
2212 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002213 carry >>= SHIFT;
2214 }
2215 for (; i < size_a; ++i) {
2216 carry += a->ob_digit[i];
2217 z->ob_digit[i] = carry & MASK;
2218 carry >>= SHIFT;
2219 }
2220 z->ob_digit[i] = carry;
2221 return long_normalize(z);
2222}
2223
2224/* Subtract the absolute values of two integers. */
2225
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002226static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002227x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002228{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002229 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002230 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002231 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002232 int sign = 1;
2233 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002234
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002235 /* Ensure a is the larger of the two: */
2236 if (size_a < size_b) {
2237 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002238 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002239 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002240 size_a = size_b;
2241 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002242 }
2243 else if (size_a == size_b) {
2244 /* Find highest digit where a and b differ: */
2245 i = size_a;
2246 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2247 ;
2248 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002249 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002250 if (a->ob_digit[i] < b->ob_digit[i]) {
2251 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002252 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002253 }
2254 size_a = size_b = i+1;
2255 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002256 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002257 if (z == NULL)
2258 return NULL;
2259 for (i = 0; i < size_b; ++i) {
2260 /* The following assumes unsigned arithmetic
2261 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002262 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002263 z->ob_digit[i] = borrow & MASK;
2264 borrow >>= SHIFT;
2265 borrow &= 1; /* Keep only one sign bit */
2266 }
2267 for (; i < size_a; ++i) {
2268 borrow = a->ob_digit[i] - borrow;
2269 z->ob_digit[i] = borrow & MASK;
2270 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002271 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002272 }
2273 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002274 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002275 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002276 return long_normalize(z);
2277}
2278
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002279static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002280long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002281{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002282 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002283
Neil Schemenauerba872e22001-01-04 01:46:03 +00002284 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2285
Guido van Rossumddefaf32007-01-14 03:31:43 +00002286 if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1)
2287 return PyInt_FromLong(MEDIUM_VALUE(a) +
2288 MEDIUM_VALUE(b));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002289 if (a->ob_size < 0) {
2290 if (b->ob_size < 0) {
2291 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002292 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002293 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002294 }
2295 else
2296 z = x_sub(b, a);
2297 }
2298 else {
2299 if (b->ob_size < 0)
2300 z = x_sub(a, b);
2301 else
2302 z = x_add(a, b);
2303 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002304 Py_DECREF(a);
2305 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002306 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002307}
2308
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002309static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002310long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002311{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002312 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002313
Neil Schemenauerba872e22001-01-04 01:46:03 +00002314 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2315
Guido van Rossumddefaf32007-01-14 03:31:43 +00002316 if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1)
2317 return PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002318 if (a->ob_size < 0) {
2319 if (b->ob_size < 0)
2320 z = x_sub(a, b);
2321 else
2322 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002323 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002324 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002325 }
2326 else {
2327 if (b->ob_size < 0)
2328 z = x_add(a, b);
2329 else
2330 z = x_sub(a, b);
2331 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002332 Py_DECREF(a);
2333 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002334 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002335}
2336
Tim Peters5af4e6c2002-08-12 02:31:19 +00002337/* Grade school multiplication, ignoring the signs.
2338 * Returns the absolute value of the product, or NULL if error.
2339 */
2340static PyLongObject *
2341x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002342{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002343 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002344 Py_ssize_t size_a = ABS(a->ob_size);
2345 Py_ssize_t size_b = ABS(b->ob_size);
2346 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002347
Tim Peters5af4e6c2002-08-12 02:31:19 +00002348 z = _PyLong_New(size_a + size_b);
2349 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002350 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002351
2352 memset(z->ob_digit, 0, z->ob_size * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002353 if (a == b) {
2354 /* Efficient squaring per HAC, Algorithm 14.16:
2355 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2356 * Gives slightly less than a 2x speedup when a == b,
2357 * via exploiting that each entry in the multiplication
2358 * pyramid appears twice (except for the size_a squares).
2359 */
2360 for (i = 0; i < size_a; ++i) {
2361 twodigits carry;
2362 twodigits f = a->ob_digit[i];
2363 digit *pz = z->ob_digit + (i << 1);
2364 digit *pa = a->ob_digit + i + 1;
2365 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002366
Tim Peters0973b992004-08-29 22:16:50 +00002367 SIGCHECK({
2368 Py_DECREF(z);
2369 return NULL;
2370 })
2371
2372 carry = *pz + f * f;
2373 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002374 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002375 assert(carry <= MASK);
2376
2377 /* Now f is added in twice in each column of the
2378 * pyramid it appears. Same as adding f<<1 once.
2379 */
2380 f <<= 1;
2381 while (pa < paend) {
2382 carry += *pz + *pa++ * f;
2383 *pz++ = (digit)(carry & MASK);
2384 carry >>= SHIFT;
2385 assert(carry <= (MASK << 1));
2386 }
2387 if (carry) {
2388 carry += *pz;
2389 *pz++ = (digit)(carry & MASK);
2390 carry >>= SHIFT;
2391 }
2392 if (carry)
2393 *pz += (digit)(carry & MASK);
2394 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002395 }
Tim Peters0973b992004-08-29 22:16:50 +00002396 }
2397 else { /* a is not the same as b -- gradeschool long mult */
2398 for (i = 0; i < size_a; ++i) {
2399 twodigits carry = 0;
2400 twodigits f = a->ob_digit[i];
2401 digit *pz = z->ob_digit + i;
2402 digit *pb = b->ob_digit;
2403 digit *pbend = b->ob_digit + size_b;
2404
2405 SIGCHECK({
2406 Py_DECREF(z);
2407 return NULL;
2408 })
2409
2410 while (pb < pbend) {
2411 carry += *pz + *pb++ * f;
2412 *pz++ = (digit)(carry & MASK);
2413 carry >>= SHIFT;
2414 assert(carry <= MASK);
2415 }
2416 if (carry)
2417 *pz += (digit)(carry & MASK);
2418 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002419 }
2420 }
Tim Peters44121a62002-08-12 06:17:58 +00002421 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002422}
2423
2424/* A helper for Karatsuba multiplication (k_mul).
2425 Takes a long "n" and an integer "size" representing the place to
2426 split, and sets low and high such that abs(n) == (high << size) + low,
2427 viewing the shift as being by digits. The sign bit is ignored, and
2428 the return values are >= 0.
2429 Returns 0 on success, -1 on failure.
2430*/
2431static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002432kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002433{
2434 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002435 Py_ssize_t size_lo, size_hi;
2436 const Py_ssize_t size_n = ABS(n->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002437
2438 size_lo = MIN(size_n, size);
2439 size_hi = size_n - size_lo;
2440
2441 if ((hi = _PyLong_New(size_hi)) == NULL)
2442 return -1;
2443 if ((lo = _PyLong_New(size_lo)) == NULL) {
2444 Py_DECREF(hi);
2445 return -1;
2446 }
2447
2448 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2449 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2450
2451 *high = long_normalize(hi);
2452 *low = long_normalize(lo);
2453 return 0;
2454}
2455
Tim Peters60004642002-08-12 22:01:34 +00002456static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2457
Tim Peters5af4e6c2002-08-12 02:31:19 +00002458/* Karatsuba multiplication. Ignores the input signs, and returns the
2459 * absolute value of the product (or NULL if error).
2460 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2461 */
2462static PyLongObject *
2463k_mul(PyLongObject *a, PyLongObject *b)
2464{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002465 Py_ssize_t asize = ABS(a->ob_size);
2466 Py_ssize_t bsize = ABS(b->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002467 PyLongObject *ah = NULL;
2468 PyLongObject *al = NULL;
2469 PyLongObject *bh = NULL;
2470 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002471 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002472 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002473 Py_ssize_t shift; /* the number of digits we split off */
2474 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002475
Tim Peters5af4e6c2002-08-12 02:31:19 +00002476 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2477 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2478 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002479 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002480 * By picking X to be a power of 2, "*X" is just shifting, and it's
2481 * been reduced to 3 multiplies on numbers half the size.
2482 */
2483
Tim Petersfc07e562002-08-12 02:54:10 +00002484 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002485 * is largest.
2486 */
Tim Peters738eda72002-08-12 15:08:20 +00002487 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002488 t1 = a;
2489 a = b;
2490 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002491
2492 i = asize;
2493 asize = bsize;
2494 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002495 }
2496
2497 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002498 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2499 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002500 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002501 return _PyLong_New(0);
2502 else
2503 return x_mul(a, b);
2504 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002505
Tim Peters60004642002-08-12 22:01:34 +00002506 /* If a is small compared to b, splitting on b gives a degenerate
2507 * case with ah==0, and Karatsuba may be (even much) less efficient
2508 * than "grade school" then. However, we can still win, by viewing
2509 * b as a string of "big digits", each of width a->ob_size. That
2510 * leads to a sequence of balanced calls to k_mul.
2511 */
2512 if (2 * asize <= bsize)
2513 return k_lopsided_mul(a, b);
2514
Tim Petersd6974a52002-08-13 20:37:51 +00002515 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002516 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002517 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Tim Petersd6974a52002-08-13 20:37:51 +00002518 assert(ah->ob_size > 0); /* the split isn't degenerate */
2519
Tim Peters0973b992004-08-29 22:16:50 +00002520 if (a == b) {
2521 bh = ah;
2522 bl = al;
2523 Py_INCREF(bh);
2524 Py_INCREF(bl);
2525 }
2526 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002527
Tim Petersd64c1de2002-08-12 17:36:03 +00002528 /* The plan:
2529 * 1. Allocate result space (asize + bsize digits: that's always
2530 * enough).
2531 * 2. Compute ah*bh, and copy into result at 2*shift.
2532 * 3. Compute al*bl, and copy into result at 0. Note that this
2533 * can't overlap with #2.
2534 * 4. Subtract al*bl from the result, starting at shift. This may
2535 * underflow (borrow out of the high digit), but we don't care:
2536 * we're effectively doing unsigned arithmetic mod
2537 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2538 * borrows and carries out of the high digit can be ignored.
2539 * 5. Subtract ah*bh from the result, starting at shift.
2540 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2541 * at shift.
2542 */
2543
2544 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002545 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002546 if (ret == NULL) goto fail;
2547#ifdef Py_DEBUG
2548 /* Fill with trash, to catch reference to uninitialized digits. */
2549 memset(ret->ob_digit, 0xDF, ret->ob_size * sizeof(digit));
2550#endif
Tim Peters44121a62002-08-12 06:17:58 +00002551
Tim Petersd64c1de2002-08-12 17:36:03 +00002552 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002553 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2554 assert(t1->ob_size >= 0);
2555 assert(2*shift + t1->ob_size <= ret->ob_size);
2556 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2557 t1->ob_size * sizeof(digit));
2558
2559 /* Zero-out the digits higher than the ah*bh copy. */
2560 i = ret->ob_size - 2*shift - t1->ob_size;
Tim Peters44121a62002-08-12 06:17:58 +00002561 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002562 memset(ret->ob_digit + 2*shift + t1->ob_size, 0,
Tim Peters44121a62002-08-12 06:17:58 +00002563 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002564
Tim Petersd64c1de2002-08-12 17:36:03 +00002565 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002566 if ((t2 = k_mul(al, bl)) == NULL) {
2567 Py_DECREF(t1);
2568 goto fail;
2569 }
2570 assert(t2->ob_size >= 0);
2571 assert(t2->ob_size <= 2*shift); /* no overlap with high digits */
2572 memcpy(ret->ob_digit, t2->ob_digit, t2->ob_size * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002573
2574 /* Zero out remaining digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002575 i = 2*shift - t2->ob_size; /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002576 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002577 memset(ret->ob_digit + t2->ob_size, 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002578
Tim Petersd64c1de2002-08-12 17:36:03 +00002579 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2580 * because it's fresher in cache.
2581 */
Tim Peters738eda72002-08-12 15:08:20 +00002582 i = ret->ob_size - shift; /* # digits after shift */
Tim Petersd64c1de2002-08-12 17:36:03 +00002583 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, t2->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002584 Py_DECREF(t2);
2585
Tim Petersd64c1de2002-08-12 17:36:03 +00002586 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, t1->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002587 Py_DECREF(t1);
2588
Tim Petersd64c1de2002-08-12 17:36:03 +00002589 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002590 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2591 Py_DECREF(ah);
2592 Py_DECREF(al);
2593 ah = al = NULL;
2594
Tim Peters0973b992004-08-29 22:16:50 +00002595 if (a == b) {
2596 t2 = t1;
2597 Py_INCREF(t2);
2598 }
2599 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002600 Py_DECREF(t1);
2601 goto fail;
2602 }
2603 Py_DECREF(bh);
2604 Py_DECREF(bl);
2605 bh = bl = NULL;
2606
Tim Peters738eda72002-08-12 15:08:20 +00002607 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002608 Py_DECREF(t1);
2609 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002610 if (t3 == NULL) goto fail;
Tim Peters547607c2002-08-12 19:43:49 +00002611 assert(t3->ob_size >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002612
Tim Petersd6974a52002-08-13 20:37:51 +00002613 /* Add t3. It's not obvious why we can't run out of room here.
2614 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002615 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002616 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, t3->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002617 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002618
Tim Peters5af4e6c2002-08-12 02:31:19 +00002619 return long_normalize(ret);
2620
2621 fail:
2622 Py_XDECREF(ret);
2623 Py_XDECREF(ah);
2624 Py_XDECREF(al);
2625 Py_XDECREF(bh);
2626 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002627 return NULL;
2628}
2629
Tim Petersd6974a52002-08-13 20:37:51 +00002630/* (*) Why adding t3 can't "run out of room" above.
2631
Tim Petersab86c2b2002-08-15 20:06:00 +00002632Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2633to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002634
Tim Petersab86c2b2002-08-15 20:06:00 +000026351. For any integer i, i = c(i/2) + f(i/2). In particular,
2636 bsize = c(bsize/2) + f(bsize/2).
26372. shift = f(bsize/2)
26383. asize <= bsize
26394. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2640 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002641
Tim Petersab86c2b2002-08-15 20:06:00 +00002642We allocated asize + bsize result digits, and add t3 into them at an offset
2643of shift. This leaves asize+bsize-shift allocated digit positions for t3
2644to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2645asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002646
Tim Petersab86c2b2002-08-15 20:06:00 +00002647bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2648at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002649
Tim Petersab86c2b2002-08-15 20:06:00 +00002650If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2651digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2652most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002653
Tim Petersab86c2b2002-08-15 20:06:00 +00002654The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002655
Tim Petersab86c2b2002-08-15 20:06:00 +00002656 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002657
Tim Petersab86c2b2002-08-15 20:06:00 +00002658and we have asize + c(bsize/2) available digit positions. We need to show
2659this is always enough. An instance of c(bsize/2) cancels out in both, so
2660the question reduces to whether asize digits is enough to hold
2661(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2662then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2663asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2664digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2665asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002666c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2667is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2668bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002669
Tim Peters48d52c02002-08-14 17:07:32 +00002670Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2671clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2672ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002673*/
2674
Tim Peters60004642002-08-12 22:01:34 +00002675/* b has at least twice the digits of a, and a is big enough that Karatsuba
2676 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2677 * of slices, each with a->ob_size digits, and multiply the slices by a,
2678 * one at a time. This gives k_mul balanced inputs to work with, and is
2679 * also cache-friendly (we compute one double-width slice of the result
2680 * at a time, then move on, never bactracking except for the helpful
2681 * single-width slice overlap between successive partial sums).
2682 */
2683static PyLongObject *
2684k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2685{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002686 const Py_ssize_t asize = ABS(a->ob_size);
2687 Py_ssize_t bsize = ABS(b->ob_size);
2688 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002689 PyLongObject *ret;
2690 PyLongObject *bslice = NULL;
2691
2692 assert(asize > KARATSUBA_CUTOFF);
2693 assert(2 * asize <= bsize);
2694
2695 /* Allocate result space, and zero it out. */
2696 ret = _PyLong_New(asize + bsize);
2697 if (ret == NULL)
2698 return NULL;
2699 memset(ret->ob_digit, 0, ret->ob_size * sizeof(digit));
2700
2701 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002702 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002703 if (bslice == NULL)
2704 goto fail;
2705
2706 nbdone = 0;
2707 while (bsize > 0) {
2708 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002709 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002710
2711 /* Multiply the next slice of b by a. */
2712 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2713 nbtouse * sizeof(digit));
2714 bslice->ob_size = nbtouse;
2715 product = k_mul(a, bslice);
2716 if (product == NULL)
2717 goto fail;
2718
2719 /* Add into result. */
2720 (void)v_iadd(ret->ob_digit + nbdone, ret->ob_size - nbdone,
2721 product->ob_digit, product->ob_size);
2722 Py_DECREF(product);
2723
2724 bsize -= nbtouse;
2725 nbdone += nbtouse;
2726 }
2727
2728 Py_DECREF(bslice);
2729 return long_normalize(ret);
2730
2731 fail:
2732 Py_DECREF(ret);
2733 Py_XDECREF(bslice);
2734 return NULL;
2735}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002736
2737static PyObject *
2738long_mul(PyLongObject *v, PyLongObject *w)
2739{
2740 PyLongObject *a, *b, *z;
2741
2742 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002743 Py_INCREF(Py_NotImplemented);
2744 return Py_NotImplemented;
2745 }
2746
Guido van Rossumddefaf32007-01-14 03:31:43 +00002747 if (ABS(v->ob_size) <= 1 && ABS(w->ob_size) <= 1)
2748 return PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w));
2749
Tim Petersd64c1de2002-08-12 17:36:03 +00002750 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002751 /* Negate if exactly one of the inputs is negative. */
2752 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002753 NEGATE(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002754 Py_DECREF(a);
2755 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002756 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002757}
2758
Guido van Rossume32e0141992-01-19 16:31:05 +00002759/* The / and % operators are now defined in terms of divmod().
2760 The expression a mod b has the value a - b*floor(a/b).
2761 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002762 |a| by |b|, with the sign of a. This is also expressed
2763 as a - b*trunc(a/b), if trunc truncates towards zero.
2764 Some examples:
2765 a b a rem b a mod b
2766 13 10 3 3
2767 -13 10 -3 7
2768 13 -10 3 -7
2769 -13 -10 -3 -3
2770 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002771 have different signs. We then subtract one from the 'div'
2772 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002773
Tim Peters47e52ee2004-08-30 02:44:38 +00002774/* Compute
2775 * *pdiv, *pmod = divmod(v, w)
2776 * NULL can be passed for pdiv or pmod, in which case that part of
2777 * the result is simply thrown away. The caller owns a reference to
2778 * each of these it requests (does not pass NULL for).
2779 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002780static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002781l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002782 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002783{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002784 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002785
Guido van Rossume32e0141992-01-19 16:31:05 +00002786 if (long_divrem(v, w, &div, &mod) < 0)
2787 return -1;
Guido van Rossum472c04f1996-12-05 21:57:21 +00002788 if ((mod->ob_size < 0 && w->ob_size > 0) ||
2789 (mod->ob_size > 0 && w->ob_size < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002790 PyLongObject *temp;
2791 PyLongObject *one;
2792 temp = (PyLongObject *) long_add(mod, w);
2793 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002794 mod = temp;
2795 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002796 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002797 return -1;
2798 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002799 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002800 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002801 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2802 Py_DECREF(mod);
2803 Py_DECREF(div);
2804 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002805 return -1;
2806 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002807 Py_DECREF(one);
2808 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002809 div = temp;
2810 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002811 if (pdiv != NULL)
2812 *pdiv = div;
2813 else
2814 Py_DECREF(div);
2815
2816 if (pmod != NULL)
2817 *pmod = mod;
2818 else
2819 Py_DECREF(mod);
2820
Guido van Rossume32e0141992-01-19 16:31:05 +00002821 return 0;
2822}
2823
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002824static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002825long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002826{
Tim Peters47e52ee2004-08-30 02:44:38 +00002827 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002828
2829 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002830 if (l_divmod(a, b, &div, NULL) < 0)
2831 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002832 Py_DECREF(a);
2833 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002834 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002835}
2836
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002837static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002838long_true_divide(PyObject *v, PyObject *w)
2839{
Tim Peterse2a60002001-09-04 06:17:36 +00002840 PyLongObject *a, *b;
2841 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002842 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002843
2844 CONVERT_BINOP(v, w, &a, &b);
2845 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2846 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002847 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2848 Py_DECREF(a);
2849 Py_DECREF(b);
2850 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002851 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002852 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2853 but should really be set correctly after sucessful calls to
2854 _PyLong_AsScaledDouble() */
2855 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002856
2857 if (bd == 0.0) {
2858 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002859 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002860 return NULL;
2861 }
2862
2863 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2864 ad /= bd; /* overflow/underflow impossible here */
2865 aexp -= bexp;
2866 if (aexp > INT_MAX / SHIFT)
2867 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002868 else if (aexp < -(INT_MAX / SHIFT))
2869 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002870 errno = 0;
2871 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002872 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002873 goto overflow;
2874 return PyFloat_FromDouble(ad);
2875
2876overflow:
2877 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002878 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002879 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002880
Tim Peters20dab9f2001-09-04 05:31:47 +00002881}
2882
2883static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002884long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002885{
Tim Peters47e52ee2004-08-30 02:44:38 +00002886 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002887
2888 CONVERT_BINOP(v, w, &a, &b);
2889
Tim Peters47e52ee2004-08-30 02:44:38 +00002890 if (l_divmod(a, b, NULL, &mod) < 0)
2891 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002892 Py_DECREF(a);
2893 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002894 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002895}
2896
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002897static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002898long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002899{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002900 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002901 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002902
2903 CONVERT_BINOP(v, w, &a, &b);
2904
2905 if (l_divmod(a, b, &div, &mod) < 0) {
2906 Py_DECREF(a);
2907 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002908 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002909 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002910 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002911 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002912 PyTuple_SetItem(z, 0, (PyObject *) div);
2913 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002914 }
2915 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002916 Py_DECREF(div);
2917 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002918 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002919 Py_DECREF(a);
2920 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002921 return z;
2922}
2923
Tim Peters47e52ee2004-08-30 02:44:38 +00002924/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002925static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002926long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002927{
Tim Peters47e52ee2004-08-30 02:44:38 +00002928 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2929 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002930
Tim Peters47e52ee2004-08-30 02:44:38 +00002931 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002932 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002933 PyLongObject *temp = NULL;
2934
2935 /* 5-ary values. If the exponent is large enough, table is
2936 * precomputed so that table[i] == a**i % c for i in range(32).
2937 */
2938 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2939 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2940
2941 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002942 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002943 if (PyLong_Check(x)) {
2944 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002945 Py_INCREF(x);
2946 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002947 else if (x == Py_None)
2948 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002949 else {
2950 Py_DECREF(a);
2951 Py_DECREF(b);
2952 Py_INCREF(Py_NotImplemented);
2953 return Py_NotImplemented;
2954 }
Tim Peters4c483c42001-09-05 06:24:58 +00002955
Tim Peters47e52ee2004-08-30 02:44:38 +00002956 if (b->ob_size < 0) { /* if exponent is negative */
2957 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002958 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002959 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002960 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002961 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002962 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002963 /* else return a float. This works because we know
2964 that this calls float_pow() which converts its
2965 arguments to double. */
2966 Py_DECREF(a);
2967 Py_DECREF(b);
2968 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002969 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002970 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002971
2972 if (c) {
2973 /* if modulus == 0:
2974 raise ValueError() */
2975 if (c->ob_size == 0) {
2976 PyErr_SetString(PyExc_ValueError,
2977 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002978 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002979 }
2980
2981 /* if modulus < 0:
2982 negativeOutput = True
2983 modulus = -modulus */
2984 if (c->ob_size < 0) {
2985 negativeOutput = 1;
2986 temp = (PyLongObject *)_PyLong_Copy(c);
2987 if (temp == NULL)
2988 goto Error;
2989 Py_DECREF(c);
2990 c = temp;
2991 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00002992 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00002993 }
2994
2995 /* if modulus == 1:
2996 return 0 */
2997 if ((c->ob_size == 1) && (c->ob_digit[0] == 1)) {
2998 z = (PyLongObject *)PyLong_FromLong(0L);
2999 goto Done;
3000 }
3001
3002 /* if base < 0:
3003 base = base % modulus
3004 Having the base positive just makes things easier. */
3005 if (a->ob_size < 0) {
3006 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003007 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003008 Py_DECREF(a);
3009 a = temp;
3010 temp = NULL;
3011 }
3012 }
3013
3014 /* At this point a, b, and c are guaranteed non-negative UNLESS
3015 c is NULL, in which case a may be negative. */
3016
3017 z = (PyLongObject *)PyLong_FromLong(1L);
3018 if (z == NULL)
3019 goto Error;
3020
3021 /* Perform a modular reduction, X = X % c, but leave X alone if c
3022 * is NULL.
3023 */
3024#define REDUCE(X) \
3025 if (c != NULL) { \
3026 if (l_divmod(X, c, NULL, &temp) < 0) \
3027 goto Error; \
3028 Py_XDECREF(X); \
3029 X = temp; \
3030 temp = NULL; \
3031 }
3032
3033 /* Multiply two values, then reduce the result:
3034 result = X*Y % c. If c is NULL, skip the mod. */
3035#define MULT(X, Y, result) \
3036{ \
3037 temp = (PyLongObject *)long_mul(X, Y); \
3038 if (temp == NULL) \
3039 goto Error; \
3040 Py_XDECREF(result); \
3041 result = temp; \
3042 temp = NULL; \
3043 REDUCE(result) \
3044}
3045
3046 if (b->ob_size <= FIVEARY_CUTOFF) {
3047 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3048 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3049 for (i = b->ob_size - 1; i >= 0; --i) {
3050 digit bi = b->ob_digit[i];
3051
3052 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
3053 MULT(z, z, z)
3054 if (bi & j)
3055 MULT(z, a, z)
3056 }
3057 }
3058 }
3059 else {
3060 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3061 Py_INCREF(z); /* still holds 1L */
3062 table[0] = z;
3063 for (i = 1; i < 32; ++i)
3064 MULT(table[i-1], a, table[i])
3065
3066 for (i = b->ob_size - 1; i >= 0; --i) {
3067 const digit bi = b->ob_digit[i];
3068
3069 for (j = SHIFT - 5; j >= 0; j -= 5) {
3070 const int index = (bi >> j) & 0x1f;
3071 for (k = 0; k < 5; ++k)
3072 MULT(z, z, z)
3073 if (index)
3074 MULT(z, table[index], z)
3075 }
3076 }
3077 }
3078
3079 if (negativeOutput && (z->ob_size != 0)) {
3080 temp = (PyLongObject *)long_sub(z, c);
3081 if (temp == NULL)
3082 goto Error;
3083 Py_DECREF(z);
3084 z = temp;
3085 temp = NULL;
3086 }
3087 goto Done;
3088
3089 Error:
3090 if (z != NULL) {
3091 Py_DECREF(z);
3092 z = NULL;
3093 }
3094 /* fall through */
3095 Done:
Tim Peters47e52ee2004-08-30 02:44:38 +00003096 if (b->ob_size > FIVEARY_CUTOFF) {
3097 for (i = 0; i < 32; ++i)
3098 Py_XDECREF(table[i]);
3099 }
Tim Petersde7990b2005-07-17 23:45:23 +00003100 Py_DECREF(a);
3101 Py_DECREF(b);
3102 Py_XDECREF(c);
3103 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003104 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003105}
3106
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003107static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003108long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003109{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003110 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003111 PyLongObject *x;
3112 PyLongObject *w;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003113 if (ABS(v->ob_size) <=1)
3114 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003115 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003116 if (w == NULL)
3117 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003118 x = (PyLongObject *) long_add(v, w);
3119 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003120 if (x == NULL)
3121 return NULL;
Tim Peters40c397d2001-09-11 23:24:22 +00003122 x->ob_size = -(x->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003123 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003124}
3125
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003126static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003127long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003128{
Tim Peters69c2de32001-09-11 22:31:33 +00003129 if (PyLong_CheckExact(v)) {
3130 Py_INCREF(v);
3131 return (PyObject *)v;
3132 }
3133 else
3134 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003135}
3136
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003137static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003138long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003139{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003140 PyLongObject *z;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003141 if (ABS(v->ob_size) <= 1)
3142 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003143 z = (PyLongObject *)_PyLong_Copy(v);
3144 if (z != NULL)
3145 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003146 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003147}
3148
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003149static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003150long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003151{
3152 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003153 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003154 else
3155 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003156}
3157
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003158static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003159long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003160{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003161 return ABS(v->ob_size) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003162}
3163
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003164static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003165long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003166{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003167 PyLongObject *a, *b;
3168 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003169 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003170 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003171 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003172
Neil Schemenauerba872e22001-01-04 01:46:03 +00003173 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3174
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003175 if (a->ob_size < 0) {
3176 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003177 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003178 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003179 if (a1 == NULL)
3180 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003181 a2 = (PyLongObject *) long_rshift(a1, b);
3182 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003183 if (a2 == NULL)
3184 goto rshift_error;
3185 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003186 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003187 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003188 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003189
Neil Schemenauerba872e22001-01-04 01:46:03 +00003190 shiftby = PyLong_AsLong((PyObject *)b);
3191 if (shiftby == -1L && PyErr_Occurred())
3192 goto rshift_error;
3193 if (shiftby < 0) {
3194 PyErr_SetString(PyExc_ValueError,
3195 "negative shift count");
3196 goto rshift_error;
3197 }
3198 wordshift = shiftby / SHIFT;
3199 newsize = ABS(a->ob_size) - wordshift;
3200 if (newsize <= 0) {
3201 z = _PyLong_New(0);
3202 Py_DECREF(a);
3203 Py_DECREF(b);
3204 return (PyObject *)z;
3205 }
3206 loshift = shiftby % SHIFT;
3207 hishift = SHIFT - loshift;
3208 lomask = ((digit)1 << hishift) - 1;
3209 himask = MASK ^ lomask;
3210 z = _PyLong_New(newsize);
3211 if (z == NULL)
3212 goto rshift_error;
3213 if (a->ob_size < 0)
3214 z->ob_size = -(z->ob_size);
3215 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3216 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3217 if (i+1 < newsize)
3218 z->ob_digit[i] |=
3219 (a->ob_digit[j+1] << hishift) & himask;
3220 }
3221 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003222 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003223rshift_error:
3224 Py_DECREF(a);
3225 Py_DECREF(b);
3226 return (PyObject *) z;
3227
Guido van Rossumc6913e71991-11-19 20:26:46 +00003228}
3229
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003230static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003231long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003232{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003233 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003234 PyLongObject *a, *b;
3235 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003236 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003237 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003238 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003239
Neil Schemenauerba872e22001-01-04 01:46:03 +00003240 CONVERT_BINOP(v, w, &a, &b);
3241
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003242 shiftby = PyLong_AsLong((PyObject *)b);
3243 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003244 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003245 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003246 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003247 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003248 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003249 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003250 PyErr_SetString(PyExc_ValueError,
3251 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003252 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003253 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003254 /* wordshift, remshift = divmod(shiftby, SHIFT) */
3255 wordshift = (int)shiftby / SHIFT;
3256 remshift = (int)shiftby - wordshift * SHIFT;
3257
3258 oldsize = ABS(a->ob_size);
3259 newsize = oldsize + wordshift;
3260 if (remshift)
3261 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003262 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003263 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003264 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003265 if (a->ob_size < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003266 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003267 for (i = 0; i < wordshift; i++)
3268 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003269 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003270 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003271 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003272 z->ob_digit[i] = (digit)(accum & MASK);
3273 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003274 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003275 if (remshift)
3276 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003277 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003278 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003279 z = long_normalize(z);
3280lshift_error:
3281 Py_DECREF(a);
3282 Py_DECREF(b);
3283 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003284}
3285
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003286
3287/* Bitwise and/xor/or operations */
3288
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003289static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003290long_bitwise(PyLongObject *a,
3291 int op, /* '&', '|', '^' */
3292 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003293{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003294 digit maska, maskb; /* 0 or MASK */
3295 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003296 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003297 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003298 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003299 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003300 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003301
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003302 if (a->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003303 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003304 if (a == NULL)
3305 return NULL;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003306 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003307 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003308 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003309 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003310 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003311 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003312 if (b->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003313 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003314 if (b == NULL) {
3315 Py_DECREF(a);
3316 return NULL;
3317 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003318 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003319 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003320 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003321 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003322 maskb = 0;
3323 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003324
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003325 negz = 0;
3326 switch (op) {
3327 case '^':
3328 if (maska != maskb) {
3329 maska ^= MASK;
3330 negz = -1;
3331 }
3332 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003333 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003334 if (maska && maskb) {
3335 op = '|';
3336 maska ^= MASK;
3337 maskb ^= MASK;
3338 negz = -1;
3339 }
3340 break;
3341 case '|':
3342 if (maska || maskb) {
3343 op = '&';
3344 maska ^= MASK;
3345 maskb ^= MASK;
3346 negz = -1;
3347 }
3348 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003349 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003350
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003351 /* JRH: The original logic here was to allocate the result value (z)
3352 as the longer of the two operands. However, there are some cases
3353 where the result is guaranteed to be shorter than that: AND of two
3354 positives, OR of two negatives: use the shorter number. AND with
3355 mixed signs: use the positive number. OR with mixed signs: use the
3356 negative number. After the transformations above, op will be '&'
3357 iff one of these cases applies, and mask will be non-0 for operands
3358 whose length should be ignored.
3359 */
3360
3361 size_a = a->ob_size;
3362 size_b = b->ob_size;
3363 size_z = op == '&'
3364 ? (maska
3365 ? size_b
3366 : (maskb ? size_a : MIN(size_a, size_b)))
3367 : MAX(size_a, size_b);
3368 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003369 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003370 Py_DECREF(a);
3371 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003372 return NULL;
3373 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003374
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003375 for (i = 0; i < size_z; ++i) {
3376 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3377 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3378 switch (op) {
3379 case '&': z->ob_digit[i] = diga & digb; break;
3380 case '|': z->ob_digit[i] = diga | digb; break;
3381 case '^': z->ob_digit[i] = diga ^ digb; break;
3382 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003383 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003384
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003385 Py_DECREF(a);
3386 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003387 z = long_normalize(z);
3388 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003389 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003390 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003391 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003392 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003393}
3394
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003395static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003396long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003397{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003398 PyLongObject *a, *b;
3399 PyObject *c;
3400 CONVERT_BINOP(v, w, &a, &b);
3401 c = long_bitwise(a, '&', b);
3402 Py_DECREF(a);
3403 Py_DECREF(b);
3404 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003405}
3406
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003407static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003408long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003409{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003410 PyLongObject *a, *b;
3411 PyObject *c;
3412 CONVERT_BINOP(v, w, &a, &b);
3413 c = long_bitwise(a, '^', b);
3414 Py_DECREF(a);
3415 Py_DECREF(b);
3416 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003417}
3418
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003419static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003420long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003421{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003422 PyLongObject *a, *b;
3423 PyObject *c;
3424 CONVERT_BINOP(v, w, &a, &b);
3425 c = long_bitwise(a, '|', b);
3426 Py_DECREF(a);
3427 Py_DECREF(b);
3428 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003429}
3430
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003431static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003432long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003433{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003434 if (PyLong_CheckExact(v))
3435 Py_INCREF(v);
3436 else
3437 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003438 return v;
3439}
3440
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003441static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003442long_int(PyObject *v)
3443{
Guido van Rossumddefaf32007-01-14 03:31:43 +00003444 return long_long(v);
Walter Dörwaldf1715402002-11-19 20:49:15 +00003445}
3446
3447static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003448long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003449{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003450 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003451 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003452 if (result == -1.0 && PyErr_Occurred())
3453 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003454 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003455}
3456
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003457static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003458long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003459{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00003460 return long_format(v, 8);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003461}
3462
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003463static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003464long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003465{
Guido van Rossumd2dbecb2006-08-18 16:29:54 +00003466 return long_format(v, 16);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003467}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003468
3469static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003470long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003471
Tim Peters6d6c1a32001-08-02 04:15:00 +00003472static PyObject *
3473long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3474{
3475 PyObject *x = NULL;
3476 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003477 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003478
Guido van Rossumbef14172001-08-29 15:47:46 +00003479 if (type != &PyLong_Type)
3480 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003481 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482 &x, &base))
3483 return NULL;
3484 if (x == NULL)
3485 return PyLong_FromLong(0L);
3486 if (base == -909)
3487 return PyNumber_Long(x);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003488 else if (PyString_Check(x)) {
3489 char *s = PyString_AS_STRING(x);
3490 char *end;
3491 PyObject *r = PyLong_FromString(s, &end, base);
3492 if (r != NULL && end != s + PyString_GET_SIZE(x)) {
3493 PyErr_SetString(PyExc_ValueError,
3494 "null byte in argument for int()");
3495 Py_DECREF(r);
3496 r = NULL;
3497 }
3498 return r;
3499 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003500#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003501 else if (PyUnicode_Check(x))
3502 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3503 PyUnicode_GET_SIZE(x),
3504 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003505#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003506 else {
3507 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003508 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003509 return NULL;
3510 }
3511}
3512
Guido van Rossumbef14172001-08-29 15:47:46 +00003513/* Wimpy, slow approach to tp_new calls for subtypes of long:
3514 first create a regular long from whatever arguments we got,
3515 then allocate a subtype instance and initialize it from
3516 the regular long. The regular long is then thrown away.
3517*/
3518static PyObject *
3519long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3520{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003521 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003522 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003523
3524 assert(PyType_IsSubtype(type, &PyLong_Type));
3525 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3526 if (tmp == NULL)
3527 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003528 assert(PyLong_CheckExact(tmp));
Guido van Rossumbef14172001-08-29 15:47:46 +00003529 n = tmp->ob_size;
3530 if (n < 0)
3531 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003532 newobj = (PyLongObject *)type->tp_alloc(type, n);
3533 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003534 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003535 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003536 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003537 assert(PyLong_Check(newobj));
3538 newobj->ob_size = tmp->ob_size;
Guido van Rossumbef14172001-08-29 15:47:46 +00003539 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003540 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003541 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003542 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003543}
3544
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003545static PyObject *
3546long_getnewargs(PyLongObject *v)
3547{
3548 return Py_BuildValue("(N)", _PyLong_Copy(v));
3549}
3550
3551static PyMethodDef long_methods[] = {
3552 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3553 {NULL, NULL} /* sentinel */
3554};
3555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003556PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003557"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003558\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003559Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003560point argument will be truncated towards zero (this does not include a\n\
3561string representation of a floating point number!) When converting a\n\
3562string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003563converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003564
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003565static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003566 (binaryfunc) long_add, /*nb_add*/
3567 (binaryfunc) long_sub, /*nb_subtract*/
3568 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003569 long_mod, /*nb_remainder*/
3570 long_divmod, /*nb_divmod*/
3571 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003572 (unaryfunc) long_neg, /*nb_negative*/
3573 (unaryfunc) long_pos, /*tp_positive*/
3574 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003575 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003576 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003577 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003578 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003579 long_and, /*nb_and*/
3580 long_xor, /*nb_xor*/
3581 long_or, /*nb_or*/
Neal Norwitzca810462006-08-29 07:57:59 +00003582 0, /*nb_coerce*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003583 long_int, /*nb_int*/
3584 long_long, /*nb_long*/
3585 long_float, /*nb_float*/
3586 long_oct, /*nb_oct*/
3587 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003588 0, /* nb_inplace_add */
3589 0, /* nb_inplace_subtract */
3590 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003591 0, /* nb_inplace_remainder */
3592 0, /* nb_inplace_power */
3593 0, /* nb_inplace_lshift */
3594 0, /* nb_inplace_rshift */
3595 0, /* nb_inplace_and */
3596 0, /* nb_inplace_xor */
3597 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003598 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003599 long_true_divide, /* nb_true_divide */
3600 0, /* nb_inplace_floor_divide */
3601 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003602 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003603};
3604
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003605PyTypeObject PyLong_Type = {
3606 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607 0, /* ob_size */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003608 "int", /* tp_name */
3609 /* See _PyLong_New for why this isn't
3610 sizeof(PyLongObject) - sizeof(digit) */
3611 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003612 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003613 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003614 0, /* tp_print */
3615 0, /* tp_getattr */
3616 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003617 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003618 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003619 &long_as_number, /* tp_as_number */
3620 0, /* tp_as_sequence */
3621 0, /* tp_as_mapping */
3622 (hashfunc)long_hash, /* tp_hash */
3623 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003624 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625 PyObject_GenericGetAttr, /* tp_getattro */
3626 0, /* tp_setattro */
3627 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003628 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003629 long_doc, /* tp_doc */
3630 0, /* tp_traverse */
3631 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003632 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003633 0, /* tp_weaklistoffset */
3634 0, /* tp_iter */
3635 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003636 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637 0, /* tp_members */
3638 0, /* tp_getset */
3639 0, /* tp_base */
3640 0, /* tp_dict */
3641 0, /* tp_descr_get */
3642 0, /* tp_descr_set */
3643 0, /* tp_dictoffset */
3644 0, /* tp_init */
3645 0, /* tp_alloc */
3646 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003647 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003648};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003649
3650int
3651_PyLong_Init(void)
3652{
3653#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3654 int ival;
3655 PyLongObject *v = small_ints;
3656 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3657 PyObject_INIT(v, &PyLong_Type);
3658 v->ob_size = -1;
3659 v->ob_digit[0] = -ival;
3660 }
3661 for (; ival < NSMALLPOSINTS; ival++, v++) {
3662 PyObject_INIT(v, &PyLong_Type);
3663 v->ob_size = ival ? 1 : 0;
3664 v->ob_digit[0] = ival;
3665 }
3666#endif
3667 return 1;
3668}
3669
3670void
3671PyLong_Fini(void)
3672{
3673#if 0
3674 int i;
3675 /* This is currently not needed; the small integers
3676 are statically allocated */
3677#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3678 PyIntObject **q;
3679
3680 i = NSMALLNEGINTS + NSMALLPOSINTS;
3681 q = small_ints;
3682 while (--i >= 0) {
3683 Py_XDECREF(*q);
3684 *q++ = NULL;
3685 }
3686#endif
3687#endif
3688}