blob: 1c127baccd3d10fe332f34ee7fb2fe11d17245c5 [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 Rossum149e9ea1991-06-03 10:58:24 +0000263 if (dval < 0.0) {
264 neg = 1;
265 dval = -dval;
266 }
267 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
268 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000269 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000270 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000272 if (v == NULL)
273 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000274 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000275 for (i = ndig; --i >= 0; ) {
276 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000277 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000278 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000279 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000280 }
281 if (neg)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000282 Py_Size(v) = -(Py_Size(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000283 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000284}
285
Thomas Wouters89f507f2006-12-13 04:49:30 +0000286/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
287 * anything about what happens when a signed integer operation overflows,
288 * and some compilers think they're doing you a favor by being "clever"
289 * then. The bit pattern for the largest postive signed long is
290 * (unsigned long)LONG_MAX, and for the smallest negative signed long
291 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
292 * However, some other compilers warn about applying unary minus to an
293 * unsigned operand. Hence the weird "0-".
294 */
295#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
296#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
297
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000298/* Get a C long int from a long int object.
299 Returns -1 and sets an error condition if overflow occurs. */
300
301long
Tim Peters9f688bf2000-07-07 15:53:28 +0000302PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000303{
Guido van Rossumf7531811998-05-26 14:33:37 +0000304 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000305 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000306 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000307 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000308 Py_ssize_t i;
309 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000310 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000311
Guido van Rossumddefaf32007-01-14 03:31:43 +0000312 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000313 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000314 return -1;
315 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000316
317 if (!PyLong_Check(vv)) {
318 PyNumberMethods *nb;
319 if ((nb = vv->ob_type->tp_as_number) == NULL ||
320 nb->nb_int == NULL) {
321 PyErr_SetString(PyExc_TypeError, "an integer is required");
322 return -1;
323 }
324 vv = (*nb->nb_int) (vv);
325 if (vv == NULL)
326 return -1;
327 do_decref = 1;
328 if (!PyLong_Check(vv)) {
329 Py_DECREF(vv);
330 PyErr_SetString(PyExc_TypeError,
331 "nb_int should return int object");
332 return -1;
333 }
334 }
335
Georg Brandl61c31b02007-02-26 14:46:30 +0000336 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000337 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000338 i = Py_Size(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000339
Georg Brandl61c31b02007-02-26 14:46:30 +0000340 switch (i) {
341 case -1:
342 res = -v->ob_digit[0];
343 break;
344 case 0:
345 res = 0;
346 break;
347 case 1:
348 res = v->ob_digit[0];
349 break;
350 default:
351 sign = 1;
352 x = 0;
353 if (i < 0) {
354 sign = -1;
355 i = -(i);
356 }
357 while (--i >= 0) {
358 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000359 x = (x << PyLong_SHIFT) + v->ob_digit[i];
360 if ((x >> PyLong_SHIFT) != prev) {
Georg Brandl61c31b02007-02-26 14:46:30 +0000361 PyErr_SetString(PyExc_OverflowError,
362 "Python int too large to convert to C long");
363 goto exit;
364 }
365 }
366 /* Haven't lost any bits, but casting to long requires extra care
367 * (see comment above).
368 */
369 if (x <= (unsigned long)LONG_MAX) {
370 res = (long)x * sign;
371 }
372 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
373 res = LONG_MIN;
374 }
375 else {
376 PyErr_SetString(PyExc_OverflowError,
377 "Python int too large to convert to C long");
378 }
379 }
380 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000381 if (do_decref) {
382 Py_DECREF(vv);
383 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000384 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000385}
386
Guido van Rossumddefaf32007-01-14 03:31:43 +0000387int
388_PyLong_FitsInLong(PyObject *vv)
389{
390 int size;
391 if (!PyLong_CheckExact(vv)) {
392 PyErr_BadInternalCall();
393 return 0;
394 }
395 /* conservative estimate */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000396 size = Py_Size(vv);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000397 return -2 <= size && size <= 2;
398}
399
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000400/* Get a Py_ssize_t from a long int object.
401 Returns -1 and sets an error condition if overflow occurs. */
402
403Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000404PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000405 register PyLongObject *v;
406 size_t x, prev;
407 Py_ssize_t i;
408 int sign;
409
410 if (vv == NULL || !PyLong_Check(vv)) {
411 PyErr_BadInternalCall();
412 return -1;
413 }
414 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000415 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000416 switch (i) {
417 case -1: return -v->ob_digit[0];
418 case 0: return 0;
419 case 1: return v->ob_digit[0];
420 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000421 sign = 1;
422 x = 0;
423 if (i < 0) {
424 sign = -1;
425 i = -(i);
426 }
427 while (--i >= 0) {
428 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000429 x = (x << PyLong_SHIFT) + v->ob_digit[i];
430 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000431 goto overflow;
432 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000433 /* Haven't lost any bits, but casting to a signed type requires
434 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000435 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000436 if (x <= (size_t)PY_SSIZE_T_MAX) {
437 return (Py_ssize_t)x * sign;
438 }
439 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
440 return PY_SSIZE_T_MIN;
441 }
442 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000443
444 overflow:
445 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000446 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000447 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000448}
449
Guido van Rossumd8c80482002-08-13 00:24:58 +0000450/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000451 Returns -1 and sets an error condition if overflow occurs. */
452
453unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000454PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000455{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000457 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000458 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000459
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000460 if (vv == NULL || !PyLong_Check(vv)) {
461 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000462 return (unsigned long) -1;
463 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000464 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000465 i = Py_Size(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000466 x = 0;
467 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000469 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000470 return (unsigned long) -1;
471 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000472 switch (i) {
473 case 0: return 0;
474 case 1: return v->ob_digit[0];
475 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000476 while (--i >= 0) {
477 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000478 x = (x << PyLong_SHIFT) + v->ob_digit[i];
479 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000480 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000481 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000482 return (unsigned long) -1;
483 }
484 }
485 return x;
486}
487
488/* Get a C unsigned long int from a long int object.
489 Returns -1 and sets an error condition if overflow occurs. */
490
491size_t
492PyLong_AsSize_t(PyObject *vv)
493{
494 register PyLongObject *v;
495 size_t x, prev;
496 Py_ssize_t i;
497
498 if (vv == NULL || !PyLong_Check(vv)) {
499 PyErr_BadInternalCall();
500 return (unsigned long) -1;
501 }
502 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000503 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000504 x = 0;
505 if (i < 0) {
506 PyErr_SetString(PyExc_OverflowError,
507 "can't convert negative value to size_t");
508 return (size_t) -1;
509 }
510 switch (i) {
511 case 0: return 0;
512 case 1: return v->ob_digit[0];
513 }
514 while (--i >= 0) {
515 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000516 x = (x << PyLong_SHIFT) + v->ob_digit[i];
517 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000518 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000519 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000520 return (unsigned long) -1;
521 }
522 }
523 return x;
524}
525
Thomas Hellera4ea6032003-04-17 18:55:45 +0000526/* Get a C unsigned long int from a long int object, ignoring the high bits.
527 Returns -1 and sets an error condition if an error occurs. */
528
Guido van Rossumddefaf32007-01-14 03:31:43 +0000529static unsigned long
530_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000531{
532 register PyLongObject *v;
533 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000534 Py_ssize_t i;
535 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000536
537 if (vv == NULL || !PyLong_Check(vv)) {
538 PyErr_BadInternalCall();
539 return (unsigned long) -1;
540 }
541 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000542 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000543 switch (i) {
544 case 0: return 0;
545 case 1: return v->ob_digit[0];
546 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000547 sign = 1;
548 x = 0;
549 if (i < 0) {
550 sign = -1;
551 i = -i;
552 }
553 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000554 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000555 }
556 return x * sign;
557}
558
Guido van Rossumddefaf32007-01-14 03:31:43 +0000559unsigned long
560PyLong_AsUnsignedLongMask(register PyObject *op)
561{
562 PyNumberMethods *nb;
563 PyLongObject *lo;
564 unsigned long val;
565
566 if (op && PyLong_Check(op))
567 return _PyLong_AsUnsignedLongMask(op);
568
569 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
570 nb->nb_int == NULL) {
571 PyErr_SetString(PyExc_TypeError, "an integer is required");
572 return (unsigned long)-1;
573 }
574
575 lo = (PyLongObject*) (*nb->nb_int) (op);
576 if (lo == NULL)
577 return (unsigned long)-1;
578 if (PyLong_Check(lo)) {
579 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
580 Py_DECREF(lo);
581 if (PyErr_Occurred())
582 return (unsigned long)-1;
583 return val;
584 }
585 else
586 {
587 Py_DECREF(lo);
588 PyErr_SetString(PyExc_TypeError,
589 "nb_int should return int object");
590 return (unsigned long)-1;
591 }
592}
593
Tim Peters5b8132f2003-01-31 15:52:05 +0000594int
595_PyLong_Sign(PyObject *vv)
596{
597 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000598
599 assert(v != NULL);
600 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000601
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000602 return Py_Size(v) == 0 ? 0 : (Py_Size(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000603}
604
Tim Petersbaefd9e2003-01-28 20:37:45 +0000605size_t
606_PyLong_NumBits(PyObject *vv)
607{
608 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000609 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000610 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000611
612 assert(v != NULL);
613 assert(PyLong_Check(v));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000614 ndigits = ABS(Py_Size(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000615 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
616 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000617 digit msd = v->ob_digit[ndigits - 1];
618
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000619 result = (ndigits - 1) * PyLong_SHIFT;
620 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000621 goto Overflow;
622 do {
623 ++result;
624 if (result == 0)
625 goto Overflow;
626 msd >>= 1;
627 } while (msd);
628 }
629 return result;
630
631Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000632 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000633 "to express in a platform size_t");
634 return (size_t)-1;
635}
636
Tim Peters2a9b3672001-06-11 21:23:58 +0000637PyObject *
638_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
639 int little_endian, int is_signed)
640{
641 const unsigned char* pstartbyte;/* LSB of bytes */
642 int incr; /* direction to move pstartbyte */
643 const unsigned char* pendbyte; /* MSB of bytes */
644 size_t numsignificantbytes; /* number of bytes that matter */
645 size_t ndigits; /* number of Python long digits */
646 PyLongObject* v; /* result */
647 int idigit = 0; /* next free index in v->ob_digit */
648
649 if (n == 0)
650 return PyLong_FromLong(0L);
651
652 if (little_endian) {
653 pstartbyte = bytes;
654 pendbyte = bytes + n - 1;
655 incr = 1;
656 }
657 else {
658 pstartbyte = bytes + n - 1;
659 pendbyte = bytes;
660 incr = -1;
661 }
662
663 if (is_signed)
664 is_signed = *pendbyte >= 0x80;
665
666 /* Compute numsignificantbytes. This consists of finding the most
667 significant byte. Leading 0 bytes are insignficant if the number
668 is positive, and leading 0xff bytes if negative. */
669 {
670 size_t i;
671 const unsigned char* p = pendbyte;
672 const int pincr = -incr; /* search MSB to LSB */
673 const unsigned char insignficant = is_signed ? 0xff : 0x00;
674
675 for (i = 0; i < n; ++i, p += pincr) {
676 if (*p != insignficant)
677 break;
678 }
679 numsignificantbytes = n - i;
680 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
681 actually has 2 significant bytes. OTOH, 0xff0001 ==
682 -0x00ffff, so we wouldn't *need* to bump it there; but we
683 do for 0xffff = -0x0001. To be safe without bothering to
684 check every case, bump it regardless. */
685 if (is_signed && numsignificantbytes < n)
686 ++numsignificantbytes;
687 }
688
689 /* How many Python long digits do we need? We have
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000690 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000691 bits, so it's the ceiling of the quotient. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000692 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000693 if (ndigits > (size_t)INT_MAX)
694 return PyErr_NoMemory();
695 v = _PyLong_New((int)ndigits);
696 if (v == NULL)
697 return NULL;
698
699 /* Copy the bits over. The tricky parts are computing 2's-comp on
700 the fly for signed numbers, and dealing with the mismatch between
701 8-bit bytes and (probably) 15-bit Python digits.*/
702 {
703 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000704 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000705 twodigits accum = 0; /* sliding register */
706 unsigned int accumbits = 0; /* number of bits in accum */
707 const unsigned char* p = pstartbyte;
708
709 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000710 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000711 /* Compute correction for 2's comp, if needed. */
712 if (is_signed) {
713 thisbyte = (0xff ^ thisbyte) + carry;
714 carry = thisbyte >> 8;
715 thisbyte &= 0xff;
716 }
717 /* Because we're going LSB to MSB, thisbyte is
718 more significant than what's already in accum,
719 so needs to be prepended to accum. */
720 accum |= thisbyte << accumbits;
721 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000722 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000723 /* There's enough to fill a Python digit. */
724 assert(idigit < (int)ndigits);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000725 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000726 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000727 accum >>= PyLong_SHIFT;
728 accumbits -= PyLong_SHIFT;
729 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000730 }
731 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000732 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000733 if (accumbits) {
734 assert(idigit < (int)ndigits);
735 v->ob_digit[idigit] = (digit)accum;
736 ++idigit;
737 }
738 }
739
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000740 Py_Size(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000741 return (PyObject *)long_normalize(v);
742}
743
744int
745_PyLong_AsByteArray(PyLongObject* v,
746 unsigned char* bytes, size_t n,
747 int little_endian, int is_signed)
748{
749 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000750 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000751 twodigits accum; /* sliding register */
752 unsigned int accumbits; /* # bits in accum */
753 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
754 twodigits carry; /* for computing 2's-comp */
755 size_t j; /* # bytes filled */
756 unsigned char* p; /* pointer to next byte in bytes */
757 int pincr; /* direction to move p */
758
759 assert(v != NULL && PyLong_Check(v));
760
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000761 if (Py_Size(v) < 0) {
762 ndigits = -(Py_Size(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000763 if (!is_signed) {
764 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000765 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000766 return -1;
767 }
768 do_twos_comp = 1;
769 }
770 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000771 ndigits = Py_Size(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000772 do_twos_comp = 0;
773 }
774
775 if (little_endian) {
776 p = bytes;
777 pincr = 1;
778 }
779 else {
780 p = bytes + n - 1;
781 pincr = -1;
782 }
783
Tim Peters898cf852001-06-13 20:50:08 +0000784 /* Copy over all the Python digits.
785 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000786 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000787 normalized. */
788 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000789 j = 0;
790 accum = 0;
791 accumbits = 0;
792 carry = do_twos_comp ? 1 : 0;
793 for (i = 0; i < ndigits; ++i) {
794 twodigits thisdigit = v->ob_digit[i];
795 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000796 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
797 carry = thisdigit >> PyLong_SHIFT;
798 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000799 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000800 /* Because we're going LSB to MSB, thisdigit is more
801 significant than what's already in accum, so needs to be
802 prepended to accum. */
803 accum |= thisdigit << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000804 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000805
Tim Petersede05092001-06-14 08:53:38 +0000806 /* The most-significant digit may be (probably is) at least
807 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000808 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000809 /* Count # of sign bits -- they needn't be stored,
810 * although for signed conversion we need later to
811 * make sure at least one sign bit gets stored.
812 * First shift conceptual sign bit to real sign bit.
813 */
814 stwodigits s = (stwodigits)(thisdigit <<
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000815 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000816 unsigned int nsignbits = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000817 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000818 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000819 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000820 }
Tim Petersede05092001-06-14 08:53:38 +0000821 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000822 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000823
Tim Peters2a9b3672001-06-11 21:23:58 +0000824 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000825 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000826 if (j >= n)
827 goto Overflow;
828 ++j;
829 *p = (unsigned char)(accum & 0xff);
830 p += pincr;
831 accumbits -= 8;
832 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000833 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000834 }
835
836 /* Store the straggler (if any). */
837 assert(accumbits < 8);
838 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000839 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000840 if (j >= n)
841 goto Overflow;
842 ++j;
843 if (do_twos_comp) {
844 /* Fill leading bits of the byte with sign bits
845 (appropriately pretending that the long had an
846 infinite supply of sign bits). */
847 accum |= (~(twodigits)0) << accumbits;
848 }
849 *p = (unsigned char)(accum & 0xff);
850 p += pincr;
851 }
Tim Peters05607ad2001-06-13 21:01:27 +0000852 else if (j == n && n > 0 && is_signed) {
853 /* The main loop filled the byte array exactly, so the code
854 just above didn't get to ensure there's a sign bit, and the
855 loop below wouldn't add one either. Make sure a sign bit
856 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000857 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000858 int sign_bit_set = msb >= 0x80;
859 assert(accumbits == 0);
860 if (sign_bit_set == do_twos_comp)
861 return 0;
862 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000863 goto Overflow;
864 }
Tim Peters05607ad2001-06-13 21:01:27 +0000865
866 /* Fill remaining bytes with copies of the sign bit. */
867 {
868 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
869 for ( ; j < n; ++j, p += pincr)
870 *p = signbyte;
871 }
872
Tim Peters2a9b3672001-06-11 21:23:58 +0000873 return 0;
874
875Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000876 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000877 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000878
Tim Peters2a9b3672001-06-11 21:23:58 +0000879}
880
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000881double
882_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
883{
884/* NBITS_WANTED should be > the number of bits in a double's precision,
885 but small enough so that 2**NBITS_WANTED is within the normal double
886 range. nbitsneeded is set to 1 less than that because the most-significant
887 Python digit contains at least 1 significant bit, but we don't want to
888 bother counting them (catering to the worst case cheaply).
889
890 57 is one more than VAX-D double precision; I (Tim) don't know of a double
891 format with more precision than that; it's 1 larger so that we add in at
892 least one round bit to stand in for the ignored least-significant bits.
893*/
894#define NBITS_WANTED 57
895 PyLongObject *v;
896 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000897 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000898 Py_ssize_t i;
899 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000900 int nbitsneeded;
901
902 if (vv == NULL || !PyLong_Check(vv)) {
903 PyErr_BadInternalCall();
904 return -1;
905 }
906 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000907 i = Py_Size(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000908 sign = 1;
909 if (i < 0) {
910 sign = -1;
911 i = -(i);
912 }
913 else if (i == 0) {
914 *exponent = 0;
915 return 0.0;
916 }
917 --i;
918 x = (double)v->ob_digit[i];
919 nbitsneeded = NBITS_WANTED - 1;
920 /* Invariant: i Python digits remain unaccounted for. */
921 while (i > 0 && nbitsneeded > 0) {
922 --i;
923 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000924 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000925 }
926 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000927 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000928 *exponent = i;
929 assert(x > 0.0);
930 return x * sign;
931#undef NBITS_WANTED
932}
933
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000934/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000935
936double
Tim Peters9f688bf2000-07-07 15:53:28 +0000937PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000938{
Thomas Wouters553489a2006-02-01 21:32:04 +0000939 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000940 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000941
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000942 if (vv == NULL || !PyLong_Check(vv)) {
943 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000944 return -1;
945 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000946 x = _PyLong_AsScaledDouble(vv, &e);
947 if (x == -1.0 && PyErr_Occurred())
948 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000949 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
950 set correctly after a successful _PyLong_AsScaledDouble() call */
951 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000952 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000953 goto overflow;
954 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000955 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000956 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000957 goto overflow;
958 return x;
959
960overflow:
961 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000962 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000963 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000964}
965
Guido van Rossum78694d91998-09-18 14:14:13 +0000966/* Create a new long (or int) object from a C pointer */
967
968PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000969PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000970{
Tim Peters70128a12001-06-16 08:48:40 +0000971#ifndef HAVE_LONG_LONG
972# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
973#endif
974#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000975# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000976#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000977 /* special-case null pointer */
978 if (!p)
Tim Peters70128a12001-06-16 08:48:40 +0000979 return PyInt_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000980 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000981
Guido van Rossum78694d91998-09-18 14:14:13 +0000982}
983
984/* Get a C pointer from a long object (or an int object in some cases) */
985
986void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000987PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000988{
989 /* This function will allow int or long objects. If vv is neither,
990 then the PyLong_AsLong*() functions will raise the exception:
991 PyExc_SystemError, "bad argument to internal function"
992 */
Tim Peters70128a12001-06-16 08:48:40 +0000993#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000994 long x;
995
Guido van Rossumddefaf32007-01-14 03:31:43 +0000996 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000997 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000998 else
999 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001000#else
Tim Peters70128a12001-06-16 08:48:40 +00001001
1002#ifndef HAVE_LONG_LONG
1003# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1004#endif
1005#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001006# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001007#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001008 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001009
Guido van Rossumddefaf32007-01-14 03:31:43 +00001010 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001011 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001012 else
1013 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001014
1015#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001016
1017 if (x == -1 && PyErr_Occurred())
1018 return NULL;
1019 return (void *)x;
1020}
1021
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001022#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001023
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001024/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001025 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001026 */
1027
Tim Peterscf37dfc2001-06-14 18:42:50 +00001028#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001029
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001030/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001031
1032PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001033PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001034{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001035 PyLongObject *v;
1036 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1037 int ndigits = 0;
1038 int negative = 0;
1039
Guido van Rossumddefaf32007-01-14 03:31:43 +00001040 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041 if (ival < 0) {
1042 ival = -ival;
1043 negative = 1;
1044 }
1045
1046 /* Count the number of Python digits.
1047 We used to pick 5 ("big enough for anything"), but that's a
1048 waste of time and space given that 5*15 = 75 bits are rarely
1049 needed. */
1050 t = (unsigned PY_LONG_LONG)ival;
1051 while (t) {
1052 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001053 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001054 }
1055 v = _PyLong_New(ndigits);
1056 if (v != NULL) {
1057 digit *p = v->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001058 Py_Size(v) = negative ? -ndigits : ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001059 t = (unsigned PY_LONG_LONG)ival;
1060 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001061 *p++ = (digit)(t & PyLong_MASK);
1062 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001063 }
1064 }
1065 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001066}
1067
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001068/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001069
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001070PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001071PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001072{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001073 PyLongObject *v;
1074 unsigned PY_LONG_LONG t;
1075 int ndigits = 0;
1076
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001077 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001078 return PyLong_FromLong(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079 /* Count the number of Python digits. */
1080 t = (unsigned PY_LONG_LONG)ival;
1081 while (t) {
1082 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001083 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084 }
1085 v = _PyLong_New(ndigits);
1086 if (v != NULL) {
1087 digit *p = v->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001088 Py_Size(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001089 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001090 *p++ = (digit)(ival & PyLong_MASK);
1091 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001092 }
1093 }
1094 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001095}
1096
Martin v. Löwis18e16552006-02-15 17:27:45 +00001097/* Create a new long int object from a C Py_ssize_t. */
1098
1099PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001100PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001101{
1102 Py_ssize_t bytes = ival;
1103 int one = 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001104 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001105 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001106 return _PyLong_FromByteArray(
1107 (unsigned char *)&bytes,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001108 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001109}
1110
1111/* Create a new long int object from a C size_t. */
1112
1113PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001114PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001115{
1116 size_t bytes = ival;
1117 int one = 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001118 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001119 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001120 return _PyLong_FromByteArray(
1121 (unsigned char *)&bytes,
1122 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
1123}
1124
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001125/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001126 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001127
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001128PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001129PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001130{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001131 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001132 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001133 int one = 1;
1134 int res;
1135
Tim Petersd38b1c72001-09-30 05:09:37 +00001136 if (vv == NULL) {
1137 PyErr_BadInternalCall();
1138 return -1;
1139 }
1140 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001141 PyNumberMethods *nb;
1142 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001143 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1144 nb->nb_int == NULL) {
1145 PyErr_SetString(PyExc_TypeError, "an integer is required");
1146 return -1;
1147 }
1148 io = (*nb->nb_int) (vv);
1149 if (io == NULL)
1150 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001151 if (PyLong_Check(io)) {
1152 bytes = PyLong_AsLongLong(io);
1153 Py_DECREF(io);
1154 return bytes;
1155 }
1156 Py_DECREF(io);
1157 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001158 return -1;
1159 }
1160
Guido van Rossumddefaf32007-01-14 03:31:43 +00001161 v = (PyLongObject*)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001162 switch(Py_Size(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001163 case -1: return -v->ob_digit[0];
1164 case 0: return 0;
1165 case 1: return v->ob_digit[0];
1166 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001167 res = _PyLong_AsByteArray(
1168 (PyLongObject *)vv, (unsigned char *)&bytes,
1169 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001170
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001171 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001172 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001173 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001174 else
1175 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001176}
1177
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001178/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001179 Return -1 and set an error if overflow occurs. */
1180
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001181unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001182PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001183{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001184 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001185 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001186 int one = 1;
1187 int res;
1188
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001189 if (vv == NULL || !PyLong_Check(vv)) {
1190 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001191 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001192 }
1193
Guido van Rossumddefaf32007-01-14 03:31:43 +00001194 v = (PyLongObject*)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001195 switch(Py_Size(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001196 case 0: return 0;
1197 case 1: return v->ob_digit[0];
1198 }
1199
Tim Petersd1a7da62001-06-13 00:35:57 +00001200 res = _PyLong_AsByteArray(
1201 (PyLongObject *)vv, (unsigned char *)&bytes,
1202 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001203
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001204 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001205 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001206 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001207 else
1208 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001209}
Tim Petersd1a7da62001-06-13 00:35:57 +00001210
Thomas Hellera4ea6032003-04-17 18:55:45 +00001211/* Get a C unsigned long int from a long int object, ignoring the high bits.
1212 Returns -1 and sets an error condition if an error occurs. */
1213
Guido van Rossumddefaf32007-01-14 03:31:43 +00001214static unsigned PY_LONG_LONG
1215_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001216{
1217 register PyLongObject *v;
1218 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001219 Py_ssize_t i;
1220 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001221
1222 if (vv == NULL || !PyLong_Check(vv)) {
1223 PyErr_BadInternalCall();
1224 return (unsigned long) -1;
1225 }
1226 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001227 switch(Py_Size(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001228 case 0: return 0;
1229 case 1: return v->ob_digit[0];
1230 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001231 i = Py_Size(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001232 sign = 1;
1233 x = 0;
1234 if (i < 0) {
1235 sign = -1;
1236 i = -i;
1237 }
1238 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001239 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001240 }
1241 return x * sign;
1242}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001243
1244unsigned PY_LONG_LONG
1245PyLong_AsUnsignedLongLongMask(register PyObject *op)
1246{
1247 PyNumberMethods *nb;
1248 PyLongObject *lo;
1249 unsigned PY_LONG_LONG val;
1250
1251 if (op && PyLong_Check(op))
1252 return _PyLong_AsUnsignedLongLongMask(op);
1253
1254 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1255 nb->nb_int == NULL) {
1256 PyErr_SetString(PyExc_TypeError, "an integer is required");
1257 return (unsigned PY_LONG_LONG)-1;
1258 }
1259
1260 lo = (PyLongObject*) (*nb->nb_int) (op);
1261 if (lo == NULL)
1262 return (unsigned PY_LONG_LONG)-1;
1263 if (PyLong_Check(lo)) {
1264 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1265 Py_DECREF(lo);
1266 if (PyErr_Occurred())
1267 return (unsigned PY_LONG_LONG)-1;
1268 return val;
1269 }
1270 else
1271 {
1272 Py_DECREF(lo);
1273 PyErr_SetString(PyExc_TypeError,
1274 "nb_int should return int object");
1275 return (unsigned PY_LONG_LONG)-1;
1276 }
1277}
Tim Petersd1a7da62001-06-13 00:35:57 +00001278#undef IS_LITTLE_ENDIAN
1279
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001280#endif /* HAVE_LONG_LONG */
1281
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001282#define CHECK_BINOP(v,w) \
1283 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001284 Py_INCREF(Py_NotImplemented); \
1285 return Py_NotImplemented; \
1286 }
1287
Tim Peters877a2122002-08-12 05:09:36 +00001288/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1289 * is modified in place, by adding y to it. Carries are propagated as far as
1290 * x[m-1], and the remaining carry (0 or 1) is returned.
1291 */
1292static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001293v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001294{
1295 int i;
1296 digit carry = 0;
1297
1298 assert(m >= n);
1299 for (i = 0; i < n; ++i) {
1300 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001301 x[i] = carry & PyLong_MASK;
1302 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001303 assert((carry & 1) == carry);
1304 }
1305 for (; carry && i < m; ++i) {
1306 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001307 x[i] = carry & PyLong_MASK;
1308 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001309 assert((carry & 1) == carry);
1310 }
1311 return carry;
1312}
1313
1314/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1315 * is modified in place, by subtracting y from it. Borrows are propagated as
1316 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1317 */
1318static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001319v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001320{
1321 int i;
1322 digit borrow = 0;
1323
1324 assert(m >= n);
1325 for (i = 0; i < n; ++i) {
1326 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001327 x[i] = borrow & PyLong_MASK;
1328 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001329 borrow &= 1; /* keep only 1 sign bit */
1330 }
1331 for (; borrow && i < m; ++i) {
1332 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001333 x[i] = borrow & PyLong_MASK;
1334 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001335 borrow &= 1;
1336 }
1337 return borrow;
1338}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001339
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001340/* Multiply by a single digit, ignoring the sign. */
1341
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001342static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001343mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001344{
1345 return muladd1(a, n, (digit)0);
1346}
1347
1348/* Multiply by a single digit and add a single digit, ignoring the sign. */
1349
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001350static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001351muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001352{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001353 Py_ssize_t size_a = ABS(Py_Size(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001354 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001355 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001356 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001357
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001358 if (z == NULL)
1359 return NULL;
1360 for (i = 0; i < size_a; ++i) {
1361 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001362 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1363 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001364 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001365 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001366 return long_normalize(z);
1367}
1368
Tim Peters212e6142001-07-14 12:23:19 +00001369/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1370 in pout, and returning the remainder. pin and pout point at the LSD.
1371 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001372 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001373 immutable. */
1374
1375static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001376inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001377{
1378 twodigits rem = 0;
1379
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001380 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001381 pin += size;
1382 pout += size;
1383 while (--size >= 0) {
1384 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001385 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001386 *--pout = hi = (digit)(rem / n);
1387 rem -= hi * n;
1388 }
1389 return (digit)rem;
1390}
1391
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001392/* Divide a long integer by a digit, returning both the quotient
1393 (as function result) and the remainder (through *prem).
1394 The sign of a is ignored; n should not be zero. */
1395
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001396static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001397divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001398{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001399 const Py_ssize_t size = ABS(Py_Size(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001400 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001401
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001402 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001403 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001404 if (z == NULL)
1405 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001406 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001407 return long_normalize(z);
1408}
1409
1410/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001411 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001412 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001413
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001414PyObject *
1415_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001416{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001417 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001418 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001419 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001420 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001421 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001422 int bits;
1423 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001424
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001425 if (a == NULL || !PyLong_Check(a)) {
1426 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001427 return NULL;
1428 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001429 assert(base >= 2 && base <= 36);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001430 size_a = ABS(Py_Size(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001431
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001432 /* Compute a rough upper bound for the length of the string */
1433 i = base;
1434 bits = 0;
1435 while (i > 1) {
1436 ++bits;
1437 i >>= 1;
1438 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001439 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001440 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001441 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001442 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001443 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001444 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001445 return NULL;
1446 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001447 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001448 if (str == NULL)
1449 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001450 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001451 *p = '\0';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001452 if (Py_Size(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001453 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001454
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001455 if (Py_Size(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001456 *--p = '0';
1457 }
1458 else if ((base & (base - 1)) == 0) {
1459 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001460 twodigits accum = 0;
1461 int accumbits = 0; /* # of bits in accum */
1462 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001463 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001464 while ((i >>= 1) > 1)
1465 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001466
1467 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001468 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001469 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001470 assert(accumbits >= basebits);
1471 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001472 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001473 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001474 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001475 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001476 accumbits -= basebits;
1477 accum >>= basebits;
1478 } while (i < size_a-1 ? accumbits >= basebits :
1479 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001480 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001481 }
1482 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001483 /* Not 0, and base not a power of 2. Divide repeatedly by
1484 base, but for speed use the highest power of base that
1485 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001486 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001487 digit *pin = a->ob_digit;
1488 PyLongObject *scratch;
1489 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001490 digit powbase = base; /* powbase == base ** power */
1491 int power = 1;
1492 for (;;) {
1493 unsigned long newpow = powbase * (unsigned long)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001494 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001495 break;
1496 powbase = (digit)newpow;
1497 ++power;
1498 }
Tim Peters212e6142001-07-14 12:23:19 +00001499
1500 /* Get a scratch area for repeated division. */
1501 scratch = _PyLong_New(size);
1502 if (scratch == NULL) {
1503 Py_DECREF(str);
1504 return NULL;
1505 }
1506
1507 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001508 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001509 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001510 digit rem = inplace_divrem1(scratch->ob_digit,
1511 pin, size, powbase);
1512 pin = scratch->ob_digit; /* no need to use a again */
1513 if (pin[size - 1] == 0)
1514 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001515 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001516 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001517 Py_DECREF(str);
1518 return NULL;
1519 })
Tim Peters212e6142001-07-14 12:23:19 +00001520
1521 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001522 assert(ntostore > 0);
1523 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001524 digit nextrem = (digit)(rem / base);
1525 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001526 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001527 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001528 *--p = c;
1529 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001530 --ntostore;
1531 /* Termination is a bit delicate: must not
1532 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001533 remaining quotient and rem are both 0. */
1534 } while (ntostore && (size || rem));
1535 } while (size != 0);
1536 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001537 }
1538
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001539 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001540 *--p = 'x';
1541 *--p = '0';
1542 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001543 else if (base == 8) {
1544 *--p = 'o';
1545 *--p = '0';
1546 }
1547 else if (base == 2) {
1548 *--p = 'b';
1549 *--p = '0';
1550 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001551 else if (base != 10) {
1552 *--p = '#';
1553 *--p = '0' + base%10;
1554 if (base > 10)
1555 *--p = '0' + base/10;
1556 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001557 if (sign)
1558 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001559 if (p != PyUnicode_AS_UNICODE(str)) {
1560 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001561 assert(p > q);
1562 do {
1563 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001564 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001565 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1566 Py_DECREF(str);
1567 return NULL;
1568 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001569 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001570 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001571}
1572
Thomas Wouters477c8d52006-05-27 19:21:47 +00001573/* Table of digit values for 8-bit string -> integer conversion.
1574 * '0' maps to 0, ..., '9' maps to 9.
1575 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1576 * All other indices map to 37.
1577 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001578 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001579 */
1580int _PyLong_DigitValue[256] = {
1581 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1582 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1583 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1584 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1585 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1586 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1587 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1588 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1589 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1590 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1591 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1592 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1593 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1594 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1595 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1596 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1597};
1598
1599/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001600 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1601 * non-digit (which may be *str!). A normalized long is returned.
1602 * The point to this routine is that it takes time linear in the number of
1603 * string characters.
1604 */
1605static PyLongObject *
1606long_from_binary_base(char **str, int base)
1607{
1608 char *p = *str;
1609 char *start = p;
1610 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001611 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001612 PyLongObject *z;
1613 twodigits accum;
1614 int bits_in_accum;
1615 digit *pdigit;
1616
1617 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1618 n = base;
1619 for (bits_per_char = -1; n; ++bits_per_char)
1620 n >>= 1;
1621 /* n <- total # of bits needed, while setting p to end-of-string */
1622 n = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001623 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001624 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001625 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001626 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1627 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001628 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001629 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001630 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001631 return NULL;
1632 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001633 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001634 z = _PyLong_New(n);
1635 if (z == NULL)
1636 return NULL;
1637 /* Read string from right, and fill in long from left; i.e.,
1638 * from least to most significant in both.
1639 */
1640 accum = 0;
1641 bits_in_accum = 0;
1642 pdigit = z->ob_digit;
1643 while (--p >= start) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001644 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001645 assert(k >= 0 && k < base);
1646 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001647 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001648 if (bits_in_accum >= PyLong_SHIFT) {
1649 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001650 assert(pdigit - z->ob_digit <= (int)n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001651 accum >>= PyLong_SHIFT;
1652 bits_in_accum -= PyLong_SHIFT;
1653 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001654 }
1655 }
1656 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001657 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001658 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001659 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001660 }
1661 while (pdigit - z->ob_digit < n)
1662 *pdigit++ = 0;
1663 return long_normalize(z);
1664}
1665
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001666PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001667PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001668{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001669 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001670 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001671 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001672 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001673 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001674
Guido van Rossum472c04f1996-12-05 21:57:21 +00001675 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001676 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001677 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001678 return NULL;
1679 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001680 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001681 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001682 if (*str == '+')
1683 ++str;
1684 else if (*str == '-') {
1685 ++str;
1686 sign = -1;
1687 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001688 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001689 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001690 if (base == 0) {
1691 if (str[0] != '0')
1692 base = 10;
1693 else if (str[1] == 'x' || str[1] == 'X')
1694 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001695 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001696 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001697 else if (str[1] == 'b' || str[1] == 'B')
1698 base = 2;
1699 else {
1700 /* "old" (C-style) octal literal, now invalid.
1701 it might still be zero though */
1702 error_if_nonzero = 1;
1703 base = 10;
1704 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001705 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001706 if (str[0] == '0' &&
1707 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1708 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1709 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001710 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001711
Guido van Rossume6762971998-06-22 03:54:46 +00001712 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001713 if ((base & (base - 1)) == 0)
1714 z = long_from_binary_base(&str, base);
1715 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001716/***
1717Binary bases can be converted in time linear in the number of digits, because
1718Python's representation base is binary. Other bases (including decimal!) use
1719the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001720
Thomas Wouters477c8d52006-05-27 19:21:47 +00001721First some math: the largest integer that can be expressed in N base-B digits
1722is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1723case number of Python digits needed to hold it is the smallest integer n s.t.
1724
1725 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1726 BASE**n >= B**N [taking logs to base BASE]
1727 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1728
1729The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1730this quickly. A Python long with that much space is reserved near the start,
1731and the result is computed into it.
1732
1733The input string is actually treated as being in base base**i (i.e., i digits
1734are processed at a time), where two more static arrays hold:
1735
1736 convwidth_base[base] = the largest integer i such that base**i <= BASE
1737 convmultmax_base[base] = base ** convwidth_base[base]
1738
1739The first of these is the largest i such that i consecutive input digits
1740must fit in a single Python digit. The second is effectively the input
1741base we're really using.
1742
1743Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1744convmultmax_base[base], the result is "simply"
1745
1746 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1747
1748where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001749
1750Error analysis: as above, the number of Python digits `n` needed is worst-
1751case
1752
1753 n >= N * log(B)/log(BASE)
1754
1755where `N` is the number of input digits in base `B`. This is computed via
1756
1757 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1758
1759below. Two numeric concerns are how much space this can waste, and whether
1760the computed result can be too small. To be concrete, assume BASE = 2**15,
1761which is the default (and it's unlikely anyone changes that).
1762
1763Waste isn't a problem: provided the first input digit isn't 0, the difference
1764between the worst-case input with N digits and the smallest input with N
1765digits is about a factor of B, but B is small compared to BASE so at most
1766one allocated Python digit can remain unused on that count. If
1767N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1768and adding 1 returns a result 1 larger than necessary. However, that can't
1769happen: whenever B is a power of 2, long_from_binary_base() is called
1770instead, and it's impossible for B**i to be an integer power of 2**15 when
1771B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1772an exact integer when B is not a power of 2, since B**i has a prime factor
1773other than 2 in that case, but (2**15)**j's only prime factor is 2).
1774
1775The computed result can be too small if the true value of N*log(B)/log(BASE)
1776is a little bit larger than an exact integer, but due to roundoff errors (in
1777computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1778yields a numeric result a little less than that integer. Unfortunately, "how
1779close can a transcendental function get to an integer over some range?"
1780questions are generally theoretically intractable. Computer analysis via
1781continued fractions is practical: expand log(B)/log(BASE) via continued
1782fractions, giving a sequence i/j of "the best" rational approximations. Then
1783j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1784we can get very close to being in trouble, but very rarely. For example,
178576573 is a denominator in one of the continued-fraction approximations to
1786log(10)/log(2**15), and indeed:
1787
1788 >>> log(10)/log(2**15)*76573
1789 16958.000000654003
1790
1791is very close to an integer. If we were working with IEEE single-precision,
1792rounding errors could kill us. Finding worst cases in IEEE double-precision
1793requires better-than-double-precision log() functions, and Tim didn't bother.
1794Instead the code checks to see whether the allocated space is enough as each
1795new Python digit is added, and copies the whole thing to a larger long if not.
1796This should happen extremely rarely, and in fact I don't have a test case
1797that triggers it(!). Instead the code was tested by artificially allocating
1798just 1 digit at the start, so that the copying code was exercised for every
1799digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001800***/
1801 register twodigits c; /* current input character */
1802 Py_ssize_t size_z;
1803 int i;
1804 int convwidth;
1805 twodigits convmultmax, convmult;
1806 digit *pz, *pzstop;
1807 char* scan;
1808
1809 static double log_base_BASE[37] = {0.0e0,};
1810 static int convwidth_base[37] = {0,};
1811 static twodigits convmultmax_base[37] = {0,};
1812
1813 if (log_base_BASE[base] == 0.0) {
1814 twodigits convmax = base;
1815 int i = 1;
1816
1817 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001818 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001819 for (;;) {
1820 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001821 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001822 break;
1823 convmax = next;
1824 ++i;
1825 }
1826 convmultmax_base[base] = convmax;
1827 assert(i > 0);
1828 convwidth_base[base] = i;
1829 }
1830
1831 /* Find length of the string of numeric characters. */
1832 scan = str;
1833 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1834 ++scan;
1835
1836 /* Create a long object that can contain the largest possible
1837 * integer with this base and length. Note that there's no
1838 * need to initialize z->ob_digit -- no slot is read up before
1839 * being stored into.
1840 */
1841 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001842 /* Uncomment next line to test exceedingly rare copy code */
1843 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001844 assert(size_z > 0);
1845 z = _PyLong_New(size_z);
1846 if (z == NULL)
1847 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001848 Py_Size(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001849
1850 /* `convwidth` consecutive input digits are treated as a single
1851 * digit in base `convmultmax`.
1852 */
1853 convwidth = convwidth_base[base];
1854 convmultmax = convmultmax_base[base];
1855
1856 /* Work ;-) */
1857 while (str < scan) {
1858 /* grab up to convwidth digits from the input string */
1859 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1860 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1861 c = (twodigits)(c * base +
1862 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001863 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001864 }
1865
1866 convmult = convmultmax;
1867 /* Calculate the shift only if we couldn't get
1868 * convwidth digits.
1869 */
1870 if (i != convwidth) {
1871 convmult = base;
1872 for ( ; i > 1; --i)
1873 convmult *= base;
1874 }
1875
1876 /* Multiply z by convmult, and add c. */
1877 pz = z->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001878 pzstop = pz + Py_Size(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001879 for (; pz < pzstop; ++pz) {
1880 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001881 *pz = (digit)(c & PyLong_MASK);
1882 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001883 }
1884 /* carry off the current end? */
1885 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001886 assert(c < PyLong_BASE);
1887 if (Py_Size(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001888 *pz = (digit)c;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001889 ++Py_Size(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001890 }
1891 else {
1892 PyLongObject *tmp;
1893 /* Extremely rare. Get more space. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001894 assert(Py_Size(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001895 tmp = _PyLong_New(size_z + 1);
1896 if (tmp == NULL) {
1897 Py_DECREF(z);
1898 return NULL;
1899 }
1900 memcpy(tmp->ob_digit,
1901 z->ob_digit,
1902 sizeof(digit) * size_z);
1903 Py_DECREF(z);
1904 z = tmp;
1905 z->ob_digit[size_z] = (digit)c;
1906 ++size_z;
1907 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001908 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001909 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001910 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001911 if (z == NULL)
1912 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001913 if (error_if_nonzero) {
1914 /* reset the base to 0, else the exception message
1915 doesn't make too much sense */
1916 base = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001917 if (Py_Size(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001918 goto onError;
1919 /* there might still be other problems, therefore base
1920 remains zero here for the same reason */
1921 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001922 if (str == start)
1923 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001924 if (sign < 0)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001925 Py_Size(z) = -(Py_Size(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001926 if (*str == 'L' || *str == 'l')
1927 str++;
1928 while (*str && isspace(Py_CHARMASK(*str)))
1929 str++;
1930 if (*str != '\0')
1931 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001932 if (pend)
1933 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001934 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001935
1936 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001937 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001938 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00001939 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001940 if (strobj == NULL)
1941 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001942 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00001943 "invalid literal for int() with base %d: %R",
1944 base, strobj);
1945 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001946 return NULL;
1947}
1948
1949PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001950PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001951{
Walter Dörwald07e14762002-11-06 16:15:14 +00001952 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001953 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001954
Walter Dörwald07e14762002-11-06 16:15:14 +00001955 if (buffer == NULL)
1956 return NULL;
1957
1958 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1959 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001960 return NULL;
1961 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001962 result = PyLong_FromString(buffer, NULL, base);
1963 PyMem_FREE(buffer);
1964 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001965}
1966
Tim Peters9f688bf2000-07-07 15:53:28 +00001967/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001968static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001969 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001970static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00001971static int long_divrem(PyLongObject *, PyLongObject *,
1972 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001973
1974/* Long division with remainder, top-level routine */
1975
Guido van Rossume32e0141992-01-19 16:31:05 +00001976static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001977long_divrem(PyLongObject *a, PyLongObject *b,
1978 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001979{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001980 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001981 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001982
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001983 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001984 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001985 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001986 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001987 }
1988 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001989 (size_a == size_b &&
1990 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001991 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00001992 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001993 if (*pdiv == NULL)
1994 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001995 Py_INCREF(a);
1996 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001997 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001998 }
1999 if (size_b == 1) {
2000 digit rem = 0;
2001 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002002 if (z == NULL)
2003 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002004 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002005 if (*prem == NULL) {
2006 Py_DECREF(z);
2007 return -1;
2008 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002009 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002010 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002011 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002012 if (z == NULL)
2013 return -1;
2014 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002015 /* Set the signs.
2016 The quotient z has the sign of a*b;
2017 the remainder r has the sign of a,
2018 so a = b*z + r. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002019 if ((Py_Size(a) < 0) != (Py_Size(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002020 NEGATE(z);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002021 if (Py_Size(a) < 0 && Py_Size(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002022 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002023 *pdiv = z;
2024 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002025}
2026
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002027/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002028
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002029static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002030x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002031{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002032 Py_ssize_t size_v = ABS(Py_Size(v1)), size_w = ABS(Py_Size(w1));
2033 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002034 PyLongObject *v = mul1(v1, d);
2035 PyLongObject *w = mul1(w1, d);
2036 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002037 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002038
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002039 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002040 Py_XDECREF(v);
2041 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002042 return NULL;
2043 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002044
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002045 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002046 assert(Py_Refcnt(v) == 1); /* Since v will be used as accumulator! */
2047 assert(size_w == ABS(Py_Size(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002048
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002049 size_v = ABS(Py_Size(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002050 k = size_v - size_w;
2051 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002052
Thomas Wouters477c8d52006-05-27 19:21:47 +00002053 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002054 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2055 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002056 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002057 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002058
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002059 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002060 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002061 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002062 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002063 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002064 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002065 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002066 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002067 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002068 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002069
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002070 while (w->ob_digit[size_w-2]*q >
2071 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002072 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002073 + v->ob_digit[j-1]
2074 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002075 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002076 + v->ob_digit[j-2])
2077 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002078
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079 for (i = 0; i < size_w && i+k < size_v; ++i) {
2080 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002081 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002082 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002083 + ((twodigits)zz << PyLong_SHIFT);
2084 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002085 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002086 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002087 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002088 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002089
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090 if (i+k < size_v) {
2091 carry += v->ob_digit[i+k];
2092 v->ob_digit[i+k] = 0;
2093 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002094
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002095 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002096 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002097 else {
2098 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002099 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002100 carry = 0;
2101 for (i = 0; i < size_w && i+k < size_v; ++i) {
2102 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002103 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002104 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2105 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002106 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002107 }
2108 }
2109 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002110
Guido van Rossumc206c761995-01-10 15:23:19 +00002111 if (a == NULL)
2112 *prem = NULL;
2113 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002114 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002115 *prem = divrem1(v, d, &d);
2116 /* d receives the (unused) remainder */
2117 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002118 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002119 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002120 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002121 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002122 Py_DECREF(v);
2123 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002124 return a;
2125}
2126
2127/* Methods */
2128
2129static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002130long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002131{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002132 Py_Type(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002133}
2134
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002135static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002136long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002137{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002138 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002139}
2140
2141static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002142long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002143{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002144 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002145
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002146 if (Py_Size(a) != Py_Size(b)) {
2147 if (ABS(Py_Size(a)) == 0 && ABS(Py_Size(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002148 sign = 0;
2149 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002150 sign = Py_Size(a) - Py_Size(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002151 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002152 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002153 Py_ssize_t i = ABS(Py_Size(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002154 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2155 ;
2156 if (i < 0)
2157 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002158 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002159 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002160 if (Py_Size(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002161 sign = -sign;
2162 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002163 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002164 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002165}
2166
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002167static PyObject *
2168long_richcompare(PyObject *self, PyObject *other, int op)
2169{
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002170 PyObject *result;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002171 CHECK_BINOP(self, other);
2172 result = Py_CmpToRich(op, long_compare((PyLongObject*)self,
2173 (PyLongObject*)other));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002174 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002175}
2176
Guido van Rossum9bfef441993-03-29 10:43:31 +00002177static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002178long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002179{
2180 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002181 Py_ssize_t i;
2182 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002183
2184 /* This is designed so that Python ints and longs with the
2185 same value hash to the same value, otherwise comparisons
2186 of mapping keys will turn out weird */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002187 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002188 switch(i) {
2189 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2190 case 0: return 0;
2191 case 1: return v->ob_digit[0];
2192 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002193 sign = 1;
2194 x = 0;
2195 if (i < 0) {
2196 sign = -1;
2197 i = -(i);
2198 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002199#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002200 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002201 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002202 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002203 x += v->ob_digit[i];
2204 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002205#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002206 x = x * sign;
2207 if (x == -1)
2208 x = -2;
2209 return x;
2210}
2211
2212
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002213/* Add the absolute values of two long integers. */
2214
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002215static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002216x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002217{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002218 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002219 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002220 int i;
2221 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002222
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002223 /* Ensure a is the larger of the two: */
2224 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002225 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002226 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002227 size_a = size_b;
2228 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002229 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002230 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002231 if (z == NULL)
2232 return NULL;
2233 for (i = 0; i < size_b; ++i) {
2234 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002235 z->ob_digit[i] = carry & PyLong_MASK;
2236 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002237 }
2238 for (; i < size_a; ++i) {
2239 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002240 z->ob_digit[i] = carry & PyLong_MASK;
2241 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002242 }
2243 z->ob_digit[i] = carry;
2244 return long_normalize(z);
2245}
2246
2247/* Subtract the absolute values of two integers. */
2248
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002249static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002250x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002251{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002252 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002253 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002254 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002255 int sign = 1;
2256 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002257
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002258 /* Ensure a is the larger of the two: */
2259 if (size_a < size_b) {
2260 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002261 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002262 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002263 size_a = size_b;
2264 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002265 }
2266 else if (size_a == size_b) {
2267 /* Find highest digit where a and b differ: */
2268 i = size_a;
2269 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2270 ;
2271 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002272 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002273 if (a->ob_digit[i] < b->ob_digit[i]) {
2274 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002275 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002276 }
2277 size_a = size_b = i+1;
2278 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002279 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002280 if (z == NULL)
2281 return NULL;
2282 for (i = 0; i < size_b; ++i) {
2283 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002284 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002285 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002286 z->ob_digit[i] = borrow & PyLong_MASK;
2287 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002288 borrow &= 1; /* Keep only one sign bit */
2289 }
2290 for (; i < size_a; ++i) {
2291 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002292 z->ob_digit[i] = borrow & PyLong_MASK;
2293 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002294 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002295 }
2296 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002297 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002298 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002299 return long_normalize(z);
2300}
2301
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002302static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002303long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002304{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002305 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002306
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002307 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002308
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002309 if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002310 PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) +
2311 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002312 return result;
2313 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002314 if (Py_Size(a) < 0) {
2315 if (Py_Size(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002316 z = x_add(a, b);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002317 if (z != NULL && Py_Size(z) != 0)
2318 Py_Size(z) = -(Py_Size(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002319 }
2320 else
2321 z = x_sub(b, a);
2322 }
2323 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002324 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002325 z = x_sub(a, b);
2326 else
2327 z = x_add(a, b);
2328 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002329 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002330}
2331
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002332static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002333long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002334{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002335 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002336
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002337 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002338
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002339 if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002340 PyObject* r;
2341 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002342 return r;
2343 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002344 if (Py_Size(a) < 0) {
2345 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002346 z = x_sub(a, b);
2347 else
2348 z = x_add(a, b);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002349 if (z != NULL && Py_Size(z) != 0)
2350 Py_Size(z) = -(Py_Size(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002351 }
2352 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002353 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002354 z = x_add(a, b);
2355 else
2356 z = x_sub(a, b);
2357 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002358 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002359}
2360
Tim Peters5af4e6c2002-08-12 02:31:19 +00002361/* Grade school multiplication, ignoring the signs.
2362 * Returns the absolute value of the product, or NULL if error.
2363 */
2364static PyLongObject *
2365x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002366{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002367 PyLongObject *z;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002368 Py_ssize_t size_a = ABS(Py_Size(a));
2369 Py_ssize_t size_b = ABS(Py_Size(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002370 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002371
Tim Peters5af4e6c2002-08-12 02:31:19 +00002372 z = _PyLong_New(size_a + size_b);
2373 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002374 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002375
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002376 memset(z->ob_digit, 0, Py_Size(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002377 if (a == b) {
2378 /* Efficient squaring per HAC, Algorithm 14.16:
2379 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2380 * Gives slightly less than a 2x speedup when a == b,
2381 * via exploiting that each entry in the multiplication
2382 * pyramid appears twice (except for the size_a squares).
2383 */
2384 for (i = 0; i < size_a; ++i) {
2385 twodigits carry;
2386 twodigits f = a->ob_digit[i];
2387 digit *pz = z->ob_digit + (i << 1);
2388 digit *pa = a->ob_digit + i + 1;
2389 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002390
Tim Peters0973b992004-08-29 22:16:50 +00002391 SIGCHECK({
2392 Py_DECREF(z);
2393 return NULL;
2394 })
2395
2396 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002397 *pz++ = (digit)(carry & PyLong_MASK);
2398 carry >>= PyLong_SHIFT;
2399 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002400
2401 /* Now f is added in twice in each column of the
2402 * pyramid it appears. Same as adding f<<1 once.
2403 */
2404 f <<= 1;
2405 while (pa < paend) {
2406 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002407 *pz++ = (digit)(carry & PyLong_MASK);
2408 carry >>= PyLong_SHIFT;
2409 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002410 }
2411 if (carry) {
2412 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002413 *pz++ = (digit)(carry & PyLong_MASK);
2414 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002415 }
2416 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002417 *pz += (digit)(carry & PyLong_MASK);
2418 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002419 }
Tim Peters0973b992004-08-29 22:16:50 +00002420 }
2421 else { /* a is not the same as b -- gradeschool long mult */
2422 for (i = 0; i < size_a; ++i) {
2423 twodigits carry = 0;
2424 twodigits f = a->ob_digit[i];
2425 digit *pz = z->ob_digit + i;
2426 digit *pb = b->ob_digit;
2427 digit *pbend = b->ob_digit + size_b;
2428
2429 SIGCHECK({
2430 Py_DECREF(z);
2431 return NULL;
2432 })
2433
2434 while (pb < pbend) {
2435 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002436 *pz++ = (digit)(carry & PyLong_MASK);
2437 carry >>= PyLong_SHIFT;
2438 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002439 }
2440 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002441 *pz += (digit)(carry & PyLong_MASK);
2442 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002443 }
2444 }
Tim Peters44121a62002-08-12 06:17:58 +00002445 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002446}
2447
2448/* A helper for Karatsuba multiplication (k_mul).
2449 Takes a long "n" and an integer "size" representing the place to
2450 split, and sets low and high such that abs(n) == (high << size) + low,
2451 viewing the shift as being by digits. The sign bit is ignored, and
2452 the return values are >= 0.
2453 Returns 0 on success, -1 on failure.
2454*/
2455static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002456kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002457{
2458 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002459 Py_ssize_t size_lo, size_hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002460 const Py_ssize_t size_n = ABS(Py_Size(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002461
2462 size_lo = MIN(size_n, size);
2463 size_hi = size_n - size_lo;
2464
2465 if ((hi = _PyLong_New(size_hi)) == NULL)
2466 return -1;
2467 if ((lo = _PyLong_New(size_lo)) == NULL) {
2468 Py_DECREF(hi);
2469 return -1;
2470 }
2471
2472 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2473 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2474
2475 *high = long_normalize(hi);
2476 *low = long_normalize(lo);
2477 return 0;
2478}
2479
Tim Peters60004642002-08-12 22:01:34 +00002480static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2481
Tim Peters5af4e6c2002-08-12 02:31:19 +00002482/* Karatsuba multiplication. Ignores the input signs, and returns the
2483 * absolute value of the product (or NULL if error).
2484 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2485 */
2486static PyLongObject *
2487k_mul(PyLongObject *a, PyLongObject *b)
2488{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002489 Py_ssize_t asize = ABS(Py_Size(a));
2490 Py_ssize_t bsize = ABS(Py_Size(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002491 PyLongObject *ah = NULL;
2492 PyLongObject *al = NULL;
2493 PyLongObject *bh = NULL;
2494 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002495 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002496 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002497 Py_ssize_t shift; /* the number of digits we split off */
2498 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002499
Tim Peters5af4e6c2002-08-12 02:31:19 +00002500 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2501 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2502 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002503 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002504 * By picking X to be a power of 2, "*X" is just shifting, and it's
2505 * been reduced to 3 multiplies on numbers half the size.
2506 */
2507
Tim Petersfc07e562002-08-12 02:54:10 +00002508 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002509 * is largest.
2510 */
Tim Peters738eda72002-08-12 15:08:20 +00002511 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002512 t1 = a;
2513 a = b;
2514 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002515
2516 i = asize;
2517 asize = bsize;
2518 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002519 }
2520
2521 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002522 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2523 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002524 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002525 return _PyLong_New(0);
2526 else
2527 return x_mul(a, b);
2528 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002529
Tim Peters60004642002-08-12 22:01:34 +00002530 /* If a is small compared to b, splitting on b gives a degenerate
2531 * case with ah==0, and Karatsuba may be (even much) less efficient
2532 * than "grade school" then. However, we can still win, by viewing
2533 * b as a string of "big digits", each of width a->ob_size. That
2534 * leads to a sequence of balanced calls to k_mul.
2535 */
2536 if (2 * asize <= bsize)
2537 return k_lopsided_mul(a, b);
2538
Tim Petersd6974a52002-08-13 20:37:51 +00002539 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002540 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002541 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002542 assert(Py_Size(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002543
Tim Peters0973b992004-08-29 22:16:50 +00002544 if (a == b) {
2545 bh = ah;
2546 bl = al;
2547 Py_INCREF(bh);
2548 Py_INCREF(bl);
2549 }
2550 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002551
Tim Petersd64c1de2002-08-12 17:36:03 +00002552 /* The plan:
2553 * 1. Allocate result space (asize + bsize digits: that's always
2554 * enough).
2555 * 2. Compute ah*bh, and copy into result at 2*shift.
2556 * 3. Compute al*bl, and copy into result at 0. Note that this
2557 * can't overlap with #2.
2558 * 4. Subtract al*bl from the result, starting at shift. This may
2559 * underflow (borrow out of the high digit), but we don't care:
2560 * we're effectively doing unsigned arithmetic mod
2561 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2562 * borrows and carries out of the high digit can be ignored.
2563 * 5. Subtract ah*bh from the result, starting at shift.
2564 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2565 * at shift.
2566 */
2567
2568 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002569 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002570 if (ret == NULL) goto fail;
2571#ifdef Py_DEBUG
2572 /* Fill with trash, to catch reference to uninitialized digits. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002573 memset(ret->ob_digit, 0xDF, Py_Size(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002574#endif
Tim Peters44121a62002-08-12 06:17:58 +00002575
Tim Petersd64c1de2002-08-12 17:36:03 +00002576 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002577 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002578 assert(Py_Size(t1) >= 0);
2579 assert(2*shift + Py_Size(t1) <= Py_Size(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002580 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002581 Py_Size(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002582
2583 /* Zero-out the digits higher than the ah*bh copy. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002584 i = Py_Size(ret) - 2*shift - Py_Size(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002585 if (i)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002586 memset(ret->ob_digit + 2*shift + Py_Size(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002587 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002588
Tim Petersd64c1de2002-08-12 17:36:03 +00002589 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002590 if ((t2 = k_mul(al, bl)) == NULL) {
2591 Py_DECREF(t1);
2592 goto fail;
2593 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002594 assert(Py_Size(t2) >= 0);
2595 assert(Py_Size(t2) <= 2*shift); /* no overlap with high digits */
2596 memcpy(ret->ob_digit, t2->ob_digit, Py_Size(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002597
2598 /* Zero out remaining digits. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002599 i = 2*shift - Py_Size(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002600 if (i)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002601 memset(ret->ob_digit + Py_Size(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002602
Tim Petersd64c1de2002-08-12 17:36:03 +00002603 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2604 * because it's fresher in cache.
2605 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002606 i = Py_Size(ret) - shift; /* # digits after shift */
2607 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_Size(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002608 Py_DECREF(t2);
2609
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002610 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_Size(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002611 Py_DECREF(t1);
2612
Tim Petersd64c1de2002-08-12 17:36:03 +00002613 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002614 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2615 Py_DECREF(ah);
2616 Py_DECREF(al);
2617 ah = al = NULL;
2618
Tim Peters0973b992004-08-29 22:16:50 +00002619 if (a == b) {
2620 t2 = t1;
2621 Py_INCREF(t2);
2622 }
2623 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002624 Py_DECREF(t1);
2625 goto fail;
2626 }
2627 Py_DECREF(bh);
2628 Py_DECREF(bl);
2629 bh = bl = NULL;
2630
Tim Peters738eda72002-08-12 15:08:20 +00002631 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002632 Py_DECREF(t1);
2633 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002634 if (t3 == NULL) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002635 assert(Py_Size(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002636
Tim Petersd6974a52002-08-13 20:37:51 +00002637 /* Add t3. It's not obvious why we can't run out of room here.
2638 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002639 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002640 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_Size(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002641 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002642
Tim Peters5af4e6c2002-08-12 02:31:19 +00002643 return long_normalize(ret);
2644
2645 fail:
2646 Py_XDECREF(ret);
2647 Py_XDECREF(ah);
2648 Py_XDECREF(al);
2649 Py_XDECREF(bh);
2650 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002651 return NULL;
2652}
2653
Tim Petersd6974a52002-08-13 20:37:51 +00002654/* (*) Why adding t3 can't "run out of room" above.
2655
Tim Petersab86c2b2002-08-15 20:06:00 +00002656Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2657to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002658
Tim Petersab86c2b2002-08-15 20:06:00 +000026591. For any integer i, i = c(i/2) + f(i/2). In particular,
2660 bsize = c(bsize/2) + f(bsize/2).
26612. shift = f(bsize/2)
26623. asize <= bsize
26634. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2664 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002665
Tim Petersab86c2b2002-08-15 20:06:00 +00002666We allocated asize + bsize result digits, and add t3 into them at an offset
2667of shift. This leaves asize+bsize-shift allocated digit positions for t3
2668to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2669asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002670
Tim Petersab86c2b2002-08-15 20:06:00 +00002671bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2672at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002673
Tim Petersab86c2b2002-08-15 20:06:00 +00002674If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2675digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2676most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002677
Tim Petersab86c2b2002-08-15 20:06:00 +00002678The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002679
Tim Petersab86c2b2002-08-15 20:06:00 +00002680 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002681
Tim Petersab86c2b2002-08-15 20:06:00 +00002682and we have asize + c(bsize/2) available digit positions. We need to show
2683this is always enough. An instance of c(bsize/2) cancels out in both, so
2684the question reduces to whether asize digits is enough to hold
2685(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2686then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2687asize 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 +00002688digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002689asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002690c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2691is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2692bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002693
Tim Peters48d52c02002-08-14 17:07:32 +00002694Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2695clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2696ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002697*/
2698
Tim Peters60004642002-08-12 22:01:34 +00002699/* b has at least twice the digits of a, and a is big enough that Karatsuba
2700 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2701 * of slices, each with a->ob_size digits, and multiply the slices by a,
2702 * one at a time. This gives k_mul balanced inputs to work with, and is
2703 * also cache-friendly (we compute one double-width slice of the result
2704 * at a time, then move on, never bactracking except for the helpful
2705 * single-width slice overlap between successive partial sums).
2706 */
2707static PyLongObject *
2708k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2709{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002710 const Py_ssize_t asize = ABS(Py_Size(a));
2711 Py_ssize_t bsize = ABS(Py_Size(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002712 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002713 PyLongObject *ret;
2714 PyLongObject *bslice = NULL;
2715
2716 assert(asize > KARATSUBA_CUTOFF);
2717 assert(2 * asize <= bsize);
2718
2719 /* Allocate result space, and zero it out. */
2720 ret = _PyLong_New(asize + bsize);
2721 if (ret == NULL)
2722 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002723 memset(ret->ob_digit, 0, Py_Size(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002724
2725 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002726 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002727 if (bslice == NULL)
2728 goto fail;
2729
2730 nbdone = 0;
2731 while (bsize > 0) {
2732 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002733 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002734
2735 /* Multiply the next slice of b by a. */
2736 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2737 nbtouse * sizeof(digit));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002738 Py_Size(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002739 product = k_mul(a, bslice);
2740 if (product == NULL)
2741 goto fail;
2742
2743 /* Add into result. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002744 (void)v_iadd(ret->ob_digit + nbdone, Py_Size(ret) - nbdone,
2745 product->ob_digit, Py_Size(product));
Tim Peters60004642002-08-12 22:01:34 +00002746 Py_DECREF(product);
2747
2748 bsize -= nbtouse;
2749 nbdone += nbtouse;
2750 }
2751
2752 Py_DECREF(bslice);
2753 return long_normalize(ret);
2754
2755 fail:
2756 Py_DECREF(ret);
2757 Py_XDECREF(bslice);
2758 return NULL;
2759}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002760
2761static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002762long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002763{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002764 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002765
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002766 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002767
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002768 if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002769 PyObject *r;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002770 r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002771 return r;
2772 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002773
Tim Petersd64c1de2002-08-12 17:36:03 +00002774 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002775 /* Negate if exactly one of the inputs is negative. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002776 if (((Py_Size(a) ^ Py_Size(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002777 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002778 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002779}
2780
Guido van Rossume32e0141992-01-19 16:31:05 +00002781/* The / and % operators are now defined in terms of divmod().
2782 The expression a mod b has the value a - b*floor(a/b).
2783 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002784 |a| by |b|, with the sign of a. This is also expressed
2785 as a - b*trunc(a/b), if trunc truncates towards zero.
2786 Some examples:
2787 a b a rem b a mod b
2788 13 10 3 3
2789 -13 10 -3 7
2790 13 -10 3 -7
2791 -13 -10 -3 -3
2792 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002793 have different signs. We then subtract one from the 'div'
2794 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002795
Tim Peters47e52ee2004-08-30 02:44:38 +00002796/* Compute
2797 * *pdiv, *pmod = divmod(v, w)
2798 * NULL can be passed for pdiv or pmod, in which case that part of
2799 * the result is simply thrown away. The caller owns a reference to
2800 * each of these it requests (does not pass NULL for).
2801 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002802static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002803l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002804 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002805{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002806 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002807
Guido van Rossume32e0141992-01-19 16:31:05 +00002808 if (long_divrem(v, w, &div, &mod) < 0)
2809 return -1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002810 if ((Py_Size(mod) < 0 && Py_Size(w) > 0) ||
2811 (Py_Size(mod) > 0 && Py_Size(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002812 PyLongObject *temp;
2813 PyLongObject *one;
2814 temp = (PyLongObject *) long_add(mod, w);
2815 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002816 mod = temp;
2817 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002818 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002819 return -1;
2820 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002821 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002822 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002823 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2824 Py_DECREF(mod);
2825 Py_DECREF(div);
2826 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002827 return -1;
2828 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002829 Py_DECREF(one);
2830 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002831 div = temp;
2832 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002833 if (pdiv != NULL)
2834 *pdiv = div;
2835 else
2836 Py_DECREF(div);
2837
2838 if (pmod != NULL)
2839 *pmod = mod;
2840 else
2841 Py_DECREF(mod);
2842
Guido van Rossume32e0141992-01-19 16:31:05 +00002843 return 0;
2844}
2845
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002846static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002847long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002848{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002849 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002850
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002851 CHECK_BINOP(a, b);
2852 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002853 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002854 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002855}
2856
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002857static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002858long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002859{
Tim Peterse2a60002001-09-04 06:17:36 +00002860 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002861 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002862
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002863 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002864 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2865 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002866 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002867 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002868 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002869 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2870 but should really be set correctly after sucessful calls to
2871 _PyLong_AsScaledDouble() */
2872 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002873
2874 if (bd == 0.0) {
2875 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002876 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002877 return NULL;
2878 }
2879
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002880 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002881 ad /= bd; /* overflow/underflow impossible here */
2882 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002883 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002884 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002885 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002886 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002887 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002888 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002889 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002890 goto overflow;
2891 return PyFloat_FromDouble(ad);
2892
2893overflow:
2894 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002895 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002896 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002897
Tim Peters20dab9f2001-09-04 05:31:47 +00002898}
2899
2900static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002901long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002902{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002903 PyLongObject *mod;
2904
2905 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002906
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002907 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002908 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002909 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002910}
2911
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002912static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002913long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002914{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002915 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002916 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002917
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002918 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002919
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002920 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002921 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002922 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002923 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002924 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002925 PyTuple_SetItem(z, 0, (PyObject *) div);
2926 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002927 }
2928 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002929 Py_DECREF(div);
2930 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002931 }
2932 return z;
2933}
2934
Tim Peters47e52ee2004-08-30 02:44:38 +00002935/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002936static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002937long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002938{
Tim Peters47e52ee2004-08-30 02:44:38 +00002939 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2940 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002941
Tim Peters47e52ee2004-08-30 02:44:38 +00002942 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002943 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002944 PyLongObject *temp = NULL;
2945
2946 /* 5-ary values. If the exponent is large enough, table is
2947 * precomputed so that table[i] == a**i % c for i in range(32).
2948 */
2949 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2950 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2951
2952 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002953 CHECK_BINOP(v, w);
2954 a = (PyLongObject*)v; Py_INCREF(a);
2955 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002956 if (PyLong_Check(x)) {
2957 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002958 Py_INCREF(x);
2959 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002960 else if (x == Py_None)
2961 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002962 else {
2963 Py_DECREF(a);
2964 Py_DECREF(b);
2965 Py_INCREF(Py_NotImplemented);
2966 return Py_NotImplemented;
2967 }
Tim Peters4c483c42001-09-05 06:24:58 +00002968
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002969 if (Py_Size(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00002970 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002971 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002972 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002973 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002974 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002975 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002976 /* else return a float. This works because we know
2977 that this calls float_pow() which converts its
2978 arguments to double. */
2979 Py_DECREF(a);
2980 Py_DECREF(b);
2981 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002982 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002983 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002984
2985 if (c) {
2986 /* if modulus == 0:
2987 raise ValueError() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002988 if (Py_Size(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002989 PyErr_SetString(PyExc_ValueError,
2990 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002991 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002992 }
2993
2994 /* if modulus < 0:
2995 negativeOutput = True
2996 modulus = -modulus */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002997 if (Py_Size(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002998 negativeOutput = 1;
2999 temp = (PyLongObject *)_PyLong_Copy(c);
3000 if (temp == NULL)
3001 goto Error;
3002 Py_DECREF(c);
3003 c = temp;
3004 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003005 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003006 }
3007
3008 /* if modulus == 1:
3009 return 0 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003010 if ((Py_Size(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003011 z = (PyLongObject *)PyLong_FromLong(0L);
3012 goto Done;
3013 }
3014
3015 /* if base < 0:
3016 base = base % modulus
3017 Having the base positive just makes things easier. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003018 if (Py_Size(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003019 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003020 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003021 Py_DECREF(a);
3022 a = temp;
3023 temp = NULL;
3024 }
3025 }
3026
3027 /* At this point a, b, and c are guaranteed non-negative UNLESS
3028 c is NULL, in which case a may be negative. */
3029
3030 z = (PyLongObject *)PyLong_FromLong(1L);
3031 if (z == NULL)
3032 goto Error;
3033
3034 /* Perform a modular reduction, X = X % c, but leave X alone if c
3035 * is NULL.
3036 */
3037#define REDUCE(X) \
3038 if (c != NULL) { \
3039 if (l_divmod(X, c, NULL, &temp) < 0) \
3040 goto Error; \
3041 Py_XDECREF(X); \
3042 X = temp; \
3043 temp = NULL; \
3044 }
3045
3046 /* Multiply two values, then reduce the result:
3047 result = X*Y % c. If c is NULL, skip the mod. */
3048#define MULT(X, Y, result) \
3049{ \
3050 temp = (PyLongObject *)long_mul(X, Y); \
3051 if (temp == NULL) \
3052 goto Error; \
3053 Py_XDECREF(result); \
3054 result = temp; \
3055 temp = NULL; \
3056 REDUCE(result) \
3057}
3058
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003059 if (Py_Size(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003060 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3061 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003062 for (i = Py_Size(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003063 digit bi = b->ob_digit[i];
3064
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003065 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003066 MULT(z, z, z)
3067 if (bi & j)
3068 MULT(z, a, z)
3069 }
3070 }
3071 }
3072 else {
3073 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3074 Py_INCREF(z); /* still holds 1L */
3075 table[0] = z;
3076 for (i = 1; i < 32; ++i)
3077 MULT(table[i-1], a, table[i])
3078
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003079 for (i = Py_Size(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003080 const digit bi = b->ob_digit[i];
3081
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003082 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003083 const int index = (bi >> j) & 0x1f;
3084 for (k = 0; k < 5; ++k)
3085 MULT(z, z, z)
3086 if (index)
3087 MULT(z, table[index], z)
3088 }
3089 }
3090 }
3091
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003092 if (negativeOutput && (Py_Size(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003093 temp = (PyLongObject *)long_sub(z, c);
3094 if (temp == NULL)
3095 goto Error;
3096 Py_DECREF(z);
3097 z = temp;
3098 temp = NULL;
3099 }
3100 goto Done;
3101
3102 Error:
3103 if (z != NULL) {
3104 Py_DECREF(z);
3105 z = NULL;
3106 }
3107 /* fall through */
3108 Done:
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003109 if (Py_Size(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003110 for (i = 0; i < 32; ++i)
3111 Py_XDECREF(table[i]);
3112 }
Tim Petersde7990b2005-07-17 23:45:23 +00003113 Py_DECREF(a);
3114 Py_DECREF(b);
3115 Py_XDECREF(c);
3116 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003117 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003118}
3119
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003120static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003121long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003122{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003123 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003124 PyLongObject *x;
3125 PyLongObject *w;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003126 if (ABS(Py_Size(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003127 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003128 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003129 if (w == NULL)
3130 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003131 x = (PyLongObject *) long_add(v, w);
3132 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003133 if (x == NULL)
3134 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003135 Py_Size(x) = -(Py_Size(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003136 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003137}
3138
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003139static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003140long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003141{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003142 PyLongObject *z;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003143 if (ABS(Py_Size(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003144 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003145 z = (PyLongObject *)_PyLong_Copy(v);
3146 if (z != NULL)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003147 Py_Size(z) = -(Py_Size(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003148 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003149}
3150
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003151static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003152long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003153{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003154 if (Py_Size(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003155 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003156 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003157 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003158}
3159
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003160static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003161long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003162{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003163 return ABS(Py_Size(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003164}
3165
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003166static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003167long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003168{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003169 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003170 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003171 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003172 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003173
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003174 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003175
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003176 if (Py_Size(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003177 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003178 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003179 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003180 if (a1 == NULL)
3181 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003182 a2 = (PyLongObject *) long_rshift(a1, b);
3183 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003184 if (a2 == NULL)
3185 goto rshift_error;
3186 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003187 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003188 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003189 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003190
Neil Schemenauerba872e22001-01-04 01:46:03 +00003191 shiftby = PyLong_AsLong((PyObject *)b);
3192 if (shiftby == -1L && PyErr_Occurred())
3193 goto rshift_error;
3194 if (shiftby < 0) {
3195 PyErr_SetString(PyExc_ValueError,
3196 "negative shift count");
3197 goto rshift_error;
3198 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003199 wordshift = shiftby / PyLong_SHIFT;
3200 newsize = ABS(Py_Size(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003201 if (newsize <= 0) {
3202 z = _PyLong_New(0);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003203 return (PyObject *)z;
3204 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003205 loshift = shiftby % PyLong_SHIFT;
3206 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003207 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003208 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003209 z = _PyLong_New(newsize);
3210 if (z == NULL)
3211 goto rshift_error;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003212 if (Py_Size(a) < 0)
3213 Py_Size(z) = -(Py_Size(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003214 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3215 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3216 if (i+1 < newsize)
3217 z->ob_digit[i] |=
3218 (a->ob_digit[j+1] << hishift) & himask;
3219 }
3220 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003221 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003222rshift_error:
Neil Schemenauerba872e22001-01-04 01:46:03 +00003223 return (PyObject *) z;
3224
Guido van Rossumc6913e71991-11-19 20:26:46 +00003225}
3226
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003227static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003228long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003229{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003230 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003231 PyLongObject *a = (PyLongObject*)v;
3232 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003233 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003234 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003235 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003236 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003237
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003238 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003239
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003240 shiftby = PyLong_AsLong((PyObject *)b);
3241 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003242 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003243 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003244 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003245 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003246 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003247 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003248 PyErr_SetString(PyExc_ValueError,
3249 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003250 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003251 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003252 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3253 wordshift = (int)shiftby / PyLong_SHIFT;
3254 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003255
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003256 oldsize = ABS(Py_Size(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003257 newsize = oldsize + wordshift;
3258 if (remshift)
3259 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003260 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003261 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003262 goto lshift_error;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003263 if (Py_Size(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003264 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003265 for (i = 0; i < wordshift; i++)
3266 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003267 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003268 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003269 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003270 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3271 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003272 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003273 if (remshift)
3274 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003275 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003276 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003277 z = long_normalize(z);
3278lshift_error:
Neil Schemenauerba872e22001-01-04 01:46:03 +00003279 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003280}
3281
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003282
3283/* Bitwise and/xor/or operations */
3284
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003285static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003286long_bitwise(PyLongObject *a,
3287 int op, /* '&', '|', '^' */
3288 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003289{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003290 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003291 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003292 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003293 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003294 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003295 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003296 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003297
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003298 if (Py_Size(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003299 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003300 if (a == NULL)
3301 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003302 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003303 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003304 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003305 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003306 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003307 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003308 if (Py_Size(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003309 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003310 if (b == NULL) {
3311 Py_DECREF(a);
3312 return NULL;
3313 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003314 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003315 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003316 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003317 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003318 maskb = 0;
3319 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003320
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003321 negz = 0;
3322 switch (op) {
3323 case '^':
3324 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003325 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003326 negz = -1;
3327 }
3328 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003329 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003330 if (maska && maskb) {
3331 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003332 maska ^= PyLong_MASK;
3333 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003334 negz = -1;
3335 }
3336 break;
3337 case '|':
3338 if (maska || maskb) {
3339 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003340 maska ^= PyLong_MASK;
3341 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003342 negz = -1;
3343 }
3344 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003345 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003346
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003347 /* JRH: The original logic here was to allocate the result value (z)
3348 as the longer of the two operands. However, there are some cases
3349 where the result is guaranteed to be shorter than that: AND of two
3350 positives, OR of two negatives: use the shorter number. AND with
3351 mixed signs: use the positive number. OR with mixed signs: use the
3352 negative number. After the transformations above, op will be '&'
3353 iff one of these cases applies, and mask will be non-0 for operands
3354 whose length should be ignored.
3355 */
3356
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003357 size_a = Py_Size(a);
3358 size_b = Py_Size(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003359 size_z = op == '&'
3360 ? (maska
3361 ? size_b
3362 : (maskb ? size_a : MIN(size_a, size_b)))
3363 : MAX(size_a, size_b);
3364 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003365 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003366 Py_DECREF(a);
3367 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003368 return NULL;
3369 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003370
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003371 for (i = 0; i < size_z; ++i) {
3372 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3373 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3374 switch (op) {
3375 case '&': z->ob_digit[i] = diga & digb; break;
3376 case '|': z->ob_digit[i] = diga | digb; break;
3377 case '^': z->ob_digit[i] = diga ^ digb; break;
3378 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003379 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003380
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003381 Py_DECREF(a);
3382 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003383 z = long_normalize(z);
3384 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003385 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003386 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003387 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003388 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003389}
3390
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003391static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003392long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003393{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003394 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003395 CHECK_BINOP(a, b);
3396 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003397 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003398}
3399
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003400static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003401long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003402{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003403 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003404 CHECK_BINOP(a, b);
3405 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003406 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003407}
3408
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003409static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003410long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003411{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003412 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003413 CHECK_BINOP(a, b);
3414 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003415 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003416}
3417
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003418static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003419long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003420{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003421 if (PyLong_CheckExact(v))
3422 Py_INCREF(v);
3423 else
3424 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003425 return v;
3426}
3427
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003428static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003429long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003430{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003431 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003432 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003433 if (result == -1.0 && PyErr_Occurred())
3434 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003435 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003436}
3437
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003438static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003439long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003440
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441static PyObject *
3442long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3443{
3444 PyObject *x = NULL;
3445 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003446 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003447
Guido van Rossumbef14172001-08-29 15:47:46 +00003448 if (type != &PyLong_Type)
3449 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003450 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003451 &x, &base))
3452 return NULL;
3453 if (x == NULL)
3454 return PyLong_FromLong(0L);
3455 if (base == -909)
3456 return PyNumber_Long(x);
Neal Norwitzed2b7392007-08-26 04:51:10 +00003457 else if (PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003458 /* Since PyLong_FromString doesn't have a length parameter,
3459 * check here for possible NULs in the string. */
Neal Norwitzed2b7392007-08-26 04:51:10 +00003460 char *string = PyBytes_AS_STRING(x);
3461 int size = PyBytes_GET_SIZE(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003462 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003463 /* We only see this if there's a null byte in x,
3464 x is a str8 or a bytes, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003465 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003466 "invalid literal for int() with base %d: %R",
3467 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003468 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003469 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003470 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003471 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003472 else if (PyUnicode_Check(x))
3473 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3474 PyUnicode_GET_SIZE(x),
3475 base);
3476 else {
3477 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003478 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003479 return NULL;
3480 }
3481}
3482
Guido van Rossumbef14172001-08-29 15:47:46 +00003483/* Wimpy, slow approach to tp_new calls for subtypes of long:
3484 first create a regular long from whatever arguments we got,
3485 then allocate a subtype instance and initialize it from
3486 the regular long. The regular long is then thrown away.
3487*/
3488static PyObject *
3489long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3490{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003491 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003492 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003493
3494 assert(PyType_IsSubtype(type, &PyLong_Type));
3495 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3496 if (tmp == NULL)
3497 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003498 assert(PyLong_CheckExact(tmp));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003499 n = Py_Size(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003500 if (n < 0)
3501 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003502 newobj = (PyLongObject *)type->tp_alloc(type, n);
3503 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003504 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003505 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003506 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003507 assert(PyLong_Check(newobj));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003508 Py_Size(newobj) = Py_Size(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003509 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003510 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003511 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003512 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003513}
3514
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003515static PyObject *
3516long_getnewargs(PyLongObject *v)
3517{
3518 return Py_BuildValue("(N)", _PyLong_Copy(v));
3519}
3520
Guido van Rossumb43daf72007-08-01 18:08:08 +00003521static PyObject *
3522long_getN(PyLongObject *v, void *context) {
3523 return PyLong_FromLong((intptr_t)context);
3524}
3525
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003526static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003527long__format__(PyObject *self, PyObject *args)
3528{
3529 /* when back porting this to 2.6, check type of the format_spec
3530 and call either unicode_long__format__ or
3531 string_long__format__ */
3532 return unicode_long__format__(self, args);
3533}
3534
3535
3536static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003537long_round(PyObject *self, PyObject *args)
3538{
3539#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
3540 int ndigits = UNDEF_NDIGITS;
3541 double x;
3542 PyObject *res;
3543
3544 if (!PyArg_ParseTuple(args, "|i", &ndigits))
3545 return NULL;
3546
3547 if (ndigits == UNDEF_NDIGITS)
3548 return long_long(self);
3549
3550 /* If called with two args, defer to float.__round__(). */
3551 x = PyLong_AsDouble(self);
3552 if (x == -1.0 && PyErr_Occurred())
3553 return NULL;
3554 self = PyFloat_FromDouble(x);
3555 if (self == NULL)
3556 return NULL;
3557 res = PyObject_CallMethod(self, "__round__", "i", ndigits);
3558 Py_DECREF(self);
3559 return res;
3560#undef UNDEF_NDIGITS
3561}
3562
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003563static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003564 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3565 "Returns self, the complex conjugate of any int."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003566 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3567 "Truncating an Integral returns itself."},
3568 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3569 "Flooring an Integral returns itself."},
3570 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3571 "Ceiling of an Integral returns itself."},
3572 {"__round__", (PyCFunction)long_round, METH_VARARGS,
3573 "Rounding an Integral returns itself.\n"
3574 "Rounding with an ndigits arguments defers to float.__round__."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003575 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003576 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003577 {NULL, NULL} /* sentinel */
3578};
3579
Guido van Rossumb43daf72007-08-01 18:08:08 +00003580static PyGetSetDef long_getset[] = {
3581 {"real",
3582 (getter)long_long, (setter)NULL,
3583 "the real part of a complex number",
3584 NULL},
3585 {"imag",
3586 (getter)long_getN, (setter)NULL,
3587 "the imaginary part of a complex number",
3588 (void*)0},
3589 {"numerator",
3590 (getter)long_long, (setter)NULL,
3591 "the numerator of a rational number in lowest terms",
3592 NULL},
3593 {"denominator",
3594 (getter)long_getN, (setter)NULL,
3595 "the denominator of a rational number in lowest terms",
3596 (void*)1},
3597 {NULL} /* Sentinel */
3598};
3599
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003600PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003601"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003603Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003604point argument will be truncated towards zero (this does not include a\n\
3605string representation of a floating point number!) When converting a\n\
3606string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003607converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003609static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003610 (binaryfunc) long_add, /*nb_add*/
3611 (binaryfunc) long_sub, /*nb_subtract*/
3612 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003613 long_mod, /*nb_remainder*/
3614 long_divmod, /*nb_divmod*/
3615 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003616 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003617 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003618 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003619 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003620 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003621 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003622 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003623 long_and, /*nb_and*/
3624 long_xor, /*nb_xor*/
3625 long_or, /*nb_or*/
Neal Norwitzca810462006-08-29 07:57:59 +00003626 0, /*nb_coerce*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003627 long_long, /*nb_int*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003628 long_long, /*nb_long*/
3629 long_float, /*nb_float*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003630 0, /*nb_oct*/ /* not used */
3631 0, /*nb_hex*/ /* not used */
Guido van Rossum4668b002001-08-08 05:00:18 +00003632 0, /* nb_inplace_add */
3633 0, /* nb_inplace_subtract */
3634 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003635 0, /* nb_inplace_remainder */
3636 0, /* nb_inplace_power */
3637 0, /* nb_inplace_lshift */
3638 0, /* nb_inplace_rshift */
3639 0, /* nb_inplace_and */
3640 0, /* nb_inplace_xor */
3641 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003642 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003643 long_true_divide, /* nb_true_divide */
3644 0, /* nb_inplace_floor_divide */
3645 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003646 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003647};
3648
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003649PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003650 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003651 "int", /* tp_name */
3652 /* See _PyLong_New for why this isn't
3653 sizeof(PyLongObject) - sizeof(digit) */
3654 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003655 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003656 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003657 0, /* tp_print */
3658 0, /* tp_getattr */
3659 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003660 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003661 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003662 &long_as_number, /* tp_as_number */
3663 0, /* tp_as_sequence */
3664 0, /* tp_as_mapping */
3665 (hashfunc)long_hash, /* tp_hash */
3666 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003667 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003668 PyObject_GenericGetAttr, /* tp_getattro */
3669 0, /* tp_setattro */
3670 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003671 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3672 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673 long_doc, /* tp_doc */
3674 0, /* tp_traverse */
3675 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003676 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003677 0, /* tp_weaklistoffset */
3678 0, /* tp_iter */
3679 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003680 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003681 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003682 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683 0, /* tp_base */
3684 0, /* tp_dict */
3685 0, /* tp_descr_get */
3686 0, /* tp_descr_set */
3687 0, /* tp_dictoffset */
3688 0, /* tp_init */
3689 0, /* tp_alloc */
3690 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003691 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003692};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003693
3694int
3695_PyLong_Init(void)
3696{
3697#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3698 int ival;
3699 PyLongObject *v = small_ints;
3700 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3701 PyObject_INIT(v, &PyLong_Type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003702 Py_Size(v) = -1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003703 v->ob_digit[0] = -ival;
3704 }
3705 for (; ival < NSMALLPOSINTS; ival++, v++) {
3706 PyObject_INIT(v, &PyLong_Type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003707 Py_Size(v) = ival ? 1 : 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003708 v->ob_digit[0] = ival;
3709 }
3710#endif
3711 return 1;
3712}
3713
3714void
3715PyLong_Fini(void)
3716{
3717#if 0
3718 int i;
3719 /* This is currently not needed; the small integers
3720 are statically allocated */
3721#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3722 PyIntObject **q;
3723
3724 i = NSMALLNEGINTS + NSMALLPOSINTS;
3725 q = small_ints;
3726 while (--i >= 0) {
3727 Py_XDECREF(*q);
3728 *q++ = NULL;
3729 }
3730#endif
3731#endif
3732}