blob: b724edf3e078740eef200ba25e19e8767e5a212b [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 Rossum22201222007-08-07 22:02:18 +000012long
13PyInt_GetMax(void)
14{
15 return LONG_MAX; /* To initialize sys.maxint */
16}
17
Guido van Rossumddefaf32007-01-14 03:31:43 +000018#ifndef NSMALLPOSINTS
19#define NSMALLPOSINTS 257
20#endif
21#ifndef NSMALLNEGINTS
22#define NSMALLNEGINTS 5
23#endif
24#if NSMALLNEGINTS + NSMALLPOSINTS > 0
25/* Small integers are preallocated in this array so that they
26 can be shared.
27 The integers that are preallocated are those in the range
28 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
29*/
30static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
31#ifdef COUNT_ALLOCS
32int quick_int_allocs, quick_neg_int_allocs;
33#endif
34
Guido van Rossum7eaf8222007-06-18 17:58:50 +000035static PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +000036get_small_int(int ival)
37{
38 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
39 Py_INCREF(v);
40#ifdef COUNT_ALLOCS
41 if (ival >= 0)
42 quick_int_allocs++;
43 else
44 quick_neg_int_allocs++;
45#endif
46 return v;
47}
48#define CHECK_SMALL_INT(ival) \
49 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
50 return get_small_int(ival); \
51 } while(0)
52
53#else
54#define CHECK_SMALL_INT(ival)
55#endif
56
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000057#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 +000058/* If a freshly-allocated long is already shared, it must
59 be a small integer, so negating it must go to PyLong_FromLong */
60#define NEGATE(x) \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000061 do if (Py_Refcnt(x) == 1) Py_Size(x) = -Py_Size(x); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000062 else { PyObject* tmp=PyInt_FromLong(-MEDIUM_VALUE(x)); \
63 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
64 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000065/* For long multiplication, use the O(N**2) school algorithm unless
66 * both operands contain more than KARATSUBA_CUTOFF digits (this
67 * being an internal Python long digit, in base BASE).
68 */
Tim Peters0973b992004-08-29 22:16:50 +000069#define KARATSUBA_CUTOFF 70
70#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000071
Tim Peters47e52ee2004-08-30 02:44:38 +000072/* For exponentiation, use the binary left-to-right algorithm
73 * unless the exponent contains more than FIVEARY_CUTOFF digits.
74 * In that case, do 5 bits at a time. The potential drawback is that
75 * a table of 2**5 intermediate results is computed.
76 */
77#define FIVEARY_CUTOFF 8
78
Guido van Rossume32e0141992-01-19 16:31:05 +000079#define ABS(x) ((x) < 0 ? -(x) : (x))
80
Tim Peters5af4e6c2002-08-12 02:31:19 +000081#undef MIN
82#undef MAX
83#define MAX(x, y) ((x) < (y) ? (y) : (x))
84#define MIN(x, y) ((x) > (y) ? (y) : (x))
85
Guido van Rossume32e0141992-01-19 16:31:05 +000086/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000087static PyLongObject *long_normalize(PyLongObject *);
88static PyLongObject *mul1(PyLongObject *, wdigit);
89static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000090static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Guido van Rossume32e0141992-01-19 16:31:05 +000091
Guido van Rossumc0b618a1997-05-02 03:12:38 +000092#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000093 if (--_Py_Ticker < 0) { \
94 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +000095 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000096 }
97
Guido van Rossumedcc38a1991-05-05 20:09:44 +000098/* Normalize (remove leading zeros from) a long int object.
99 Doesn't attempt to free the storage--in most cases, due to the nature
100 of the algorithms used, this could save at most be one word anyway. */
101
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000103long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000104{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000105 Py_ssize_t j = ABS(Py_Size(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000106 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000107
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108 while (i > 0 && v->ob_digit[i-1] == 0)
109 --i;
110 if (i != j)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000111 Py_Size(v) = (Py_Size(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000112 return v;
113}
114
115/* Allocate a new long int object with size digits.
116 Return NULL and set exception if we run out of memory. */
117
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000118PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000119_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000120{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000121 PyLongObject *result;
122 /* Can't use sizeof(PyLongObject) here, since the
123 compiler takes padding at the end into account.
124 As the consequence, this would waste 2 bytes on
125 a 32-bit system, and 6 bytes on a 64-bit system.
126 This computation would be incorrect on systems
127 which have padding before the digits; with 16-bit
128 digits this should not happen. */
129 result = PyObject_MALLOC(sizeof(PyVarObject) +
130 size*sizeof(digit));
131 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000132 PyErr_NoMemory();
133 return NULL;
134 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000135 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000136}
137
Tim Peters64b5ce32001-09-10 20:52:51 +0000138PyObject *
139_PyLong_Copy(PyLongObject *src)
140{
141 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000142 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000143
144 assert(src != NULL);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000145 i = Py_Size(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000146 if (i < 0)
147 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000148 if (i < 2) {
149 int ival = src->ob_digit[0];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000150 if (Py_Size(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000151 ival = -ival;
152 CHECK_SMALL_INT(ival);
153 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000154 result = _PyLong_New(i);
155 if (result != NULL) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000156 Py_Size(result) = Py_Size(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000157 while (--i >= 0)
158 result->ob_digit[i] = src->ob_digit[i];
159 }
160 return (PyObject *)result;
161}
162
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000163/* Create a new long int object from a C long int */
164
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000165PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000166PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000167{
Tim Petersce9de2f2001-06-14 04:56:19 +0000168 PyLongObject *v;
169 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
170 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000171 int sign = 1;
172
173 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000174
175 if (ival < 0) {
176 ival = -ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000177 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000178 }
179
Guido van Rossumddefaf32007-01-14 03:31:43 +0000180 /* Fast path for single-digits ints */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000181 if (!(ival>>PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000182 v = _PyLong_New(1);
183 if (v) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000184 Py_Size(v) = sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000185 v->ob_digit[0] = ival;
186 }
187 return (PyObject*)v;
188 }
189
190 /* 2 digits */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000191 if (!(ival >> 2*PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000192 v = _PyLong_New(2);
193 if (v) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000194 Py_Size(v) = 2*sign;
195 v->ob_digit[0] = (digit)ival & PyLong_MASK;
196 v->ob_digit[1] = ival >> PyLong_SHIFT;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000197 }
198 return (PyObject*)v;
199 }
200
201 /* Larger numbers: loop to determine number of digits */
Tim Petersce9de2f2001-06-14 04:56:19 +0000202 t = (unsigned long)ival;
203 while (t) {
204 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000205 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000206 }
207 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000208 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000209 digit *p = v->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000210 Py_Size(v) = ndigits*sign;
Tim Petersce9de2f2001-06-14 04:56:19 +0000211 t = (unsigned long)ival;
212 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000213 *p++ = (digit)(t & PyLong_MASK);
214 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000215 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000216 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000217 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000218}
219
Guido van Rossum53756b11997-01-03 17:14:46 +0000220/* Create a new long int object from a C unsigned long int */
221
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000222PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000223PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000224{
Tim Petersce9de2f2001-06-14 04:56:19 +0000225 PyLongObject *v;
226 unsigned long t;
227 int ndigits = 0;
228
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000229 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000230 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000231 /* Count the number of Python digits. */
232 t = (unsigned long)ival;
233 while (t) {
234 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000235 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000236 }
237 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000238 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000239 digit *p = v->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000240 Py_Size(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000241 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000242 *p++ = (digit)(ival & PyLong_MASK);
243 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000244 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000245 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000247}
248
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000249/* Create a new long int object from a C double */
250
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000251PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000252PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000253{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000254 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000255 double frac;
256 int i, ndig, expo, neg;
257 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000258 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000259 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000260 "cannot convert float infinity to int");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000261 return NULL;
262 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000263 CHECK_SMALL_INT((int)dval);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000264 if (dval < 0.0) {
265 neg = 1;
266 dval = -dval;
267 }
268 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
269 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000270 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000271 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000273 if (v == NULL)
274 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000275 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000276 for (i = ndig; --i >= 0; ) {
277 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000278 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000279 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000280 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000281 }
282 if (neg)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000283 Py_Size(v) = -(Py_Size(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000284 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000285}
286
Thomas Wouters89f507f2006-12-13 04:49:30 +0000287/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
288 * anything about what happens when a signed integer operation overflows,
289 * and some compilers think they're doing you a favor by being "clever"
290 * then. The bit pattern for the largest postive signed long is
291 * (unsigned long)LONG_MAX, and for the smallest negative signed long
292 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
293 * However, some other compilers warn about applying unary minus to an
294 * unsigned operand. Hence the weird "0-".
295 */
296#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
297#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
298
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000299/* Get a C long int from a long int object.
300 Returns -1 and sets an error condition if overflow occurs. */
301
302long
Tim Peters9f688bf2000-07-07 15:53:28 +0000303PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000304{
Guido van Rossumf7531811998-05-26 14:33:37 +0000305 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000306 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000307 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000308 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000309 Py_ssize_t i;
310 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000311 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000312
Guido van Rossumddefaf32007-01-14 03:31:43 +0000313 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000314 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000315 return -1;
316 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000317
318 if (!PyLong_Check(vv)) {
319 PyNumberMethods *nb;
320 if ((nb = vv->ob_type->tp_as_number) == NULL ||
321 nb->nb_int == NULL) {
322 PyErr_SetString(PyExc_TypeError, "an integer is required");
323 return -1;
324 }
325 vv = (*nb->nb_int) (vv);
326 if (vv == NULL)
327 return -1;
328 do_decref = 1;
329 if (!PyLong_Check(vv)) {
330 Py_DECREF(vv);
331 PyErr_SetString(PyExc_TypeError,
332 "nb_int should return int object");
333 return -1;
334 }
335 }
336
Georg Brandl61c31b02007-02-26 14:46:30 +0000337 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000339 i = Py_Size(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000340
Georg Brandl61c31b02007-02-26 14:46:30 +0000341 switch (i) {
342 case -1:
343 res = -v->ob_digit[0];
344 break;
345 case 0:
346 res = 0;
347 break;
348 case 1:
349 res = v->ob_digit[0];
350 break;
351 default:
352 sign = 1;
353 x = 0;
354 if (i < 0) {
355 sign = -1;
356 i = -(i);
357 }
358 while (--i >= 0) {
359 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000360 x = (x << PyLong_SHIFT) + v->ob_digit[i];
361 if ((x >> PyLong_SHIFT) != prev) {
Georg Brandl61c31b02007-02-26 14:46:30 +0000362 PyErr_SetString(PyExc_OverflowError,
363 "Python int too large to convert to C long");
364 goto exit;
365 }
366 }
367 /* Haven't lost any bits, but casting to long requires extra care
368 * (see comment above).
369 */
370 if (x <= (unsigned long)LONG_MAX) {
371 res = (long)x * sign;
372 }
373 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
374 res = LONG_MIN;
375 }
376 else {
377 PyErr_SetString(PyExc_OverflowError,
378 "Python int too large to convert to C long");
379 }
380 }
381 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000382 if (do_decref) {
383 Py_DECREF(vv);
384 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000385 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000386}
387
Guido van Rossumddefaf32007-01-14 03:31:43 +0000388int
389_PyLong_FitsInLong(PyObject *vv)
390{
391 int size;
392 if (!PyLong_CheckExact(vv)) {
393 PyErr_BadInternalCall();
394 return 0;
395 }
396 /* conservative estimate */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000397 size = Py_Size(vv);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000398 return -2 <= size && size <= 2;
399}
400
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000401/* Get a Py_ssize_t from a long int object.
402 Returns -1 and sets an error condition if overflow occurs. */
403
404Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000405PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000406 register PyLongObject *v;
407 size_t x, prev;
408 Py_ssize_t i;
409 int sign;
410
411 if (vv == NULL || !PyLong_Check(vv)) {
412 PyErr_BadInternalCall();
413 return -1;
414 }
415 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000416 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000417 switch (i) {
418 case -1: return -v->ob_digit[0];
419 case 0: return 0;
420 case 1: return v->ob_digit[0];
421 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000422 sign = 1;
423 x = 0;
424 if (i < 0) {
425 sign = -1;
426 i = -(i);
427 }
428 while (--i >= 0) {
429 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000430 x = (x << PyLong_SHIFT) + v->ob_digit[i];
431 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000432 goto overflow;
433 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000434 /* Haven't lost any bits, but casting to a signed type requires
435 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000436 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000437 if (x <= (size_t)PY_SSIZE_T_MAX) {
438 return (Py_ssize_t)x * sign;
439 }
440 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
441 return PY_SSIZE_T_MIN;
442 }
443 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000444
445 overflow:
446 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000447 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000448 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000449}
450
Guido van Rossumd8c80482002-08-13 00:24:58 +0000451/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000452 Returns -1 and sets an error condition if overflow occurs. */
453
454unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000455PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000456{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000458 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000459 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000460
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000461 if (vv == NULL || !PyLong_Check(vv)) {
462 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000463 return (unsigned long) -1;
464 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000465 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000466 i = Py_Size(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000467 x = 0;
468 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000469 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000470 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000471 return (unsigned long) -1;
472 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000473 switch (i) {
474 case 0: return 0;
475 case 1: return v->ob_digit[0];
476 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000477 while (--i >= 0) {
478 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000479 x = (x << PyLong_SHIFT) + v->ob_digit[i];
480 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000481 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000482 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000483 return (unsigned long) -1;
484 }
485 }
486 return x;
487}
488
489/* Get a C unsigned long int from a long int object.
490 Returns -1 and sets an error condition if overflow occurs. */
491
492size_t
493PyLong_AsSize_t(PyObject *vv)
494{
495 register PyLongObject *v;
496 size_t x, prev;
497 Py_ssize_t i;
498
499 if (vv == NULL || !PyLong_Check(vv)) {
500 PyErr_BadInternalCall();
501 return (unsigned long) -1;
502 }
503 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000504 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000505 x = 0;
506 if (i < 0) {
507 PyErr_SetString(PyExc_OverflowError,
508 "can't convert negative value to size_t");
509 return (size_t) -1;
510 }
511 switch (i) {
512 case 0: return 0;
513 case 1: return v->ob_digit[0];
514 }
515 while (--i >= 0) {
516 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000517 x = (x << PyLong_SHIFT) + v->ob_digit[i];
518 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000519 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000520 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000521 return (unsigned long) -1;
522 }
523 }
524 return x;
525}
526
Thomas Hellera4ea6032003-04-17 18:55:45 +0000527/* Get a C unsigned long int from a long int object, ignoring the high bits.
528 Returns -1 and sets an error condition if an error occurs. */
529
Guido van Rossumddefaf32007-01-14 03:31:43 +0000530static unsigned long
531_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000532{
533 register PyLongObject *v;
534 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000535 Py_ssize_t i;
536 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000537
538 if (vv == NULL || !PyLong_Check(vv)) {
539 PyErr_BadInternalCall();
540 return (unsigned long) -1;
541 }
542 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000543 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000544 switch (i) {
545 case 0: return 0;
546 case 1: return v->ob_digit[0];
547 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000548 sign = 1;
549 x = 0;
550 if (i < 0) {
551 sign = -1;
552 i = -i;
553 }
554 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000555 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000556 }
557 return x * sign;
558}
559
Guido van Rossumddefaf32007-01-14 03:31:43 +0000560unsigned long
561PyLong_AsUnsignedLongMask(register PyObject *op)
562{
563 PyNumberMethods *nb;
564 PyLongObject *lo;
565 unsigned long val;
566
567 if (op && PyLong_Check(op))
568 return _PyLong_AsUnsignedLongMask(op);
569
570 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
571 nb->nb_int == NULL) {
572 PyErr_SetString(PyExc_TypeError, "an integer is required");
573 return (unsigned long)-1;
574 }
575
576 lo = (PyLongObject*) (*nb->nb_int) (op);
577 if (lo == NULL)
578 return (unsigned long)-1;
579 if (PyLong_Check(lo)) {
580 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
581 Py_DECREF(lo);
582 if (PyErr_Occurred())
583 return (unsigned long)-1;
584 return val;
585 }
586 else
587 {
588 Py_DECREF(lo);
589 PyErr_SetString(PyExc_TypeError,
590 "nb_int should return int object");
591 return (unsigned long)-1;
592 }
593}
594
Tim Peters5b8132f2003-01-31 15:52:05 +0000595int
596_PyLong_Sign(PyObject *vv)
597{
598 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000599
600 assert(v != NULL);
601 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000602
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000603 return Py_Size(v) == 0 ? 0 : (Py_Size(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000604}
605
Tim Petersbaefd9e2003-01-28 20:37:45 +0000606size_t
607_PyLong_NumBits(PyObject *vv)
608{
609 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000610 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000611 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000612
613 assert(v != NULL);
614 assert(PyLong_Check(v));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000615 ndigits = ABS(Py_Size(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000616 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
617 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000618 digit msd = v->ob_digit[ndigits - 1];
619
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000620 result = (ndigits - 1) * PyLong_SHIFT;
621 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000622 goto Overflow;
623 do {
624 ++result;
625 if (result == 0)
626 goto Overflow;
627 msd >>= 1;
628 } while (msd);
629 }
630 return result;
631
632Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000633 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000634 "to express in a platform size_t");
635 return (size_t)-1;
636}
637
Tim Peters2a9b3672001-06-11 21:23:58 +0000638PyObject *
639_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
640 int little_endian, int is_signed)
641{
642 const unsigned char* pstartbyte;/* LSB of bytes */
643 int incr; /* direction to move pstartbyte */
644 const unsigned char* pendbyte; /* MSB of bytes */
645 size_t numsignificantbytes; /* number of bytes that matter */
646 size_t ndigits; /* number of Python long digits */
647 PyLongObject* v; /* result */
648 int idigit = 0; /* next free index in v->ob_digit */
649
650 if (n == 0)
651 return PyLong_FromLong(0L);
652
653 if (little_endian) {
654 pstartbyte = bytes;
655 pendbyte = bytes + n - 1;
656 incr = 1;
657 }
658 else {
659 pstartbyte = bytes + n - 1;
660 pendbyte = bytes;
661 incr = -1;
662 }
663
664 if (is_signed)
665 is_signed = *pendbyte >= 0x80;
666
667 /* Compute numsignificantbytes. This consists of finding the most
668 significant byte. Leading 0 bytes are insignficant if the number
669 is positive, and leading 0xff bytes if negative. */
670 {
671 size_t i;
672 const unsigned char* p = pendbyte;
673 const int pincr = -incr; /* search MSB to LSB */
674 const unsigned char insignficant = is_signed ? 0xff : 0x00;
675
676 for (i = 0; i < n; ++i, p += pincr) {
677 if (*p != insignficant)
678 break;
679 }
680 numsignificantbytes = n - i;
681 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
682 actually has 2 significant bytes. OTOH, 0xff0001 ==
683 -0x00ffff, so we wouldn't *need* to bump it there; but we
684 do for 0xffff = -0x0001. To be safe without bothering to
685 check every case, bump it regardless. */
686 if (is_signed && numsignificantbytes < n)
687 ++numsignificantbytes;
688 }
689
690 /* How many Python long digits do we need? We have
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000691 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000692 bits, so it's the ceiling of the quotient. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000693 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000694 if (ndigits > (size_t)INT_MAX)
695 return PyErr_NoMemory();
696 v = _PyLong_New((int)ndigits);
697 if (v == NULL)
698 return NULL;
699
700 /* Copy the bits over. The tricky parts are computing 2's-comp on
701 the fly for signed numbers, and dealing with the mismatch between
702 8-bit bytes and (probably) 15-bit Python digits.*/
703 {
704 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000705 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000706 twodigits accum = 0; /* sliding register */
707 unsigned int accumbits = 0; /* number of bits in accum */
708 const unsigned char* p = pstartbyte;
709
710 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000711 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000712 /* Compute correction for 2's comp, if needed. */
713 if (is_signed) {
714 thisbyte = (0xff ^ thisbyte) + carry;
715 carry = thisbyte >> 8;
716 thisbyte &= 0xff;
717 }
718 /* Because we're going LSB to MSB, thisbyte is
719 more significant than what's already in accum,
720 so needs to be prepended to accum. */
721 accum |= thisbyte << accumbits;
722 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000723 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000724 /* There's enough to fill a Python digit. */
725 assert(idigit < (int)ndigits);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000726 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000727 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000728 accum >>= PyLong_SHIFT;
729 accumbits -= PyLong_SHIFT;
730 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000731 }
732 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000733 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000734 if (accumbits) {
735 assert(idigit < (int)ndigits);
736 v->ob_digit[idigit] = (digit)accum;
737 ++idigit;
738 }
739 }
740
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000741 Py_Size(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000742 return (PyObject *)long_normalize(v);
743}
744
745int
746_PyLong_AsByteArray(PyLongObject* v,
747 unsigned char* bytes, size_t n,
748 int little_endian, int is_signed)
749{
750 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000751 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000752 twodigits accum; /* sliding register */
753 unsigned int accumbits; /* # bits in accum */
754 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
755 twodigits carry; /* for computing 2's-comp */
756 size_t j; /* # bytes filled */
757 unsigned char* p; /* pointer to next byte in bytes */
758 int pincr; /* direction to move p */
759
760 assert(v != NULL && PyLong_Check(v));
761
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000762 if (Py_Size(v) < 0) {
763 ndigits = -(Py_Size(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000764 if (!is_signed) {
765 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000766 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000767 return -1;
768 }
769 do_twos_comp = 1;
770 }
771 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000772 ndigits = Py_Size(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000773 do_twos_comp = 0;
774 }
775
776 if (little_endian) {
777 p = bytes;
778 pincr = 1;
779 }
780 else {
781 p = bytes + n - 1;
782 pincr = -1;
783 }
784
Tim Peters898cf852001-06-13 20:50:08 +0000785 /* Copy over all the Python digits.
786 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000787 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000788 normalized. */
789 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000790 j = 0;
791 accum = 0;
792 accumbits = 0;
793 carry = do_twos_comp ? 1 : 0;
794 for (i = 0; i < ndigits; ++i) {
795 twodigits thisdigit = v->ob_digit[i];
796 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000797 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
798 carry = thisdigit >> PyLong_SHIFT;
799 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000800 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000801 /* Because we're going LSB to MSB, thisdigit is more
802 significant than what's already in accum, so needs to be
803 prepended to accum. */
804 accum |= thisdigit << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000805 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000806
Tim Petersede05092001-06-14 08:53:38 +0000807 /* The most-significant digit may be (probably is) at least
808 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000809 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000810 /* Count # of sign bits -- they needn't be stored,
811 * although for signed conversion we need later to
812 * make sure at least one sign bit gets stored.
813 * First shift conceptual sign bit to real sign bit.
814 */
815 stwodigits s = (stwodigits)(thisdigit <<
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000816 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000817 unsigned int nsignbits = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000818 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000819 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000820 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000821 }
Tim Petersede05092001-06-14 08:53:38 +0000822 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000823 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000824
Tim Peters2a9b3672001-06-11 21:23:58 +0000825 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000826 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000827 if (j >= n)
828 goto Overflow;
829 ++j;
830 *p = (unsigned char)(accum & 0xff);
831 p += pincr;
832 accumbits -= 8;
833 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000834 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000835 }
836
837 /* Store the straggler (if any). */
838 assert(accumbits < 8);
839 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000840 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000841 if (j >= n)
842 goto Overflow;
843 ++j;
844 if (do_twos_comp) {
845 /* Fill leading bits of the byte with sign bits
846 (appropriately pretending that the long had an
847 infinite supply of sign bits). */
848 accum |= (~(twodigits)0) << accumbits;
849 }
850 *p = (unsigned char)(accum & 0xff);
851 p += pincr;
852 }
Tim Peters05607ad2001-06-13 21:01:27 +0000853 else if (j == n && n > 0 && is_signed) {
854 /* The main loop filled the byte array exactly, so the code
855 just above didn't get to ensure there's a sign bit, and the
856 loop below wouldn't add one either. Make sure a sign bit
857 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000858 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000859 int sign_bit_set = msb >= 0x80;
860 assert(accumbits == 0);
861 if (sign_bit_set == do_twos_comp)
862 return 0;
863 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000864 goto Overflow;
865 }
Tim Peters05607ad2001-06-13 21:01:27 +0000866
867 /* Fill remaining bytes with copies of the sign bit. */
868 {
869 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
870 for ( ; j < n; ++j, p += pincr)
871 *p = signbyte;
872 }
873
Tim Peters2a9b3672001-06-11 21:23:58 +0000874 return 0;
875
876Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000877 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000878 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000879
Tim Peters2a9b3672001-06-11 21:23:58 +0000880}
881
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000882double
883_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
884{
885/* NBITS_WANTED should be > the number of bits in a double's precision,
886 but small enough so that 2**NBITS_WANTED is within the normal double
887 range. nbitsneeded is set to 1 less than that because the most-significant
888 Python digit contains at least 1 significant bit, but we don't want to
889 bother counting them (catering to the worst case cheaply).
890
891 57 is one more than VAX-D double precision; I (Tim) don't know of a double
892 format with more precision than that; it's 1 larger so that we add in at
893 least one round bit to stand in for the ignored least-significant bits.
894*/
895#define NBITS_WANTED 57
896 PyLongObject *v;
897 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000898 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000899 Py_ssize_t i;
900 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000901 int nbitsneeded;
902
903 if (vv == NULL || !PyLong_Check(vv)) {
904 PyErr_BadInternalCall();
905 return -1;
906 }
907 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000908 i = Py_Size(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000909 sign = 1;
910 if (i < 0) {
911 sign = -1;
912 i = -(i);
913 }
914 else if (i == 0) {
915 *exponent = 0;
916 return 0.0;
917 }
918 --i;
919 x = (double)v->ob_digit[i];
920 nbitsneeded = NBITS_WANTED - 1;
921 /* Invariant: i Python digits remain unaccounted for. */
922 while (i > 0 && nbitsneeded > 0) {
923 --i;
924 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000925 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000926 }
927 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000928 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000929 *exponent = i;
930 assert(x > 0.0);
931 return x * sign;
932#undef NBITS_WANTED
933}
934
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000935/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000936
937double
Tim Peters9f688bf2000-07-07 15:53:28 +0000938PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000939{
Thomas Wouters553489a2006-02-01 21:32:04 +0000940 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000941 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000942
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000943 if (vv == NULL || !PyLong_Check(vv)) {
944 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000945 return -1;
946 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000947 x = _PyLong_AsScaledDouble(vv, &e);
948 if (x == -1.0 && PyErr_Occurred())
949 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000950 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
951 set correctly after a successful _PyLong_AsScaledDouble() call */
952 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000953 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000954 goto overflow;
955 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000956 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000957 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000958 goto overflow;
959 return x;
960
961overflow:
962 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000963 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000964 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000965}
966
Guido van Rossum78694d91998-09-18 14:14:13 +0000967/* Create a new long (or int) object from a C pointer */
968
969PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000970PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000971{
Tim Peters70128a12001-06-16 08:48:40 +0000972#ifndef HAVE_LONG_LONG
973# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
974#endif
975#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000976# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000977#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000978 /* special-case null pointer */
979 if (!p)
Tim Peters70128a12001-06-16 08:48:40 +0000980 return PyInt_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000981 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000982
Guido van Rossum78694d91998-09-18 14:14:13 +0000983}
984
985/* Get a C pointer from a long object (or an int object in some cases) */
986
987void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000988PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000989{
990 /* This function will allow int or long objects. If vv is neither,
991 then the PyLong_AsLong*() functions will raise the exception:
992 PyExc_SystemError, "bad argument to internal function"
993 */
Tim Peters70128a12001-06-16 08:48:40 +0000994#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000995 long x;
996
Guido van Rossumddefaf32007-01-14 03:31:43 +0000997 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000998 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000999 else
1000 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001001#else
Tim Peters70128a12001-06-16 08:48:40 +00001002
1003#ifndef HAVE_LONG_LONG
1004# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1005#endif
1006#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001007# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001008#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001009 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001010
Guido van Rossumddefaf32007-01-14 03:31:43 +00001011 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001012 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001013 else
1014 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001015
1016#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001017
1018 if (x == -1 && PyErr_Occurred())
1019 return NULL;
1020 return (void *)x;
1021}
1022
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001023#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001024
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001025/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001026 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001027 */
1028
Tim Peterscf37dfc2001-06-14 18:42:50 +00001029#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001030
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001031/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001032
1033PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001034PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001035{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001036 PyLongObject *v;
1037 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1038 int ndigits = 0;
1039 int negative = 0;
1040
Guido van Rossumddefaf32007-01-14 03:31:43 +00001041 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001042 if (ival < 0) {
1043 ival = -ival;
1044 negative = 1;
1045 }
1046
1047 /* Count the number of Python digits.
1048 We used to pick 5 ("big enough for anything"), but that's a
1049 waste of time and space given that 5*15 = 75 bits are rarely
1050 needed. */
1051 t = (unsigned PY_LONG_LONG)ival;
1052 while (t) {
1053 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001054 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001055 }
1056 v = _PyLong_New(ndigits);
1057 if (v != NULL) {
1058 digit *p = v->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001059 Py_Size(v) = negative ? -ndigits : ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001060 t = (unsigned PY_LONG_LONG)ival;
1061 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001062 *p++ = (digit)(t & PyLong_MASK);
1063 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001064 }
1065 }
1066 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001067}
1068
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001069/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001070
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001071PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001072PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001073{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001074 PyLongObject *v;
1075 unsigned PY_LONG_LONG t;
1076 int ndigits = 0;
1077
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001078 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001079 return PyLong_FromLong(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001080 /* Count the number of Python digits. */
1081 t = (unsigned PY_LONG_LONG)ival;
1082 while (t) {
1083 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001084 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001085 }
1086 v = _PyLong_New(ndigits);
1087 if (v != NULL) {
1088 digit *p = v->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001089 Py_Size(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001090 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001091 *p++ = (digit)(ival & PyLong_MASK);
1092 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001093 }
1094 }
1095 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001096}
1097
Martin v. Löwis18e16552006-02-15 17:27:45 +00001098/* Create a new long int object from a C Py_ssize_t. */
1099
1100PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001101PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001102{
1103 Py_ssize_t bytes = ival;
1104 int one = 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001105 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001106 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001107 return _PyLong_FromByteArray(
1108 (unsigned char *)&bytes,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001109 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001110}
1111
1112/* Create a new long int object from a C size_t. */
1113
1114PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001115PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001116{
1117 size_t bytes = ival;
1118 int one = 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001119 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001120 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001121 return _PyLong_FromByteArray(
1122 (unsigned char *)&bytes,
1123 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
1124}
1125
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001126/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001127 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001128
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001129PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001130PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001131{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001132 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001133 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001134 int one = 1;
1135 int res;
1136
Tim Petersd38b1c72001-09-30 05:09:37 +00001137 if (vv == NULL) {
1138 PyErr_BadInternalCall();
1139 return -1;
1140 }
1141 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001142 PyNumberMethods *nb;
1143 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001144 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1145 nb->nb_int == NULL) {
1146 PyErr_SetString(PyExc_TypeError, "an integer is required");
1147 return -1;
1148 }
1149 io = (*nb->nb_int) (vv);
1150 if (io == NULL)
1151 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001152 if (PyLong_Check(io)) {
1153 bytes = PyLong_AsLongLong(io);
1154 Py_DECREF(io);
1155 return bytes;
1156 }
1157 Py_DECREF(io);
1158 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001159 return -1;
1160 }
1161
Guido van Rossumddefaf32007-01-14 03:31:43 +00001162 v = (PyLongObject*)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001163 switch(Py_Size(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001164 case -1: return -v->ob_digit[0];
1165 case 0: return 0;
1166 case 1: return v->ob_digit[0];
1167 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001168 res = _PyLong_AsByteArray(
1169 (PyLongObject *)vv, (unsigned char *)&bytes,
1170 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001171
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001172 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001173 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001174 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001175 else
1176 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001177}
1178
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001179/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001180 Return -1 and set an error if overflow occurs. */
1181
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001182unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001183PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001184{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001185 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001186 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001187 int one = 1;
1188 int res;
1189
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001190 if (vv == NULL || !PyLong_Check(vv)) {
1191 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001192 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001193 }
1194
Guido van Rossumddefaf32007-01-14 03:31:43 +00001195 v = (PyLongObject*)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001196 switch(Py_Size(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001197 case 0: return 0;
1198 case 1: return v->ob_digit[0];
1199 }
1200
Tim Petersd1a7da62001-06-13 00:35:57 +00001201 res = _PyLong_AsByteArray(
1202 (PyLongObject *)vv, (unsigned char *)&bytes,
1203 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001204
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001205 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001206 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001207 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001208 else
1209 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001210}
Tim Petersd1a7da62001-06-13 00:35:57 +00001211
Thomas Hellera4ea6032003-04-17 18:55:45 +00001212/* Get a C unsigned long int from a long int object, ignoring the high bits.
1213 Returns -1 and sets an error condition if an error occurs. */
1214
Guido van Rossumddefaf32007-01-14 03:31:43 +00001215static unsigned PY_LONG_LONG
1216_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001217{
1218 register PyLongObject *v;
1219 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001220 Py_ssize_t i;
1221 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001222
1223 if (vv == NULL || !PyLong_Check(vv)) {
1224 PyErr_BadInternalCall();
1225 return (unsigned long) -1;
1226 }
1227 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001228 switch(Py_Size(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001229 case 0: return 0;
1230 case 1: return v->ob_digit[0];
1231 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001232 i = Py_Size(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001233 sign = 1;
1234 x = 0;
1235 if (i < 0) {
1236 sign = -1;
1237 i = -i;
1238 }
1239 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001240 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001241 }
1242 return x * sign;
1243}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001244
1245unsigned PY_LONG_LONG
1246PyLong_AsUnsignedLongLongMask(register PyObject *op)
1247{
1248 PyNumberMethods *nb;
1249 PyLongObject *lo;
1250 unsigned PY_LONG_LONG val;
1251
1252 if (op && PyLong_Check(op))
1253 return _PyLong_AsUnsignedLongLongMask(op);
1254
1255 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1256 nb->nb_int == NULL) {
1257 PyErr_SetString(PyExc_TypeError, "an integer is required");
1258 return (unsigned PY_LONG_LONG)-1;
1259 }
1260
1261 lo = (PyLongObject*) (*nb->nb_int) (op);
1262 if (lo == NULL)
1263 return (unsigned PY_LONG_LONG)-1;
1264 if (PyLong_Check(lo)) {
1265 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1266 Py_DECREF(lo);
1267 if (PyErr_Occurred())
1268 return (unsigned PY_LONG_LONG)-1;
1269 return val;
1270 }
1271 else
1272 {
1273 Py_DECREF(lo);
1274 PyErr_SetString(PyExc_TypeError,
1275 "nb_int should return int object");
1276 return (unsigned PY_LONG_LONG)-1;
1277 }
1278}
Tim Petersd1a7da62001-06-13 00:35:57 +00001279#undef IS_LITTLE_ENDIAN
1280
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001281#endif /* HAVE_LONG_LONG */
1282
Neil Schemenauerba872e22001-01-04 01:46:03 +00001283
1284static int
1285convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001286 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001287 *a = (PyLongObject *) v;
1288 Py_INCREF(v);
1289 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001290 else {
1291 return 0;
1292 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001293 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001294 *b = (PyLongObject *) w;
1295 Py_INCREF(w);
1296 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001297 else {
1298 Py_DECREF(*a);
1299 return 0;
1300 }
1301 return 1;
1302}
1303
1304#define CONVERT_BINOP(v, w, a, b) \
1305 if (!convert_binop(v, w, a, b)) { \
1306 Py_INCREF(Py_NotImplemented); \
1307 return Py_NotImplemented; \
1308 }
1309
Tim Peters877a2122002-08-12 05:09:36 +00001310/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1311 * is modified in place, by adding y to it. Carries are propagated as far as
1312 * x[m-1], and the remaining carry (0 or 1) is returned.
1313 */
1314static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001315v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001316{
1317 int i;
1318 digit carry = 0;
1319
1320 assert(m >= n);
1321 for (i = 0; i < n; ++i) {
1322 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001323 x[i] = carry & PyLong_MASK;
1324 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001325 assert((carry & 1) == carry);
1326 }
1327 for (; carry && i < m; ++i) {
1328 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001329 x[i] = carry & PyLong_MASK;
1330 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001331 assert((carry & 1) == carry);
1332 }
1333 return carry;
1334}
1335
1336/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1337 * is modified in place, by subtracting y from it. Borrows are propagated as
1338 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1339 */
1340static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001341v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001342{
1343 int i;
1344 digit borrow = 0;
1345
1346 assert(m >= n);
1347 for (i = 0; i < n; ++i) {
1348 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001349 x[i] = borrow & PyLong_MASK;
1350 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001351 borrow &= 1; /* keep only 1 sign bit */
1352 }
1353 for (; borrow && i < m; ++i) {
1354 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001355 x[i] = borrow & PyLong_MASK;
1356 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001357 borrow &= 1;
1358 }
1359 return borrow;
1360}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001361
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001362/* Multiply by a single digit, ignoring the sign. */
1363
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001364static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001365mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001366{
1367 return muladd1(a, n, (digit)0);
1368}
1369
1370/* Multiply by a single digit and add a single digit, ignoring the sign. */
1371
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001372static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001373muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001374{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001375 Py_ssize_t size_a = ABS(Py_Size(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001376 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001377 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001378 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001379
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001380 if (z == NULL)
1381 return NULL;
1382 for (i = 0; i < size_a; ++i) {
1383 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001384 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1385 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001386 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001387 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001388 return long_normalize(z);
1389}
1390
Tim Peters212e6142001-07-14 12:23:19 +00001391/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1392 in pout, and returning the remainder. pin and pout point at the LSD.
1393 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001394 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001395 immutable. */
1396
1397static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001398inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001399{
1400 twodigits rem = 0;
1401
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001402 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001403 pin += size;
1404 pout += size;
1405 while (--size >= 0) {
1406 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001407 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001408 *--pout = hi = (digit)(rem / n);
1409 rem -= hi * n;
1410 }
1411 return (digit)rem;
1412}
1413
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001414/* Divide a long integer by a digit, returning both the quotient
1415 (as function result) and the remainder (through *prem).
1416 The sign of a is ignored; n should not be zero. */
1417
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001418static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001419divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001420{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001421 const Py_ssize_t size = ABS(Py_Size(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001422 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001423
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001424 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001425 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001426 if (z == NULL)
1427 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001428 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001429 return long_normalize(z);
1430}
1431
1432/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001433 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001434 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001435
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001436PyObject *
1437_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001438{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001439 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001440 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001441 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001442 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001443 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001444 int bits;
1445 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001446
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001447 if (a == NULL || !PyLong_Check(a)) {
1448 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001449 return NULL;
1450 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001451 assert(base >= 2 && base <= 36);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001452 size_a = ABS(Py_Size(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001453
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001454 /* Compute a rough upper bound for the length of the string */
1455 i = base;
1456 bits = 0;
1457 while (i > 1) {
1458 ++bits;
1459 i >>= 1;
1460 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001461 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001462 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001463 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001464 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001465 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001466 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001467 return NULL;
1468 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001469 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001470 if (str == NULL)
1471 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001472 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001473 *p = '\0';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001474 if (Py_Size(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001475 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001476
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001477 if (Py_Size(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001478 *--p = '0';
1479 }
1480 else if ((base & (base - 1)) == 0) {
1481 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001482 twodigits accum = 0;
1483 int accumbits = 0; /* # of bits in accum */
1484 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001485 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001486 while ((i >>= 1) > 1)
1487 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001488
1489 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001490 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001491 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001492 assert(accumbits >= basebits);
1493 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001494 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001495 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001496 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001497 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001498 accumbits -= basebits;
1499 accum >>= basebits;
1500 } while (i < size_a-1 ? accumbits >= basebits :
1501 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001502 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001503 }
1504 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001505 /* Not 0, and base not a power of 2. Divide repeatedly by
1506 base, but for speed use the highest power of base that
1507 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001508 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001509 digit *pin = a->ob_digit;
1510 PyLongObject *scratch;
1511 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001512 digit powbase = base; /* powbase == base ** power */
1513 int power = 1;
1514 for (;;) {
1515 unsigned long newpow = powbase * (unsigned long)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001516 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001517 break;
1518 powbase = (digit)newpow;
1519 ++power;
1520 }
Tim Peters212e6142001-07-14 12:23:19 +00001521
1522 /* Get a scratch area for repeated division. */
1523 scratch = _PyLong_New(size);
1524 if (scratch == NULL) {
1525 Py_DECREF(str);
1526 return NULL;
1527 }
1528
1529 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001530 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001531 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001532 digit rem = inplace_divrem1(scratch->ob_digit,
1533 pin, size, powbase);
1534 pin = scratch->ob_digit; /* no need to use a again */
1535 if (pin[size - 1] == 0)
1536 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001537 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001538 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001539 Py_DECREF(str);
1540 return NULL;
1541 })
Tim Peters212e6142001-07-14 12:23:19 +00001542
1543 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001544 assert(ntostore > 0);
1545 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001546 digit nextrem = (digit)(rem / base);
1547 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001548 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001549 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001550 *--p = c;
1551 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001552 --ntostore;
1553 /* Termination is a bit delicate: must not
1554 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001555 remaining quotient and rem are both 0. */
1556 } while (ntostore && (size || rem));
1557 } while (size != 0);
1558 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001559 }
1560
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001561 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001562 *--p = 'x';
1563 *--p = '0';
1564 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001565 else if (base == 8) {
1566 *--p = 'o';
1567 *--p = '0';
1568 }
1569 else if (base == 2) {
1570 *--p = 'b';
1571 *--p = '0';
1572 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001573 else if (base != 10) {
1574 *--p = '#';
1575 *--p = '0' + base%10;
1576 if (base > 10)
1577 *--p = '0' + base/10;
1578 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001579 if (sign)
1580 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001581 if (p != PyUnicode_AS_UNICODE(str)) {
1582 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001583 assert(p > q);
1584 do {
1585 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001586 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001587 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1588 Py_DECREF(str);
1589 return NULL;
1590 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001591 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001592 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001593}
1594
Thomas Wouters477c8d52006-05-27 19:21:47 +00001595/* Table of digit values for 8-bit string -> integer conversion.
1596 * '0' maps to 0, ..., '9' maps to 9.
1597 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1598 * All other indices map to 37.
1599 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001600 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001601 */
1602int _PyLong_DigitValue[256] = {
1603 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1604 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1605 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1606 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1607 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1608 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1609 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1610 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1611 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1612 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1613 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1614 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1615 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1616 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1617 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1618 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1619};
1620
1621/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001622 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1623 * non-digit (which may be *str!). A normalized long is returned.
1624 * The point to this routine is that it takes time linear in the number of
1625 * string characters.
1626 */
1627static PyLongObject *
1628long_from_binary_base(char **str, int base)
1629{
1630 char *p = *str;
1631 char *start = p;
1632 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001633 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001634 PyLongObject *z;
1635 twodigits accum;
1636 int bits_in_accum;
1637 digit *pdigit;
1638
1639 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1640 n = base;
1641 for (bits_per_char = -1; n; ++bits_per_char)
1642 n >>= 1;
1643 /* n <- total # of bits needed, while setting p to end-of-string */
1644 n = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001645 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001646 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001647 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001648 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1649 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001650 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001651 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001652 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001653 return NULL;
1654 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001655 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001656 z = _PyLong_New(n);
1657 if (z == NULL)
1658 return NULL;
1659 /* Read string from right, and fill in long from left; i.e.,
1660 * from least to most significant in both.
1661 */
1662 accum = 0;
1663 bits_in_accum = 0;
1664 pdigit = z->ob_digit;
1665 while (--p >= start) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001666 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001667 assert(k >= 0 && k < base);
1668 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001669 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001670 if (bits_in_accum >= PyLong_SHIFT) {
1671 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001672 assert(pdigit - z->ob_digit <= (int)n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001673 accum >>= PyLong_SHIFT;
1674 bits_in_accum -= PyLong_SHIFT;
1675 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001676 }
1677 }
1678 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001679 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001680 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001681 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001682 }
1683 while (pdigit - z->ob_digit < n)
1684 *pdigit++ = 0;
1685 return long_normalize(z);
1686}
1687
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001688PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001689PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001690{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001691 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001692 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001693 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001694 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001695 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001696
Guido van Rossum472c04f1996-12-05 21:57:21 +00001697 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001698 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001699 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001700 return NULL;
1701 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001702 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001703 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001704 if (*str == '+')
1705 ++str;
1706 else if (*str == '-') {
1707 ++str;
1708 sign = -1;
1709 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001710 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001711 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001712 if (base == 0) {
1713 if (str[0] != '0')
1714 base = 10;
1715 else if (str[1] == 'x' || str[1] == 'X')
1716 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001717 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001718 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001719 else if (str[1] == 'b' || str[1] == 'B')
1720 base = 2;
1721 else {
1722 /* "old" (C-style) octal literal, now invalid.
1723 it might still be zero though */
1724 error_if_nonzero = 1;
1725 base = 10;
1726 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001727 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001728 if (str[0] == '0' &&
1729 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1730 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1731 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001732 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001733
Guido van Rossume6762971998-06-22 03:54:46 +00001734 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001735 if ((base & (base - 1)) == 0)
1736 z = long_from_binary_base(&str, base);
1737 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001738/***
1739Binary bases can be converted in time linear in the number of digits, because
1740Python's representation base is binary. Other bases (including decimal!) use
1741the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001742
Thomas Wouters477c8d52006-05-27 19:21:47 +00001743First some math: the largest integer that can be expressed in N base-B digits
1744is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1745case number of Python digits needed to hold it is the smallest integer n s.t.
1746
1747 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1748 BASE**n >= B**N [taking logs to base BASE]
1749 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1750
1751The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1752this quickly. A Python long with that much space is reserved near the start,
1753and the result is computed into it.
1754
1755The input string is actually treated as being in base base**i (i.e., i digits
1756are processed at a time), where two more static arrays hold:
1757
1758 convwidth_base[base] = the largest integer i such that base**i <= BASE
1759 convmultmax_base[base] = base ** convwidth_base[base]
1760
1761The first of these is the largest i such that i consecutive input digits
1762must fit in a single Python digit. The second is effectively the input
1763base we're really using.
1764
1765Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1766convmultmax_base[base], the result is "simply"
1767
1768 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1769
1770where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001771
1772Error analysis: as above, the number of Python digits `n` needed is worst-
1773case
1774
1775 n >= N * log(B)/log(BASE)
1776
1777where `N` is the number of input digits in base `B`. This is computed via
1778
1779 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1780
1781below. Two numeric concerns are how much space this can waste, and whether
1782the computed result can be too small. To be concrete, assume BASE = 2**15,
1783which is the default (and it's unlikely anyone changes that).
1784
1785Waste isn't a problem: provided the first input digit isn't 0, the difference
1786between the worst-case input with N digits and the smallest input with N
1787digits is about a factor of B, but B is small compared to BASE so at most
1788one allocated Python digit can remain unused on that count. If
1789N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1790and adding 1 returns a result 1 larger than necessary. However, that can't
1791happen: whenever B is a power of 2, long_from_binary_base() is called
1792instead, and it's impossible for B**i to be an integer power of 2**15 when
1793B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1794an exact integer when B is not a power of 2, since B**i has a prime factor
1795other than 2 in that case, but (2**15)**j's only prime factor is 2).
1796
1797The computed result can be too small if the true value of N*log(B)/log(BASE)
1798is a little bit larger than an exact integer, but due to roundoff errors (in
1799computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1800yields a numeric result a little less than that integer. Unfortunately, "how
1801close can a transcendental function get to an integer over some range?"
1802questions are generally theoretically intractable. Computer analysis via
1803continued fractions is practical: expand log(B)/log(BASE) via continued
1804fractions, giving a sequence i/j of "the best" rational approximations. Then
1805j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1806we can get very close to being in trouble, but very rarely. For example,
180776573 is a denominator in one of the continued-fraction approximations to
1808log(10)/log(2**15), and indeed:
1809
1810 >>> log(10)/log(2**15)*76573
1811 16958.000000654003
1812
1813is very close to an integer. If we were working with IEEE single-precision,
1814rounding errors could kill us. Finding worst cases in IEEE double-precision
1815requires better-than-double-precision log() functions, and Tim didn't bother.
1816Instead the code checks to see whether the allocated space is enough as each
1817new Python digit is added, and copies the whole thing to a larger long if not.
1818This should happen extremely rarely, and in fact I don't have a test case
1819that triggers it(!). Instead the code was tested by artificially allocating
1820just 1 digit at the start, so that the copying code was exercised for every
1821digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001822***/
1823 register twodigits c; /* current input character */
1824 Py_ssize_t size_z;
1825 int i;
1826 int convwidth;
1827 twodigits convmultmax, convmult;
1828 digit *pz, *pzstop;
1829 char* scan;
1830
1831 static double log_base_BASE[37] = {0.0e0,};
1832 static int convwidth_base[37] = {0,};
1833 static twodigits convmultmax_base[37] = {0,};
1834
1835 if (log_base_BASE[base] == 0.0) {
1836 twodigits convmax = base;
1837 int i = 1;
1838
1839 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001840 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001841 for (;;) {
1842 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001843 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001844 break;
1845 convmax = next;
1846 ++i;
1847 }
1848 convmultmax_base[base] = convmax;
1849 assert(i > 0);
1850 convwidth_base[base] = i;
1851 }
1852
1853 /* Find length of the string of numeric characters. */
1854 scan = str;
1855 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1856 ++scan;
1857
1858 /* Create a long object that can contain the largest possible
1859 * integer with this base and length. Note that there's no
1860 * need to initialize z->ob_digit -- no slot is read up before
1861 * being stored into.
1862 */
1863 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001864 /* Uncomment next line to test exceedingly rare copy code */
1865 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001866 assert(size_z > 0);
1867 z = _PyLong_New(size_z);
1868 if (z == NULL)
1869 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001870 Py_Size(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001871
1872 /* `convwidth` consecutive input digits are treated as a single
1873 * digit in base `convmultmax`.
1874 */
1875 convwidth = convwidth_base[base];
1876 convmultmax = convmultmax_base[base];
1877
1878 /* Work ;-) */
1879 while (str < scan) {
1880 /* grab up to convwidth digits from the input string */
1881 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1882 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1883 c = (twodigits)(c * base +
1884 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001885 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001886 }
1887
1888 convmult = convmultmax;
1889 /* Calculate the shift only if we couldn't get
1890 * convwidth digits.
1891 */
1892 if (i != convwidth) {
1893 convmult = base;
1894 for ( ; i > 1; --i)
1895 convmult *= base;
1896 }
1897
1898 /* Multiply z by convmult, and add c. */
1899 pz = z->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001900 pzstop = pz + Py_Size(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001901 for (; pz < pzstop; ++pz) {
1902 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001903 *pz = (digit)(c & PyLong_MASK);
1904 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001905 }
1906 /* carry off the current end? */
1907 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001908 assert(c < PyLong_BASE);
1909 if (Py_Size(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001910 *pz = (digit)c;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001911 ++Py_Size(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001912 }
1913 else {
1914 PyLongObject *tmp;
1915 /* Extremely rare. Get more space. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001916 assert(Py_Size(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001917 tmp = _PyLong_New(size_z + 1);
1918 if (tmp == NULL) {
1919 Py_DECREF(z);
1920 return NULL;
1921 }
1922 memcpy(tmp->ob_digit,
1923 z->ob_digit,
1924 sizeof(digit) * size_z);
1925 Py_DECREF(z);
1926 z = tmp;
1927 z->ob_digit[size_z] = (digit)c;
1928 ++size_z;
1929 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001930 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001931 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001932 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001933 if (z == NULL)
1934 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001935 if (error_if_nonzero) {
1936 /* reset the base to 0, else the exception message
1937 doesn't make too much sense */
1938 base = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001939 if (Py_Size(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001940 goto onError;
1941 /* there might still be other problems, therefore base
1942 remains zero here for the same reason */
1943 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001944 if (str == start)
1945 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001946 if (sign < 0)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001947 Py_Size(z) = -(Py_Size(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001948 if (*str == 'L' || *str == 'l')
1949 str++;
1950 while (*str && isspace(Py_CHARMASK(*str)))
1951 str++;
1952 if (*str != '\0')
1953 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001954 if (pend)
1955 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001956 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001957
1958 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001959 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001960 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00001961 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001962 if (strobj == NULL)
1963 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001964 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00001965 "invalid literal for int() with base %d: %R",
1966 base, strobj);
1967 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001968 return NULL;
1969}
1970
1971PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001972PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001973{
Walter Dörwald07e14762002-11-06 16:15:14 +00001974 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001975 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001976
Walter Dörwald07e14762002-11-06 16:15:14 +00001977 if (buffer == NULL)
1978 return NULL;
1979
1980 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1981 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001982 return NULL;
1983 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001984 result = PyLong_FromString(buffer, NULL, base);
1985 PyMem_FREE(buffer);
1986 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001987}
1988
Tim Peters9f688bf2000-07-07 15:53:28 +00001989/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001990static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001991 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001992static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00001993static int long_divrem(PyLongObject *, PyLongObject *,
1994 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001995
1996/* Long division with remainder, top-level routine */
1997
Guido van Rossume32e0141992-01-19 16:31:05 +00001998static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001999long_divrem(PyLongObject *a, PyLongObject *b,
2000 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002001{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002002 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002003 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002004
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002005 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002006 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002007 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002008 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002009 }
2010 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002011 (size_a == size_b &&
2012 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002013 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002014 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002015 if (*pdiv == NULL)
2016 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002017 Py_INCREF(a);
2018 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002019 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002020 }
2021 if (size_b == 1) {
2022 digit rem = 0;
2023 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002024 if (z == NULL)
2025 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002026 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002027 if (*prem == NULL) {
2028 Py_DECREF(z);
2029 return -1;
2030 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002031 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002032 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002033 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002034 if (z == NULL)
2035 return -1;
2036 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002037 /* Set the signs.
2038 The quotient z has the sign of a*b;
2039 the remainder r has the sign of a,
2040 so a = b*z + r. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002041 if ((Py_Size(a) < 0) != (Py_Size(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002042 NEGATE(z);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002043 if (Py_Size(a) < 0 && Py_Size(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002044 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002045 *pdiv = z;
2046 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002047}
2048
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002049/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002050
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002051static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002052x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002053{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002054 Py_ssize_t size_v = ABS(Py_Size(v1)), size_w = ABS(Py_Size(w1));
2055 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002056 PyLongObject *v = mul1(v1, d);
2057 PyLongObject *w = mul1(w1, d);
2058 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002059 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002060
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002061 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002062 Py_XDECREF(v);
2063 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002064 return NULL;
2065 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002066
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002067 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002068 assert(Py_Refcnt(v) == 1); /* Since v will be used as accumulator! */
2069 assert(size_w == ABS(Py_Size(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002070
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002071 size_v = ABS(Py_Size(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002072 k = size_v - size_w;
2073 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002074
Thomas Wouters477c8d52006-05-27 19:21:47 +00002075 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002076 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2077 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002078 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002080
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002081 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002082 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002083 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002084 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002085 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002086 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002087 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002088 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002089 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002091
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002092 while (w->ob_digit[size_w-2]*q >
2093 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002094 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002095 + v->ob_digit[j-1]
2096 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002097 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002098 + v->ob_digit[j-2])
2099 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002100
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002101 for (i = 0; i < size_w && i+k < size_v; ++i) {
2102 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002103 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002104 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002105 + ((twodigits)zz << PyLong_SHIFT);
2106 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002107 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002108 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002109 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002110 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002111
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002112 if (i+k < size_v) {
2113 carry += v->ob_digit[i+k];
2114 v->ob_digit[i+k] = 0;
2115 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002116
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002117 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002118 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002119 else {
2120 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002121 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002122 carry = 0;
2123 for (i = 0; i < size_w && i+k < size_v; ++i) {
2124 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002125 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002126 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2127 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002128 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002129 }
2130 }
2131 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002132
Guido van Rossumc206c761995-01-10 15:23:19 +00002133 if (a == NULL)
2134 *prem = NULL;
2135 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002136 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002137 *prem = divrem1(v, d, &d);
2138 /* d receives the (unused) remainder */
2139 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002140 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002141 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002142 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002143 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002144 Py_DECREF(v);
2145 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002146 return a;
2147}
2148
2149/* Methods */
2150
2151static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002152long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002153{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002154 Py_Type(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002155}
2156
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002157static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002158long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002159{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002160 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002161}
2162
2163static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002164long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002165{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002166 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002167
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002168 if (Py_Size(a) != Py_Size(b)) {
2169 if (ABS(Py_Size(a)) == 0 && ABS(Py_Size(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002170 sign = 0;
2171 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002172 sign = Py_Size(a) - Py_Size(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002173 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002174 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002175 Py_ssize_t i = ABS(Py_Size(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002176 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2177 ;
2178 if (i < 0)
2179 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002180 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002181 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002182 if (Py_Size(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002183 sign = -sign;
2184 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002185 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002186 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002187}
2188
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002189static PyObject *
2190long_richcompare(PyObject *self, PyObject *other, int op)
2191{
2192 PyLongObject *a, *b;
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002193 PyObject *result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002194 CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b);
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002195 result = Py_CmpToRich(op, long_compare(a, b));
2196 Py_DECREF(a);
2197 Py_DECREF(b);
2198 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002199}
2200
Guido van Rossum9bfef441993-03-29 10:43:31 +00002201static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002202long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002203{
2204 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002205 Py_ssize_t i;
2206 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002207
2208 /* This is designed so that Python ints and longs with the
2209 same value hash to the same value, otherwise comparisons
2210 of mapping keys will turn out weird */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002211 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002212 switch(i) {
2213 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2214 case 0: return 0;
2215 case 1: return v->ob_digit[0];
2216 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002217 sign = 1;
2218 x = 0;
2219 if (i < 0) {
2220 sign = -1;
2221 i = -(i);
2222 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002223#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002224 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002225 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002226 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002227 x += v->ob_digit[i];
2228 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002229#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002230 x = x * sign;
2231 if (x == -1)
2232 x = -2;
2233 return x;
2234}
2235
2236
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002237/* Add the absolute values of two long integers. */
2238
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002239static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002240x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002241{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002242 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002243 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002244 int i;
2245 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002246
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002247 /* Ensure a is the larger of the two: */
2248 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002249 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002250 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002251 size_a = size_b;
2252 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002253 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002254 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002255 if (z == NULL)
2256 return NULL;
2257 for (i = 0; i < size_b; ++i) {
2258 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002259 z->ob_digit[i] = carry & PyLong_MASK;
2260 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002261 }
2262 for (; i < size_a; ++i) {
2263 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002264 z->ob_digit[i] = carry & PyLong_MASK;
2265 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002266 }
2267 z->ob_digit[i] = carry;
2268 return long_normalize(z);
2269}
2270
2271/* Subtract the absolute values of two integers. */
2272
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002273static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002274x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002275{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002276 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002277 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002278 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002279 int sign = 1;
2280 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002281
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002282 /* Ensure a is the larger of the two: */
2283 if (size_a < size_b) {
2284 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002285 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002286 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002287 size_a = size_b;
2288 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002289 }
2290 else if (size_a == size_b) {
2291 /* Find highest digit where a and b differ: */
2292 i = size_a;
2293 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2294 ;
2295 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002296 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002297 if (a->ob_digit[i] < b->ob_digit[i]) {
2298 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002299 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002300 }
2301 size_a = size_b = i+1;
2302 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002303 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002304 if (z == NULL)
2305 return NULL;
2306 for (i = 0; i < size_b; ++i) {
2307 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002308 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002309 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002310 z->ob_digit[i] = borrow & PyLong_MASK;
2311 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002312 borrow &= 1; /* Keep only one sign bit */
2313 }
2314 for (; i < size_a; ++i) {
2315 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002316 z->ob_digit[i] = borrow & PyLong_MASK;
2317 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002318 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002319 }
2320 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002321 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002322 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002323 return long_normalize(z);
2324}
2325
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002326static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002327long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002328{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002329 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002330
Neil Schemenauerba872e22001-01-04 01:46:03 +00002331 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2332
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002333 if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002334 PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) +
2335 MEDIUM_VALUE(b));
2336 Py_DECREF(a);
2337 Py_DECREF(b);
2338 return result;
2339 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002340 if (Py_Size(a) < 0) {
2341 if (Py_Size(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002342 z = x_add(a, b);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002343 if (z != NULL && Py_Size(z) != 0)
2344 Py_Size(z) = -(Py_Size(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002345 }
2346 else
2347 z = x_sub(b, a);
2348 }
2349 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002350 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002351 z = x_sub(a, b);
2352 else
2353 z = x_add(a, b);
2354 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002355 Py_DECREF(a);
2356 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002357 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002358}
2359
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002360static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002361long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002362{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002363 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002364
Neil Schemenauerba872e22001-01-04 01:46:03 +00002365 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2366
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002367 if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002368 PyObject* r;
2369 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2370 Py_DECREF(a);
2371 Py_DECREF(b);
2372 return r;
2373 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002374 if (Py_Size(a) < 0) {
2375 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002376 z = x_sub(a, b);
2377 else
2378 z = x_add(a, b);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002379 if (z != NULL && Py_Size(z) != 0)
2380 Py_Size(z) = -(Py_Size(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002381 }
2382 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002383 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002384 z = x_add(a, b);
2385 else
2386 z = x_sub(a, b);
2387 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002388 Py_DECREF(a);
2389 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002390 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002391}
2392
Tim Peters5af4e6c2002-08-12 02:31:19 +00002393/* Grade school multiplication, ignoring the signs.
2394 * Returns the absolute value of the product, or NULL if error.
2395 */
2396static PyLongObject *
2397x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002398{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002399 PyLongObject *z;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002400 Py_ssize_t size_a = ABS(Py_Size(a));
2401 Py_ssize_t size_b = ABS(Py_Size(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002402 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002403
Tim Peters5af4e6c2002-08-12 02:31:19 +00002404 z = _PyLong_New(size_a + size_b);
2405 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002406 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002407
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002408 memset(z->ob_digit, 0, Py_Size(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002409 if (a == b) {
2410 /* Efficient squaring per HAC, Algorithm 14.16:
2411 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2412 * Gives slightly less than a 2x speedup when a == b,
2413 * via exploiting that each entry in the multiplication
2414 * pyramid appears twice (except for the size_a squares).
2415 */
2416 for (i = 0; i < size_a; ++i) {
2417 twodigits carry;
2418 twodigits f = a->ob_digit[i];
2419 digit *pz = z->ob_digit + (i << 1);
2420 digit *pa = a->ob_digit + i + 1;
2421 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002422
Tim Peters0973b992004-08-29 22:16:50 +00002423 SIGCHECK({
2424 Py_DECREF(z);
2425 return NULL;
2426 })
2427
2428 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002429 *pz++ = (digit)(carry & PyLong_MASK);
2430 carry >>= PyLong_SHIFT;
2431 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002432
2433 /* Now f is added in twice in each column of the
2434 * pyramid it appears. Same as adding f<<1 once.
2435 */
2436 f <<= 1;
2437 while (pa < paend) {
2438 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002439 *pz++ = (digit)(carry & PyLong_MASK);
2440 carry >>= PyLong_SHIFT;
2441 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002442 }
2443 if (carry) {
2444 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002445 *pz++ = (digit)(carry & PyLong_MASK);
2446 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002447 }
2448 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002449 *pz += (digit)(carry & PyLong_MASK);
2450 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002451 }
Tim Peters0973b992004-08-29 22:16:50 +00002452 }
2453 else { /* a is not the same as b -- gradeschool long mult */
2454 for (i = 0; i < size_a; ++i) {
2455 twodigits carry = 0;
2456 twodigits f = a->ob_digit[i];
2457 digit *pz = z->ob_digit + i;
2458 digit *pb = b->ob_digit;
2459 digit *pbend = b->ob_digit + size_b;
2460
2461 SIGCHECK({
2462 Py_DECREF(z);
2463 return NULL;
2464 })
2465
2466 while (pb < pbend) {
2467 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002468 *pz++ = (digit)(carry & PyLong_MASK);
2469 carry >>= PyLong_SHIFT;
2470 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002471 }
2472 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002473 *pz += (digit)(carry & PyLong_MASK);
2474 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002475 }
2476 }
Tim Peters44121a62002-08-12 06:17:58 +00002477 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002478}
2479
2480/* A helper for Karatsuba multiplication (k_mul).
2481 Takes a long "n" and an integer "size" representing the place to
2482 split, and sets low and high such that abs(n) == (high << size) + low,
2483 viewing the shift as being by digits. The sign bit is ignored, and
2484 the return values are >= 0.
2485 Returns 0 on success, -1 on failure.
2486*/
2487static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002488kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002489{
2490 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002491 Py_ssize_t size_lo, size_hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002492 const Py_ssize_t size_n = ABS(Py_Size(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002493
2494 size_lo = MIN(size_n, size);
2495 size_hi = size_n - size_lo;
2496
2497 if ((hi = _PyLong_New(size_hi)) == NULL)
2498 return -1;
2499 if ((lo = _PyLong_New(size_lo)) == NULL) {
2500 Py_DECREF(hi);
2501 return -1;
2502 }
2503
2504 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2505 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2506
2507 *high = long_normalize(hi);
2508 *low = long_normalize(lo);
2509 return 0;
2510}
2511
Tim Peters60004642002-08-12 22:01:34 +00002512static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2513
Tim Peters5af4e6c2002-08-12 02:31:19 +00002514/* Karatsuba multiplication. Ignores the input signs, and returns the
2515 * absolute value of the product (or NULL if error).
2516 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2517 */
2518static PyLongObject *
2519k_mul(PyLongObject *a, PyLongObject *b)
2520{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002521 Py_ssize_t asize = ABS(Py_Size(a));
2522 Py_ssize_t bsize = ABS(Py_Size(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002523 PyLongObject *ah = NULL;
2524 PyLongObject *al = NULL;
2525 PyLongObject *bh = NULL;
2526 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002527 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002528 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002529 Py_ssize_t shift; /* the number of digits we split off */
2530 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002531
Tim Peters5af4e6c2002-08-12 02:31:19 +00002532 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2533 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2534 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002535 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002536 * By picking X to be a power of 2, "*X" is just shifting, and it's
2537 * been reduced to 3 multiplies on numbers half the size.
2538 */
2539
Tim Petersfc07e562002-08-12 02:54:10 +00002540 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002541 * is largest.
2542 */
Tim Peters738eda72002-08-12 15:08:20 +00002543 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002544 t1 = a;
2545 a = b;
2546 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002547
2548 i = asize;
2549 asize = bsize;
2550 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002551 }
2552
2553 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002554 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2555 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002556 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002557 return _PyLong_New(0);
2558 else
2559 return x_mul(a, b);
2560 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002561
Tim Peters60004642002-08-12 22:01:34 +00002562 /* If a is small compared to b, splitting on b gives a degenerate
2563 * case with ah==0, and Karatsuba may be (even much) less efficient
2564 * than "grade school" then. However, we can still win, by viewing
2565 * b as a string of "big digits", each of width a->ob_size. That
2566 * leads to a sequence of balanced calls to k_mul.
2567 */
2568 if (2 * asize <= bsize)
2569 return k_lopsided_mul(a, b);
2570
Tim Petersd6974a52002-08-13 20:37:51 +00002571 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002572 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002573 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002574 assert(Py_Size(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002575
Tim Peters0973b992004-08-29 22:16:50 +00002576 if (a == b) {
2577 bh = ah;
2578 bl = al;
2579 Py_INCREF(bh);
2580 Py_INCREF(bl);
2581 }
2582 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002583
Tim Petersd64c1de2002-08-12 17:36:03 +00002584 /* The plan:
2585 * 1. Allocate result space (asize + bsize digits: that's always
2586 * enough).
2587 * 2. Compute ah*bh, and copy into result at 2*shift.
2588 * 3. Compute al*bl, and copy into result at 0. Note that this
2589 * can't overlap with #2.
2590 * 4. Subtract al*bl from the result, starting at shift. This may
2591 * underflow (borrow out of the high digit), but we don't care:
2592 * we're effectively doing unsigned arithmetic mod
2593 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2594 * borrows and carries out of the high digit can be ignored.
2595 * 5. Subtract ah*bh from the result, starting at shift.
2596 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2597 * at shift.
2598 */
2599
2600 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002601 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002602 if (ret == NULL) goto fail;
2603#ifdef Py_DEBUG
2604 /* Fill with trash, to catch reference to uninitialized digits. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002605 memset(ret->ob_digit, 0xDF, Py_Size(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002606#endif
Tim Peters44121a62002-08-12 06:17:58 +00002607
Tim Petersd64c1de2002-08-12 17:36:03 +00002608 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002609 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002610 assert(Py_Size(t1) >= 0);
2611 assert(2*shift + Py_Size(t1) <= Py_Size(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002612 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002613 Py_Size(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002614
2615 /* Zero-out the digits higher than the ah*bh copy. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002616 i = Py_Size(ret) - 2*shift - Py_Size(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002617 if (i)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002618 memset(ret->ob_digit + 2*shift + Py_Size(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002619 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002620
Tim Petersd64c1de2002-08-12 17:36:03 +00002621 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002622 if ((t2 = k_mul(al, bl)) == NULL) {
2623 Py_DECREF(t1);
2624 goto fail;
2625 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002626 assert(Py_Size(t2) >= 0);
2627 assert(Py_Size(t2) <= 2*shift); /* no overlap with high digits */
2628 memcpy(ret->ob_digit, t2->ob_digit, Py_Size(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002629
2630 /* Zero out remaining digits. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002631 i = 2*shift - Py_Size(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002632 if (i)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002633 memset(ret->ob_digit + Py_Size(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002634
Tim Petersd64c1de2002-08-12 17:36:03 +00002635 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2636 * because it's fresher in cache.
2637 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002638 i = Py_Size(ret) - shift; /* # digits after shift */
2639 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_Size(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002640 Py_DECREF(t2);
2641
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002642 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_Size(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002643 Py_DECREF(t1);
2644
Tim Petersd64c1de2002-08-12 17:36:03 +00002645 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002646 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2647 Py_DECREF(ah);
2648 Py_DECREF(al);
2649 ah = al = NULL;
2650
Tim Peters0973b992004-08-29 22:16:50 +00002651 if (a == b) {
2652 t2 = t1;
2653 Py_INCREF(t2);
2654 }
2655 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002656 Py_DECREF(t1);
2657 goto fail;
2658 }
2659 Py_DECREF(bh);
2660 Py_DECREF(bl);
2661 bh = bl = NULL;
2662
Tim Peters738eda72002-08-12 15:08:20 +00002663 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002664 Py_DECREF(t1);
2665 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002666 if (t3 == NULL) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002667 assert(Py_Size(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002668
Tim Petersd6974a52002-08-13 20:37:51 +00002669 /* Add t3. It's not obvious why we can't run out of room here.
2670 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002671 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002672 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_Size(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002673 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002674
Tim Peters5af4e6c2002-08-12 02:31:19 +00002675 return long_normalize(ret);
2676
2677 fail:
2678 Py_XDECREF(ret);
2679 Py_XDECREF(ah);
2680 Py_XDECREF(al);
2681 Py_XDECREF(bh);
2682 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002683 return NULL;
2684}
2685
Tim Petersd6974a52002-08-13 20:37:51 +00002686/* (*) Why adding t3 can't "run out of room" above.
2687
Tim Petersab86c2b2002-08-15 20:06:00 +00002688Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2689to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002690
Tim Petersab86c2b2002-08-15 20:06:00 +000026911. For any integer i, i = c(i/2) + f(i/2). In particular,
2692 bsize = c(bsize/2) + f(bsize/2).
26932. shift = f(bsize/2)
26943. asize <= bsize
26954. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2696 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002697
Tim Petersab86c2b2002-08-15 20:06:00 +00002698We allocated asize + bsize result digits, and add t3 into them at an offset
2699of shift. This leaves asize+bsize-shift allocated digit positions for t3
2700to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2701asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002702
Tim Petersab86c2b2002-08-15 20:06:00 +00002703bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2704at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002705
Tim Petersab86c2b2002-08-15 20:06:00 +00002706If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2707digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2708most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002709
Tim Petersab86c2b2002-08-15 20:06:00 +00002710The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002711
Tim Petersab86c2b2002-08-15 20:06:00 +00002712 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002713
Tim Petersab86c2b2002-08-15 20:06:00 +00002714and we have asize + c(bsize/2) available digit positions. We need to show
2715this is always enough. An instance of c(bsize/2) cancels out in both, so
2716the question reduces to whether asize digits is enough to hold
2717(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2718then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2719asize 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 +00002720digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002721asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002722c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2723is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2724bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002725
Tim Peters48d52c02002-08-14 17:07:32 +00002726Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2727clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2728ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002729*/
2730
Tim Peters60004642002-08-12 22:01:34 +00002731/* b has at least twice the digits of a, and a is big enough that Karatsuba
2732 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2733 * of slices, each with a->ob_size digits, and multiply the slices by a,
2734 * one at a time. This gives k_mul balanced inputs to work with, and is
2735 * also cache-friendly (we compute one double-width slice of the result
2736 * at a time, then move on, never bactracking except for the helpful
2737 * single-width slice overlap between successive partial sums).
2738 */
2739static PyLongObject *
2740k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2741{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002742 const Py_ssize_t asize = ABS(Py_Size(a));
2743 Py_ssize_t bsize = ABS(Py_Size(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002744 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002745 PyLongObject *ret;
2746 PyLongObject *bslice = NULL;
2747
2748 assert(asize > KARATSUBA_CUTOFF);
2749 assert(2 * asize <= bsize);
2750
2751 /* Allocate result space, and zero it out. */
2752 ret = _PyLong_New(asize + bsize);
2753 if (ret == NULL)
2754 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002755 memset(ret->ob_digit, 0, Py_Size(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002756
2757 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002758 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002759 if (bslice == NULL)
2760 goto fail;
2761
2762 nbdone = 0;
2763 while (bsize > 0) {
2764 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002765 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002766
2767 /* Multiply the next slice of b by a. */
2768 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2769 nbtouse * sizeof(digit));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002770 Py_Size(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002771 product = k_mul(a, bslice);
2772 if (product == NULL)
2773 goto fail;
2774
2775 /* Add into result. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002776 (void)v_iadd(ret->ob_digit + nbdone, Py_Size(ret) - nbdone,
2777 product->ob_digit, Py_Size(product));
Tim Peters60004642002-08-12 22:01:34 +00002778 Py_DECREF(product);
2779
2780 bsize -= nbtouse;
2781 nbdone += nbtouse;
2782 }
2783
2784 Py_DECREF(bslice);
2785 return long_normalize(ret);
2786
2787 fail:
2788 Py_DECREF(ret);
2789 Py_XDECREF(bslice);
2790 return NULL;
2791}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002792
2793static PyObject *
2794long_mul(PyLongObject *v, PyLongObject *w)
2795{
2796 PyLongObject *a, *b, *z;
2797
2798 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002799 Py_INCREF(Py_NotImplemented);
2800 return Py_NotImplemented;
2801 }
2802
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002803 if (ABS(Py_Size(v)) <= 1 && ABS(Py_Size(w)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002804 PyObject *r;
2805 r = PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w));
2806 Py_DECREF(a);
2807 Py_DECREF(b);
2808 return r;
2809 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002810
Tim Petersd64c1de2002-08-12 17:36:03 +00002811 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002812 /* Negate if exactly one of the inputs is negative. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002813 if (((Py_Size(a) ^ Py_Size(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002814 NEGATE(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002815 Py_DECREF(a);
2816 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002817 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002818}
2819
Guido van Rossume32e0141992-01-19 16:31:05 +00002820/* The / and % operators are now defined in terms of divmod().
2821 The expression a mod b has the value a - b*floor(a/b).
2822 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002823 |a| by |b|, with the sign of a. This is also expressed
2824 as a - b*trunc(a/b), if trunc truncates towards zero.
2825 Some examples:
2826 a b a rem b a mod b
2827 13 10 3 3
2828 -13 10 -3 7
2829 13 -10 3 -7
2830 -13 -10 -3 -3
2831 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002832 have different signs. We then subtract one from the 'div'
2833 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002834
Tim Peters47e52ee2004-08-30 02:44:38 +00002835/* Compute
2836 * *pdiv, *pmod = divmod(v, w)
2837 * NULL can be passed for pdiv or pmod, in which case that part of
2838 * the result is simply thrown away. The caller owns a reference to
2839 * each of these it requests (does not pass NULL for).
2840 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002841static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002842l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002843 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002844{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002845 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002846
Guido van Rossume32e0141992-01-19 16:31:05 +00002847 if (long_divrem(v, w, &div, &mod) < 0)
2848 return -1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002849 if ((Py_Size(mod) < 0 && Py_Size(w) > 0) ||
2850 (Py_Size(mod) > 0 && Py_Size(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002851 PyLongObject *temp;
2852 PyLongObject *one;
2853 temp = (PyLongObject *) long_add(mod, w);
2854 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002855 mod = temp;
2856 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002857 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002858 return -1;
2859 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002860 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002861 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002862 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2863 Py_DECREF(mod);
2864 Py_DECREF(div);
2865 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002866 return -1;
2867 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002868 Py_DECREF(one);
2869 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002870 div = temp;
2871 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002872 if (pdiv != NULL)
2873 *pdiv = div;
2874 else
2875 Py_DECREF(div);
2876
2877 if (pmod != NULL)
2878 *pmod = mod;
2879 else
2880 Py_DECREF(mod);
2881
Guido van Rossume32e0141992-01-19 16:31:05 +00002882 return 0;
2883}
2884
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002885static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002886long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002887{
Tim Peters47e52ee2004-08-30 02:44:38 +00002888 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002889
2890 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002891 if (l_divmod(a, b, &div, NULL) < 0)
2892 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002893 Py_DECREF(a);
2894 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002895 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002896}
2897
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002898static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002899long_true_divide(PyObject *v, PyObject *w)
2900{
Tim Peterse2a60002001-09-04 06:17:36 +00002901 PyLongObject *a, *b;
2902 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002903 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002904
2905 CONVERT_BINOP(v, w, &a, &b);
2906 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2907 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002908 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2909 Py_DECREF(a);
2910 Py_DECREF(b);
2911 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002912 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002913 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2914 but should really be set correctly after sucessful calls to
2915 _PyLong_AsScaledDouble() */
2916 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002917
2918 if (bd == 0.0) {
2919 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002920 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002921 return NULL;
2922 }
2923
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002924 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002925 ad /= bd; /* overflow/underflow impossible here */
2926 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002927 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002928 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002929 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002930 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002931 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002932 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002933 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002934 goto overflow;
2935 return PyFloat_FromDouble(ad);
2936
2937overflow:
2938 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002939 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002940 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002941
Tim Peters20dab9f2001-09-04 05:31:47 +00002942}
2943
2944static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002945long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002946{
Tim Peters47e52ee2004-08-30 02:44:38 +00002947 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002948
2949 CONVERT_BINOP(v, w, &a, &b);
2950
Tim Peters47e52ee2004-08-30 02:44:38 +00002951 if (l_divmod(a, b, NULL, &mod) < 0)
2952 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002953 Py_DECREF(a);
2954 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002955 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002956}
2957
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002958static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002959long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002960{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002961 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002962 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002963
2964 CONVERT_BINOP(v, w, &a, &b);
2965
2966 if (l_divmod(a, b, &div, &mod) < 0) {
2967 Py_DECREF(a);
2968 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002969 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002970 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002971 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002972 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002973 PyTuple_SetItem(z, 0, (PyObject *) div);
2974 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002975 }
2976 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002977 Py_DECREF(div);
2978 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002979 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002980 Py_DECREF(a);
2981 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002982 return z;
2983}
2984
Tim Peters47e52ee2004-08-30 02:44:38 +00002985/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002986static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002987long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002988{
Tim Peters47e52ee2004-08-30 02:44:38 +00002989 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2990 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002991
Tim Peters47e52ee2004-08-30 02:44:38 +00002992 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002993 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002994 PyLongObject *temp = NULL;
2995
2996 /* 5-ary values. If the exponent is large enough, table is
2997 * precomputed so that table[i] == a**i % c for i in range(32).
2998 */
2999 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3000 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3001
3002 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003003 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003004 if (PyLong_Check(x)) {
3005 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003006 Py_INCREF(x);
3007 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003008 else if (x == Py_None)
3009 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003010 else {
3011 Py_DECREF(a);
3012 Py_DECREF(b);
3013 Py_INCREF(Py_NotImplemented);
3014 return Py_NotImplemented;
3015 }
Tim Peters4c483c42001-09-05 06:24:58 +00003016
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003017 if (Py_Size(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003018 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003019 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003020 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003021 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003022 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003023 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003024 /* else return a float. This works because we know
3025 that this calls float_pow() which converts its
3026 arguments to double. */
3027 Py_DECREF(a);
3028 Py_DECREF(b);
3029 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003030 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003031 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003032
3033 if (c) {
3034 /* if modulus == 0:
3035 raise ValueError() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003036 if (Py_Size(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003037 PyErr_SetString(PyExc_ValueError,
3038 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003039 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003040 }
3041
3042 /* if modulus < 0:
3043 negativeOutput = True
3044 modulus = -modulus */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003045 if (Py_Size(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003046 negativeOutput = 1;
3047 temp = (PyLongObject *)_PyLong_Copy(c);
3048 if (temp == NULL)
3049 goto Error;
3050 Py_DECREF(c);
3051 c = temp;
3052 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003053 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003054 }
3055
3056 /* if modulus == 1:
3057 return 0 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003058 if ((Py_Size(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003059 z = (PyLongObject *)PyLong_FromLong(0L);
3060 goto Done;
3061 }
3062
3063 /* if base < 0:
3064 base = base % modulus
3065 Having the base positive just makes things easier. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003066 if (Py_Size(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003067 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003068 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003069 Py_DECREF(a);
3070 a = temp;
3071 temp = NULL;
3072 }
3073 }
3074
3075 /* At this point a, b, and c are guaranteed non-negative UNLESS
3076 c is NULL, in which case a may be negative. */
3077
3078 z = (PyLongObject *)PyLong_FromLong(1L);
3079 if (z == NULL)
3080 goto Error;
3081
3082 /* Perform a modular reduction, X = X % c, but leave X alone if c
3083 * is NULL.
3084 */
3085#define REDUCE(X) \
3086 if (c != NULL) { \
3087 if (l_divmod(X, c, NULL, &temp) < 0) \
3088 goto Error; \
3089 Py_XDECREF(X); \
3090 X = temp; \
3091 temp = NULL; \
3092 }
3093
3094 /* Multiply two values, then reduce the result:
3095 result = X*Y % c. If c is NULL, skip the mod. */
3096#define MULT(X, Y, result) \
3097{ \
3098 temp = (PyLongObject *)long_mul(X, Y); \
3099 if (temp == NULL) \
3100 goto Error; \
3101 Py_XDECREF(result); \
3102 result = temp; \
3103 temp = NULL; \
3104 REDUCE(result) \
3105}
3106
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003107 if (Py_Size(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003108 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3109 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003110 for (i = Py_Size(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003111 digit bi = b->ob_digit[i];
3112
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003113 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003114 MULT(z, z, z)
3115 if (bi & j)
3116 MULT(z, a, z)
3117 }
3118 }
3119 }
3120 else {
3121 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3122 Py_INCREF(z); /* still holds 1L */
3123 table[0] = z;
3124 for (i = 1; i < 32; ++i)
3125 MULT(table[i-1], a, table[i])
3126
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003127 for (i = Py_Size(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003128 const digit bi = b->ob_digit[i];
3129
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003130 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003131 const int index = (bi >> j) & 0x1f;
3132 for (k = 0; k < 5; ++k)
3133 MULT(z, z, z)
3134 if (index)
3135 MULT(z, table[index], z)
3136 }
3137 }
3138 }
3139
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003140 if (negativeOutput && (Py_Size(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003141 temp = (PyLongObject *)long_sub(z, c);
3142 if (temp == NULL)
3143 goto Error;
3144 Py_DECREF(z);
3145 z = temp;
3146 temp = NULL;
3147 }
3148 goto Done;
3149
3150 Error:
3151 if (z != NULL) {
3152 Py_DECREF(z);
3153 z = NULL;
3154 }
3155 /* fall through */
3156 Done:
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003157 if (Py_Size(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003158 for (i = 0; i < 32; ++i)
3159 Py_XDECREF(table[i]);
3160 }
Tim Petersde7990b2005-07-17 23:45:23 +00003161 Py_DECREF(a);
3162 Py_DECREF(b);
3163 Py_XDECREF(c);
3164 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003165 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003166}
3167
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003168static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003169long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003170{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003171 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003172 PyLongObject *x;
3173 PyLongObject *w;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003174 if (ABS(Py_Size(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003175 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003176 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003177 if (w == NULL)
3178 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003179 x = (PyLongObject *) long_add(v, w);
3180 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003181 if (x == NULL)
3182 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003183 Py_Size(x) = -(Py_Size(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003184 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003185}
3186
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003187static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003188long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003189{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003190 PyLongObject *z;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003191 if (ABS(Py_Size(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003192 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003193 z = (PyLongObject *)_PyLong_Copy(v);
3194 if (z != NULL)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003195 Py_Size(z) = -(Py_Size(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003196 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003197}
3198
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003199static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003200long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003201{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003202 if (Py_Size(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003203 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003204 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003205 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003206}
3207
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003208static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003209long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003210{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003211 return ABS(Py_Size(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003212}
3213
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003214static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003215long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003216{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003217 PyLongObject *a, *b;
3218 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003219 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003220 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003221 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003222
Neil Schemenauerba872e22001-01-04 01:46:03 +00003223 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3224
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003225 if (Py_Size(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003226 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003227 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003228 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003229 if (a1 == NULL)
3230 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003231 a2 = (PyLongObject *) long_rshift(a1, b);
3232 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003233 if (a2 == NULL)
3234 goto rshift_error;
3235 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003236 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003237 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003238 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003239
Neil Schemenauerba872e22001-01-04 01:46:03 +00003240 shiftby = PyLong_AsLong((PyObject *)b);
3241 if (shiftby == -1L && PyErr_Occurred())
3242 goto rshift_error;
3243 if (shiftby < 0) {
3244 PyErr_SetString(PyExc_ValueError,
3245 "negative shift count");
3246 goto rshift_error;
3247 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003248 wordshift = shiftby / PyLong_SHIFT;
3249 newsize = ABS(Py_Size(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003250 if (newsize <= 0) {
3251 z = _PyLong_New(0);
3252 Py_DECREF(a);
3253 Py_DECREF(b);
3254 return (PyObject *)z;
3255 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003256 loshift = shiftby % PyLong_SHIFT;
3257 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003258 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003259 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003260 z = _PyLong_New(newsize);
3261 if (z == NULL)
3262 goto rshift_error;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003263 if (Py_Size(a) < 0)
3264 Py_Size(z) = -(Py_Size(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003265 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3266 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3267 if (i+1 < newsize)
3268 z->ob_digit[i] |=
3269 (a->ob_digit[j+1] << hishift) & himask;
3270 }
3271 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003272 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003273rshift_error:
3274 Py_DECREF(a);
3275 Py_DECREF(b);
3276 return (PyObject *) z;
3277
Guido van Rossumc6913e71991-11-19 20:26:46 +00003278}
3279
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003280static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003281long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003282{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003283 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003284 PyLongObject *a, *b;
3285 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003286 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003287 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003288 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003289
Neil Schemenauerba872e22001-01-04 01:46:03 +00003290 CONVERT_BINOP(v, w, &a, &b);
3291
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003292 shiftby = PyLong_AsLong((PyObject *)b);
3293 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003294 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003295 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003296 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003297 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003298 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003299 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003300 PyErr_SetString(PyExc_ValueError,
3301 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003302 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003303 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003304 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3305 wordshift = (int)shiftby / PyLong_SHIFT;
3306 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003307
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003308 oldsize = ABS(Py_Size(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003309 newsize = oldsize + wordshift;
3310 if (remshift)
3311 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003312 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003313 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003314 goto lshift_error;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003315 if (Py_Size(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003316 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003317 for (i = 0; i < wordshift; i++)
3318 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003319 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003320 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003321 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003322 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3323 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003324 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003325 if (remshift)
3326 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003327 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003328 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003329 z = long_normalize(z);
3330lshift_error:
3331 Py_DECREF(a);
3332 Py_DECREF(b);
3333 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003334}
3335
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003336
3337/* Bitwise and/xor/or operations */
3338
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003339static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003340long_bitwise(PyLongObject *a,
3341 int op, /* '&', '|', '^' */
3342 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003343{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003344 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003345 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003346 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003347 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003348 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003349 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003350 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003351
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003352 if (Py_Size(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003353 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003354 if (a == NULL)
3355 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003356 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003357 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003358 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003359 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003360 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003361 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003362 if (Py_Size(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003363 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003364 if (b == NULL) {
3365 Py_DECREF(a);
3366 return NULL;
3367 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003368 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003369 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003370 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003371 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003372 maskb = 0;
3373 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003374
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003375 negz = 0;
3376 switch (op) {
3377 case '^':
3378 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003379 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003380 negz = -1;
3381 }
3382 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003383 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003384 if (maska && maskb) {
3385 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003386 maska ^= PyLong_MASK;
3387 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003388 negz = -1;
3389 }
3390 break;
3391 case '|':
3392 if (maska || maskb) {
3393 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003394 maska ^= PyLong_MASK;
3395 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003396 negz = -1;
3397 }
3398 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003399 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003400
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003401 /* JRH: The original logic here was to allocate the result value (z)
3402 as the longer of the two operands. However, there are some cases
3403 where the result is guaranteed to be shorter than that: AND of two
3404 positives, OR of two negatives: use the shorter number. AND with
3405 mixed signs: use the positive number. OR with mixed signs: use the
3406 negative number. After the transformations above, op will be '&'
3407 iff one of these cases applies, and mask will be non-0 for operands
3408 whose length should be ignored.
3409 */
3410
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003411 size_a = Py_Size(a);
3412 size_b = Py_Size(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003413 size_z = op == '&'
3414 ? (maska
3415 ? size_b
3416 : (maskb ? size_a : MIN(size_a, size_b)))
3417 : MAX(size_a, size_b);
3418 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003419 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003420 Py_DECREF(a);
3421 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003422 return NULL;
3423 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003424
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003425 for (i = 0; i < size_z; ++i) {
3426 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3427 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3428 switch (op) {
3429 case '&': z->ob_digit[i] = diga & digb; break;
3430 case '|': z->ob_digit[i] = diga | digb; break;
3431 case '^': z->ob_digit[i] = diga ^ digb; break;
3432 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003433 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003434
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003435 Py_DECREF(a);
3436 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003437 z = long_normalize(z);
3438 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003439 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003440 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003441 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003442 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003443}
3444
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003445static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003446long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003447{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003448 PyLongObject *a, *b;
3449 PyObject *c;
3450 CONVERT_BINOP(v, w, &a, &b);
3451 c = long_bitwise(a, '&', b);
3452 Py_DECREF(a);
3453 Py_DECREF(b);
3454 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003455}
3456
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003457static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003458long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003459{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003460 PyLongObject *a, *b;
3461 PyObject *c;
3462 CONVERT_BINOP(v, w, &a, &b);
3463 c = long_bitwise(a, '^', b);
3464 Py_DECREF(a);
3465 Py_DECREF(b);
3466 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003467}
3468
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003469static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003470long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003471{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003472 PyLongObject *a, *b;
3473 PyObject *c;
3474 CONVERT_BINOP(v, w, &a, &b);
3475 c = long_bitwise(a, '|', b);
3476 Py_DECREF(a);
3477 Py_DECREF(b);
3478 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003479}
3480
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003481static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003482long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003483{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003484 if (PyLong_CheckExact(v))
3485 Py_INCREF(v);
3486 else
3487 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003488 return v;
3489}
3490
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003491static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003492long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003493{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003494 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003495 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003496 if (result == -1.0 && PyErr_Occurred())
3497 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003498 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003499}
3500
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003501static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003502long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003503
Tim Peters6d6c1a32001-08-02 04:15:00 +00003504static PyObject *
3505long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3506{
3507 PyObject *x = NULL;
3508 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003509 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003510
Guido van Rossumbef14172001-08-29 15:47:46 +00003511 if (type != &PyLong_Type)
3512 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003513 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003514 &x, &base))
3515 return NULL;
3516 if (x == NULL)
3517 return PyLong_FromLong(0L);
3518 if (base == -909)
3519 return PyNumber_Long(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003520 else if (PyString_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003521 /* Since PyLong_FromString doesn't have a length parameter,
3522 * check here for possible NULs in the string. */
Guido van Rossum4581ae52007-05-22 21:56:47 +00003523 char *string;
3524 int size;
3525 if (PyBytes_Check(x)) {
3526 string = PyBytes_AS_STRING(x);
3527 size = PyBytes_GET_SIZE(x);
3528 }
3529 else {
3530 string = PyString_AS_STRING(x);
3531 size = PyString_GET_SIZE(x);
3532 }
3533 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003534 /* We only see this if there's a null byte in x,
3535 x is a str8 or a bytes, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003536 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003537 "invalid literal for int() with base %d: %R",
3538 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003539 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003540 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003541 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003542 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003543 else if (PyUnicode_Check(x))
3544 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3545 PyUnicode_GET_SIZE(x),
3546 base);
3547 else {
3548 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003549 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003550 return NULL;
3551 }
3552}
3553
Guido van Rossumbef14172001-08-29 15:47:46 +00003554/* Wimpy, slow approach to tp_new calls for subtypes of long:
3555 first create a regular long from whatever arguments we got,
3556 then allocate a subtype instance and initialize it from
3557 the regular long. The regular long is then thrown away.
3558*/
3559static PyObject *
3560long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3561{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003562 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003563 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003564
3565 assert(PyType_IsSubtype(type, &PyLong_Type));
3566 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3567 if (tmp == NULL)
3568 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003569 assert(PyLong_CheckExact(tmp));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003570 n = Py_Size(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003571 if (n < 0)
3572 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003573 newobj = (PyLongObject *)type->tp_alloc(type, n);
3574 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003575 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003576 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003577 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003578 assert(PyLong_Check(newobj));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003579 Py_Size(newobj) = Py_Size(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003580 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003581 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003582 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003583 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003584}
3585
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003586static PyObject *
3587long_getnewargs(PyLongObject *v)
3588{
3589 return Py_BuildValue("(N)", _PyLong_Copy(v));
3590}
3591
Guido van Rossumb43daf72007-08-01 18:08:08 +00003592static PyObject *
3593long_getN(PyLongObject *v, void *context) {
3594 return PyLong_FromLong((intptr_t)context);
3595}
3596
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003597static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003598long__format__(PyObject *self, PyObject *args)
3599{
3600 /* when back porting this to 2.6, check type of the format_spec
3601 and call either unicode_long__format__ or
3602 string_long__format__ */
3603 return unicode_long__format__(self, args);
3604}
3605
3606
3607static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003608long_round(PyObject *self, PyObject *args)
3609{
3610#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
3611 int ndigits = UNDEF_NDIGITS;
3612 double x;
3613 PyObject *res;
3614
3615 if (!PyArg_ParseTuple(args, "|i", &ndigits))
3616 return NULL;
3617
3618 if (ndigits == UNDEF_NDIGITS)
3619 return long_long(self);
3620
3621 /* If called with two args, defer to float.__round__(). */
3622 x = PyLong_AsDouble(self);
3623 if (x == -1.0 && PyErr_Occurred())
3624 return NULL;
3625 self = PyFloat_FromDouble(x);
3626 if (self == NULL)
3627 return NULL;
3628 res = PyObject_CallMethod(self, "__round__", "i", ndigits);
3629 Py_DECREF(self);
3630 return res;
3631#undef UNDEF_NDIGITS
3632}
3633
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003634static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003635 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3636 "Returns self, the complex conjugate of any int."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003637 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3638 "Truncating an Integral returns itself."},
3639 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3640 "Flooring an Integral returns itself."},
3641 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3642 "Ceiling of an Integral returns itself."},
3643 {"__round__", (PyCFunction)long_round, METH_VARARGS,
3644 "Rounding an Integral returns itself.\n"
3645 "Rounding with an ndigits arguments defers to float.__round__."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003646 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003647 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003648 {NULL, NULL} /* sentinel */
3649};
3650
Guido van Rossumb43daf72007-08-01 18:08:08 +00003651static PyGetSetDef long_getset[] = {
3652 {"real",
3653 (getter)long_long, (setter)NULL,
3654 "the real part of a complex number",
3655 NULL},
3656 {"imag",
3657 (getter)long_getN, (setter)NULL,
3658 "the imaginary part of a complex number",
3659 (void*)0},
3660 {"numerator",
3661 (getter)long_long, (setter)NULL,
3662 "the numerator of a rational number in lowest terms",
3663 NULL},
3664 {"denominator",
3665 (getter)long_getN, (setter)NULL,
3666 "the denominator of a rational number in lowest terms",
3667 (void*)1},
3668 {NULL} /* Sentinel */
3669};
3670
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003671PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003672"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003674Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003675point argument will be truncated towards zero (this does not include a\n\
3676string representation of a floating point number!) When converting a\n\
3677string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003678converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003679
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003680static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003681 (binaryfunc) long_add, /*nb_add*/
3682 (binaryfunc) long_sub, /*nb_subtract*/
3683 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003684 long_mod, /*nb_remainder*/
3685 long_divmod, /*nb_divmod*/
3686 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003687 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003688 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003689 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003690 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003691 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003692 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003693 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003694 long_and, /*nb_and*/
3695 long_xor, /*nb_xor*/
3696 long_or, /*nb_or*/
Neal Norwitzca810462006-08-29 07:57:59 +00003697 0, /*nb_coerce*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003698 long_long, /*nb_int*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003699 long_long, /*nb_long*/
3700 long_float, /*nb_float*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003701 0, /*nb_oct*/ /* not used */
3702 0, /*nb_hex*/ /* not used */
Guido van Rossum4668b002001-08-08 05:00:18 +00003703 0, /* nb_inplace_add */
3704 0, /* nb_inplace_subtract */
3705 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003706 0, /* nb_inplace_remainder */
3707 0, /* nb_inplace_power */
3708 0, /* nb_inplace_lshift */
3709 0, /* nb_inplace_rshift */
3710 0, /* nb_inplace_and */
3711 0, /* nb_inplace_xor */
3712 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003713 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003714 long_true_divide, /* nb_true_divide */
3715 0, /* nb_inplace_floor_divide */
3716 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003717 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003718};
3719
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003720PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003721 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003722 "int", /* tp_name */
3723 /* See _PyLong_New for why this isn't
3724 sizeof(PyLongObject) - sizeof(digit) */
3725 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003727 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003728 0, /* tp_print */
3729 0, /* tp_getattr */
3730 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003731 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003732 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003733 &long_as_number, /* tp_as_number */
3734 0, /* tp_as_sequence */
3735 0, /* tp_as_mapping */
3736 (hashfunc)long_hash, /* tp_hash */
3737 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003738 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003739 PyObject_GenericGetAttr, /* tp_getattro */
3740 0, /* tp_setattro */
3741 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003742 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3743 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003744 long_doc, /* tp_doc */
3745 0, /* tp_traverse */
3746 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003747 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003748 0, /* tp_weaklistoffset */
3749 0, /* tp_iter */
3750 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003751 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003752 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003753 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003754 0, /* tp_base */
3755 0, /* tp_dict */
3756 0, /* tp_descr_get */
3757 0, /* tp_descr_set */
3758 0, /* tp_dictoffset */
3759 0, /* tp_init */
3760 0, /* tp_alloc */
3761 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003762 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003763};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003764
3765int
3766_PyLong_Init(void)
3767{
3768#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3769 int ival;
3770 PyLongObject *v = small_ints;
3771 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3772 PyObject_INIT(v, &PyLong_Type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003773 Py_Size(v) = -1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003774 v->ob_digit[0] = -ival;
3775 }
3776 for (; ival < NSMALLPOSINTS; ival++, v++) {
3777 PyObject_INIT(v, &PyLong_Type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003778 Py_Size(v) = ival ? 1 : 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003779 v->ob_digit[0] = ival;
3780 }
3781#endif
3782 return 1;
3783}
3784
3785void
3786PyLong_Fini(void)
3787{
3788#if 0
3789 int i;
3790 /* This is currently not needed; the small integers
3791 are statically allocated */
3792#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3793 PyIntObject **q;
3794
3795 i = NSMALLNEGINTS + NSMALLPOSINTS;
3796 q = small_ints;
3797 while (--i >= 0) {
3798 Py_XDECREF(*q);
3799 *q++ = NULL;
3800 }
3801#endif
3802#endif
3803}