blob: cf7cb4713b18ac4d1e3786e8f9ad6c1b5514ecf1 [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); \
Christian Heimes217cfd12007-12-02 14:31:20 +000062 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000063 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
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000302PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
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
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000312 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000313 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000314 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000315 return -1;
316 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000317
318 if (!PyLong_Check(vv)) {
319 PyNumberMethods *nb;
320 if ((nb = vv->ob_type->tp_as_number) == NULL ||
321 nb->nb_int == NULL) {
322 PyErr_SetString(PyExc_TypeError, "an integer is required");
323 return -1;
324 }
325 vv = (*nb->nb_int) (vv);
326 if (vv == NULL)
327 return -1;
328 do_decref = 1;
329 if (!PyLong_Check(vv)) {
330 Py_DECREF(vv);
331 PyErr_SetString(PyExc_TypeError,
332 "nb_int should return int object");
333 return -1;
334 }
335 }
336
Georg Brandl61c31b02007-02-26 14:46:30 +0000337 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000339 i = Py_Size(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000340
Georg Brandl61c31b02007-02-26 14:46:30 +0000341 switch (i) {
342 case -1:
343 res = -v->ob_digit[0];
344 break;
345 case 0:
346 res = 0;
347 break;
348 case 1:
349 res = v->ob_digit[0];
350 break;
351 default:
352 sign = 1;
353 x = 0;
354 if (i < 0) {
355 sign = -1;
356 i = -(i);
357 }
358 while (--i >= 0) {
359 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000360 x = (x << PyLong_SHIFT) + v->ob_digit[i];
361 if ((x >> PyLong_SHIFT) != prev) {
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000362 *overflow = Py_Size(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000363 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 {
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000376 *overflow = Py_Size(v) > 0 ? 1 : -1;
377 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000378 }
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
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000387long
388PyLong_AsLong(PyObject *obj)
389{
390 int overflow;
391 long result = PyLong_AsLongAndOverflow(obj, &overflow);
392 if (overflow) {
393 /* XXX: could be cute and give a different
394 message for overflow == -1 */
395 PyErr_SetString(PyExc_OverflowError,
396 "Python int too large to convert to C long");
397 }
398 return result;
399}
400
Guido van Rossumddefaf32007-01-14 03:31:43 +0000401int
402_PyLong_FitsInLong(PyObject *vv)
403{
404 int size;
405 if (!PyLong_CheckExact(vv)) {
406 PyErr_BadInternalCall();
407 return 0;
408 }
409 /* conservative estimate */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000410 size = Py_Size(vv);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000411 return -2 <= size && size <= 2;
412}
413
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000414/* Get a Py_ssize_t from a long int object.
415 Returns -1 and sets an error condition if overflow occurs. */
416
417Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000418PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000419 register PyLongObject *v;
420 size_t x, prev;
421 Py_ssize_t i;
422 int sign;
423
424 if (vv == NULL || !PyLong_Check(vv)) {
425 PyErr_BadInternalCall();
426 return -1;
427 }
428 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000429 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000430 switch (i) {
431 case -1: return -v->ob_digit[0];
432 case 0: return 0;
433 case 1: return v->ob_digit[0];
434 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000435 sign = 1;
436 x = 0;
437 if (i < 0) {
438 sign = -1;
439 i = -(i);
440 }
441 while (--i >= 0) {
442 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000443 x = (x << PyLong_SHIFT) + v->ob_digit[i];
444 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000445 goto overflow;
446 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000447 /* Haven't lost any bits, but casting to a signed type requires
448 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000449 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000450 if (x <= (size_t)PY_SSIZE_T_MAX) {
451 return (Py_ssize_t)x * sign;
452 }
453 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
454 return PY_SSIZE_T_MIN;
455 }
456 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000457
458 overflow:
459 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000460 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000461 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000462}
463
Guido van Rossumd8c80482002-08-13 00:24:58 +0000464/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000465 Returns -1 and sets an error condition if overflow occurs. */
466
467unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000468PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000469{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000470 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000471 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000472 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000473
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000474 if (vv == NULL || !PyLong_Check(vv)) {
475 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000476 return (unsigned long) -1;
477 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000478 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000479 i = Py_Size(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000480 x = 0;
481 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000482 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000483 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000484 return (unsigned long) -1;
485 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000486 switch (i) {
487 case 0: return 0;
488 case 1: return v->ob_digit[0];
489 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000490 while (--i >= 0) {
491 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000492 x = (x << PyLong_SHIFT) + v->ob_digit[i];
493 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000494 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000495 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000496 return (unsigned long) -1;
497 }
498 }
499 return x;
500}
501
502/* Get a C unsigned long int from a long int object.
503 Returns -1 and sets an error condition if overflow occurs. */
504
505size_t
506PyLong_AsSize_t(PyObject *vv)
507{
508 register PyLongObject *v;
509 size_t x, prev;
510 Py_ssize_t i;
511
512 if (vv == NULL || !PyLong_Check(vv)) {
513 PyErr_BadInternalCall();
514 return (unsigned long) -1;
515 }
516 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000517 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000518 x = 0;
519 if (i < 0) {
520 PyErr_SetString(PyExc_OverflowError,
521 "can't convert negative value to size_t");
522 return (size_t) -1;
523 }
524 switch (i) {
525 case 0: return 0;
526 case 1: return v->ob_digit[0];
527 }
528 while (--i >= 0) {
529 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000530 x = (x << PyLong_SHIFT) + v->ob_digit[i];
531 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000532 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000533 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000534 return (unsigned long) -1;
535 }
536 }
537 return x;
538}
539
Thomas Hellera4ea6032003-04-17 18:55:45 +0000540/* Get a C unsigned long int from a long int object, ignoring the high bits.
541 Returns -1 and sets an error condition if an error occurs. */
542
Guido van Rossumddefaf32007-01-14 03:31:43 +0000543static unsigned long
544_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000545{
546 register PyLongObject *v;
547 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000548 Py_ssize_t i;
549 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000550
551 if (vv == NULL || !PyLong_Check(vv)) {
552 PyErr_BadInternalCall();
553 return (unsigned long) -1;
554 }
555 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000556 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000557 switch (i) {
558 case 0: return 0;
559 case 1: return v->ob_digit[0];
560 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000561 sign = 1;
562 x = 0;
563 if (i < 0) {
564 sign = -1;
565 i = -i;
566 }
567 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000568 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000569 }
570 return x * sign;
571}
572
Guido van Rossumddefaf32007-01-14 03:31:43 +0000573unsigned long
574PyLong_AsUnsignedLongMask(register PyObject *op)
575{
576 PyNumberMethods *nb;
577 PyLongObject *lo;
578 unsigned long val;
579
580 if (op && PyLong_Check(op))
581 return _PyLong_AsUnsignedLongMask(op);
582
583 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
584 nb->nb_int == NULL) {
585 PyErr_SetString(PyExc_TypeError, "an integer is required");
586 return (unsigned long)-1;
587 }
588
589 lo = (PyLongObject*) (*nb->nb_int) (op);
590 if (lo == NULL)
591 return (unsigned long)-1;
592 if (PyLong_Check(lo)) {
593 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
594 Py_DECREF(lo);
595 if (PyErr_Occurred())
596 return (unsigned long)-1;
597 return val;
598 }
599 else
600 {
601 Py_DECREF(lo);
602 PyErr_SetString(PyExc_TypeError,
603 "nb_int should return int object");
604 return (unsigned long)-1;
605 }
606}
607
Tim Peters5b8132f2003-01-31 15:52:05 +0000608int
609_PyLong_Sign(PyObject *vv)
610{
611 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000612
613 assert(v != NULL);
614 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000615
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000616 return Py_Size(v) == 0 ? 0 : (Py_Size(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000617}
618
Tim Petersbaefd9e2003-01-28 20:37:45 +0000619size_t
620_PyLong_NumBits(PyObject *vv)
621{
622 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000623 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000624 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000625
626 assert(v != NULL);
627 assert(PyLong_Check(v));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000628 ndigits = ABS(Py_Size(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000629 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
630 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000631 digit msd = v->ob_digit[ndigits - 1];
632
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000633 result = (ndigits - 1) * PyLong_SHIFT;
634 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000635 goto Overflow;
636 do {
637 ++result;
638 if (result == 0)
639 goto Overflow;
640 msd >>= 1;
641 } while (msd);
642 }
643 return result;
644
645Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000646 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000647 "to express in a platform size_t");
648 return (size_t)-1;
649}
650
Tim Peters2a9b3672001-06-11 21:23:58 +0000651PyObject *
652_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
653 int little_endian, int is_signed)
654{
655 const unsigned char* pstartbyte;/* LSB of bytes */
656 int incr; /* direction to move pstartbyte */
657 const unsigned char* pendbyte; /* MSB of bytes */
658 size_t numsignificantbytes; /* number of bytes that matter */
659 size_t ndigits; /* number of Python long digits */
660 PyLongObject* v; /* result */
661 int idigit = 0; /* next free index in v->ob_digit */
662
663 if (n == 0)
664 return PyLong_FromLong(0L);
665
666 if (little_endian) {
667 pstartbyte = bytes;
668 pendbyte = bytes + n - 1;
669 incr = 1;
670 }
671 else {
672 pstartbyte = bytes + n - 1;
673 pendbyte = bytes;
674 incr = -1;
675 }
676
677 if (is_signed)
678 is_signed = *pendbyte >= 0x80;
679
680 /* Compute numsignificantbytes. This consists of finding the most
681 significant byte. Leading 0 bytes are insignficant if the number
682 is positive, and leading 0xff bytes if negative. */
683 {
684 size_t i;
685 const unsigned char* p = pendbyte;
686 const int pincr = -incr; /* search MSB to LSB */
687 const unsigned char insignficant = is_signed ? 0xff : 0x00;
688
689 for (i = 0; i < n; ++i, p += pincr) {
690 if (*p != insignficant)
691 break;
692 }
693 numsignificantbytes = n - i;
694 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
695 actually has 2 significant bytes. OTOH, 0xff0001 ==
696 -0x00ffff, so we wouldn't *need* to bump it there; but we
697 do for 0xffff = -0x0001. To be safe without bothering to
698 check every case, bump it regardless. */
699 if (is_signed && numsignificantbytes < n)
700 ++numsignificantbytes;
701 }
702
703 /* How many Python long digits do we need? We have
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000704 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000705 bits, so it's the ceiling of the quotient. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000706 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000707 if (ndigits > (size_t)INT_MAX)
708 return PyErr_NoMemory();
709 v = _PyLong_New((int)ndigits);
710 if (v == NULL)
711 return NULL;
712
713 /* Copy the bits over. The tricky parts are computing 2's-comp on
714 the fly for signed numbers, and dealing with the mismatch between
715 8-bit bytes and (probably) 15-bit Python digits.*/
716 {
717 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000718 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000719 twodigits accum = 0; /* sliding register */
720 unsigned int accumbits = 0; /* number of bits in accum */
721 const unsigned char* p = pstartbyte;
722
723 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000724 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000725 /* Compute correction for 2's comp, if needed. */
726 if (is_signed) {
727 thisbyte = (0xff ^ thisbyte) + carry;
728 carry = thisbyte >> 8;
729 thisbyte &= 0xff;
730 }
731 /* Because we're going LSB to MSB, thisbyte is
732 more significant than what's already in accum,
733 so needs to be prepended to accum. */
734 accum |= thisbyte << accumbits;
735 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000736 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000737 /* There's enough to fill a Python digit. */
738 assert(idigit < (int)ndigits);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000739 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000740 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000741 accum >>= PyLong_SHIFT;
742 accumbits -= PyLong_SHIFT;
743 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000744 }
745 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000746 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000747 if (accumbits) {
748 assert(idigit < (int)ndigits);
749 v->ob_digit[idigit] = (digit)accum;
750 ++idigit;
751 }
752 }
753
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000754 Py_Size(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000755 return (PyObject *)long_normalize(v);
756}
757
758int
759_PyLong_AsByteArray(PyLongObject* v,
760 unsigned char* bytes, size_t n,
761 int little_endian, int is_signed)
762{
763 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000764 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000765 twodigits accum; /* sliding register */
766 unsigned int accumbits; /* # bits in accum */
767 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
768 twodigits carry; /* for computing 2's-comp */
769 size_t j; /* # bytes filled */
770 unsigned char* p; /* pointer to next byte in bytes */
771 int pincr; /* direction to move p */
772
773 assert(v != NULL && PyLong_Check(v));
774
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000775 if (Py_Size(v) < 0) {
776 ndigits = -(Py_Size(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000777 if (!is_signed) {
778 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000779 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000780 return -1;
781 }
782 do_twos_comp = 1;
783 }
784 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000785 ndigits = Py_Size(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000786 do_twos_comp = 0;
787 }
788
789 if (little_endian) {
790 p = bytes;
791 pincr = 1;
792 }
793 else {
794 p = bytes + n - 1;
795 pincr = -1;
796 }
797
Tim Peters898cf852001-06-13 20:50:08 +0000798 /* Copy over all the Python digits.
799 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000800 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000801 normalized. */
802 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000803 j = 0;
804 accum = 0;
805 accumbits = 0;
806 carry = do_twos_comp ? 1 : 0;
807 for (i = 0; i < ndigits; ++i) {
808 twodigits thisdigit = v->ob_digit[i];
809 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000810 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
811 carry = thisdigit >> PyLong_SHIFT;
812 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000813 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000814 /* Because we're going LSB to MSB, thisdigit is more
815 significant than what's already in accum, so needs to be
816 prepended to accum. */
817 accum |= thisdigit << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000818 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000819
Tim Petersede05092001-06-14 08:53:38 +0000820 /* The most-significant digit may be (probably is) at least
821 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000822 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000823 /* Count # of sign bits -- they needn't be stored,
824 * although for signed conversion we need later to
825 * make sure at least one sign bit gets stored.
826 * First shift conceptual sign bit to real sign bit.
827 */
828 stwodigits s = (stwodigits)(thisdigit <<
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000829 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000830 unsigned int nsignbits = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000831 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000832 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000833 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000834 }
Tim Petersede05092001-06-14 08:53:38 +0000835 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000836 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000837
Tim Peters2a9b3672001-06-11 21:23:58 +0000838 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000839 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000840 if (j >= n)
841 goto Overflow;
842 ++j;
843 *p = (unsigned char)(accum & 0xff);
844 p += pincr;
845 accumbits -= 8;
846 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000847 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000848 }
849
850 /* Store the straggler (if any). */
851 assert(accumbits < 8);
852 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000853 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000854 if (j >= n)
855 goto Overflow;
856 ++j;
857 if (do_twos_comp) {
858 /* Fill leading bits of the byte with sign bits
859 (appropriately pretending that the long had an
860 infinite supply of sign bits). */
861 accum |= (~(twodigits)0) << accumbits;
862 }
863 *p = (unsigned char)(accum & 0xff);
864 p += pincr;
865 }
Tim Peters05607ad2001-06-13 21:01:27 +0000866 else if (j == n && n > 0 && is_signed) {
867 /* The main loop filled the byte array exactly, so the code
868 just above didn't get to ensure there's a sign bit, and the
869 loop below wouldn't add one either. Make sure a sign bit
870 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000871 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000872 int sign_bit_set = msb >= 0x80;
873 assert(accumbits == 0);
874 if (sign_bit_set == do_twos_comp)
875 return 0;
876 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000877 goto Overflow;
878 }
Tim Peters05607ad2001-06-13 21:01:27 +0000879
880 /* Fill remaining bytes with copies of the sign bit. */
881 {
882 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
883 for ( ; j < n; ++j, p += pincr)
884 *p = signbyte;
885 }
886
Tim Peters2a9b3672001-06-11 21:23:58 +0000887 return 0;
888
889Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000890 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000891 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000892
Tim Peters2a9b3672001-06-11 21:23:58 +0000893}
894
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000895double
896_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
897{
898/* NBITS_WANTED should be > the number of bits in a double's precision,
899 but small enough so that 2**NBITS_WANTED is within the normal double
900 range. nbitsneeded is set to 1 less than that because the most-significant
901 Python digit contains at least 1 significant bit, but we don't want to
902 bother counting them (catering to the worst case cheaply).
903
904 57 is one more than VAX-D double precision; I (Tim) don't know of a double
905 format with more precision than that; it's 1 larger so that we add in at
906 least one round bit to stand in for the ignored least-significant bits.
907*/
908#define NBITS_WANTED 57
909 PyLongObject *v;
910 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000911 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000912 Py_ssize_t i;
913 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000914 int nbitsneeded;
915
916 if (vv == NULL || !PyLong_Check(vv)) {
917 PyErr_BadInternalCall();
918 return -1;
919 }
920 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000921 i = Py_Size(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000922 sign = 1;
923 if (i < 0) {
924 sign = -1;
925 i = -(i);
926 }
927 else if (i == 0) {
928 *exponent = 0;
929 return 0.0;
930 }
931 --i;
932 x = (double)v->ob_digit[i];
933 nbitsneeded = NBITS_WANTED - 1;
934 /* Invariant: i Python digits remain unaccounted for. */
935 while (i > 0 && nbitsneeded > 0) {
936 --i;
937 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000938 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000939 }
940 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000941 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000942 *exponent = i;
943 assert(x > 0.0);
944 return x * sign;
945#undef NBITS_WANTED
946}
947
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000948/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000949
950double
Tim Peters9f688bf2000-07-07 15:53:28 +0000951PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000952{
Thomas Wouters553489a2006-02-01 21:32:04 +0000953 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000954 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000955
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000956 if (vv == NULL || !PyLong_Check(vv)) {
957 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000958 return -1;
959 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000960 x = _PyLong_AsScaledDouble(vv, &e);
961 if (x == -1.0 && PyErr_Occurred())
962 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000963 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
964 set correctly after a successful _PyLong_AsScaledDouble() call */
965 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000966 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000967 goto overflow;
968 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000969 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000970 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000971 goto overflow;
972 return x;
973
974overflow:
975 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000976 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000977 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000978}
979
Guido van Rossum78694d91998-09-18 14:14:13 +0000980/* Create a new long (or int) object from a C pointer */
981
982PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000983PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000984{
Tim Peters70128a12001-06-16 08:48:40 +0000985#ifndef HAVE_LONG_LONG
986# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
987#endif
988#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000989# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000990#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000991 /* special-case null pointer */
992 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +0000993 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000994 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000995
Guido van Rossum78694d91998-09-18 14:14:13 +0000996}
997
998/* Get a C pointer from a long object (or an int object in some cases) */
999
1000void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001001PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001002{
1003 /* This function will allow int or long objects. If vv is neither,
1004 then the PyLong_AsLong*() functions will raise the exception:
1005 PyExc_SystemError, "bad argument to internal function"
1006 */
Tim Peters70128a12001-06-16 08:48:40 +00001007#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +00001008 long x;
1009
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_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001012 else
1013 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001014#else
Tim Peters70128a12001-06-16 08:48:40 +00001015
1016#ifndef HAVE_LONG_LONG
1017# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1018#endif
1019#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001020# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001021#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001022 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001023
Guido van Rossumddefaf32007-01-14 03:31:43 +00001024 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001025 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001026 else
1027 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001028
1029#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001030
1031 if (x == -1 && PyErr_Occurred())
1032 return NULL;
1033 return (void *)x;
1034}
1035
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001036#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001037
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001038/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001039 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001040 */
1041
Tim Peterscf37dfc2001-06-14 18:42:50 +00001042#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001043
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001044/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001045
1046PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001047PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001048{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049 PyLongObject *v;
1050 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1051 int ndigits = 0;
1052 int negative = 0;
1053
Guido van Rossumddefaf32007-01-14 03:31:43 +00001054 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001055 if (ival < 0) {
1056 ival = -ival;
1057 negative = 1;
1058 }
1059
1060 /* Count the number of Python digits.
1061 We used to pick 5 ("big enough for anything"), but that's a
1062 waste of time and space given that 5*15 = 75 bits are rarely
1063 needed. */
1064 t = (unsigned PY_LONG_LONG)ival;
1065 while (t) {
1066 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001067 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001068 }
1069 v = _PyLong_New(ndigits);
1070 if (v != NULL) {
1071 digit *p = v->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001072 Py_Size(v) = negative ? -ndigits : ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001073 t = (unsigned PY_LONG_LONG)ival;
1074 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001075 *p++ = (digit)(t & PyLong_MASK);
1076 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001077 }
1078 }
1079 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001080}
1081
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001082/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001083
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001084PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001085PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001086{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001087 PyLongObject *v;
1088 unsigned PY_LONG_LONG t;
1089 int ndigits = 0;
1090
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001091 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001092 return PyLong_FromLong(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001093 /* Count the number of Python digits. */
1094 t = (unsigned PY_LONG_LONG)ival;
1095 while (t) {
1096 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001097 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001098 }
1099 v = _PyLong_New(ndigits);
1100 if (v != NULL) {
1101 digit *p = v->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001102 Py_Size(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001103 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001104 *p++ = (digit)(ival & PyLong_MASK);
1105 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001106 }
1107 }
1108 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001109}
1110
Martin v. Löwis18e16552006-02-15 17:27:45 +00001111/* Create a new long int object from a C Py_ssize_t. */
1112
1113PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001114PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001115{
1116 Py_ssize_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,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001122 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001123}
1124
1125/* Create a new long int object from a C size_t. */
1126
1127PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001128PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001129{
1130 size_t bytes = ival;
1131 int one = 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001132 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001133 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001134 return _PyLong_FromByteArray(
1135 (unsigned char *)&bytes,
1136 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
1137}
1138
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001139/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001140 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001141
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001142PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001143PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001144{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001145 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001146 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001147 int one = 1;
1148 int res;
1149
Tim Petersd38b1c72001-09-30 05:09:37 +00001150 if (vv == NULL) {
1151 PyErr_BadInternalCall();
1152 return -1;
1153 }
1154 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001155 PyNumberMethods *nb;
1156 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001157 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1158 nb->nb_int == NULL) {
1159 PyErr_SetString(PyExc_TypeError, "an integer is required");
1160 return -1;
1161 }
1162 io = (*nb->nb_int) (vv);
1163 if (io == NULL)
1164 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001165 if (PyLong_Check(io)) {
1166 bytes = PyLong_AsLongLong(io);
1167 Py_DECREF(io);
1168 return bytes;
1169 }
1170 Py_DECREF(io);
1171 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001172 return -1;
1173 }
1174
Guido van Rossumddefaf32007-01-14 03:31:43 +00001175 v = (PyLongObject*)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001176 switch(Py_Size(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001177 case -1: return -v->ob_digit[0];
1178 case 0: return 0;
1179 case 1: return v->ob_digit[0];
1180 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001181 res = _PyLong_AsByteArray(
1182 (PyLongObject *)vv, (unsigned char *)&bytes,
1183 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001184
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001185 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001186 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001187 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001188 else
1189 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001190}
1191
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001192/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001193 Return -1 and set an error if overflow occurs. */
1194
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001195unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001196PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001197{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001198 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001199 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001200 int one = 1;
1201 int res;
1202
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001203 if (vv == NULL || !PyLong_Check(vv)) {
1204 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001205 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001206 }
1207
Guido van Rossumddefaf32007-01-14 03:31:43 +00001208 v = (PyLongObject*)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001209 switch(Py_Size(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001210 case 0: return 0;
1211 case 1: return v->ob_digit[0];
1212 }
1213
Tim Petersd1a7da62001-06-13 00:35:57 +00001214 res = _PyLong_AsByteArray(
1215 (PyLongObject *)vv, (unsigned char *)&bytes,
1216 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001217
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001218 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001219 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001220 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001221 else
1222 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001223}
Tim Petersd1a7da62001-06-13 00:35:57 +00001224
Thomas Hellera4ea6032003-04-17 18:55:45 +00001225/* Get a C unsigned long int from a long int object, ignoring the high bits.
1226 Returns -1 and sets an error condition if an error occurs. */
1227
Guido van Rossumddefaf32007-01-14 03:31:43 +00001228static unsigned PY_LONG_LONG
1229_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001230{
1231 register PyLongObject *v;
1232 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001233 Py_ssize_t i;
1234 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001235
1236 if (vv == NULL || !PyLong_Check(vv)) {
1237 PyErr_BadInternalCall();
1238 return (unsigned long) -1;
1239 }
1240 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001241 switch(Py_Size(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001242 case 0: return 0;
1243 case 1: return v->ob_digit[0];
1244 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001245 i = Py_Size(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001246 sign = 1;
1247 x = 0;
1248 if (i < 0) {
1249 sign = -1;
1250 i = -i;
1251 }
1252 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001253 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001254 }
1255 return x * sign;
1256}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001257
1258unsigned PY_LONG_LONG
1259PyLong_AsUnsignedLongLongMask(register PyObject *op)
1260{
1261 PyNumberMethods *nb;
1262 PyLongObject *lo;
1263 unsigned PY_LONG_LONG val;
1264
1265 if (op && PyLong_Check(op))
1266 return _PyLong_AsUnsignedLongLongMask(op);
1267
1268 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1269 nb->nb_int == NULL) {
1270 PyErr_SetString(PyExc_TypeError, "an integer is required");
1271 return (unsigned PY_LONG_LONG)-1;
1272 }
1273
1274 lo = (PyLongObject*) (*nb->nb_int) (op);
1275 if (lo == NULL)
1276 return (unsigned PY_LONG_LONG)-1;
1277 if (PyLong_Check(lo)) {
1278 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1279 Py_DECREF(lo);
1280 if (PyErr_Occurred())
1281 return (unsigned PY_LONG_LONG)-1;
1282 return val;
1283 }
1284 else
1285 {
1286 Py_DECREF(lo);
1287 PyErr_SetString(PyExc_TypeError,
1288 "nb_int should return int object");
1289 return (unsigned PY_LONG_LONG)-1;
1290 }
1291}
Tim Petersd1a7da62001-06-13 00:35:57 +00001292#undef IS_LITTLE_ENDIAN
1293
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001294#endif /* HAVE_LONG_LONG */
1295
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001296#define CHECK_BINOP(v,w) \
1297 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001298 Py_INCREF(Py_NotImplemented); \
1299 return Py_NotImplemented; \
1300 }
1301
Tim Peters877a2122002-08-12 05:09:36 +00001302/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1303 * is modified in place, by adding y to it. Carries are propagated as far as
1304 * x[m-1], and the remaining carry (0 or 1) is returned.
1305 */
1306static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001307v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001308{
1309 int i;
1310 digit carry = 0;
1311
1312 assert(m >= n);
1313 for (i = 0; i < n; ++i) {
1314 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001315 x[i] = carry & PyLong_MASK;
1316 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001317 assert((carry & 1) == carry);
1318 }
1319 for (; carry && i < m; ++i) {
1320 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001321 x[i] = carry & PyLong_MASK;
1322 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001323 assert((carry & 1) == carry);
1324 }
1325 return carry;
1326}
1327
1328/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1329 * is modified in place, by subtracting y from it. Borrows are propagated as
1330 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1331 */
1332static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001333v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001334{
1335 int i;
1336 digit borrow = 0;
1337
1338 assert(m >= n);
1339 for (i = 0; i < n; ++i) {
1340 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001341 x[i] = borrow & PyLong_MASK;
1342 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001343 borrow &= 1; /* keep only 1 sign bit */
1344 }
1345 for (; borrow && i < m; ++i) {
1346 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001347 x[i] = borrow & PyLong_MASK;
1348 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001349 borrow &= 1;
1350 }
1351 return borrow;
1352}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001353
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001354/* Multiply by a single digit, ignoring the sign. */
1355
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001356static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001357mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001358{
1359 return muladd1(a, n, (digit)0);
1360}
1361
1362/* Multiply by a single digit and add a single digit, ignoring the sign. */
1363
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001364static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001365muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001366{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001367 Py_ssize_t size_a = ABS(Py_Size(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001368 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001369 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001370 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001371
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001372 if (z == NULL)
1373 return NULL;
1374 for (i = 0; i < size_a; ++i) {
1375 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001376 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1377 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001378 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001379 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001380 return long_normalize(z);
1381}
1382
Tim Peters212e6142001-07-14 12:23:19 +00001383/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1384 in pout, and returning the remainder. pin and pout point at the LSD.
1385 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001386 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001387 immutable. */
1388
1389static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001390inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001391{
1392 twodigits rem = 0;
1393
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001394 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001395 pin += size;
1396 pout += size;
1397 while (--size >= 0) {
1398 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001399 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001400 *--pout = hi = (digit)(rem / n);
1401 rem -= hi * n;
1402 }
1403 return (digit)rem;
1404}
1405
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001406/* Divide a long integer by a digit, returning both the quotient
1407 (as function result) and the remainder (through *prem).
1408 The sign of a is ignored; n should not be zero. */
1409
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001410static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001411divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001412{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001413 const Py_ssize_t size = ABS(Py_Size(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001414 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001415
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001416 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001417 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001418 if (z == NULL)
1419 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001420 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001421 return long_normalize(z);
1422}
1423
1424/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001425 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001426 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001427
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001428PyObject *
1429_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001430{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001431 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001432 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001433 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001434 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001435 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001436 int bits;
1437 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001438
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001439 if (a == NULL || !PyLong_Check(a)) {
1440 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001441 return NULL;
1442 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001443 assert(base >= 2 && base <= 36);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001444 size_a = ABS(Py_Size(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001445
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001446 /* Compute a rough upper bound for the length of the string */
1447 i = base;
1448 bits = 0;
1449 while (i > 1) {
1450 ++bits;
1451 i >>= 1;
1452 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001453 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001454 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001455 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001456 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001457 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001458 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001459 return NULL;
1460 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001461 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001462 if (str == NULL)
1463 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001464 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001465 *p = '\0';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001466 if (Py_Size(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001467 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001468
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001469 if (Py_Size(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001470 *--p = '0';
1471 }
1472 else if ((base & (base - 1)) == 0) {
1473 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001474 twodigits accum = 0;
1475 int accumbits = 0; /* # of bits in accum */
1476 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001477 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001478 while ((i >>= 1) > 1)
1479 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001480
1481 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001482 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001483 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001484 assert(accumbits >= basebits);
1485 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001486 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001487 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001488 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001489 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001490 accumbits -= basebits;
1491 accum >>= basebits;
1492 } while (i < size_a-1 ? accumbits >= basebits :
1493 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001494 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001495 }
1496 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001497 /* Not 0, and base not a power of 2. Divide repeatedly by
1498 base, but for speed use the highest power of base that
1499 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001500 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001501 digit *pin = a->ob_digit;
1502 PyLongObject *scratch;
1503 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001504 digit powbase = base; /* powbase == base ** power */
1505 int power = 1;
1506 for (;;) {
1507 unsigned long newpow = powbase * (unsigned long)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001508 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001509 break;
1510 powbase = (digit)newpow;
1511 ++power;
1512 }
Tim Peters212e6142001-07-14 12:23:19 +00001513
1514 /* Get a scratch area for repeated division. */
1515 scratch = _PyLong_New(size);
1516 if (scratch == NULL) {
1517 Py_DECREF(str);
1518 return NULL;
1519 }
1520
1521 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001522 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001523 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001524 digit rem = inplace_divrem1(scratch->ob_digit,
1525 pin, size, powbase);
1526 pin = scratch->ob_digit; /* no need to use a again */
1527 if (pin[size - 1] == 0)
1528 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001529 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001530 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001531 Py_DECREF(str);
1532 return NULL;
1533 })
Tim Peters212e6142001-07-14 12:23:19 +00001534
1535 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001536 assert(ntostore > 0);
1537 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001538 digit nextrem = (digit)(rem / base);
1539 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001540 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001541 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001542 *--p = c;
1543 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001544 --ntostore;
1545 /* Termination is a bit delicate: must not
1546 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001547 remaining quotient and rem are both 0. */
1548 } while (ntostore && (size || rem));
1549 } while (size != 0);
1550 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001551 }
1552
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001553 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001554 *--p = 'x';
1555 *--p = '0';
1556 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001557 else if (base == 8) {
1558 *--p = 'o';
1559 *--p = '0';
1560 }
1561 else if (base == 2) {
1562 *--p = 'b';
1563 *--p = '0';
1564 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001565 else if (base != 10) {
1566 *--p = '#';
1567 *--p = '0' + base%10;
1568 if (base > 10)
1569 *--p = '0' + base/10;
1570 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001571 if (sign)
1572 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001573 if (p != PyUnicode_AS_UNICODE(str)) {
1574 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001575 assert(p > q);
1576 do {
1577 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001578 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001579 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1580 Py_DECREF(str);
1581 return NULL;
1582 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001583 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001584 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001585}
1586
Thomas Wouters477c8d52006-05-27 19:21:47 +00001587/* Table of digit values for 8-bit string -> integer conversion.
1588 * '0' maps to 0, ..., '9' maps to 9.
1589 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1590 * All other indices map to 37.
1591 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001592 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001593 */
1594int _PyLong_DigitValue[256] = {
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 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1598 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1599 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1600 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1601 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1602 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1603 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1604 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1605 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1606 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1607 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1608 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1609 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1610 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1611};
1612
1613/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001614 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1615 * non-digit (which may be *str!). A normalized long is returned.
1616 * The point to this routine is that it takes time linear in the number of
1617 * string characters.
1618 */
1619static PyLongObject *
1620long_from_binary_base(char **str, int base)
1621{
1622 char *p = *str;
1623 char *start = p;
1624 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001625 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001626 PyLongObject *z;
1627 twodigits accum;
1628 int bits_in_accum;
1629 digit *pdigit;
1630
1631 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1632 n = base;
1633 for (bits_per_char = -1; n; ++bits_per_char)
1634 n >>= 1;
1635 /* n <- total # of bits needed, while setting p to end-of-string */
1636 n = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001637 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001638 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001639 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001640 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1641 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001642 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001643 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001644 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001645 return NULL;
1646 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001647 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001648 z = _PyLong_New(n);
1649 if (z == NULL)
1650 return NULL;
1651 /* Read string from right, and fill in long from left; i.e.,
1652 * from least to most significant in both.
1653 */
1654 accum = 0;
1655 bits_in_accum = 0;
1656 pdigit = z->ob_digit;
1657 while (--p >= start) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001658 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001659 assert(k >= 0 && k < base);
1660 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001661 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001662 if (bits_in_accum >= PyLong_SHIFT) {
1663 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001664 assert(pdigit - z->ob_digit <= (int)n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001665 accum >>= PyLong_SHIFT;
1666 bits_in_accum -= PyLong_SHIFT;
1667 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001668 }
1669 }
1670 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001671 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001672 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001673 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001674 }
1675 while (pdigit - z->ob_digit < n)
1676 *pdigit++ = 0;
1677 return long_normalize(z);
1678}
1679
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001680PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001681PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001682{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001683 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001684 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001685 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001686 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001687 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001688
Guido van Rossum472c04f1996-12-05 21:57:21 +00001689 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001690 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001691 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001692 return NULL;
1693 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001694 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001695 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001696 if (*str == '+')
1697 ++str;
1698 else if (*str == '-') {
1699 ++str;
1700 sign = -1;
1701 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001702 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001703 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001704 if (base == 0) {
1705 if (str[0] != '0')
1706 base = 10;
1707 else if (str[1] == 'x' || str[1] == 'X')
1708 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001709 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001710 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001711 else if (str[1] == 'b' || str[1] == 'B')
1712 base = 2;
1713 else {
1714 /* "old" (C-style) octal literal, now invalid.
1715 it might still be zero though */
1716 error_if_nonzero = 1;
1717 base = 10;
1718 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001719 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001720 if (str[0] == '0' &&
1721 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1722 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1723 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001724 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001725
Guido van Rossume6762971998-06-22 03:54:46 +00001726 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001727 if ((base & (base - 1)) == 0)
1728 z = long_from_binary_base(&str, base);
1729 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001730/***
1731Binary bases can be converted in time linear in the number of digits, because
1732Python's representation base is binary. Other bases (including decimal!) use
1733the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001734
Thomas Wouters477c8d52006-05-27 19:21:47 +00001735First some math: the largest integer that can be expressed in N base-B digits
1736is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1737case number of Python digits needed to hold it is the smallest integer n s.t.
1738
1739 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1740 BASE**n >= B**N [taking logs to base BASE]
1741 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1742
1743The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1744this quickly. A Python long with that much space is reserved near the start,
1745and the result is computed into it.
1746
1747The input string is actually treated as being in base base**i (i.e., i digits
1748are processed at a time), where two more static arrays hold:
1749
1750 convwidth_base[base] = the largest integer i such that base**i <= BASE
1751 convmultmax_base[base] = base ** convwidth_base[base]
1752
1753The first of these is the largest i such that i consecutive input digits
1754must fit in a single Python digit. The second is effectively the input
1755base we're really using.
1756
1757Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1758convmultmax_base[base], the result is "simply"
1759
1760 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1761
1762where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001763
1764Error analysis: as above, the number of Python digits `n` needed is worst-
1765case
1766
1767 n >= N * log(B)/log(BASE)
1768
1769where `N` is the number of input digits in base `B`. This is computed via
1770
1771 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1772
1773below. Two numeric concerns are how much space this can waste, and whether
1774the computed result can be too small. To be concrete, assume BASE = 2**15,
1775which is the default (and it's unlikely anyone changes that).
1776
1777Waste isn't a problem: provided the first input digit isn't 0, the difference
1778between the worst-case input with N digits and the smallest input with N
1779digits is about a factor of B, but B is small compared to BASE so at most
1780one allocated Python digit can remain unused on that count. If
1781N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1782and adding 1 returns a result 1 larger than necessary. However, that can't
1783happen: whenever B is a power of 2, long_from_binary_base() is called
1784instead, and it's impossible for B**i to be an integer power of 2**15 when
1785B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1786an exact integer when B is not a power of 2, since B**i has a prime factor
1787other than 2 in that case, but (2**15)**j's only prime factor is 2).
1788
1789The computed result can be too small if the true value of N*log(B)/log(BASE)
1790is a little bit larger than an exact integer, but due to roundoff errors (in
1791computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1792yields a numeric result a little less than that integer. Unfortunately, "how
1793close can a transcendental function get to an integer over some range?"
1794questions are generally theoretically intractable. Computer analysis via
1795continued fractions is practical: expand log(B)/log(BASE) via continued
1796fractions, giving a sequence i/j of "the best" rational approximations. Then
1797j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1798we can get very close to being in trouble, but very rarely. For example,
179976573 is a denominator in one of the continued-fraction approximations to
1800log(10)/log(2**15), and indeed:
1801
1802 >>> log(10)/log(2**15)*76573
1803 16958.000000654003
1804
1805is very close to an integer. If we were working with IEEE single-precision,
1806rounding errors could kill us. Finding worst cases in IEEE double-precision
1807requires better-than-double-precision log() functions, and Tim didn't bother.
1808Instead the code checks to see whether the allocated space is enough as each
1809new Python digit is added, and copies the whole thing to a larger long if not.
1810This should happen extremely rarely, and in fact I don't have a test case
1811that triggers it(!). Instead the code was tested by artificially allocating
1812just 1 digit at the start, so that the copying code was exercised for every
1813digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001814***/
1815 register twodigits c; /* current input character */
1816 Py_ssize_t size_z;
1817 int i;
1818 int convwidth;
1819 twodigits convmultmax, convmult;
1820 digit *pz, *pzstop;
1821 char* scan;
1822
1823 static double log_base_BASE[37] = {0.0e0,};
1824 static int convwidth_base[37] = {0,};
1825 static twodigits convmultmax_base[37] = {0,};
1826
1827 if (log_base_BASE[base] == 0.0) {
1828 twodigits convmax = base;
1829 int i = 1;
1830
1831 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001832 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001833 for (;;) {
1834 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001835 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001836 break;
1837 convmax = next;
1838 ++i;
1839 }
1840 convmultmax_base[base] = convmax;
1841 assert(i > 0);
1842 convwidth_base[base] = i;
1843 }
1844
1845 /* Find length of the string of numeric characters. */
1846 scan = str;
1847 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1848 ++scan;
1849
1850 /* Create a long object that can contain the largest possible
1851 * integer with this base and length. Note that there's no
1852 * need to initialize z->ob_digit -- no slot is read up before
1853 * being stored into.
1854 */
1855 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001856 /* Uncomment next line to test exceedingly rare copy code */
1857 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001858 assert(size_z > 0);
1859 z = _PyLong_New(size_z);
1860 if (z == NULL)
1861 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001862 Py_Size(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001863
1864 /* `convwidth` consecutive input digits are treated as a single
1865 * digit in base `convmultmax`.
1866 */
1867 convwidth = convwidth_base[base];
1868 convmultmax = convmultmax_base[base];
1869
1870 /* Work ;-) */
1871 while (str < scan) {
1872 /* grab up to convwidth digits from the input string */
1873 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1874 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1875 c = (twodigits)(c * base +
1876 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001877 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001878 }
1879
1880 convmult = convmultmax;
1881 /* Calculate the shift only if we couldn't get
1882 * convwidth digits.
1883 */
1884 if (i != convwidth) {
1885 convmult = base;
1886 for ( ; i > 1; --i)
1887 convmult *= base;
1888 }
1889
1890 /* Multiply z by convmult, and add c. */
1891 pz = z->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001892 pzstop = pz + Py_Size(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001893 for (; pz < pzstop; ++pz) {
1894 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001895 *pz = (digit)(c & PyLong_MASK);
1896 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001897 }
1898 /* carry off the current end? */
1899 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001900 assert(c < PyLong_BASE);
1901 if (Py_Size(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001902 *pz = (digit)c;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001903 ++Py_Size(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001904 }
1905 else {
1906 PyLongObject *tmp;
1907 /* Extremely rare. Get more space. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001908 assert(Py_Size(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001909 tmp = _PyLong_New(size_z + 1);
1910 if (tmp == NULL) {
1911 Py_DECREF(z);
1912 return NULL;
1913 }
1914 memcpy(tmp->ob_digit,
1915 z->ob_digit,
1916 sizeof(digit) * size_z);
1917 Py_DECREF(z);
1918 z = tmp;
1919 z->ob_digit[size_z] = (digit)c;
1920 ++size_z;
1921 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001922 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001923 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001924 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001925 if (z == NULL)
1926 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001927 if (error_if_nonzero) {
1928 /* reset the base to 0, else the exception message
1929 doesn't make too much sense */
1930 base = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001931 if (Py_Size(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001932 goto onError;
1933 /* there might still be other problems, therefore base
1934 remains zero here for the same reason */
1935 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001936 if (str == start)
1937 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001938 if (sign < 0)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001939 Py_Size(z) = -(Py_Size(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001940 if (*str == 'L' || *str == 'l')
1941 str++;
1942 while (*str && isspace(Py_CHARMASK(*str)))
1943 str++;
1944 if (*str != '\0')
1945 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001946 if (pend)
1947 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001948 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001949
1950 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001951 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001952 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00001953 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001954 if (strobj == NULL)
1955 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001956 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00001957 "invalid literal for int() with base %d: %R",
1958 base, strobj);
1959 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001960 return NULL;
1961}
1962
1963PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001964PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001965{
Walter Dörwald07e14762002-11-06 16:15:14 +00001966 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001967 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001968
Walter Dörwald07e14762002-11-06 16:15:14 +00001969 if (buffer == NULL)
1970 return NULL;
1971
1972 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1973 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001974 return NULL;
1975 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001976 result = PyLong_FromString(buffer, NULL, base);
1977 PyMem_FREE(buffer);
1978 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001979}
1980
Tim Peters9f688bf2000-07-07 15:53:28 +00001981/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001982static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001983 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001984static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00001985static int long_divrem(PyLongObject *, PyLongObject *,
1986 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001987
1988/* Long division with remainder, top-level routine */
1989
Guido van Rossume32e0141992-01-19 16:31:05 +00001990static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001991long_divrem(PyLongObject *a, PyLongObject *b,
1992 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001993{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001994 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001995 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001996
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001997 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001998 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001999 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002000 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002001 }
2002 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002003 (size_a == size_b &&
2004 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002005 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002006 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002007 if (*pdiv == NULL)
2008 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002009 Py_INCREF(a);
2010 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002011 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002012 }
2013 if (size_b == 1) {
2014 digit rem = 0;
2015 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002016 if (z == NULL)
2017 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002018 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002019 if (*prem == NULL) {
2020 Py_DECREF(z);
2021 return -1;
2022 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002023 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002024 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002025 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002026 if (z == NULL)
2027 return -1;
2028 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002029 /* Set the signs.
2030 The quotient z has the sign of a*b;
2031 the remainder r has the sign of a,
2032 so a = b*z + r. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002033 if ((Py_Size(a) < 0) != (Py_Size(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002034 NEGATE(z);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002035 if (Py_Size(a) < 0 && Py_Size(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002036 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002037 *pdiv = z;
2038 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002039}
2040
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002041/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002042
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002043static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002044x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002045{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002046 Py_ssize_t size_v = ABS(Py_Size(v1)), size_w = ABS(Py_Size(w1));
2047 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002048 PyLongObject *v = mul1(v1, d);
2049 PyLongObject *w = mul1(w1, d);
2050 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002051 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002052
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002053 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002054 Py_XDECREF(v);
2055 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002056 return NULL;
2057 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002058
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002059 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002060 assert(Py_Refcnt(v) == 1); /* Since v will be used as accumulator! */
2061 assert(size_w == ABS(Py_Size(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002062
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002063 size_v = ABS(Py_Size(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002064 k = size_v - size_w;
2065 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002066
Thomas Wouters477c8d52006-05-27 19:21:47 +00002067 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002068 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2069 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002070 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002071 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002072
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002073 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002074 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002075 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002076 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002077 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002078 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002079 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002080 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002081 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002082 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002083
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002084 while (w->ob_digit[size_w-2]*q >
2085 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002086 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002087 + v->ob_digit[j-1]
2088 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002089 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090 + v->ob_digit[j-2])
2091 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002092
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002093 for (i = 0; i < size_w && i+k < size_v; ++i) {
2094 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002095 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002096 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002097 + ((twodigits)zz << PyLong_SHIFT);
2098 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002099 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002100 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002101 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002102 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002103
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002104 if (i+k < size_v) {
2105 carry += v->ob_digit[i+k];
2106 v->ob_digit[i+k] = 0;
2107 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002108
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002109 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002110 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002111 else {
2112 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002113 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002114 carry = 0;
2115 for (i = 0; i < size_w && i+k < size_v; ++i) {
2116 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002117 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002118 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2119 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002120 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002121 }
2122 }
2123 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002124
Guido van Rossumc206c761995-01-10 15:23:19 +00002125 if (a == NULL)
2126 *prem = NULL;
2127 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002128 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002129 *prem = divrem1(v, d, &d);
2130 /* d receives the (unused) remainder */
2131 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002132 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002133 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002134 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002135 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002136 Py_DECREF(v);
2137 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002138 return a;
2139}
2140
2141/* Methods */
2142
2143static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002144long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002145{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002146 Py_Type(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002147}
2148
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002149static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002150long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002151{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002152 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002153}
2154
2155static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002156long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002157{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002158 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002159
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002160 if (Py_Size(a) != Py_Size(b)) {
2161 if (ABS(Py_Size(a)) == 0 && ABS(Py_Size(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002162 sign = 0;
2163 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002164 sign = Py_Size(a) - Py_Size(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002165 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002166 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002167 Py_ssize_t i = ABS(Py_Size(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002168 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2169 ;
2170 if (i < 0)
2171 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002172 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002173 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002174 if (Py_Size(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002175 sign = -sign;
2176 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002177 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002178 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002179}
2180
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002181static PyObject *
2182long_richcompare(PyObject *self, PyObject *other, int op)
2183{
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002184 PyObject *result;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002185 CHECK_BINOP(self, other);
2186 result = Py_CmpToRich(op, long_compare((PyLongObject*)self,
2187 (PyLongObject*)other));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002188 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002189}
2190
Guido van Rossum9bfef441993-03-29 10:43:31 +00002191static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002192long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002193{
2194 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002195 Py_ssize_t i;
2196 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002197
2198 /* This is designed so that Python ints and longs with the
2199 same value hash to the same value, otherwise comparisons
2200 of mapping keys will turn out weird */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002201 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002202 switch(i) {
2203 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2204 case 0: return 0;
2205 case 1: return v->ob_digit[0];
2206 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002207 sign = 1;
2208 x = 0;
2209 if (i < 0) {
2210 sign = -1;
2211 i = -(i);
2212 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002213#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Thomas Woutersce272b62007-09-19 21:19:28 +00002214 /* The following loop produces a C long x such that (unsigned long)x
2215 is congruent to the absolute value of v modulo ULONG_MAX. The
2216 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002217 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002218 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002219 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002220 x += v->ob_digit[i];
Thomas Woutersce272b62007-09-19 21:19:28 +00002221 /* If the addition above overflowed (thinking of x as
2222 unsigned), we compensate by incrementing. This preserves
2223 the value modulo ULONG_MAX. */
2224 if ((unsigned long)x < v->ob_digit[i])
2225 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002226 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002227#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002228 x = x * sign;
2229 if (x == -1)
2230 x = -2;
2231 return x;
2232}
2233
2234
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002235/* Add the absolute values of two long integers. */
2236
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002237static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002238x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002239{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002240 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002241 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002242 int i;
2243 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002244
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002245 /* Ensure a is the larger of the two: */
2246 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002247 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002248 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002249 size_a = size_b;
2250 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002251 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002252 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002253 if (z == NULL)
2254 return NULL;
2255 for (i = 0; i < size_b; ++i) {
2256 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002257 z->ob_digit[i] = carry & PyLong_MASK;
2258 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002259 }
2260 for (; i < size_a; ++i) {
2261 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002262 z->ob_digit[i] = carry & PyLong_MASK;
2263 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002264 }
2265 z->ob_digit[i] = carry;
2266 return long_normalize(z);
2267}
2268
2269/* Subtract the absolute values of two integers. */
2270
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002271static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002272x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002273{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002274 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002275 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002276 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002277 int sign = 1;
2278 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002279
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002280 /* Ensure a is the larger of the two: */
2281 if (size_a < size_b) {
2282 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002283 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002284 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002285 size_a = size_b;
2286 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002287 }
2288 else if (size_a == size_b) {
2289 /* Find highest digit where a and b differ: */
2290 i = size_a;
2291 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2292 ;
2293 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002294 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002295 if (a->ob_digit[i] < b->ob_digit[i]) {
2296 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002297 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002298 }
2299 size_a = size_b = i+1;
2300 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002301 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002302 if (z == NULL)
2303 return NULL;
2304 for (i = 0; i < size_b; ++i) {
2305 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002306 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002307 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002308 z->ob_digit[i] = borrow & PyLong_MASK;
2309 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002310 borrow &= 1; /* Keep only one sign bit */
2311 }
2312 for (; i < size_a; ++i) {
2313 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002314 z->ob_digit[i] = borrow & PyLong_MASK;
2315 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002316 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002317 }
2318 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002319 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002320 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002321 return long_normalize(z);
2322}
2323
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002324static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002325long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002326{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002327 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002328
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002329 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002330
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002331 if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002332 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002333 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002334 return result;
2335 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002336 if (Py_Size(a) < 0) {
2337 if (Py_Size(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002338 z = x_add(a, b);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002339 if (z != NULL && Py_Size(z) != 0)
2340 Py_Size(z) = -(Py_Size(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002341 }
2342 else
2343 z = x_sub(b, a);
2344 }
2345 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002346 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002347 z = x_sub(a, b);
2348 else
2349 z = x_add(a, b);
2350 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002351 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002352}
2353
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002354static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002355long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002356{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002357 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002358
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002359 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002360
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002361 if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002362 PyObject* r;
2363 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002364 return r;
2365 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002366 if (Py_Size(a) < 0) {
2367 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002368 z = x_sub(a, b);
2369 else
2370 z = x_add(a, b);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002371 if (z != NULL && Py_Size(z) != 0)
2372 Py_Size(z) = -(Py_Size(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002373 }
2374 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002375 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002376 z = x_add(a, b);
2377 else
2378 z = x_sub(a, b);
2379 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002380 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002381}
2382
Tim Peters5af4e6c2002-08-12 02:31:19 +00002383/* Grade school multiplication, ignoring the signs.
2384 * Returns the absolute value of the product, or NULL if error.
2385 */
2386static PyLongObject *
2387x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002388{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002389 PyLongObject *z;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002390 Py_ssize_t size_a = ABS(Py_Size(a));
2391 Py_ssize_t size_b = ABS(Py_Size(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002392 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002393
Tim Peters5af4e6c2002-08-12 02:31:19 +00002394 z = _PyLong_New(size_a + size_b);
2395 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002396 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002397
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002398 memset(z->ob_digit, 0, Py_Size(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002399 if (a == b) {
2400 /* Efficient squaring per HAC, Algorithm 14.16:
2401 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2402 * Gives slightly less than a 2x speedup when a == b,
2403 * via exploiting that each entry in the multiplication
2404 * pyramid appears twice (except for the size_a squares).
2405 */
2406 for (i = 0; i < size_a; ++i) {
2407 twodigits carry;
2408 twodigits f = a->ob_digit[i];
2409 digit *pz = z->ob_digit + (i << 1);
2410 digit *pa = a->ob_digit + i + 1;
2411 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002412
Tim Peters0973b992004-08-29 22:16:50 +00002413 SIGCHECK({
2414 Py_DECREF(z);
2415 return NULL;
2416 })
2417
2418 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002419 *pz++ = (digit)(carry & PyLong_MASK);
2420 carry >>= PyLong_SHIFT;
2421 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002422
2423 /* Now f is added in twice in each column of the
2424 * pyramid it appears. Same as adding f<<1 once.
2425 */
2426 f <<= 1;
2427 while (pa < paend) {
2428 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002429 *pz++ = (digit)(carry & PyLong_MASK);
2430 carry >>= PyLong_SHIFT;
2431 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002432 }
2433 if (carry) {
2434 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002435 *pz++ = (digit)(carry & PyLong_MASK);
2436 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002437 }
2438 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002439 *pz += (digit)(carry & PyLong_MASK);
2440 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002441 }
Tim Peters0973b992004-08-29 22:16:50 +00002442 }
2443 else { /* a is not the same as b -- gradeschool long mult */
2444 for (i = 0; i < size_a; ++i) {
2445 twodigits carry = 0;
2446 twodigits f = a->ob_digit[i];
2447 digit *pz = z->ob_digit + i;
2448 digit *pb = b->ob_digit;
2449 digit *pbend = b->ob_digit + size_b;
2450
2451 SIGCHECK({
2452 Py_DECREF(z);
2453 return NULL;
2454 })
2455
2456 while (pb < pbend) {
2457 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002458 *pz++ = (digit)(carry & PyLong_MASK);
2459 carry >>= PyLong_SHIFT;
2460 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002461 }
2462 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002463 *pz += (digit)(carry & PyLong_MASK);
2464 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002465 }
2466 }
Tim Peters44121a62002-08-12 06:17:58 +00002467 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002468}
2469
2470/* A helper for Karatsuba multiplication (k_mul).
2471 Takes a long "n" and an integer "size" representing the place to
2472 split, and sets low and high such that abs(n) == (high << size) + low,
2473 viewing the shift as being by digits. The sign bit is ignored, and
2474 the return values are >= 0.
2475 Returns 0 on success, -1 on failure.
2476*/
2477static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002478kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002479{
2480 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002481 Py_ssize_t size_lo, size_hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002482 const Py_ssize_t size_n = ABS(Py_Size(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002483
2484 size_lo = MIN(size_n, size);
2485 size_hi = size_n - size_lo;
2486
2487 if ((hi = _PyLong_New(size_hi)) == NULL)
2488 return -1;
2489 if ((lo = _PyLong_New(size_lo)) == NULL) {
2490 Py_DECREF(hi);
2491 return -1;
2492 }
2493
2494 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2495 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2496
2497 *high = long_normalize(hi);
2498 *low = long_normalize(lo);
2499 return 0;
2500}
2501
Tim Peters60004642002-08-12 22:01:34 +00002502static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2503
Tim Peters5af4e6c2002-08-12 02:31:19 +00002504/* Karatsuba multiplication. Ignores the input signs, and returns the
2505 * absolute value of the product (or NULL if error).
2506 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2507 */
2508static PyLongObject *
2509k_mul(PyLongObject *a, PyLongObject *b)
2510{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002511 Py_ssize_t asize = ABS(Py_Size(a));
2512 Py_ssize_t bsize = ABS(Py_Size(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002513 PyLongObject *ah = NULL;
2514 PyLongObject *al = NULL;
2515 PyLongObject *bh = NULL;
2516 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002517 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002518 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002519 Py_ssize_t shift; /* the number of digits we split off */
2520 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002521
Tim Peters5af4e6c2002-08-12 02:31:19 +00002522 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2523 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2524 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002525 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002526 * By picking X to be a power of 2, "*X" is just shifting, and it's
2527 * been reduced to 3 multiplies on numbers half the size.
2528 */
2529
Tim Petersfc07e562002-08-12 02:54:10 +00002530 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002531 * is largest.
2532 */
Tim Peters738eda72002-08-12 15:08:20 +00002533 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002534 t1 = a;
2535 a = b;
2536 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002537
2538 i = asize;
2539 asize = bsize;
2540 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002541 }
2542
2543 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002544 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2545 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002546 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002547 return _PyLong_New(0);
2548 else
2549 return x_mul(a, b);
2550 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002551
Tim Peters60004642002-08-12 22:01:34 +00002552 /* If a is small compared to b, splitting on b gives a degenerate
2553 * case with ah==0, and Karatsuba may be (even much) less efficient
2554 * than "grade school" then. However, we can still win, by viewing
2555 * b as a string of "big digits", each of width a->ob_size. That
2556 * leads to a sequence of balanced calls to k_mul.
2557 */
2558 if (2 * asize <= bsize)
2559 return k_lopsided_mul(a, b);
2560
Tim Petersd6974a52002-08-13 20:37:51 +00002561 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002562 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002563 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002564 assert(Py_Size(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002565
Tim Peters0973b992004-08-29 22:16:50 +00002566 if (a == b) {
2567 bh = ah;
2568 bl = al;
2569 Py_INCREF(bh);
2570 Py_INCREF(bl);
2571 }
2572 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002573
Tim Petersd64c1de2002-08-12 17:36:03 +00002574 /* The plan:
2575 * 1. Allocate result space (asize + bsize digits: that's always
2576 * enough).
2577 * 2. Compute ah*bh, and copy into result at 2*shift.
2578 * 3. Compute al*bl, and copy into result at 0. Note that this
2579 * can't overlap with #2.
2580 * 4. Subtract al*bl from the result, starting at shift. This may
2581 * underflow (borrow out of the high digit), but we don't care:
2582 * we're effectively doing unsigned arithmetic mod
2583 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2584 * borrows and carries out of the high digit can be ignored.
2585 * 5. Subtract ah*bh from the result, starting at shift.
2586 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2587 * at shift.
2588 */
2589
2590 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002591 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002592 if (ret == NULL) goto fail;
2593#ifdef Py_DEBUG
2594 /* Fill with trash, to catch reference to uninitialized digits. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002595 memset(ret->ob_digit, 0xDF, Py_Size(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002596#endif
Tim Peters44121a62002-08-12 06:17:58 +00002597
Tim Petersd64c1de2002-08-12 17:36:03 +00002598 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002599 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002600 assert(Py_Size(t1) >= 0);
2601 assert(2*shift + Py_Size(t1) <= Py_Size(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002602 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002603 Py_Size(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002604
2605 /* Zero-out the digits higher than the ah*bh copy. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002606 i = Py_Size(ret) - 2*shift - Py_Size(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002607 if (i)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002608 memset(ret->ob_digit + 2*shift + Py_Size(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002609 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002610
Tim Petersd64c1de2002-08-12 17:36:03 +00002611 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002612 if ((t2 = k_mul(al, bl)) == NULL) {
2613 Py_DECREF(t1);
2614 goto fail;
2615 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002616 assert(Py_Size(t2) >= 0);
2617 assert(Py_Size(t2) <= 2*shift); /* no overlap with high digits */
2618 memcpy(ret->ob_digit, t2->ob_digit, Py_Size(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002619
2620 /* Zero out remaining digits. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002621 i = 2*shift - Py_Size(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002622 if (i)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002623 memset(ret->ob_digit + Py_Size(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002624
Tim Petersd64c1de2002-08-12 17:36:03 +00002625 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2626 * because it's fresher in cache.
2627 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002628 i = Py_Size(ret) - shift; /* # digits after shift */
2629 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_Size(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002630 Py_DECREF(t2);
2631
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002632 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_Size(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002633 Py_DECREF(t1);
2634
Tim Petersd64c1de2002-08-12 17:36:03 +00002635 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002636 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2637 Py_DECREF(ah);
2638 Py_DECREF(al);
2639 ah = al = NULL;
2640
Tim Peters0973b992004-08-29 22:16:50 +00002641 if (a == b) {
2642 t2 = t1;
2643 Py_INCREF(t2);
2644 }
2645 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002646 Py_DECREF(t1);
2647 goto fail;
2648 }
2649 Py_DECREF(bh);
2650 Py_DECREF(bl);
2651 bh = bl = NULL;
2652
Tim Peters738eda72002-08-12 15:08:20 +00002653 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002654 Py_DECREF(t1);
2655 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002656 if (t3 == NULL) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002657 assert(Py_Size(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002658
Tim Petersd6974a52002-08-13 20:37:51 +00002659 /* Add t3. It's not obvious why we can't run out of room here.
2660 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002661 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002662 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_Size(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002663 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002664
Tim Peters5af4e6c2002-08-12 02:31:19 +00002665 return long_normalize(ret);
2666
2667 fail:
2668 Py_XDECREF(ret);
2669 Py_XDECREF(ah);
2670 Py_XDECREF(al);
2671 Py_XDECREF(bh);
2672 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002673 return NULL;
2674}
2675
Tim Petersd6974a52002-08-13 20:37:51 +00002676/* (*) Why adding t3 can't "run out of room" above.
2677
Tim Petersab86c2b2002-08-15 20:06:00 +00002678Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2679to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002680
Tim Petersab86c2b2002-08-15 20:06:00 +000026811. For any integer i, i = c(i/2) + f(i/2). In particular,
2682 bsize = c(bsize/2) + f(bsize/2).
26832. shift = f(bsize/2)
26843. asize <= bsize
26854. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2686 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002687
Tim Petersab86c2b2002-08-15 20:06:00 +00002688We allocated asize + bsize result digits, and add t3 into them at an offset
2689of shift. This leaves asize+bsize-shift allocated digit positions for t3
2690to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2691asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002692
Tim Petersab86c2b2002-08-15 20:06:00 +00002693bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2694at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002695
Tim Petersab86c2b2002-08-15 20:06:00 +00002696If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2697digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2698most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002699
Tim Petersab86c2b2002-08-15 20:06:00 +00002700The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002701
Tim Petersab86c2b2002-08-15 20:06:00 +00002702 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002703
Tim Petersab86c2b2002-08-15 20:06:00 +00002704and we have asize + c(bsize/2) available digit positions. We need to show
2705this is always enough. An instance of c(bsize/2) cancels out in both, so
2706the question reduces to whether asize digits is enough to hold
2707(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2708then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2709asize 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 +00002710digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002711asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002712c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2713is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2714bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002715
Tim Peters48d52c02002-08-14 17:07:32 +00002716Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2717clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2718ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002719*/
2720
Tim Peters60004642002-08-12 22:01:34 +00002721/* b has at least twice the digits of a, and a is big enough that Karatsuba
2722 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2723 * of slices, each with a->ob_size digits, and multiply the slices by a,
2724 * one at a time. This gives k_mul balanced inputs to work with, and is
2725 * also cache-friendly (we compute one double-width slice of the result
2726 * at a time, then move on, never bactracking except for the helpful
2727 * single-width slice overlap between successive partial sums).
2728 */
2729static PyLongObject *
2730k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2731{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002732 const Py_ssize_t asize = ABS(Py_Size(a));
2733 Py_ssize_t bsize = ABS(Py_Size(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002734 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002735 PyLongObject *ret;
2736 PyLongObject *bslice = NULL;
2737
2738 assert(asize > KARATSUBA_CUTOFF);
2739 assert(2 * asize <= bsize);
2740
2741 /* Allocate result space, and zero it out. */
2742 ret = _PyLong_New(asize + bsize);
2743 if (ret == NULL)
2744 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002745 memset(ret->ob_digit, 0, Py_Size(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002746
2747 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002748 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002749 if (bslice == NULL)
2750 goto fail;
2751
2752 nbdone = 0;
2753 while (bsize > 0) {
2754 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002755 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002756
2757 /* Multiply the next slice of b by a. */
2758 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2759 nbtouse * sizeof(digit));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002760 Py_Size(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002761 product = k_mul(a, bslice);
2762 if (product == NULL)
2763 goto fail;
2764
2765 /* Add into result. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002766 (void)v_iadd(ret->ob_digit + nbdone, Py_Size(ret) - nbdone,
2767 product->ob_digit, Py_Size(product));
Tim Peters60004642002-08-12 22:01:34 +00002768 Py_DECREF(product);
2769
2770 bsize -= nbtouse;
2771 nbdone += nbtouse;
2772 }
2773
2774 Py_DECREF(bslice);
2775 return long_normalize(ret);
2776
2777 fail:
2778 Py_DECREF(ret);
2779 Py_XDECREF(bslice);
2780 return NULL;
2781}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002782
2783static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002784long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002785{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002786 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002787
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002788 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002789
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002790 if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002791 PyObject *r;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002792 r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002793 return r;
2794 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002795
Tim Petersd64c1de2002-08-12 17:36:03 +00002796 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002797 /* Negate if exactly one of the inputs is negative. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002798 if (((Py_Size(a) ^ Py_Size(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002799 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002800 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002801}
2802
Guido van Rossume32e0141992-01-19 16:31:05 +00002803/* The / and % operators are now defined in terms of divmod().
2804 The expression a mod b has the value a - b*floor(a/b).
2805 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002806 |a| by |b|, with the sign of a. This is also expressed
2807 as a - b*trunc(a/b), if trunc truncates towards zero.
2808 Some examples:
2809 a b a rem b a mod b
2810 13 10 3 3
2811 -13 10 -3 7
2812 13 -10 3 -7
2813 -13 -10 -3 -3
2814 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002815 have different signs. We then subtract one from the 'div'
2816 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002817
Tim Peters47e52ee2004-08-30 02:44:38 +00002818/* Compute
2819 * *pdiv, *pmod = divmod(v, w)
2820 * NULL can be passed for pdiv or pmod, in which case that part of
2821 * the result is simply thrown away. The caller owns a reference to
2822 * each of these it requests (does not pass NULL for).
2823 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002824static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002825l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002826 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002827{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002828 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002829
Guido van Rossume32e0141992-01-19 16:31:05 +00002830 if (long_divrem(v, w, &div, &mod) < 0)
2831 return -1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002832 if ((Py_Size(mod) < 0 && Py_Size(w) > 0) ||
2833 (Py_Size(mod) > 0 && Py_Size(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002834 PyLongObject *temp;
2835 PyLongObject *one;
2836 temp = (PyLongObject *) long_add(mod, w);
2837 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002838 mod = temp;
2839 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002840 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002841 return -1;
2842 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002843 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002844 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002845 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2846 Py_DECREF(mod);
2847 Py_DECREF(div);
2848 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002849 return -1;
2850 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002851 Py_DECREF(one);
2852 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002853 div = temp;
2854 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002855 if (pdiv != NULL)
2856 *pdiv = div;
2857 else
2858 Py_DECREF(div);
2859
2860 if (pmod != NULL)
2861 *pmod = mod;
2862 else
2863 Py_DECREF(mod);
2864
Guido van Rossume32e0141992-01-19 16:31:05 +00002865 return 0;
2866}
2867
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002868static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002869long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002870{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002871 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002872
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002873 CHECK_BINOP(a, b);
2874 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002875 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002876 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002877}
2878
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002879static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002880long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002881{
Tim Peterse2a60002001-09-04 06:17:36 +00002882 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002883 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002884
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002885 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002886 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2887 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002888 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002889 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002890 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002891 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2892 but should really be set correctly after sucessful calls to
2893 _PyLong_AsScaledDouble() */
2894 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002895
2896 if (bd == 0.0) {
2897 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002898 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002899 return NULL;
2900 }
2901
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002902 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002903 ad /= bd; /* overflow/underflow impossible here */
2904 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002905 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002906 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002907 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002908 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002909 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002910 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002911 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002912 goto overflow;
2913 return PyFloat_FromDouble(ad);
2914
2915overflow:
2916 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002917 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002918 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002919
Tim Peters20dab9f2001-09-04 05:31:47 +00002920}
2921
2922static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002923long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002924{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002925 PyLongObject *mod;
2926
2927 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002928
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002929 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002930 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002931 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002932}
2933
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002934static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002935long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002936{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002937 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002938 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002939
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002940 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002941
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002942 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002943 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002944 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002945 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002946 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002947 PyTuple_SetItem(z, 0, (PyObject *) div);
2948 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002949 }
2950 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002951 Py_DECREF(div);
2952 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002953 }
2954 return z;
2955}
2956
Tim Peters47e52ee2004-08-30 02:44:38 +00002957/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002958static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002959long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002960{
Tim Peters47e52ee2004-08-30 02:44:38 +00002961 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2962 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002963
Tim Peters47e52ee2004-08-30 02:44:38 +00002964 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002965 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002966 PyLongObject *temp = NULL;
2967
2968 /* 5-ary values. If the exponent is large enough, table is
2969 * precomputed so that table[i] == a**i % c for i in range(32).
2970 */
2971 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2972 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2973
2974 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002975 CHECK_BINOP(v, w);
2976 a = (PyLongObject*)v; Py_INCREF(a);
2977 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002978 if (PyLong_Check(x)) {
2979 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002980 Py_INCREF(x);
2981 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002982 else if (x == Py_None)
2983 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002984 else {
2985 Py_DECREF(a);
2986 Py_DECREF(b);
2987 Py_INCREF(Py_NotImplemented);
2988 return Py_NotImplemented;
2989 }
Tim Peters4c483c42001-09-05 06:24:58 +00002990
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002991 if (Py_Size(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00002992 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002993 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002994 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002995 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002996 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002997 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002998 /* else return a float. This works because we know
2999 that this calls float_pow() which converts its
3000 arguments to double. */
3001 Py_DECREF(a);
3002 Py_DECREF(b);
3003 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003004 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003005 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003006
3007 if (c) {
3008 /* if modulus == 0:
3009 raise ValueError() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003010 if (Py_Size(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003011 PyErr_SetString(PyExc_ValueError,
3012 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003013 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003014 }
3015
3016 /* if modulus < 0:
3017 negativeOutput = True
3018 modulus = -modulus */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003019 if (Py_Size(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003020 negativeOutput = 1;
3021 temp = (PyLongObject *)_PyLong_Copy(c);
3022 if (temp == NULL)
3023 goto Error;
3024 Py_DECREF(c);
3025 c = temp;
3026 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003027 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003028 }
3029
3030 /* if modulus == 1:
3031 return 0 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003032 if ((Py_Size(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003033 z = (PyLongObject *)PyLong_FromLong(0L);
3034 goto Done;
3035 }
3036
3037 /* if base < 0:
3038 base = base % modulus
3039 Having the base positive just makes things easier. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003040 if (Py_Size(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003041 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003042 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003043 Py_DECREF(a);
3044 a = temp;
3045 temp = NULL;
3046 }
3047 }
3048
3049 /* At this point a, b, and c are guaranteed non-negative UNLESS
3050 c is NULL, in which case a may be negative. */
3051
3052 z = (PyLongObject *)PyLong_FromLong(1L);
3053 if (z == NULL)
3054 goto Error;
3055
3056 /* Perform a modular reduction, X = X % c, but leave X alone if c
3057 * is NULL.
3058 */
3059#define REDUCE(X) \
3060 if (c != NULL) { \
3061 if (l_divmod(X, c, NULL, &temp) < 0) \
3062 goto Error; \
3063 Py_XDECREF(X); \
3064 X = temp; \
3065 temp = NULL; \
3066 }
3067
3068 /* Multiply two values, then reduce the result:
3069 result = X*Y % c. If c is NULL, skip the mod. */
3070#define MULT(X, Y, result) \
3071{ \
3072 temp = (PyLongObject *)long_mul(X, Y); \
3073 if (temp == NULL) \
3074 goto Error; \
3075 Py_XDECREF(result); \
3076 result = temp; \
3077 temp = NULL; \
3078 REDUCE(result) \
3079}
3080
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003081 if (Py_Size(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003082 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3083 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003084 for (i = Py_Size(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003085 digit bi = b->ob_digit[i];
3086
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003087 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003088 MULT(z, z, z)
3089 if (bi & j)
3090 MULT(z, a, z)
3091 }
3092 }
3093 }
3094 else {
3095 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3096 Py_INCREF(z); /* still holds 1L */
3097 table[0] = z;
3098 for (i = 1; i < 32; ++i)
3099 MULT(table[i-1], a, table[i])
3100
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003101 for (i = Py_Size(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003102 const digit bi = b->ob_digit[i];
3103
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003104 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003105 const int index = (bi >> j) & 0x1f;
3106 for (k = 0; k < 5; ++k)
3107 MULT(z, z, z)
3108 if (index)
3109 MULT(z, table[index], z)
3110 }
3111 }
3112 }
3113
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003114 if (negativeOutput && (Py_Size(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003115 temp = (PyLongObject *)long_sub(z, c);
3116 if (temp == NULL)
3117 goto Error;
3118 Py_DECREF(z);
3119 z = temp;
3120 temp = NULL;
3121 }
3122 goto Done;
3123
3124 Error:
3125 if (z != NULL) {
3126 Py_DECREF(z);
3127 z = NULL;
3128 }
3129 /* fall through */
3130 Done:
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003131 if (Py_Size(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003132 for (i = 0; i < 32; ++i)
3133 Py_XDECREF(table[i]);
3134 }
Tim Petersde7990b2005-07-17 23:45:23 +00003135 Py_DECREF(a);
3136 Py_DECREF(b);
3137 Py_XDECREF(c);
3138 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003139 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003140}
3141
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003142static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003143long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003144{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003145 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003146 PyLongObject *x;
3147 PyLongObject *w;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003148 if (ABS(Py_Size(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003149 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003150 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003151 if (w == NULL)
3152 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003153 x = (PyLongObject *) long_add(v, w);
3154 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003155 if (x == NULL)
3156 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003157 Py_Size(x) = -(Py_Size(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003158 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003159}
3160
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003161static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003162long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003163{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003164 PyLongObject *z;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003165 if (ABS(Py_Size(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003166 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003167 z = (PyLongObject *)_PyLong_Copy(v);
3168 if (z != NULL)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003169 Py_Size(z) = -(Py_Size(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003170 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003171}
3172
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003173static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003174long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003175{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003176 if (Py_Size(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003177 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003178 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003179 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003180}
3181
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003182static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003183long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003184{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003185 return ABS(Py_Size(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003186}
3187
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003188static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003189long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003190{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003191 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003192 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003193 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003194 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003195
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003196 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003197
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003198 if (Py_Size(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003199 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003200 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003201 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003202 if (a1 == NULL)
3203 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003204 a2 = (PyLongObject *) long_rshift(a1, b);
3205 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003206 if (a2 == NULL)
3207 goto rshift_error;
3208 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003209 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003210 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003211 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003212
Neil Schemenauerba872e22001-01-04 01:46:03 +00003213 shiftby = PyLong_AsLong((PyObject *)b);
3214 if (shiftby == -1L && PyErr_Occurred())
3215 goto rshift_error;
3216 if (shiftby < 0) {
3217 PyErr_SetString(PyExc_ValueError,
3218 "negative shift count");
3219 goto rshift_error;
3220 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003221 wordshift = shiftby / PyLong_SHIFT;
3222 newsize = ABS(Py_Size(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003223 if (newsize <= 0) {
3224 z = _PyLong_New(0);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003225 return (PyObject *)z;
3226 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003227 loshift = shiftby % PyLong_SHIFT;
3228 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003229 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003230 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003231 z = _PyLong_New(newsize);
3232 if (z == NULL)
3233 goto rshift_error;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003234 if (Py_Size(a) < 0)
3235 Py_Size(z) = -(Py_Size(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003236 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3237 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3238 if (i+1 < newsize)
3239 z->ob_digit[i] |=
3240 (a->ob_digit[j+1] << hishift) & himask;
3241 }
3242 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003243 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003244rshift_error:
Neil Schemenauerba872e22001-01-04 01:46:03 +00003245 return (PyObject *) z;
3246
Guido van Rossumc6913e71991-11-19 20:26:46 +00003247}
3248
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003249static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003250long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003251{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003252 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003253 PyLongObject *a = (PyLongObject*)v;
3254 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003255 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003256 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003257 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003258 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003259
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003260 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003261
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003262 shiftby = PyLong_AsLong((PyObject *)b);
3263 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003264 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003265 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003266 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003267 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003268 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003269 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003270 PyErr_SetString(PyExc_ValueError,
3271 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003272 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003273 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003274 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3275 wordshift = (int)shiftby / PyLong_SHIFT;
3276 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003277
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003278 oldsize = ABS(Py_Size(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003279 newsize = oldsize + wordshift;
3280 if (remshift)
3281 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003282 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003283 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003284 goto lshift_error;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003285 if (Py_Size(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003286 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003287 for (i = 0; i < wordshift; i++)
3288 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003289 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003290 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003291 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003292 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3293 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003294 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003295 if (remshift)
3296 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003297 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003298 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003299 z = long_normalize(z);
3300lshift_error:
Neil Schemenauerba872e22001-01-04 01:46:03 +00003301 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003302}
3303
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003304
3305/* Bitwise and/xor/or operations */
3306
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003307static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003308long_bitwise(PyLongObject *a,
3309 int op, /* '&', '|', '^' */
3310 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003311{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003312 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003313 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003314 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003315 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003316 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003317 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003318 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003319
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003320 if (Py_Size(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003321 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003322 if (a == NULL)
3323 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003324 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003325 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003326 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003327 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003328 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003329 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003330 if (Py_Size(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003331 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003332 if (b == NULL) {
3333 Py_DECREF(a);
3334 return NULL;
3335 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003336 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003337 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003338 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003339 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003340 maskb = 0;
3341 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003342
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003343 negz = 0;
3344 switch (op) {
3345 case '^':
3346 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003347 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003348 negz = -1;
3349 }
3350 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003351 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003352 if (maska && maskb) {
3353 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003354 maska ^= PyLong_MASK;
3355 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003356 negz = -1;
3357 }
3358 break;
3359 case '|':
3360 if (maska || maskb) {
3361 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003362 maska ^= PyLong_MASK;
3363 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003364 negz = -1;
3365 }
3366 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003367 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003368
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003369 /* JRH: The original logic here was to allocate the result value (z)
3370 as the longer of the two operands. However, there are some cases
3371 where the result is guaranteed to be shorter than that: AND of two
3372 positives, OR of two negatives: use the shorter number. AND with
3373 mixed signs: use the positive number. OR with mixed signs: use the
3374 negative number. After the transformations above, op will be '&'
3375 iff one of these cases applies, and mask will be non-0 for operands
3376 whose length should be ignored.
3377 */
3378
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003379 size_a = Py_Size(a);
3380 size_b = Py_Size(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003381 size_z = op == '&'
3382 ? (maska
3383 ? size_b
3384 : (maskb ? size_a : MIN(size_a, size_b)))
3385 : MAX(size_a, size_b);
3386 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003387 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003388 Py_DECREF(a);
3389 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003390 return NULL;
3391 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003392
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003393 for (i = 0; i < size_z; ++i) {
3394 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3395 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3396 switch (op) {
3397 case '&': z->ob_digit[i] = diga & digb; break;
3398 case '|': z->ob_digit[i] = diga | digb; break;
3399 case '^': z->ob_digit[i] = diga ^ digb; break;
3400 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003401 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003402
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003403 Py_DECREF(a);
3404 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003405 z = long_normalize(z);
3406 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003407 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003408 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003409 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003410 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003411}
3412
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003413static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003414long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003415{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003416 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003417 CHECK_BINOP(a, b);
3418 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003419 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003420}
3421
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003422static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003423long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003424{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003425 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003426 CHECK_BINOP(a, b);
3427 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003428 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003429}
3430
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003431static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003432long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003433{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003434 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003435 CHECK_BINOP(a, b);
3436 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003437 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003438}
3439
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003440static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003441long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003442{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003443 if (PyLong_CheckExact(v))
3444 Py_INCREF(v);
3445 else
3446 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003447 return v;
3448}
3449
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003450static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003451long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003452{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003453 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003454 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003455 if (result == -1.0 && PyErr_Occurred())
3456 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003457 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003458}
3459
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003460static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003461long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003462
Tim Peters6d6c1a32001-08-02 04:15:00 +00003463static PyObject *
3464long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3465{
3466 PyObject *x = NULL;
3467 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003468 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003469
Guido van Rossumbef14172001-08-29 15:47:46 +00003470 if (type != &PyLong_Type)
3471 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003472 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473 &x, &base))
3474 return NULL;
3475 if (x == NULL)
3476 return PyLong_FromLong(0L);
3477 if (base == -909)
3478 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003479 else if (PyUnicode_Check(x))
3480 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3481 PyUnicode_GET_SIZE(x),
3482 base);
3483 else if (PyBytes_Check(x) || PyString_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003484 /* Since PyLong_FromString doesn't have a length parameter,
3485 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003486 char *string;
3487 int size = Py_Size(x);
3488 if (PyBytes_Check(x))
3489 string = PyBytes_AS_STRING(x);
3490 else
3491 string = PyString_AS_STRING(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003492 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003493 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003494 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003495 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003496 "invalid literal for int() with base %d: %R",
3497 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003498 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003499 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003500 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003501 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003502 else {
3503 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003504 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003505 return NULL;
3506 }
3507}
3508
Guido van Rossumbef14172001-08-29 15:47:46 +00003509/* Wimpy, slow approach to tp_new calls for subtypes of long:
3510 first create a regular long from whatever arguments we got,
3511 then allocate a subtype instance and initialize it from
3512 the regular long. The regular long is then thrown away.
3513*/
3514static PyObject *
3515long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3516{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003517 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003518 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003519
3520 assert(PyType_IsSubtype(type, &PyLong_Type));
3521 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3522 if (tmp == NULL)
3523 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003524 assert(PyLong_CheckExact(tmp));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003525 n = Py_Size(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003526 if (n < 0)
3527 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003528 newobj = (PyLongObject *)type->tp_alloc(type, n);
3529 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003530 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003531 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003532 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003533 assert(PyLong_Check(newobj));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003534 Py_Size(newobj) = Py_Size(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003535 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003536 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003537 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003538 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003539}
3540
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003541static PyObject *
3542long_getnewargs(PyLongObject *v)
3543{
3544 return Py_BuildValue("(N)", _PyLong_Copy(v));
3545}
3546
Guido van Rossumb43daf72007-08-01 18:08:08 +00003547static PyObject *
3548long_getN(PyLongObject *v, void *context) {
3549 return PyLong_FromLong((intptr_t)context);
3550}
3551
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003552static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003553long__format__(PyObject *self, PyObject *args)
3554{
3555 /* when back porting this to 2.6, check type of the format_spec
3556 and call either unicode_long__format__ or
3557 string_long__format__ */
3558 return unicode_long__format__(self, args);
3559}
3560
3561
3562static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003563long_round(PyObject *self, PyObject *args)
3564{
3565#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
3566 int ndigits = UNDEF_NDIGITS;
3567 double x;
3568 PyObject *res;
3569
3570 if (!PyArg_ParseTuple(args, "|i", &ndigits))
3571 return NULL;
3572
3573 if (ndigits == UNDEF_NDIGITS)
3574 return long_long(self);
3575
3576 /* If called with two args, defer to float.__round__(). */
3577 x = PyLong_AsDouble(self);
3578 if (x == -1.0 && PyErr_Occurred())
3579 return NULL;
3580 self = PyFloat_FromDouble(x);
3581 if (self == NULL)
3582 return NULL;
3583 res = PyObject_CallMethod(self, "__round__", "i", ndigits);
3584 Py_DECREF(self);
3585 return res;
3586#undef UNDEF_NDIGITS
3587}
3588
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003589static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003590 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3591 "Returns self, the complex conjugate of any int."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003592 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3593 "Truncating an Integral returns itself."},
3594 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3595 "Flooring an Integral returns itself."},
3596 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3597 "Ceiling of an Integral returns itself."},
3598 {"__round__", (PyCFunction)long_round, METH_VARARGS,
3599 "Rounding an Integral returns itself.\n"
3600 "Rounding with an ndigits arguments defers to float.__round__."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003601 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003602 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003603 {NULL, NULL} /* sentinel */
3604};
3605
Guido van Rossumb43daf72007-08-01 18:08:08 +00003606static PyGetSetDef long_getset[] = {
3607 {"real",
3608 (getter)long_long, (setter)NULL,
3609 "the real part of a complex number",
3610 NULL},
3611 {"imag",
3612 (getter)long_getN, (setter)NULL,
3613 "the imaginary part of a complex number",
3614 (void*)0},
3615 {"numerator",
3616 (getter)long_long, (setter)NULL,
3617 "the numerator of a rational number in lowest terms",
3618 NULL},
3619 {"denominator",
3620 (getter)long_getN, (setter)NULL,
3621 "the denominator of a rational number in lowest terms",
3622 (void*)1},
3623 {NULL} /* Sentinel */
3624};
3625
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003626PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003627"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003628\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003629Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630point argument will be truncated towards zero (this does not include a\n\
3631string representation of a floating point number!) When converting a\n\
3632string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003633converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003634
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003635static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003636 (binaryfunc) long_add, /*nb_add*/
3637 (binaryfunc) long_sub, /*nb_subtract*/
3638 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003639 long_mod, /*nb_remainder*/
3640 long_divmod, /*nb_divmod*/
3641 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003642 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003643 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003644 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003645 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003646 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003647 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003648 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003649 long_and, /*nb_and*/
3650 long_xor, /*nb_xor*/
3651 long_or, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00003652 0, /*nb_reserved*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003653 long_long, /*nb_int*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003654 long_long, /*nb_long*/
3655 long_float, /*nb_float*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003656 0, /*nb_oct*/ /* not used */
3657 0, /*nb_hex*/ /* not used */
Guido van Rossum4668b002001-08-08 05:00:18 +00003658 0, /* nb_inplace_add */
3659 0, /* nb_inplace_subtract */
3660 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003661 0, /* nb_inplace_remainder */
3662 0, /* nb_inplace_power */
3663 0, /* nb_inplace_lshift */
3664 0, /* nb_inplace_rshift */
3665 0, /* nb_inplace_and */
3666 0, /* nb_inplace_xor */
3667 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003668 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003669 long_true_divide, /* nb_true_divide */
3670 0, /* nb_inplace_floor_divide */
3671 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003672 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003673};
3674
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003675PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003676 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003677 "int", /* tp_name */
3678 /* See _PyLong_New for why this isn't
3679 sizeof(PyLongObject) - sizeof(digit) */
3680 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003681 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003682 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683 0, /* tp_print */
3684 0, /* tp_getattr */
3685 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003686 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003687 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688 &long_as_number, /* tp_as_number */
3689 0, /* tp_as_sequence */
3690 0, /* tp_as_mapping */
3691 (hashfunc)long_hash, /* tp_hash */
3692 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003693 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003694 PyObject_GenericGetAttr, /* tp_getattro */
3695 0, /* tp_setattro */
3696 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003697 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3698 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003699 long_doc, /* tp_doc */
3700 0, /* tp_traverse */
3701 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003702 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003703 0, /* tp_weaklistoffset */
3704 0, /* tp_iter */
3705 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003706 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003707 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003708 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003709 0, /* tp_base */
3710 0, /* tp_dict */
3711 0, /* tp_descr_get */
3712 0, /* tp_descr_set */
3713 0, /* tp_dictoffset */
3714 0, /* tp_init */
3715 0, /* tp_alloc */
3716 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003717 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003718};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003719
3720int
3721_PyLong_Init(void)
3722{
3723#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3724 int ival;
3725 PyLongObject *v = small_ints;
3726 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3727 PyObject_INIT(v, &PyLong_Type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003728 Py_Size(v) = -1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003729 v->ob_digit[0] = -ival;
3730 }
3731 for (; ival < NSMALLPOSINTS; ival++, v++) {
3732 PyObject_INIT(v, &PyLong_Type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003733 Py_Size(v) = ival ? 1 : 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003734 v->ob_digit[0] = ival;
3735 }
3736#endif
3737 return 1;
3738}
3739
3740void
3741PyLong_Fini(void)
3742{
3743#if 0
3744 int i;
3745 /* This is currently not needed; the small integers
3746 are statically allocated */
3747#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3748 PyIntObject **q;
3749
3750 i = NSMALLNEGINTS + NSMALLPOSINTS;
3751 q = small_ints;
3752 while (--i >= 0) {
3753 Py_XDECREF(*q);
3754 *q++ = NULL;
3755 }
3756#endif
3757#endif
3758}