blob: 15f56d6b43945fdf15ab63ff5df8b64b4034aaea [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
Eric Smith8c663262007-08-25 02:26:07 +00008#include "formatter_unicode.h"
9
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
13#define NSMALLPOSINTS 257
14#endif
15#ifndef NSMALLNEGINTS
16#define NSMALLNEGINTS 5
17#endif
18#if NSMALLNEGINTS + NSMALLPOSINTS > 0
19/* Small integers are preallocated in this array so that they
20 can be shared.
21 The integers that are preallocated are those in the range
22 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
23*/
24static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
25#ifdef COUNT_ALLOCS
26int quick_int_allocs, quick_neg_int_allocs;
27#endif
28
Guido van Rossum7eaf8222007-06-18 17:58:50 +000029static PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +000030get_small_int(int ival)
31{
32 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
33 Py_INCREF(v);
34#ifdef COUNT_ALLOCS
35 if (ival >= 0)
36 quick_int_allocs++;
37 else
38 quick_neg_int_allocs++;
39#endif
40 return v;
41}
42#define CHECK_SMALL_INT(ival) \
43 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
44 return get_small_int(ival); \
45 } while(0)
46
47#else
48#define CHECK_SMALL_INT(ival)
49#endif
50
Christian Heimes90aa7642007-12-19 02:45:37 +000051#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(x)->ob_digit[0] : (Py_SIZE(x) == 0 ? 0 : (x)->ob_digit[0]))
Guido van Rossumddefaf32007-01-14 03:31:43 +000052/* If a freshly-allocated long is already shared, it must
53 be a small integer, so negating it must go to PyLong_FromLong */
54#define NEGATE(x) \
Christian Heimes90aa7642007-12-19 02:45:37 +000055 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
Christian Heimes217cfd12007-12-02 14:31:20 +000056 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000057 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
58 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000059/* For long multiplication, use the O(N**2) school algorithm unless
60 * both operands contain more than KARATSUBA_CUTOFF digits (this
61 * being an internal Python long digit, in base BASE).
62 */
Tim Peters0973b992004-08-29 22:16:50 +000063#define KARATSUBA_CUTOFF 70
64#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000065
Tim Peters47e52ee2004-08-30 02:44:38 +000066/* For exponentiation, use the binary left-to-right algorithm
67 * unless the exponent contains more than FIVEARY_CUTOFF digits.
68 * In that case, do 5 bits at a time. The potential drawback is that
69 * a table of 2**5 intermediate results is computed.
70 */
71#define FIVEARY_CUTOFF 8
72
Guido van Rossume32e0141992-01-19 16:31:05 +000073#define ABS(x) ((x) < 0 ? -(x) : (x))
74
Tim Peters5af4e6c2002-08-12 02:31:19 +000075#undef MIN
76#undef MAX
77#define MAX(x, y) ((x) < (y) ? (y) : (x))
78#define MIN(x, y) ((x) > (y) ? (y) : (x))
79
Guido van Rossume32e0141992-01-19 16:31:05 +000080/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000081static PyLongObject *long_normalize(PyLongObject *);
82static PyLongObject *mul1(PyLongObject *, wdigit);
83static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000084static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Guido van Rossume32e0141992-01-19 16:31:05 +000085
Guido van Rossumc0b618a1997-05-02 03:12:38 +000086#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000087 if (--_Py_Ticker < 0) { \
88 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +000089 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000090 }
91
Guido van Rossumedcc38a1991-05-05 20:09:44 +000092/* Normalize (remove leading zeros from) a long int object.
93 Doesn't attempt to free the storage--in most cases, due to the nature
94 of the algorithms used, this could save at most be one word anyway. */
95
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000097long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000098{
Christian Heimes90aa7642007-12-19 02:45:37 +000099 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000100 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102 while (i > 0 && v->ob_digit[i-1] == 0)
103 --i;
104 if (i != j)
Christian Heimes90aa7642007-12-19 02:45:37 +0000105 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000106 return v;
107}
108
109/* Allocate a new long int object with size digits.
110 Return NULL and set exception if we run out of memory. */
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000113_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000114{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000115 PyLongObject *result;
116 /* Can't use sizeof(PyLongObject) here, since the
117 compiler takes padding at the end into account.
118 As the consequence, this would waste 2 bytes on
119 a 32-bit system, and 6 bytes on a 64-bit system.
120 This computation would be incorrect on systems
121 which have padding before the digits; with 16-bit
122 digits this should not happen. */
123 result = PyObject_MALLOC(sizeof(PyVarObject) +
124 size*sizeof(digit));
125 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126 PyErr_NoMemory();
127 return NULL;
128 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000129 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000130}
131
Tim Peters64b5ce32001-09-10 20:52:51 +0000132PyObject *
133_PyLong_Copy(PyLongObject *src)
134{
135 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000136 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000137
138 assert(src != NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +0000139 i = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000140 if (i < 0)
141 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000142 if (i < 2) {
143 int ival = src->ob_digit[0];
Christian Heimes90aa7642007-12-19 02:45:37 +0000144 if (Py_SIZE(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000145 ival = -ival;
146 CHECK_SMALL_INT(ival);
147 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000148 result = _PyLong_New(i);
149 if (result != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000150 Py_SIZE(result) = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000151 while (--i >= 0)
152 result->ob_digit[i] = src->ob_digit[i];
153 }
154 return (PyObject *)result;
155}
156
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000157/* Create a new long int object from a C long int */
158
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000160PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000161{
Tim Petersce9de2f2001-06-14 04:56:19 +0000162 PyLongObject *v;
163 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
164 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000165 int sign = 1;
166
167 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000168
169 if (ival < 0) {
170 ival = -ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000171 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000172 }
173
Guido van Rossumddefaf32007-01-14 03:31:43 +0000174 /* Fast path for single-digits ints */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000175 if (!(ival>>PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000176 v = _PyLong_New(1);
177 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000178 Py_SIZE(v) = sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000179 v->ob_digit[0] = ival;
180 }
181 return (PyObject*)v;
182 }
183
184 /* 2 digits */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000185 if (!(ival >> 2*PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000186 v = _PyLong_New(2);
187 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000188 Py_SIZE(v) = 2*sign;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000189 v->ob_digit[0] = (digit)ival & PyLong_MASK;
190 v->ob_digit[1] = ival >> PyLong_SHIFT;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000191 }
192 return (PyObject*)v;
193 }
194
195 /* Larger numbers: loop to determine number of digits */
Tim Petersce9de2f2001-06-14 04:56:19 +0000196 t = (unsigned long)ival;
197 while (t) {
198 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000199 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000200 }
201 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000202 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000203 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000204 Py_SIZE(v) = ndigits*sign;
Tim Petersce9de2f2001-06-14 04:56:19 +0000205 t = (unsigned long)ival;
206 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000207 *p++ = (digit)(t & PyLong_MASK);
208 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000209 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000210 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000212}
213
Guido van Rossum53756b11997-01-03 17:14:46 +0000214/* Create a new long int object from a C unsigned long int */
215
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000216PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000217PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000218{
Tim Petersce9de2f2001-06-14 04:56:19 +0000219 PyLongObject *v;
220 unsigned long t;
221 int ndigits = 0;
222
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000223 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000224 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000225 /* Count the number of Python digits. */
226 t = (unsigned long)ival;
227 while (t) {
228 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000229 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000230 }
231 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000232 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000233 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000234 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000235 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000236 *p++ = (digit)(ival & PyLong_MASK);
237 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000238 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000239 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000240 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000241}
242
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000243/* Create a new long int object from a C double */
244
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000245PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000247{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000248 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000249 double frac;
250 int i, ndig, expo, neg;
251 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000252 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000253 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000254 "cannot convert float infinity to int");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000255 return NULL;
256 }
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);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000264 ndig = (expo-1) / PyLong_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;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000268 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269 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;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000273 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000274 }
275 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000276 Py_SIZE(v) = -(Py_SIZE(v));
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
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000296PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000297{
Guido van Rossumf7531811998-05-26 14:33:37 +0000298 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000300 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000301 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000302 Py_ssize_t i;
303 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000304 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000305
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000306 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000307 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000309 return -1;
310 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000311
312 if (!PyLong_Check(vv)) {
313 PyNumberMethods *nb;
314 if ((nb = vv->ob_type->tp_as_number) == NULL ||
315 nb->nb_int == NULL) {
316 PyErr_SetString(PyExc_TypeError, "an integer is required");
317 return -1;
318 }
319 vv = (*nb->nb_int) (vv);
320 if (vv == NULL)
321 return -1;
322 do_decref = 1;
323 if (!PyLong_Check(vv)) {
324 Py_DECREF(vv);
325 PyErr_SetString(PyExc_TypeError,
326 "nb_int should return int object");
327 return -1;
328 }
329 }
330
Georg Brandl61c31b02007-02-26 14:46:30 +0000331 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000332 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000333 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000334
Georg Brandl61c31b02007-02-26 14:46:30 +0000335 switch (i) {
336 case -1:
337 res = -v->ob_digit[0];
338 break;
339 case 0:
340 res = 0;
341 break;
342 case 1:
343 res = v->ob_digit[0];
344 break;
345 default:
346 sign = 1;
347 x = 0;
348 if (i < 0) {
349 sign = -1;
350 i = -(i);
351 }
352 while (--i >= 0) {
353 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000354 x = (x << PyLong_SHIFT) + v->ob_digit[i];
355 if ((x >> PyLong_SHIFT) != prev) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000356 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000357 goto exit;
358 }
359 }
360 /* Haven't lost any bits, but casting to long requires extra care
361 * (see comment above).
362 */
363 if (x <= (unsigned long)LONG_MAX) {
364 res = (long)x * sign;
365 }
366 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
367 res = LONG_MIN;
368 }
369 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000370 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000371 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000372 }
373 }
374 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000375 if (do_decref) {
376 Py_DECREF(vv);
377 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000378 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000379}
380
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000381long
382PyLong_AsLong(PyObject *obj)
383{
384 int overflow;
385 long result = PyLong_AsLongAndOverflow(obj, &overflow);
386 if (overflow) {
387 /* XXX: could be cute and give a different
388 message for overflow == -1 */
389 PyErr_SetString(PyExc_OverflowError,
390 "Python int too large to convert to C long");
391 }
392 return result;
393}
394
Guido van Rossumddefaf32007-01-14 03:31:43 +0000395int
396_PyLong_FitsInLong(PyObject *vv)
397{
398 int size;
399 if (!PyLong_CheckExact(vv)) {
400 PyErr_BadInternalCall();
401 return 0;
402 }
403 /* conservative estimate */
Christian Heimes90aa7642007-12-19 02:45:37 +0000404 size = Py_SIZE(vv);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000405 return -2 <= size && size <= 2;
406}
407
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000408/* Get a Py_ssize_t from a long int object.
409 Returns -1 and sets an error condition if overflow occurs. */
410
411Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000412PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000413 register PyLongObject *v;
414 size_t x, prev;
415 Py_ssize_t i;
416 int sign;
417
418 if (vv == NULL || !PyLong_Check(vv)) {
419 PyErr_BadInternalCall();
420 return -1;
421 }
422 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000423 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000424 switch (i) {
425 case -1: return -v->ob_digit[0];
426 case 0: return 0;
427 case 1: return v->ob_digit[0];
428 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000429 sign = 1;
430 x = 0;
431 if (i < 0) {
432 sign = -1;
433 i = -(i);
434 }
435 while (--i >= 0) {
436 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000437 x = (x << PyLong_SHIFT) + v->ob_digit[i];
438 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000439 goto overflow;
440 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000441 /* Haven't lost any bits, but casting to a signed type requires
442 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000443 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000444 if (x <= (size_t)PY_SSIZE_T_MAX) {
445 return (Py_ssize_t)x * sign;
446 }
447 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
448 return PY_SSIZE_T_MIN;
449 }
450 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000451
452 overflow:
453 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000454 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000455 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000456}
457
Guido van Rossumd8c80482002-08-13 00:24:58 +0000458/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000459 Returns -1 and sets an error condition if overflow occurs. */
460
461unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000462PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000463{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000464 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000465 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000466 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000467
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468 if (vv == NULL || !PyLong_Check(vv)) {
469 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000470 return (unsigned long) -1;
471 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000472 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000473 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000474 x = 0;
475 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000477 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000478 return (unsigned long) -1;
479 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000480 switch (i) {
481 case 0: return 0;
482 case 1: return v->ob_digit[0];
483 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000484 while (--i >= 0) {
485 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000486 x = (x << PyLong_SHIFT) + v->ob_digit[i];
487 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000488 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000489 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000490 return (unsigned long) -1;
491 }
492 }
493 return x;
494}
495
496/* Get a C unsigned long int from a long int object.
497 Returns -1 and sets an error condition if overflow occurs. */
498
499size_t
500PyLong_AsSize_t(PyObject *vv)
501{
502 register PyLongObject *v;
503 size_t x, prev;
504 Py_ssize_t i;
505
506 if (vv == NULL || !PyLong_Check(vv)) {
507 PyErr_BadInternalCall();
508 return (unsigned long) -1;
509 }
510 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000511 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000512 x = 0;
513 if (i < 0) {
514 PyErr_SetString(PyExc_OverflowError,
515 "can't convert negative value to size_t");
516 return (size_t) -1;
517 }
518 switch (i) {
519 case 0: return 0;
520 case 1: return v->ob_digit[0];
521 }
522 while (--i >= 0) {
523 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000524 x = (x << PyLong_SHIFT) + v->ob_digit[i];
525 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000526 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000527 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000528 return (unsigned long) -1;
529 }
530 }
531 return x;
532}
533
Thomas Hellera4ea6032003-04-17 18:55:45 +0000534/* Get a C unsigned long int from a long int object, ignoring the high bits.
535 Returns -1 and sets an error condition if an error occurs. */
536
Guido van Rossumddefaf32007-01-14 03:31:43 +0000537static unsigned long
538_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000539{
540 register PyLongObject *v;
541 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000542 Py_ssize_t i;
543 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000544
545 if (vv == NULL || !PyLong_Check(vv)) {
546 PyErr_BadInternalCall();
547 return (unsigned long) -1;
548 }
549 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000550 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000551 switch (i) {
552 case 0: return 0;
553 case 1: return v->ob_digit[0];
554 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000555 sign = 1;
556 x = 0;
557 if (i < 0) {
558 sign = -1;
559 i = -i;
560 }
561 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000562 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000563 }
564 return x * sign;
565}
566
Guido van Rossumddefaf32007-01-14 03:31:43 +0000567unsigned long
568PyLong_AsUnsignedLongMask(register PyObject *op)
569{
570 PyNumberMethods *nb;
571 PyLongObject *lo;
572 unsigned long val;
573
574 if (op && PyLong_Check(op))
575 return _PyLong_AsUnsignedLongMask(op);
576
577 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
578 nb->nb_int == NULL) {
579 PyErr_SetString(PyExc_TypeError, "an integer is required");
580 return (unsigned long)-1;
581 }
582
583 lo = (PyLongObject*) (*nb->nb_int) (op);
584 if (lo == NULL)
585 return (unsigned long)-1;
586 if (PyLong_Check(lo)) {
587 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
588 Py_DECREF(lo);
589 if (PyErr_Occurred())
590 return (unsigned long)-1;
591 return val;
592 }
593 else
594 {
595 Py_DECREF(lo);
596 PyErr_SetString(PyExc_TypeError,
597 "nb_int should return int object");
598 return (unsigned long)-1;
599 }
600}
601
Tim Peters5b8132f2003-01-31 15:52:05 +0000602int
603_PyLong_Sign(PyObject *vv)
604{
605 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000606
607 assert(v != NULL);
608 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000609
Christian Heimes90aa7642007-12-19 02:45:37 +0000610 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000611}
612
Tim Petersbaefd9e2003-01-28 20:37:45 +0000613size_t
614_PyLong_NumBits(PyObject *vv)
615{
616 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000617 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000618 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000619
620 assert(v != NULL);
621 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000622 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000623 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
624 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000625 digit msd = v->ob_digit[ndigits - 1];
626
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000627 result = (ndigits - 1) * PyLong_SHIFT;
628 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000629 goto Overflow;
630 do {
631 ++result;
632 if (result == 0)
633 goto Overflow;
634 msd >>= 1;
635 } while (msd);
636 }
637 return result;
638
639Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000640 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000641 "to express in a platform size_t");
642 return (size_t)-1;
643}
644
Tim Peters2a9b3672001-06-11 21:23:58 +0000645PyObject *
646_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
647 int little_endian, int is_signed)
648{
649 const unsigned char* pstartbyte;/* LSB of bytes */
650 int incr; /* direction to move pstartbyte */
651 const unsigned char* pendbyte; /* MSB of bytes */
652 size_t numsignificantbytes; /* number of bytes that matter */
653 size_t ndigits; /* number of Python long digits */
654 PyLongObject* v; /* result */
655 int idigit = 0; /* next free index in v->ob_digit */
656
657 if (n == 0)
658 return PyLong_FromLong(0L);
659
660 if (little_endian) {
661 pstartbyte = bytes;
662 pendbyte = bytes + n - 1;
663 incr = 1;
664 }
665 else {
666 pstartbyte = bytes + n - 1;
667 pendbyte = bytes;
668 incr = -1;
669 }
670
671 if (is_signed)
672 is_signed = *pendbyte >= 0x80;
673
674 /* Compute numsignificantbytes. This consists of finding the most
675 significant byte. Leading 0 bytes are insignficant if the number
676 is positive, and leading 0xff bytes if negative. */
677 {
678 size_t i;
679 const unsigned char* p = pendbyte;
680 const int pincr = -incr; /* search MSB to LSB */
681 const unsigned char insignficant = is_signed ? 0xff : 0x00;
682
683 for (i = 0; i < n; ++i, p += pincr) {
684 if (*p != insignficant)
685 break;
686 }
687 numsignificantbytes = n - i;
688 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
689 actually has 2 significant bytes. OTOH, 0xff0001 ==
690 -0x00ffff, so we wouldn't *need* to bump it there; but we
691 do for 0xffff = -0x0001. To be safe without bothering to
692 check every case, bump it regardless. */
693 if (is_signed && numsignificantbytes < n)
694 ++numsignificantbytes;
695 }
696
697 /* How many Python long digits do we need? We have
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000698 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000699 bits, so it's the ceiling of the quotient. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000700 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000701 if (ndigits > (size_t)INT_MAX)
702 return PyErr_NoMemory();
703 v = _PyLong_New((int)ndigits);
704 if (v == NULL)
705 return NULL;
706
707 /* Copy the bits over. The tricky parts are computing 2's-comp on
708 the fly for signed numbers, and dealing with the mismatch between
709 8-bit bytes and (probably) 15-bit Python digits.*/
710 {
711 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000712 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000713 twodigits accum = 0; /* sliding register */
714 unsigned int accumbits = 0; /* number of bits in accum */
715 const unsigned char* p = pstartbyte;
716
717 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000718 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000719 /* Compute correction for 2's comp, if needed. */
720 if (is_signed) {
721 thisbyte = (0xff ^ thisbyte) + carry;
722 carry = thisbyte >> 8;
723 thisbyte &= 0xff;
724 }
725 /* Because we're going LSB to MSB, thisbyte is
726 more significant than what's already in accum,
727 so needs to be prepended to accum. */
728 accum |= thisbyte << accumbits;
729 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000730 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000731 /* There's enough to fill a Python digit. */
732 assert(idigit < (int)ndigits);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000733 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000734 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000735 accum >>= PyLong_SHIFT;
736 accumbits -= PyLong_SHIFT;
737 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000738 }
739 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000740 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000741 if (accumbits) {
742 assert(idigit < (int)ndigits);
743 v->ob_digit[idigit] = (digit)accum;
744 ++idigit;
745 }
746 }
747
Christian Heimes90aa7642007-12-19 02:45:37 +0000748 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000749 return (PyObject *)long_normalize(v);
750}
751
752int
753_PyLong_AsByteArray(PyLongObject* v,
754 unsigned char* bytes, size_t n,
755 int little_endian, int is_signed)
756{
757 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000758 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000759 twodigits accum; /* sliding register */
760 unsigned int accumbits; /* # bits in accum */
761 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
762 twodigits carry; /* for computing 2's-comp */
763 size_t j; /* # bytes filled */
764 unsigned char* p; /* pointer to next byte in bytes */
765 int pincr; /* direction to move p */
766
767 assert(v != NULL && PyLong_Check(v));
768
Christian Heimes90aa7642007-12-19 02:45:37 +0000769 if (Py_SIZE(v) < 0) {
770 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000771 if (!is_signed) {
772 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000773 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000774 return -1;
775 }
776 do_twos_comp = 1;
777 }
778 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000779 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000780 do_twos_comp = 0;
781 }
782
783 if (little_endian) {
784 p = bytes;
785 pincr = 1;
786 }
787 else {
788 p = bytes + n - 1;
789 pincr = -1;
790 }
791
Tim Peters898cf852001-06-13 20:50:08 +0000792 /* Copy over all the Python digits.
793 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000794 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000795 normalized. */
796 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000797 j = 0;
798 accum = 0;
799 accumbits = 0;
800 carry = do_twos_comp ? 1 : 0;
801 for (i = 0; i < ndigits; ++i) {
802 twodigits thisdigit = v->ob_digit[i];
803 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000804 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
805 carry = thisdigit >> PyLong_SHIFT;
806 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000807 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000808 /* Because we're going LSB to MSB, thisdigit is more
809 significant than what's already in accum, so needs to be
810 prepended to accum. */
811 accum |= thisdigit << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000812 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000813
Tim Petersede05092001-06-14 08:53:38 +0000814 /* The most-significant digit may be (probably is) at least
815 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000816 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000817 /* Count # of sign bits -- they needn't be stored,
818 * although for signed conversion we need later to
819 * make sure at least one sign bit gets stored.
820 * First shift conceptual sign bit to real sign bit.
821 */
822 stwodigits s = (stwodigits)(thisdigit <<
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000823 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000824 unsigned int nsignbits = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000825 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000826 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000827 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000828 }
Tim Petersede05092001-06-14 08:53:38 +0000829 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000830 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000831
Tim Peters2a9b3672001-06-11 21:23:58 +0000832 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000833 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000834 if (j >= n)
835 goto Overflow;
836 ++j;
837 *p = (unsigned char)(accum & 0xff);
838 p += pincr;
839 accumbits -= 8;
840 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000841 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000842 }
843
844 /* Store the straggler (if any). */
845 assert(accumbits < 8);
846 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000847 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000848 if (j >= n)
849 goto Overflow;
850 ++j;
851 if (do_twos_comp) {
852 /* Fill leading bits of the byte with sign bits
853 (appropriately pretending that the long had an
854 infinite supply of sign bits). */
855 accum |= (~(twodigits)0) << accumbits;
856 }
857 *p = (unsigned char)(accum & 0xff);
858 p += pincr;
859 }
Tim Peters05607ad2001-06-13 21:01:27 +0000860 else if (j == n && n > 0 && is_signed) {
861 /* The main loop filled the byte array exactly, so the code
862 just above didn't get to ensure there's a sign bit, and the
863 loop below wouldn't add one either. Make sure a sign bit
864 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000865 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000866 int sign_bit_set = msb >= 0x80;
867 assert(accumbits == 0);
868 if (sign_bit_set == do_twos_comp)
869 return 0;
870 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000871 goto Overflow;
872 }
Tim Peters05607ad2001-06-13 21:01:27 +0000873
874 /* Fill remaining bytes with copies of the sign bit. */
875 {
876 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
877 for ( ; j < n; ++j, p += pincr)
878 *p = signbyte;
879 }
880
Tim Peters2a9b3672001-06-11 21:23:58 +0000881 return 0;
882
883Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000884 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000885 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000886
Tim Peters2a9b3672001-06-11 21:23:58 +0000887}
888
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000889double
890_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
891{
892/* NBITS_WANTED should be > the number of bits in a double's precision,
893 but small enough so that 2**NBITS_WANTED is within the normal double
894 range. nbitsneeded is set to 1 less than that because the most-significant
895 Python digit contains at least 1 significant bit, but we don't want to
896 bother counting them (catering to the worst case cheaply).
897
898 57 is one more than VAX-D double precision; I (Tim) don't know of a double
899 format with more precision than that; it's 1 larger so that we add in at
900 least one round bit to stand in for the ignored least-significant bits.
901*/
902#define NBITS_WANTED 57
903 PyLongObject *v;
904 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000905 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000906 Py_ssize_t i;
907 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000908 int nbitsneeded;
909
910 if (vv == NULL || !PyLong_Check(vv)) {
911 PyErr_BadInternalCall();
912 return -1;
913 }
914 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000915 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000916 sign = 1;
917 if (i < 0) {
918 sign = -1;
919 i = -(i);
920 }
921 else if (i == 0) {
922 *exponent = 0;
923 return 0.0;
924 }
925 --i;
926 x = (double)v->ob_digit[i];
927 nbitsneeded = NBITS_WANTED - 1;
928 /* Invariant: i Python digits remain unaccounted for. */
929 while (i > 0 && nbitsneeded > 0) {
930 --i;
931 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000932 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000933 }
934 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000935 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000936 *exponent = i;
937 assert(x > 0.0);
938 return x * sign;
939#undef NBITS_WANTED
940}
941
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000942/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000943
944double
Tim Peters9f688bf2000-07-07 15:53:28 +0000945PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000946{
Thomas Wouters553489a2006-02-01 21:32:04 +0000947 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000948 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000949
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000950 if (vv == NULL || !PyLong_Check(vv)) {
951 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000952 return -1;
953 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000954 x = _PyLong_AsScaledDouble(vv, &e);
955 if (x == -1.0 && PyErr_Occurred())
956 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000957 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
958 set correctly after a successful _PyLong_AsScaledDouble() call */
959 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000960 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000961 goto overflow;
962 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000963 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000964 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000965 goto overflow;
966 return x;
967
968overflow:
969 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000970 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000971 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000972}
973
Guido van Rossum78694d91998-09-18 14:14:13 +0000974/* Create a new long (or int) object from a C pointer */
975
976PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000977PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000978{
Tim Peters70128a12001-06-16 08:48:40 +0000979#ifndef HAVE_LONG_LONG
980# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
981#endif
982#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000983# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000984#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000985 /* special-case null pointer */
986 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +0000987 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000988 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000989
Guido van Rossum78694d91998-09-18 14:14:13 +0000990}
991
992/* Get a C pointer from a long object (or an int object in some cases) */
993
994void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000995PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000996{
997 /* This function will allow int or long objects. If vv is neither,
998 then the PyLong_AsLong*() functions will raise the exception:
999 PyExc_SystemError, "bad argument to internal function"
1000 */
Tim Peters70128a12001-06-16 08:48:40 +00001001#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +00001002 long x;
1003
Guido van Rossumddefaf32007-01-14 03:31:43 +00001004 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001005 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001006 else
1007 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001008#else
Tim Peters70128a12001-06-16 08:48:40 +00001009
1010#ifndef HAVE_LONG_LONG
1011# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1012#endif
1013#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001014# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001015#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001016 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001017
Guido van Rossumddefaf32007-01-14 03:31:43 +00001018 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001019 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001020 else
1021 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001022
1023#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001024
1025 if (x == -1 && PyErr_Occurred())
1026 return NULL;
1027 return (void *)x;
1028}
1029
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001030#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001031
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001032/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001033 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001034 */
1035
Tim Peterscf37dfc2001-06-14 18:42:50 +00001036#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001037
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001038/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001039
1040PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001041PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001042{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001043 PyLongObject *v;
1044 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1045 int ndigits = 0;
1046 int negative = 0;
1047
Guido van Rossumddefaf32007-01-14 03:31:43 +00001048 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049 if (ival < 0) {
1050 ival = -ival;
1051 negative = 1;
1052 }
1053
1054 /* Count the number of Python digits.
1055 We used to pick 5 ("big enough for anything"), but that's a
1056 waste of time and space given that 5*15 = 75 bits are rarely
1057 needed. */
1058 t = (unsigned PY_LONG_LONG)ival;
1059 while (t) {
1060 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001061 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001062 }
1063 v = _PyLong_New(ndigits);
1064 if (v != NULL) {
1065 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001066 Py_SIZE(v) = negative ? -ndigits : ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001067 t = (unsigned PY_LONG_LONG)ival;
1068 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001069 *p++ = (digit)(t & PyLong_MASK);
1070 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001071 }
1072 }
1073 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001074}
1075
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001076/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001077
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001078PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001079PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001080{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001081 PyLongObject *v;
1082 unsigned PY_LONG_LONG t;
1083 int ndigits = 0;
1084
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001085 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001086 return PyLong_FromLong(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001087 /* Count the number of Python digits. */
1088 t = (unsigned PY_LONG_LONG)ival;
1089 while (t) {
1090 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001091 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001092 }
1093 v = _PyLong_New(ndigits);
1094 if (v != NULL) {
1095 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001096 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001097 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001098 *p++ = (digit)(ival & PyLong_MASK);
1099 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001100 }
1101 }
1102 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001103}
1104
Martin v. Löwis18e16552006-02-15 17:27:45 +00001105/* Create a new long int object from a C Py_ssize_t. */
1106
1107PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001108PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001109{
1110 Py_ssize_t bytes = ival;
1111 int one = 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001112 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001113 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114 return _PyLong_FromByteArray(
1115 (unsigned char *)&bytes,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001116 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001117}
1118
1119/* Create a new long int object from a C size_t. */
1120
1121PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001122PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001123{
1124 size_t bytes = ival;
1125 int one = 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001126 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001127 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001128 return _PyLong_FromByteArray(
1129 (unsigned char *)&bytes,
1130 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
1131}
1132
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001133/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001134 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001135
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001136PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001137PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001138{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001139 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001140 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001141 int one = 1;
1142 int res;
1143
Tim Petersd38b1c72001-09-30 05:09:37 +00001144 if (vv == NULL) {
1145 PyErr_BadInternalCall();
1146 return -1;
1147 }
1148 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001149 PyNumberMethods *nb;
1150 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001151 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1152 nb->nb_int == NULL) {
1153 PyErr_SetString(PyExc_TypeError, "an integer is required");
1154 return -1;
1155 }
1156 io = (*nb->nb_int) (vv);
1157 if (io == NULL)
1158 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001159 if (PyLong_Check(io)) {
1160 bytes = PyLong_AsLongLong(io);
1161 Py_DECREF(io);
1162 return bytes;
1163 }
1164 Py_DECREF(io);
1165 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001166 return -1;
1167 }
1168
Guido van Rossumddefaf32007-01-14 03:31:43 +00001169 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001170 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001171 case -1: return -v->ob_digit[0];
1172 case 0: return 0;
1173 case 1: return v->ob_digit[0];
1174 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001175 res = _PyLong_AsByteArray(
1176 (PyLongObject *)vv, (unsigned char *)&bytes,
1177 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001178
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001179 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001180 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001181 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001182 else
1183 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001184}
1185
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001186/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001187 Return -1 and set an error if overflow occurs. */
1188
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001189unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001190PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001191{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001192 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001193 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001194 int one = 1;
1195 int res;
1196
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001197 if (vv == NULL || !PyLong_Check(vv)) {
1198 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001199 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001200 }
1201
Guido van Rossumddefaf32007-01-14 03:31:43 +00001202 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001203 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001204 case 0: return 0;
1205 case 1: return v->ob_digit[0];
1206 }
1207
Tim Petersd1a7da62001-06-13 00:35:57 +00001208 res = _PyLong_AsByteArray(
1209 (PyLongObject *)vv, (unsigned char *)&bytes,
1210 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001211
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001212 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001213 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001214 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001215 else
1216 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001217}
Tim Petersd1a7da62001-06-13 00:35:57 +00001218
Thomas Hellera4ea6032003-04-17 18:55:45 +00001219/* Get a C unsigned long int from a long int object, ignoring the high bits.
1220 Returns -1 and sets an error condition if an error occurs. */
1221
Guido van Rossumddefaf32007-01-14 03:31:43 +00001222static unsigned PY_LONG_LONG
1223_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001224{
1225 register PyLongObject *v;
1226 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001227 Py_ssize_t i;
1228 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001229
1230 if (vv == NULL || !PyLong_Check(vv)) {
1231 PyErr_BadInternalCall();
1232 return (unsigned long) -1;
1233 }
1234 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001235 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001236 case 0: return 0;
1237 case 1: return v->ob_digit[0];
1238 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001239 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001240 sign = 1;
1241 x = 0;
1242 if (i < 0) {
1243 sign = -1;
1244 i = -i;
1245 }
1246 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001247 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001248 }
1249 return x * sign;
1250}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001251
1252unsigned PY_LONG_LONG
1253PyLong_AsUnsignedLongLongMask(register PyObject *op)
1254{
1255 PyNumberMethods *nb;
1256 PyLongObject *lo;
1257 unsigned PY_LONG_LONG val;
1258
1259 if (op && PyLong_Check(op))
1260 return _PyLong_AsUnsignedLongLongMask(op);
1261
1262 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1263 nb->nb_int == NULL) {
1264 PyErr_SetString(PyExc_TypeError, "an integer is required");
1265 return (unsigned PY_LONG_LONG)-1;
1266 }
1267
1268 lo = (PyLongObject*) (*nb->nb_int) (op);
1269 if (lo == NULL)
1270 return (unsigned PY_LONG_LONG)-1;
1271 if (PyLong_Check(lo)) {
1272 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1273 Py_DECREF(lo);
1274 if (PyErr_Occurred())
1275 return (unsigned PY_LONG_LONG)-1;
1276 return val;
1277 }
1278 else
1279 {
1280 Py_DECREF(lo);
1281 PyErr_SetString(PyExc_TypeError,
1282 "nb_int should return int object");
1283 return (unsigned PY_LONG_LONG)-1;
1284 }
1285}
Tim Petersd1a7da62001-06-13 00:35:57 +00001286#undef IS_LITTLE_ENDIAN
1287
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001288#endif /* HAVE_LONG_LONG */
1289
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001290#define CHECK_BINOP(v,w) \
1291 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001292 Py_INCREF(Py_NotImplemented); \
1293 return Py_NotImplemented; \
1294 }
1295
Tim Peters877a2122002-08-12 05:09:36 +00001296/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1297 * is modified in place, by adding y to it. Carries are propagated as far as
1298 * x[m-1], and the remaining carry (0 or 1) is returned.
1299 */
1300static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001301v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001302{
1303 int i;
1304 digit carry = 0;
1305
1306 assert(m >= n);
1307 for (i = 0; i < n; ++i) {
1308 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001309 x[i] = carry & PyLong_MASK;
1310 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001311 assert((carry & 1) == carry);
1312 }
1313 for (; carry && i < m; ++i) {
1314 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001315 x[i] = carry & PyLong_MASK;
1316 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001317 assert((carry & 1) == carry);
1318 }
1319 return carry;
1320}
1321
1322/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1323 * is modified in place, by subtracting y from it. Borrows are propagated as
1324 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1325 */
1326static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001327v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001328{
1329 int i;
1330 digit borrow = 0;
1331
1332 assert(m >= n);
1333 for (i = 0; i < n; ++i) {
1334 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001335 x[i] = borrow & PyLong_MASK;
1336 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001337 borrow &= 1; /* keep only 1 sign bit */
1338 }
1339 for (; borrow && i < m; ++i) {
1340 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001341 x[i] = borrow & PyLong_MASK;
1342 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001343 borrow &= 1;
1344 }
1345 return borrow;
1346}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001347
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001348/* Multiply by a single digit, ignoring the sign. */
1349
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001350static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001351mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001352{
1353 return muladd1(a, n, (digit)0);
1354}
1355
1356/* Multiply by a single digit and add a single digit, ignoring the sign. */
1357
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001358static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001359muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001360{
Christian Heimes90aa7642007-12-19 02:45:37 +00001361 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001362 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001363 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001364 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001365
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001366 if (z == NULL)
1367 return NULL;
1368 for (i = 0; i < size_a; ++i) {
1369 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001370 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1371 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001372 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001373 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001374 return long_normalize(z);
1375}
1376
Tim Peters212e6142001-07-14 12:23:19 +00001377/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1378 in pout, and returning the remainder. pin and pout point at the LSD.
1379 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001380 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001381 immutable. */
1382
1383static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001384inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001385{
1386 twodigits rem = 0;
1387
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001388 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001389 pin += size;
1390 pout += size;
1391 while (--size >= 0) {
1392 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001393 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001394 *--pout = hi = (digit)(rem / n);
1395 rem -= hi * n;
1396 }
1397 return (digit)rem;
1398}
1399
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001400/* Divide a long integer by a digit, returning both the quotient
1401 (as function result) and the remainder (through *prem).
1402 The sign of a is ignored; n should not be zero. */
1403
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001404static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001405divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001406{
Christian Heimes90aa7642007-12-19 02:45:37 +00001407 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001408 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001409
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001410 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001411 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001412 if (z == NULL)
1413 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001414 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001415 return long_normalize(z);
1416}
1417
1418/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001419 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001420 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001421
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001422PyObject *
1423_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001424{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001425 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001426 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001427 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001428 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001429 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001430 int bits;
1431 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001432
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001433 if (a == NULL || !PyLong_Check(a)) {
1434 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001435 return NULL;
1436 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001437 assert(base >= 2 && base <= 36);
Christian Heimes90aa7642007-12-19 02:45:37 +00001438 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001439
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001440 /* Compute a rough upper bound for the length of the string */
1441 i = base;
1442 bits = 0;
1443 while (i > 1) {
1444 ++bits;
1445 i >>= 1;
1446 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001447 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001448 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001449 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001450 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001451 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001452 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001453 return NULL;
1454 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001455 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001456 if (str == NULL)
1457 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001458 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001459 *p = '\0';
Christian Heimes90aa7642007-12-19 02:45:37 +00001460 if (Py_SIZE(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001461 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001462
Christian Heimes90aa7642007-12-19 02:45:37 +00001463 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001464 *--p = '0';
1465 }
1466 else if ((base & (base - 1)) == 0) {
1467 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001468 twodigits accum = 0;
1469 int accumbits = 0; /* # of bits in accum */
1470 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001471 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001472 while ((i >>= 1) > 1)
1473 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001474
1475 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001476 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001477 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001478 assert(accumbits >= basebits);
1479 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001480 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001481 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001482 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001483 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001484 accumbits -= basebits;
1485 accum >>= basebits;
1486 } while (i < size_a-1 ? accumbits >= basebits :
1487 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001488 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001489 }
1490 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001491 /* Not 0, and base not a power of 2. Divide repeatedly by
1492 base, but for speed use the highest power of base that
1493 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001494 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001495 digit *pin = a->ob_digit;
1496 PyLongObject *scratch;
1497 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001498 digit powbase = base; /* powbase == base ** power */
1499 int power = 1;
1500 for (;;) {
1501 unsigned long newpow = powbase * (unsigned long)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001502 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001503 break;
1504 powbase = (digit)newpow;
1505 ++power;
1506 }
Tim Peters212e6142001-07-14 12:23:19 +00001507
1508 /* Get a scratch area for repeated division. */
1509 scratch = _PyLong_New(size);
1510 if (scratch == NULL) {
1511 Py_DECREF(str);
1512 return NULL;
1513 }
1514
1515 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001516 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001517 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001518 digit rem = inplace_divrem1(scratch->ob_digit,
1519 pin, size, powbase);
1520 pin = scratch->ob_digit; /* no need to use a again */
1521 if (pin[size - 1] == 0)
1522 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001523 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001524 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001525 Py_DECREF(str);
1526 return NULL;
1527 })
Tim Peters212e6142001-07-14 12:23:19 +00001528
1529 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001530 assert(ntostore > 0);
1531 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001532 digit nextrem = (digit)(rem / base);
1533 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001534 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001535 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001536 *--p = c;
1537 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001538 --ntostore;
1539 /* Termination is a bit delicate: must not
1540 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001541 remaining quotient and rem are both 0. */
1542 } while (ntostore && (size || rem));
1543 } while (size != 0);
1544 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001545 }
1546
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001547 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001548 *--p = 'x';
1549 *--p = '0';
1550 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001551 else if (base == 8) {
1552 *--p = 'o';
1553 *--p = '0';
1554 }
1555 else if (base == 2) {
1556 *--p = 'b';
1557 *--p = '0';
1558 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001559 else if (base != 10) {
1560 *--p = '#';
1561 *--p = '0' + base%10;
1562 if (base > 10)
1563 *--p = '0' + base/10;
1564 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001565 if (sign)
1566 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001567 if (p != PyUnicode_AS_UNICODE(str)) {
1568 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001569 assert(p > q);
1570 do {
1571 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001572 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001573 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1574 Py_DECREF(str);
1575 return NULL;
1576 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001577 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001578 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001579}
1580
Thomas Wouters477c8d52006-05-27 19:21:47 +00001581/* Table of digit values for 8-bit string -> integer conversion.
1582 * '0' maps to 0, ..., '9' maps to 9.
1583 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1584 * All other indices map to 37.
1585 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001586 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001587 */
1588int _PyLong_DigitValue[256] = {
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 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1593 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1594 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1595 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1596 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1597 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1598 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1599 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1600 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1601 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1602 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1603 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1604 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1605};
1606
1607/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001608 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1609 * non-digit (which may be *str!). A normalized long is returned.
1610 * The point to this routine is that it takes time linear in the number of
1611 * string characters.
1612 */
1613static PyLongObject *
1614long_from_binary_base(char **str, int base)
1615{
1616 char *p = *str;
1617 char *start = p;
1618 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001619 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001620 PyLongObject *z;
1621 twodigits accum;
1622 int bits_in_accum;
1623 digit *pdigit;
1624
1625 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1626 n = base;
1627 for (bits_per_char = -1; n; ++bits_per_char)
1628 n >>= 1;
1629 /* n <- total # of bits needed, while setting p to end-of-string */
1630 n = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001631 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001632 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001633 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001634 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1635 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001636 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001637 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001638 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001639 return NULL;
1640 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001641 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001642 z = _PyLong_New(n);
1643 if (z == NULL)
1644 return NULL;
1645 /* Read string from right, and fill in long from left; i.e.,
1646 * from least to most significant in both.
1647 */
1648 accum = 0;
1649 bits_in_accum = 0;
1650 pdigit = z->ob_digit;
1651 while (--p >= start) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001652 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001653 assert(k >= 0 && k < base);
1654 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001655 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001656 if (bits_in_accum >= PyLong_SHIFT) {
1657 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001658 assert(pdigit - z->ob_digit <= (int)n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001659 accum >>= PyLong_SHIFT;
1660 bits_in_accum -= PyLong_SHIFT;
1661 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001662 }
1663 }
1664 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001665 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001666 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001667 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001668 }
1669 while (pdigit - z->ob_digit < n)
1670 *pdigit++ = 0;
1671 return long_normalize(z);
1672}
1673
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001674PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001675PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001676{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001677 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001678 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001679 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001680 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001681 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001682
Guido van Rossum472c04f1996-12-05 21:57:21 +00001683 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001684 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001685 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001686 return NULL;
1687 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001688 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001689 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001690 if (*str == '+')
1691 ++str;
1692 else if (*str == '-') {
1693 ++str;
1694 sign = -1;
1695 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001696 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001697 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001698 if (base == 0) {
1699 if (str[0] != '0')
1700 base = 10;
1701 else if (str[1] == 'x' || str[1] == 'X')
1702 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001703 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001704 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001705 else if (str[1] == 'b' || str[1] == 'B')
1706 base = 2;
1707 else {
1708 /* "old" (C-style) octal literal, now invalid.
1709 it might still be zero though */
1710 error_if_nonzero = 1;
1711 base = 10;
1712 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001713 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001714 if (str[0] == '0' &&
1715 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1716 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1717 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001718 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001719
Guido van Rossume6762971998-06-22 03:54:46 +00001720 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001721 if ((base & (base - 1)) == 0)
1722 z = long_from_binary_base(&str, base);
1723 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001724/***
1725Binary bases can be converted in time linear in the number of digits, because
1726Python's representation base is binary. Other bases (including decimal!) use
1727the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001728
Thomas Wouters477c8d52006-05-27 19:21:47 +00001729First some math: the largest integer that can be expressed in N base-B digits
1730is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1731case number of Python digits needed to hold it is the smallest integer n s.t.
1732
1733 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1734 BASE**n >= B**N [taking logs to base BASE]
1735 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1736
1737The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1738this quickly. A Python long with that much space is reserved near the start,
1739and the result is computed into it.
1740
1741The input string is actually treated as being in base base**i (i.e., i digits
1742are processed at a time), where two more static arrays hold:
1743
1744 convwidth_base[base] = the largest integer i such that base**i <= BASE
1745 convmultmax_base[base] = base ** convwidth_base[base]
1746
1747The first of these is the largest i such that i consecutive input digits
1748must fit in a single Python digit. The second is effectively the input
1749base we're really using.
1750
1751Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1752convmultmax_base[base], the result is "simply"
1753
1754 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1755
1756where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001757
1758Error analysis: as above, the number of Python digits `n` needed is worst-
1759case
1760
1761 n >= N * log(B)/log(BASE)
1762
1763where `N` is the number of input digits in base `B`. This is computed via
1764
1765 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1766
1767below. Two numeric concerns are how much space this can waste, and whether
1768the computed result can be too small. To be concrete, assume BASE = 2**15,
1769which is the default (and it's unlikely anyone changes that).
1770
1771Waste isn't a problem: provided the first input digit isn't 0, the difference
1772between the worst-case input with N digits and the smallest input with N
1773digits is about a factor of B, but B is small compared to BASE so at most
1774one allocated Python digit can remain unused on that count. If
1775N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1776and adding 1 returns a result 1 larger than necessary. However, that can't
1777happen: whenever B is a power of 2, long_from_binary_base() is called
1778instead, and it's impossible for B**i to be an integer power of 2**15 when
1779B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1780an exact integer when B is not a power of 2, since B**i has a prime factor
1781other than 2 in that case, but (2**15)**j's only prime factor is 2).
1782
1783The computed result can be too small if the true value of N*log(B)/log(BASE)
1784is a little bit larger than an exact integer, but due to roundoff errors (in
1785computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1786yields a numeric result a little less than that integer. Unfortunately, "how
1787close can a transcendental function get to an integer over some range?"
1788questions are generally theoretically intractable. Computer analysis via
1789continued fractions is practical: expand log(B)/log(BASE) via continued
1790fractions, giving a sequence i/j of "the best" rational approximations. Then
1791j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1792we can get very close to being in trouble, but very rarely. For example,
179376573 is a denominator in one of the continued-fraction approximations to
1794log(10)/log(2**15), and indeed:
1795
1796 >>> log(10)/log(2**15)*76573
1797 16958.000000654003
1798
1799is very close to an integer. If we were working with IEEE single-precision,
1800rounding errors could kill us. Finding worst cases in IEEE double-precision
1801requires better-than-double-precision log() functions, and Tim didn't bother.
1802Instead the code checks to see whether the allocated space is enough as each
1803new Python digit is added, and copies the whole thing to a larger long if not.
1804This should happen extremely rarely, and in fact I don't have a test case
1805that triggers it(!). Instead the code was tested by artificially allocating
1806just 1 digit at the start, so that the copying code was exercised for every
1807digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001808***/
1809 register twodigits c; /* current input character */
1810 Py_ssize_t size_z;
1811 int i;
1812 int convwidth;
1813 twodigits convmultmax, convmult;
1814 digit *pz, *pzstop;
1815 char* scan;
1816
1817 static double log_base_BASE[37] = {0.0e0,};
1818 static int convwidth_base[37] = {0,};
1819 static twodigits convmultmax_base[37] = {0,};
1820
1821 if (log_base_BASE[base] == 0.0) {
1822 twodigits convmax = base;
1823 int i = 1;
1824
1825 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001826 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001827 for (;;) {
1828 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001829 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001830 break;
1831 convmax = next;
1832 ++i;
1833 }
1834 convmultmax_base[base] = convmax;
1835 assert(i > 0);
1836 convwidth_base[base] = i;
1837 }
1838
1839 /* Find length of the string of numeric characters. */
1840 scan = str;
1841 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1842 ++scan;
1843
1844 /* Create a long object that can contain the largest possible
1845 * integer with this base and length. Note that there's no
1846 * need to initialize z->ob_digit -- no slot is read up before
1847 * being stored into.
1848 */
1849 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001850 /* Uncomment next line to test exceedingly rare copy code */
1851 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001852 assert(size_z > 0);
1853 z = _PyLong_New(size_z);
1854 if (z == NULL)
1855 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00001856 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001857
1858 /* `convwidth` consecutive input digits are treated as a single
1859 * digit in base `convmultmax`.
1860 */
1861 convwidth = convwidth_base[base];
1862 convmultmax = convmultmax_base[base];
1863
1864 /* Work ;-) */
1865 while (str < scan) {
1866 /* grab up to convwidth digits from the input string */
1867 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1868 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1869 c = (twodigits)(c * base +
1870 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001871 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001872 }
1873
1874 convmult = convmultmax;
1875 /* Calculate the shift only if we couldn't get
1876 * convwidth digits.
1877 */
1878 if (i != convwidth) {
1879 convmult = base;
1880 for ( ; i > 1; --i)
1881 convmult *= base;
1882 }
1883
1884 /* Multiply z by convmult, and add c. */
1885 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001886 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001887 for (; pz < pzstop; ++pz) {
1888 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001889 *pz = (digit)(c & PyLong_MASK);
1890 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001891 }
1892 /* carry off the current end? */
1893 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001894 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00001895 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001896 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00001897 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001898 }
1899 else {
1900 PyLongObject *tmp;
1901 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00001902 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001903 tmp = _PyLong_New(size_z + 1);
1904 if (tmp == NULL) {
1905 Py_DECREF(z);
1906 return NULL;
1907 }
1908 memcpy(tmp->ob_digit,
1909 z->ob_digit,
1910 sizeof(digit) * size_z);
1911 Py_DECREF(z);
1912 z = tmp;
1913 z->ob_digit[size_z] = (digit)c;
1914 ++size_z;
1915 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001916 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001917 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001918 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001919 if (z == NULL)
1920 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001921 if (error_if_nonzero) {
1922 /* reset the base to 0, else the exception message
1923 doesn't make too much sense */
1924 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00001925 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001926 goto onError;
1927 /* there might still be other problems, therefore base
1928 remains zero here for the same reason */
1929 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001930 if (str == start)
1931 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001932 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00001933 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001934 if (*str == 'L' || *str == 'l')
1935 str++;
1936 while (*str && isspace(Py_CHARMASK(*str)))
1937 str++;
1938 if (*str != '\0')
1939 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001940 if (pend)
1941 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001942 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001943
1944 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001945 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001946 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00001947 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001948 if (strobj == NULL)
1949 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001950 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00001951 "invalid literal for int() with base %d: %R",
1952 base, strobj);
1953 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001954 return NULL;
1955}
1956
1957PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001958PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001959{
Walter Dörwald07e14762002-11-06 16:15:14 +00001960 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001961 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001962
Walter Dörwald07e14762002-11-06 16:15:14 +00001963 if (buffer == NULL)
1964 return NULL;
1965
1966 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1967 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001968 return NULL;
1969 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001970 result = PyLong_FromString(buffer, NULL, base);
1971 PyMem_FREE(buffer);
1972 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001973}
1974
Tim Peters9f688bf2000-07-07 15:53:28 +00001975/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001976static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001977 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001978static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00001979static int long_divrem(PyLongObject *, PyLongObject *,
1980 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001981
1982/* Long division with remainder, top-level routine */
1983
Guido van Rossume32e0141992-01-19 16:31:05 +00001984static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001985long_divrem(PyLongObject *a, PyLongObject *b,
1986 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001987{
Christian Heimes90aa7642007-12-19 02:45:37 +00001988 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001989 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001990
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001991 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001992 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001993 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001994 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001995 }
1996 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001997 (size_a == size_b &&
1998 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001999 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002000 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002001 if (*pdiv == NULL)
2002 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002003 Py_INCREF(a);
2004 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002005 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002006 }
2007 if (size_b == 1) {
2008 digit rem = 0;
2009 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002010 if (z == NULL)
2011 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002012 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002013 if (*prem == NULL) {
2014 Py_DECREF(z);
2015 return -1;
2016 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002017 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002018 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002019 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002020 if (z == NULL)
2021 return -1;
2022 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002023 /* Set the signs.
2024 The quotient z has the sign of a*b;
2025 the remainder r has the sign of a,
2026 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002027 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002028 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002029 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002030 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002031 *pdiv = z;
2032 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002033}
2034
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002035/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002037static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002038x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002039{
Christian Heimes90aa7642007-12-19 02:45:37 +00002040 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002041 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002042 PyLongObject *v = mul1(v1, d);
2043 PyLongObject *w = mul1(w1, d);
2044 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002045 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002046
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002047 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002048 Py_XDECREF(v);
2049 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002050 return NULL;
2051 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002052
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002053 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002054 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
2055 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002056
Christian Heimes90aa7642007-12-19 02:45:37 +00002057 size_v = ABS(Py_SIZE(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002058 k = size_v - size_w;
2059 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002060
Thomas Wouters477c8d52006-05-27 19:21:47 +00002061 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002062 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2063 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002064 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002065 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002066
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002067 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002068 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002069 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002070 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002071 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002072 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002073 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002074 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002075 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002076 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002077
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002078 while (w->ob_digit[size_w-2]*q >
2079 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002080 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002081 + v->ob_digit[j-1]
2082 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002083 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002084 + v->ob_digit[j-2])
2085 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002086
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002087 for (i = 0; i < size_w && i+k < size_v; ++i) {
2088 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002089 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002090 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002091 + ((twodigits)zz << PyLong_SHIFT);
2092 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002093 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002094 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002095 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002096 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002097
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002098 if (i+k < size_v) {
2099 carry += v->ob_digit[i+k];
2100 v->ob_digit[i+k] = 0;
2101 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002102
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002103 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002104 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002105 else {
2106 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002107 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002108 carry = 0;
2109 for (i = 0; i < size_w && i+k < size_v; ++i) {
2110 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002111 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002112 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2113 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002114 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002115 }
2116 }
2117 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002118
Guido van Rossumc206c761995-01-10 15:23:19 +00002119 if (a == NULL)
2120 *prem = NULL;
2121 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002122 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002123 *prem = divrem1(v, d, &d);
2124 /* d receives the (unused) remainder */
2125 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002126 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002127 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002128 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002129 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002130 Py_DECREF(v);
2131 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002132 return a;
2133}
2134
2135/* Methods */
2136
2137static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002138long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002139{
Christian Heimes90aa7642007-12-19 02:45:37 +00002140 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002141}
2142
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002143static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002144long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002145{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002146 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002147}
2148
2149static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002150long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002151{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002152 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002153
Christian Heimes90aa7642007-12-19 02:45:37 +00002154 if (Py_SIZE(a) != Py_SIZE(b)) {
2155 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002156 sign = 0;
2157 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002158 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002159 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002160 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002161 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002162 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2163 ;
2164 if (i < 0)
2165 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002166 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002167 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002168 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002169 sign = -sign;
2170 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002171 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002172 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002173}
2174
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002175static PyObject *
2176long_richcompare(PyObject *self, PyObject *other, int op)
2177{
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002178 PyObject *result;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002179 CHECK_BINOP(self, other);
2180 result = Py_CmpToRich(op, long_compare((PyLongObject*)self,
2181 (PyLongObject*)other));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002182 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002183}
2184
Guido van Rossum9bfef441993-03-29 10:43:31 +00002185static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002186long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002187{
2188 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002189 Py_ssize_t i;
2190 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002191
2192 /* This is designed so that Python ints and longs with the
2193 same value hash to the same value, otherwise comparisons
2194 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002195 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002196 switch(i) {
2197 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2198 case 0: return 0;
2199 case 1: return v->ob_digit[0];
2200 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002201 sign = 1;
2202 x = 0;
2203 if (i < 0) {
2204 sign = -1;
2205 i = -(i);
2206 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002207#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Thomas Woutersce272b62007-09-19 21:19:28 +00002208 /* The following loop produces a C long x such that (unsigned long)x
2209 is congruent to the absolute value of v modulo ULONG_MAX. The
2210 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002211 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002212 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002213 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002214 x += v->ob_digit[i];
Thomas Woutersce272b62007-09-19 21:19:28 +00002215 /* If the addition above overflowed (thinking of x as
2216 unsigned), we compensate by incrementing. This preserves
2217 the value modulo ULONG_MAX. */
2218 if ((unsigned long)x < v->ob_digit[i])
2219 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002220 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002221#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002222 x = x * sign;
2223 if (x == -1)
2224 x = -2;
2225 return x;
2226}
2227
2228
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002229/* Add the absolute values of two long integers. */
2230
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002231static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002232x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002233{
Christian Heimes90aa7642007-12-19 02:45:37 +00002234 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002235 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002236 int i;
2237 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002238
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002239 /* Ensure a is the larger of the two: */
2240 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002241 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002242 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002243 size_a = size_b;
2244 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002245 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002246 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002247 if (z == NULL)
2248 return NULL;
2249 for (i = 0; i < size_b; ++i) {
2250 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002251 z->ob_digit[i] = carry & PyLong_MASK;
2252 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002253 }
2254 for (; i < size_a; ++i) {
2255 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002256 z->ob_digit[i] = carry & PyLong_MASK;
2257 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002258 }
2259 z->ob_digit[i] = carry;
2260 return long_normalize(z);
2261}
2262
2263/* Subtract the absolute values of two integers. */
2264
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002265static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002266x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002267{
Christian Heimes90aa7642007-12-19 02:45:37 +00002268 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002269 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002270 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002271 int sign = 1;
2272 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002273
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002274 /* Ensure a is the larger of the two: */
2275 if (size_a < size_b) {
2276 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002277 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002278 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002279 size_a = size_b;
2280 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002281 }
2282 else if (size_a == size_b) {
2283 /* Find highest digit where a and b differ: */
2284 i = size_a;
2285 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2286 ;
2287 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002288 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002289 if (a->ob_digit[i] < b->ob_digit[i]) {
2290 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002291 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002292 }
2293 size_a = size_b = i+1;
2294 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002295 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002296 if (z == NULL)
2297 return NULL;
2298 for (i = 0; i < size_b; ++i) {
2299 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002300 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002301 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002302 z->ob_digit[i] = borrow & PyLong_MASK;
2303 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002304 borrow &= 1; /* Keep only one sign bit */
2305 }
2306 for (; i < size_a; ++i) {
2307 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002308 z->ob_digit[i] = borrow & PyLong_MASK;
2309 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002310 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002311 }
2312 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002313 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002314 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002315 return long_normalize(z);
2316}
2317
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002318static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002319long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002320{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002321 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002322
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002323 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002324
Christian Heimes90aa7642007-12-19 02:45:37 +00002325 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002326 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002327 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002328 return result;
2329 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002330 if (Py_SIZE(a) < 0) {
2331 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002332 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002333 if (z != NULL && Py_SIZE(z) != 0)
2334 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002335 }
2336 else
2337 z = x_sub(b, a);
2338 }
2339 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002340 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002341 z = x_sub(a, b);
2342 else
2343 z = x_add(a, b);
2344 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002345 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002346}
2347
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002348static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002349long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002350{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002351 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002352
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002353 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002354
Christian Heimes90aa7642007-12-19 02:45:37 +00002355 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002356 PyObject* r;
2357 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002358 return r;
2359 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002360 if (Py_SIZE(a) < 0) {
2361 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002362 z = x_sub(a, b);
2363 else
2364 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002365 if (z != NULL && Py_SIZE(z) != 0)
2366 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002367 }
2368 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002369 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002370 z = x_add(a, b);
2371 else
2372 z = x_sub(a, b);
2373 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002374 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002375}
2376
Tim Peters5af4e6c2002-08-12 02:31:19 +00002377/* Grade school multiplication, ignoring the signs.
2378 * Returns the absolute value of the product, or NULL if error.
2379 */
2380static PyLongObject *
2381x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002382{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002383 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002384 Py_ssize_t size_a = ABS(Py_SIZE(a));
2385 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002386 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002387
Tim Peters5af4e6c2002-08-12 02:31:19 +00002388 z = _PyLong_New(size_a + size_b);
2389 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002390 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002391
Christian Heimes90aa7642007-12-19 02:45:37 +00002392 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002393 if (a == b) {
2394 /* Efficient squaring per HAC, Algorithm 14.16:
2395 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2396 * Gives slightly less than a 2x speedup when a == b,
2397 * via exploiting that each entry in the multiplication
2398 * pyramid appears twice (except for the size_a squares).
2399 */
2400 for (i = 0; i < size_a; ++i) {
2401 twodigits carry;
2402 twodigits f = a->ob_digit[i];
2403 digit *pz = z->ob_digit + (i << 1);
2404 digit *pa = a->ob_digit + i + 1;
2405 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002406
Tim Peters0973b992004-08-29 22:16:50 +00002407 SIGCHECK({
2408 Py_DECREF(z);
2409 return NULL;
2410 })
2411
2412 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002413 *pz++ = (digit)(carry & PyLong_MASK);
2414 carry >>= PyLong_SHIFT;
2415 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002416
2417 /* Now f is added in twice in each column of the
2418 * pyramid it appears. Same as adding f<<1 once.
2419 */
2420 f <<= 1;
2421 while (pa < paend) {
2422 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002423 *pz++ = (digit)(carry & PyLong_MASK);
2424 carry >>= PyLong_SHIFT;
2425 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002426 }
2427 if (carry) {
2428 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002429 *pz++ = (digit)(carry & PyLong_MASK);
2430 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002431 }
2432 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002433 *pz += (digit)(carry & PyLong_MASK);
2434 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002435 }
Tim Peters0973b992004-08-29 22:16:50 +00002436 }
2437 else { /* a is not the same as b -- gradeschool long mult */
2438 for (i = 0; i < size_a; ++i) {
2439 twodigits carry = 0;
2440 twodigits f = a->ob_digit[i];
2441 digit *pz = z->ob_digit + i;
2442 digit *pb = b->ob_digit;
2443 digit *pbend = b->ob_digit + size_b;
2444
2445 SIGCHECK({
2446 Py_DECREF(z);
2447 return NULL;
2448 })
2449
2450 while (pb < pbend) {
2451 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002452 *pz++ = (digit)(carry & PyLong_MASK);
2453 carry >>= PyLong_SHIFT;
2454 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002455 }
2456 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002457 *pz += (digit)(carry & PyLong_MASK);
2458 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002459 }
2460 }
Tim Peters44121a62002-08-12 06:17:58 +00002461 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002462}
2463
2464/* A helper for Karatsuba multiplication (k_mul).
2465 Takes a long "n" and an integer "size" representing the place to
2466 split, and sets low and high such that abs(n) == (high << size) + low,
2467 viewing the shift as being by digits. The sign bit is ignored, and
2468 the return values are >= 0.
2469 Returns 0 on success, -1 on failure.
2470*/
2471static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002472kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002473{
2474 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002475 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002476 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002477
2478 size_lo = MIN(size_n, size);
2479 size_hi = size_n - size_lo;
2480
2481 if ((hi = _PyLong_New(size_hi)) == NULL)
2482 return -1;
2483 if ((lo = _PyLong_New(size_lo)) == NULL) {
2484 Py_DECREF(hi);
2485 return -1;
2486 }
2487
2488 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2489 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2490
2491 *high = long_normalize(hi);
2492 *low = long_normalize(lo);
2493 return 0;
2494}
2495
Tim Peters60004642002-08-12 22:01:34 +00002496static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2497
Tim Peters5af4e6c2002-08-12 02:31:19 +00002498/* Karatsuba multiplication. Ignores the input signs, and returns the
2499 * absolute value of the product (or NULL if error).
2500 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2501 */
2502static PyLongObject *
2503k_mul(PyLongObject *a, PyLongObject *b)
2504{
Christian Heimes90aa7642007-12-19 02:45:37 +00002505 Py_ssize_t asize = ABS(Py_SIZE(a));
2506 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002507 PyLongObject *ah = NULL;
2508 PyLongObject *al = NULL;
2509 PyLongObject *bh = NULL;
2510 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002511 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002512 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002513 Py_ssize_t shift; /* the number of digits we split off */
2514 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002515
Tim Peters5af4e6c2002-08-12 02:31:19 +00002516 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2517 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2518 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002519 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002520 * By picking X to be a power of 2, "*X" is just shifting, and it's
2521 * been reduced to 3 multiplies on numbers half the size.
2522 */
2523
Tim Petersfc07e562002-08-12 02:54:10 +00002524 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002525 * is largest.
2526 */
Tim Peters738eda72002-08-12 15:08:20 +00002527 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002528 t1 = a;
2529 a = b;
2530 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002531
2532 i = asize;
2533 asize = bsize;
2534 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002535 }
2536
2537 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002538 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2539 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002540 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002541 return _PyLong_New(0);
2542 else
2543 return x_mul(a, b);
2544 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002545
Tim Peters60004642002-08-12 22:01:34 +00002546 /* If a is small compared to b, splitting on b gives a degenerate
2547 * case with ah==0, and Karatsuba may be (even much) less efficient
2548 * than "grade school" then. However, we can still win, by viewing
2549 * b as a string of "big digits", each of width a->ob_size. That
2550 * leads to a sequence of balanced calls to k_mul.
2551 */
2552 if (2 * asize <= bsize)
2553 return k_lopsided_mul(a, b);
2554
Tim Petersd6974a52002-08-13 20:37:51 +00002555 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002556 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002557 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002558 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002559
Tim Peters0973b992004-08-29 22:16:50 +00002560 if (a == b) {
2561 bh = ah;
2562 bl = al;
2563 Py_INCREF(bh);
2564 Py_INCREF(bl);
2565 }
2566 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002567
Tim Petersd64c1de2002-08-12 17:36:03 +00002568 /* The plan:
2569 * 1. Allocate result space (asize + bsize digits: that's always
2570 * enough).
2571 * 2. Compute ah*bh, and copy into result at 2*shift.
2572 * 3. Compute al*bl, and copy into result at 0. Note that this
2573 * can't overlap with #2.
2574 * 4. Subtract al*bl from the result, starting at shift. This may
2575 * underflow (borrow out of the high digit), but we don't care:
2576 * we're effectively doing unsigned arithmetic mod
2577 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2578 * borrows and carries out of the high digit can be ignored.
2579 * 5. Subtract ah*bh from the result, starting at shift.
2580 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2581 * at shift.
2582 */
2583
2584 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002585 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002586 if (ret == NULL) goto fail;
2587#ifdef Py_DEBUG
2588 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002589 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002590#endif
Tim Peters44121a62002-08-12 06:17:58 +00002591
Tim Petersd64c1de2002-08-12 17:36:03 +00002592 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002593 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002594 assert(Py_SIZE(t1) >= 0);
2595 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002596 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002597 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002598
2599 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002600 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002601 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002602 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002603 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002604
Tim Petersd64c1de2002-08-12 17:36:03 +00002605 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002606 if ((t2 = k_mul(al, bl)) == NULL) {
2607 Py_DECREF(t1);
2608 goto fail;
2609 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002610 assert(Py_SIZE(t2) >= 0);
2611 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2612 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002613
2614 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002615 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002616 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002617 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002618
Tim Petersd64c1de2002-08-12 17:36:03 +00002619 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2620 * because it's fresher in cache.
2621 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002622 i = Py_SIZE(ret) - shift; /* # digits after shift */
2623 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002624 Py_DECREF(t2);
2625
Christian Heimes90aa7642007-12-19 02:45:37 +00002626 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002627 Py_DECREF(t1);
2628
Tim Petersd64c1de2002-08-12 17:36:03 +00002629 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002630 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2631 Py_DECREF(ah);
2632 Py_DECREF(al);
2633 ah = al = NULL;
2634
Tim Peters0973b992004-08-29 22:16:50 +00002635 if (a == b) {
2636 t2 = t1;
2637 Py_INCREF(t2);
2638 }
2639 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002640 Py_DECREF(t1);
2641 goto fail;
2642 }
2643 Py_DECREF(bh);
2644 Py_DECREF(bl);
2645 bh = bl = NULL;
2646
Tim Peters738eda72002-08-12 15:08:20 +00002647 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002648 Py_DECREF(t1);
2649 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002650 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002651 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002652
Tim Petersd6974a52002-08-13 20:37:51 +00002653 /* Add t3. It's not obvious why we can't run out of room here.
2654 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002655 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002656 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002657 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002658
Tim Peters5af4e6c2002-08-12 02:31:19 +00002659 return long_normalize(ret);
2660
2661 fail:
2662 Py_XDECREF(ret);
2663 Py_XDECREF(ah);
2664 Py_XDECREF(al);
2665 Py_XDECREF(bh);
2666 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002667 return NULL;
2668}
2669
Tim Petersd6974a52002-08-13 20:37:51 +00002670/* (*) Why adding t3 can't "run out of room" above.
2671
Tim Petersab86c2b2002-08-15 20:06:00 +00002672Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2673to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002674
Tim Petersab86c2b2002-08-15 20:06:00 +000026751. For any integer i, i = c(i/2) + f(i/2). In particular,
2676 bsize = c(bsize/2) + f(bsize/2).
26772. shift = f(bsize/2)
26783. asize <= bsize
26794. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2680 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002681
Tim Petersab86c2b2002-08-15 20:06:00 +00002682We allocated asize + bsize result digits, and add t3 into them at an offset
2683of shift. This leaves asize+bsize-shift allocated digit positions for t3
2684to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2685asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002686
Tim Petersab86c2b2002-08-15 20:06:00 +00002687bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2688at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002689
Tim Petersab86c2b2002-08-15 20:06:00 +00002690If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2691digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2692most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002693
Tim Petersab86c2b2002-08-15 20:06:00 +00002694The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002695
Tim Petersab86c2b2002-08-15 20:06:00 +00002696 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002697
Tim Petersab86c2b2002-08-15 20:06:00 +00002698and we have asize + c(bsize/2) available digit positions. We need to show
2699this is always enough. An instance of c(bsize/2) cancels out in both, so
2700the question reduces to whether asize digits is enough to hold
2701(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2702then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2703asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002704digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002705asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002706c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2707is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2708bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002709
Tim Peters48d52c02002-08-14 17:07:32 +00002710Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2711clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2712ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002713*/
2714
Tim Peters60004642002-08-12 22:01:34 +00002715/* b has at least twice the digits of a, and a is big enough that Karatsuba
2716 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2717 * of slices, each with a->ob_size digits, and multiply the slices by a,
2718 * one at a time. This gives k_mul balanced inputs to work with, and is
2719 * also cache-friendly (we compute one double-width slice of the result
2720 * at a time, then move on, never bactracking except for the helpful
2721 * single-width slice overlap between successive partial sums).
2722 */
2723static PyLongObject *
2724k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2725{
Christian Heimes90aa7642007-12-19 02:45:37 +00002726 const Py_ssize_t asize = ABS(Py_SIZE(a));
2727 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002728 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002729 PyLongObject *ret;
2730 PyLongObject *bslice = NULL;
2731
2732 assert(asize > KARATSUBA_CUTOFF);
2733 assert(2 * asize <= bsize);
2734
2735 /* Allocate result space, and zero it out. */
2736 ret = _PyLong_New(asize + bsize);
2737 if (ret == NULL)
2738 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002739 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002740
2741 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002742 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002743 if (bslice == NULL)
2744 goto fail;
2745
2746 nbdone = 0;
2747 while (bsize > 0) {
2748 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002749 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002750
2751 /* Multiply the next slice of b by a. */
2752 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2753 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00002754 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002755 product = k_mul(a, bslice);
2756 if (product == NULL)
2757 goto fail;
2758
2759 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002760 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2761 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002762 Py_DECREF(product);
2763
2764 bsize -= nbtouse;
2765 nbdone += nbtouse;
2766 }
2767
2768 Py_DECREF(bslice);
2769 return long_normalize(ret);
2770
2771 fail:
2772 Py_DECREF(ret);
2773 Py_XDECREF(bslice);
2774 return NULL;
2775}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002776
2777static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002778long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002779{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002780 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002781
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002782 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002783
Christian Heimes90aa7642007-12-19 02:45:37 +00002784 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002785 PyObject *r;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002786 r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002787 return r;
2788 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002789
Tim Petersd64c1de2002-08-12 17:36:03 +00002790 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002791 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002792 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002793 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002794 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002795}
2796
Guido van Rossume32e0141992-01-19 16:31:05 +00002797/* The / and % operators are now defined in terms of divmod().
2798 The expression a mod b has the value a - b*floor(a/b).
2799 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002800 |a| by |b|, with the sign of a. This is also expressed
2801 as a - b*trunc(a/b), if trunc truncates towards zero.
2802 Some examples:
2803 a b a rem b a mod b
2804 13 10 3 3
2805 -13 10 -3 7
2806 13 -10 3 -7
2807 -13 -10 -3 -3
2808 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002809 have different signs. We then subtract one from the 'div'
2810 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002811
Tim Peters47e52ee2004-08-30 02:44:38 +00002812/* Compute
2813 * *pdiv, *pmod = divmod(v, w)
2814 * NULL can be passed for pdiv or pmod, in which case that part of
2815 * the result is simply thrown away. The caller owns a reference to
2816 * each of these it requests (does not pass NULL for).
2817 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002818static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002819l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002820 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002821{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002822 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002823
Guido van Rossume32e0141992-01-19 16:31:05 +00002824 if (long_divrem(v, w, &div, &mod) < 0)
2825 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00002826 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2827 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002828 PyLongObject *temp;
2829 PyLongObject *one;
2830 temp = (PyLongObject *) long_add(mod, w);
2831 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002832 mod = temp;
2833 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002834 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002835 return -1;
2836 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002837 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002838 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002839 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2840 Py_DECREF(mod);
2841 Py_DECREF(div);
2842 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002843 return -1;
2844 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002845 Py_DECREF(one);
2846 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002847 div = temp;
2848 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002849 if (pdiv != NULL)
2850 *pdiv = div;
2851 else
2852 Py_DECREF(div);
2853
2854 if (pmod != NULL)
2855 *pmod = mod;
2856 else
2857 Py_DECREF(mod);
2858
Guido van Rossume32e0141992-01-19 16:31:05 +00002859 return 0;
2860}
2861
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002862static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002863long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002864{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002865 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002866
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002867 CHECK_BINOP(a, b);
2868 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002869 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002870 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002871}
2872
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002873static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002874long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002875{
Tim Peterse2a60002001-09-04 06:17:36 +00002876 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002877 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002878
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002879 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002880 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2881 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002882 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002883 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002884 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002885 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2886 but should really be set correctly after sucessful calls to
2887 _PyLong_AsScaledDouble() */
2888 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002889
2890 if (bd == 0.0) {
2891 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002892 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002893 return NULL;
2894 }
2895
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002896 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002897 ad /= bd; /* overflow/underflow impossible here */
2898 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002899 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002900 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002901 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002902 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002903 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002904 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002905 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002906 goto overflow;
2907 return PyFloat_FromDouble(ad);
2908
2909overflow:
2910 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002911 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002912 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002913
Tim Peters20dab9f2001-09-04 05:31:47 +00002914}
2915
2916static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002917long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002918{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002919 PyLongObject *mod;
2920
2921 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002922
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002923 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002924 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002925 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002926}
2927
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002928static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002929long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002930{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002931 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002932 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002933
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002934 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002935
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002936 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002937 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002938 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002939 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002940 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002941 PyTuple_SetItem(z, 0, (PyObject *) div);
2942 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002943 }
2944 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002945 Py_DECREF(div);
2946 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002947 }
2948 return z;
2949}
2950
Tim Peters47e52ee2004-08-30 02:44:38 +00002951/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002952static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002953long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002954{
Tim Peters47e52ee2004-08-30 02:44:38 +00002955 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2956 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002957
Tim Peters47e52ee2004-08-30 02:44:38 +00002958 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002959 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002960 PyLongObject *temp = NULL;
2961
2962 /* 5-ary values. If the exponent is large enough, table is
2963 * precomputed so that table[i] == a**i % c for i in range(32).
2964 */
2965 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2966 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2967
2968 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002969 CHECK_BINOP(v, w);
2970 a = (PyLongObject*)v; Py_INCREF(a);
2971 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002972 if (PyLong_Check(x)) {
2973 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002974 Py_INCREF(x);
2975 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002976 else if (x == Py_None)
2977 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002978 else {
2979 Py_DECREF(a);
2980 Py_DECREF(b);
2981 Py_INCREF(Py_NotImplemented);
2982 return Py_NotImplemented;
2983 }
Tim Peters4c483c42001-09-05 06:24:58 +00002984
Christian Heimes90aa7642007-12-19 02:45:37 +00002985 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00002986 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002987 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002988 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002989 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002990 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002991 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002992 /* else return a float. This works because we know
2993 that this calls float_pow() which converts its
2994 arguments to double. */
2995 Py_DECREF(a);
2996 Py_DECREF(b);
2997 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002998 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002999 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003000
3001 if (c) {
3002 /* if modulus == 0:
3003 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003004 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003005 PyErr_SetString(PyExc_ValueError,
3006 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003007 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003008 }
3009
3010 /* if modulus < 0:
3011 negativeOutput = True
3012 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003013 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003014 negativeOutput = 1;
3015 temp = (PyLongObject *)_PyLong_Copy(c);
3016 if (temp == NULL)
3017 goto Error;
3018 Py_DECREF(c);
3019 c = temp;
3020 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003021 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003022 }
3023
3024 /* if modulus == 1:
3025 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003026 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003027 z = (PyLongObject *)PyLong_FromLong(0L);
3028 goto Done;
3029 }
3030
3031 /* if base < 0:
3032 base = base % modulus
3033 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003034 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003035 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003036 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003037 Py_DECREF(a);
3038 a = temp;
3039 temp = NULL;
3040 }
3041 }
3042
3043 /* At this point a, b, and c are guaranteed non-negative UNLESS
3044 c is NULL, in which case a may be negative. */
3045
3046 z = (PyLongObject *)PyLong_FromLong(1L);
3047 if (z == NULL)
3048 goto Error;
3049
3050 /* Perform a modular reduction, X = X % c, but leave X alone if c
3051 * is NULL.
3052 */
3053#define REDUCE(X) \
3054 if (c != NULL) { \
3055 if (l_divmod(X, c, NULL, &temp) < 0) \
3056 goto Error; \
3057 Py_XDECREF(X); \
3058 X = temp; \
3059 temp = NULL; \
3060 }
3061
3062 /* Multiply two values, then reduce the result:
3063 result = X*Y % c. If c is NULL, skip the mod. */
3064#define MULT(X, Y, result) \
3065{ \
3066 temp = (PyLongObject *)long_mul(X, Y); \
3067 if (temp == NULL) \
3068 goto Error; \
3069 Py_XDECREF(result); \
3070 result = temp; \
3071 temp = NULL; \
3072 REDUCE(result) \
3073}
3074
Christian Heimes90aa7642007-12-19 02:45:37 +00003075 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003076 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3077 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003078 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003079 digit bi = b->ob_digit[i];
3080
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003081 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003082 MULT(z, z, z)
3083 if (bi & j)
3084 MULT(z, a, z)
3085 }
3086 }
3087 }
3088 else {
3089 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3090 Py_INCREF(z); /* still holds 1L */
3091 table[0] = z;
3092 for (i = 1; i < 32; ++i)
3093 MULT(table[i-1], a, table[i])
3094
Christian Heimes90aa7642007-12-19 02:45:37 +00003095 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003096 const digit bi = b->ob_digit[i];
3097
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003098 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003099 const int index = (bi >> j) & 0x1f;
3100 for (k = 0; k < 5; ++k)
3101 MULT(z, z, z)
3102 if (index)
3103 MULT(z, table[index], z)
3104 }
3105 }
3106 }
3107
Christian Heimes90aa7642007-12-19 02:45:37 +00003108 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003109 temp = (PyLongObject *)long_sub(z, c);
3110 if (temp == NULL)
3111 goto Error;
3112 Py_DECREF(z);
3113 z = temp;
3114 temp = NULL;
3115 }
3116 goto Done;
3117
3118 Error:
3119 if (z != NULL) {
3120 Py_DECREF(z);
3121 z = NULL;
3122 }
3123 /* fall through */
3124 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003125 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003126 for (i = 0; i < 32; ++i)
3127 Py_XDECREF(table[i]);
3128 }
Tim Petersde7990b2005-07-17 23:45:23 +00003129 Py_DECREF(a);
3130 Py_DECREF(b);
3131 Py_XDECREF(c);
3132 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003133 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003134}
3135
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003136static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003137long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003138{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003139 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003140 PyLongObject *x;
3141 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003142 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003143 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003144 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003145 if (w == NULL)
3146 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003147 x = (PyLongObject *) long_add(v, w);
3148 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003149 if (x == NULL)
3150 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003151 Py_SIZE(x) = -(Py_SIZE(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003152 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003153}
3154
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003155static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003156long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003157{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003158 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003159 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003160 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003161 z = (PyLongObject *)_PyLong_Copy(v);
3162 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003163 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003164 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003165}
3166
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003167static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003168long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003169{
Christian Heimes90aa7642007-12-19 02:45:37 +00003170 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003171 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003172 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003173 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003174}
3175
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003176static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003177long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003178{
Christian Heimes90aa7642007-12-19 02:45:37 +00003179 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003180}
3181
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003182static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003183long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003184{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003185 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003186 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003187 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003188 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003189
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003190 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003191
Christian Heimes90aa7642007-12-19 02:45:37 +00003192 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003193 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003194 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003195 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003196 if (a1 == NULL)
3197 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003198 a2 = (PyLongObject *) long_rshift(a1, b);
3199 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003200 if (a2 == NULL)
3201 goto rshift_error;
3202 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003203 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003204 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003205 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003206
Neil Schemenauerba872e22001-01-04 01:46:03 +00003207 shiftby = PyLong_AsLong((PyObject *)b);
3208 if (shiftby == -1L && PyErr_Occurred())
3209 goto rshift_error;
3210 if (shiftby < 0) {
3211 PyErr_SetString(PyExc_ValueError,
3212 "negative shift count");
3213 goto rshift_error;
3214 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003215 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003216 newsize = ABS(Py_SIZE(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003217 if (newsize <= 0) {
3218 z = _PyLong_New(0);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003219 return (PyObject *)z;
3220 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003221 loshift = shiftby % PyLong_SHIFT;
3222 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003223 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003224 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003225 z = _PyLong_New(newsize);
3226 if (z == NULL)
3227 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003228 if (Py_SIZE(a) < 0)
3229 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003230 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3231 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3232 if (i+1 < newsize)
3233 z->ob_digit[i] |=
3234 (a->ob_digit[j+1] << hishift) & himask;
3235 }
3236 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003237 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003238rshift_error:
Neil Schemenauerba872e22001-01-04 01:46:03 +00003239 return (PyObject *) z;
3240
Guido van Rossumc6913e71991-11-19 20:26:46 +00003241}
3242
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003243static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003244long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003245{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003246 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003247 PyLongObject *a = (PyLongObject*)v;
3248 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003249 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003250 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003251 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003252 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003253
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003254 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003255
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003256 shiftby = PyLong_AsLong((PyObject *)b);
3257 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003258 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003259 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003260 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003261 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003262 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003263 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003264 PyErr_SetString(PyExc_ValueError,
3265 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003266 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003267 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003268 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3269 wordshift = (int)shiftby / PyLong_SHIFT;
3270 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003271
Christian Heimes90aa7642007-12-19 02:45:37 +00003272 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003273 newsize = oldsize + wordshift;
3274 if (remshift)
3275 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003276 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003277 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003278 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003279 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003280 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003281 for (i = 0; i < wordshift; i++)
3282 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003283 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003284 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003285 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003286 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3287 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003288 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003289 if (remshift)
3290 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003291 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003292 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003293 z = long_normalize(z);
3294lshift_error:
Neil Schemenauerba872e22001-01-04 01:46:03 +00003295 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003296}
3297
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003298
3299/* Bitwise and/xor/or operations */
3300
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003301static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003302long_bitwise(PyLongObject *a,
3303 int op, /* '&', '|', '^' */
3304 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003305{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003306 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003307 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003308 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003309 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003310 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003311 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003312 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003313
Christian Heimes90aa7642007-12-19 02:45:37 +00003314 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003315 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003316 if (a == NULL)
3317 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003318 maska = PyLong_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(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003322 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003323 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003324 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003325 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003326 if (b == NULL) {
3327 Py_DECREF(a);
3328 return NULL;
3329 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003330 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003331 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003332 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003333 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003334 maskb = 0;
3335 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003336
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003337 negz = 0;
3338 switch (op) {
3339 case '^':
3340 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003341 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003342 negz = -1;
3343 }
3344 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003345 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003346 if (maska && maskb) {
3347 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003348 maska ^= PyLong_MASK;
3349 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003350 negz = -1;
3351 }
3352 break;
3353 case '|':
3354 if (maska || maskb) {
3355 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003356 maska ^= PyLong_MASK;
3357 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003358 negz = -1;
3359 }
3360 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003361 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003362
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003363 /* JRH: The original logic here was to allocate the result value (z)
3364 as the longer of the two operands. However, there are some cases
3365 where the result is guaranteed to be shorter than that: AND of two
3366 positives, OR of two negatives: use the shorter number. AND with
3367 mixed signs: use the positive number. OR with mixed signs: use the
3368 negative number. After the transformations above, op will be '&'
3369 iff one of these cases applies, and mask will be non-0 for operands
3370 whose length should be ignored.
3371 */
3372
Christian Heimes90aa7642007-12-19 02:45:37 +00003373 size_a = Py_SIZE(a);
3374 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003375 size_z = op == '&'
3376 ? (maska
3377 ? size_b
3378 : (maskb ? size_a : MIN(size_a, size_b)))
3379 : MAX(size_a, size_b);
3380 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003381 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003382 Py_DECREF(a);
3383 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003384 return NULL;
3385 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003386
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003387 for (i = 0; i < size_z; ++i) {
3388 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3389 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3390 switch (op) {
3391 case '&': z->ob_digit[i] = diga & digb; break;
3392 case '|': z->ob_digit[i] = diga | digb; break;
3393 case '^': z->ob_digit[i] = diga ^ digb; break;
3394 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003395 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003396
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003397 Py_DECREF(a);
3398 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003399 z = long_normalize(z);
3400 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003401 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003402 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003403 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003404 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003405}
3406
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003407static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003408long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003409{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003410 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003411 CHECK_BINOP(a, b);
3412 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003413 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003414}
3415
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003416static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003417long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003418{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003419 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003420 CHECK_BINOP(a, b);
3421 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003422 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003423}
3424
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003425static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003426long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003427{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003428 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003429 CHECK_BINOP(a, b);
3430 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003431 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003432}
3433
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003434static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003435long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003436{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003437 if (PyLong_CheckExact(v))
3438 Py_INCREF(v);
3439 else
3440 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003441 return v;
3442}
3443
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003444static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003445long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003446{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003447 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003448 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003449 if (result == -1.0 && PyErr_Occurred())
3450 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003451 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003452}
3453
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003454static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003455long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003456
Tim Peters6d6c1a32001-08-02 04:15:00 +00003457static PyObject *
3458long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3459{
3460 PyObject *x = NULL;
3461 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003462 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003463
Guido van Rossumbef14172001-08-29 15:47:46 +00003464 if (type != &PyLong_Type)
3465 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003466 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003467 &x, &base))
3468 return NULL;
3469 if (x == NULL)
3470 return PyLong_FromLong(0L);
3471 if (base == -909)
3472 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003473 else if (PyUnicode_Check(x))
3474 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3475 PyUnicode_GET_SIZE(x),
3476 base);
3477 else if (PyBytes_Check(x) || PyString_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003478 /* Since PyLong_FromString doesn't have a length parameter,
3479 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003480 char *string;
Christian Heimes90aa7642007-12-19 02:45:37 +00003481 int size = Py_SIZE(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003482 if (PyBytes_Check(x))
3483 string = PyBytes_AS_STRING(x);
3484 else
3485 string = PyString_AS_STRING(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003486 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003487 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003488 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003489 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003490 "invalid literal for int() with base %d: %R",
3491 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003492 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003493 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003494 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003495 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003496 else {
3497 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003498 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499 return NULL;
3500 }
3501}
3502
Guido van Rossumbef14172001-08-29 15:47:46 +00003503/* Wimpy, slow approach to tp_new calls for subtypes of long:
3504 first create a regular long from whatever arguments we got,
3505 then allocate a subtype instance and initialize it from
3506 the regular long. The regular long is then thrown away.
3507*/
3508static PyObject *
3509long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3510{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003511 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003512 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003513
3514 assert(PyType_IsSubtype(type, &PyLong_Type));
3515 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3516 if (tmp == NULL)
3517 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003518 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003519 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003520 if (n < 0)
3521 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003522 newobj = (PyLongObject *)type->tp_alloc(type, n);
3523 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003524 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003525 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003526 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003527 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003528 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003529 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003530 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003531 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003532 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003533}
3534
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003535static PyObject *
3536long_getnewargs(PyLongObject *v)
3537{
3538 return Py_BuildValue("(N)", _PyLong_Copy(v));
3539}
3540
Guido van Rossumb43daf72007-08-01 18:08:08 +00003541static PyObject *
3542long_getN(PyLongObject *v, void *context) {
3543 return PyLong_FromLong((intptr_t)context);
3544}
3545
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003546static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003547long__format__(PyObject *self, PyObject *args)
3548{
3549 /* when back porting this to 2.6, check type of the format_spec
3550 and call either unicode_long__format__ or
3551 string_long__format__ */
3552 return unicode_long__format__(self, args);
3553}
3554
3555
3556static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003557long_round(PyObject *self, PyObject *args)
3558{
3559#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
3560 int ndigits = UNDEF_NDIGITS;
3561 double x;
3562 PyObject *res;
3563
3564 if (!PyArg_ParseTuple(args, "|i", &ndigits))
3565 return NULL;
3566
3567 if (ndigits == UNDEF_NDIGITS)
3568 return long_long(self);
3569
3570 /* If called with two args, defer to float.__round__(). */
3571 x = PyLong_AsDouble(self);
3572 if (x == -1.0 && PyErr_Occurred())
3573 return NULL;
3574 self = PyFloat_FromDouble(x);
3575 if (self == NULL)
3576 return NULL;
3577 res = PyObject_CallMethod(self, "__round__", "i", ndigits);
3578 Py_DECREF(self);
3579 return res;
3580#undef UNDEF_NDIGITS
3581}
3582
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003583static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003584 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3585 "Returns self, the complex conjugate of any int."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003586 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3587 "Truncating an Integral returns itself."},
3588 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3589 "Flooring an Integral returns itself."},
3590 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3591 "Ceiling of an Integral returns itself."},
3592 {"__round__", (PyCFunction)long_round, METH_VARARGS,
3593 "Rounding an Integral returns itself.\n"
3594 "Rounding with an ndigits arguments defers to float.__round__."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003595 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003596 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003597 {NULL, NULL} /* sentinel */
3598};
3599
Guido van Rossumb43daf72007-08-01 18:08:08 +00003600static PyGetSetDef long_getset[] = {
3601 {"real",
3602 (getter)long_long, (setter)NULL,
3603 "the real part of a complex number",
3604 NULL},
3605 {"imag",
3606 (getter)long_getN, (setter)NULL,
3607 "the imaginary part of a complex number",
3608 (void*)0},
3609 {"numerator",
3610 (getter)long_long, (setter)NULL,
3611 "the numerator of a rational number in lowest terms",
3612 NULL},
3613 {"denominator",
3614 (getter)long_getN, (setter)NULL,
3615 "the denominator of a rational number in lowest terms",
3616 (void*)1},
3617 {NULL} /* Sentinel */
3618};
3619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003620PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003621"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003622\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003623Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624point argument will be truncated towards zero (this does not include a\n\
3625string representation of a floating point number!) When converting a\n\
3626string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003627converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003628
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003629static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003630 (binaryfunc) long_add, /*nb_add*/
3631 (binaryfunc) long_sub, /*nb_subtract*/
3632 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003633 long_mod, /*nb_remainder*/
3634 long_divmod, /*nb_divmod*/
3635 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003636 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003637 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003638 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003639 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003640 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003641 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003642 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003643 long_and, /*nb_and*/
3644 long_xor, /*nb_xor*/
3645 long_or, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00003646 0, /*nb_reserved*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003647 long_long, /*nb_int*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003648 long_long, /*nb_long*/
3649 long_float, /*nb_float*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003650 0, /*nb_oct*/ /* not used */
3651 0, /*nb_hex*/ /* not used */
Guido van Rossum4668b002001-08-08 05:00:18 +00003652 0, /* nb_inplace_add */
3653 0, /* nb_inplace_subtract */
3654 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003655 0, /* nb_inplace_remainder */
3656 0, /* nb_inplace_power */
3657 0, /* nb_inplace_lshift */
3658 0, /* nb_inplace_rshift */
3659 0, /* nb_inplace_and */
3660 0, /* nb_inplace_xor */
3661 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003662 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003663 long_true_divide, /* nb_true_divide */
3664 0, /* nb_inplace_floor_divide */
3665 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003666 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003667};
3668
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003669PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003670 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003671 "int", /* tp_name */
3672 /* See _PyLong_New for why this isn't
3673 sizeof(PyLongObject) - sizeof(digit) */
3674 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003675 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003676 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003677 0, /* tp_print */
3678 0, /* tp_getattr */
3679 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003680 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003681 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682 &long_as_number, /* tp_as_number */
3683 0, /* tp_as_sequence */
3684 0, /* tp_as_mapping */
3685 (hashfunc)long_hash, /* tp_hash */
3686 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003687 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688 PyObject_GenericGetAttr, /* tp_getattro */
3689 0, /* tp_setattro */
3690 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003691 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3692 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693 long_doc, /* tp_doc */
3694 0, /* tp_traverse */
3695 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003696 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003697 0, /* tp_weaklistoffset */
3698 0, /* tp_iter */
3699 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003700 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003701 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003702 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003703 0, /* tp_base */
3704 0, /* tp_dict */
3705 0, /* tp_descr_get */
3706 0, /* tp_descr_set */
3707 0, /* tp_dictoffset */
3708 0, /* tp_init */
3709 0, /* tp_alloc */
3710 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003711 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003712};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003713
3714int
3715_PyLong_Init(void)
3716{
3717#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3718 int ival;
3719 PyLongObject *v = small_ints;
3720 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3721 PyObject_INIT(v, &PyLong_Type);
Christian Heimes90aa7642007-12-19 02:45:37 +00003722 Py_SIZE(v) = -1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003723 v->ob_digit[0] = -ival;
3724 }
3725 for (; ival < NSMALLPOSINTS; ival++, v++) {
3726 PyObject_INIT(v, &PyLong_Type);
Christian Heimes90aa7642007-12-19 02:45:37 +00003727 Py_SIZE(v) = ival ? 1 : 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003728 v->ob_digit[0] = ival;
3729 }
3730#endif
3731 return 1;
3732}
3733
3734void
3735PyLong_Fini(void)
3736{
3737#if 0
3738 int i;
3739 /* This is currently not needed; the small integers
3740 are statically allocated */
3741#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3742 PyIntObject **q;
3743
3744 i = NSMALLNEGINTS + NSMALLPOSINTS;
3745 q = small_ints;
3746 while (--i >= 0) {
3747 Py_XDECREF(*q);
3748 *q++ = NULL;
3749 }
3750#endif
3751#endif
3752}