blob: 79d734e4f2b8920994271aa26f10e65acdcf7121 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00008#include <ctype.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +00009
Guido van Rossum22201222007-08-07 22:02:18 +000010long
11PyInt_GetMax(void)
12{
13 return LONG_MAX; /* To initialize sys.maxint */
14}
15
Guido van Rossumddefaf32007-01-14 03:31:43 +000016#ifndef NSMALLPOSINTS
17#define NSMALLPOSINTS 257
18#endif
19#ifndef NSMALLNEGINTS
20#define NSMALLNEGINTS 5
21#endif
22#if NSMALLNEGINTS + NSMALLPOSINTS > 0
23/* Small integers are preallocated in this array so that they
24 can be shared.
25 The integers that are preallocated are those in the range
26 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
27*/
28static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
29#ifdef COUNT_ALLOCS
30int quick_int_allocs, quick_neg_int_allocs;
31#endif
32
Guido van Rossum7eaf8222007-06-18 17:58:50 +000033static PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +000034get_small_int(int ival)
35{
36 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
37 Py_INCREF(v);
38#ifdef COUNT_ALLOCS
39 if (ival >= 0)
40 quick_int_allocs++;
41 else
42 quick_neg_int_allocs++;
43#endif
44 return v;
45}
46#define CHECK_SMALL_INT(ival) \
47 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
48 return get_small_int(ival); \
49 } while(0)
50
51#else
52#define CHECK_SMALL_INT(ival)
53#endif
54
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000055#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 +000056/* If a freshly-allocated long is already shared, it must
57 be a small integer, so negating it must go to PyLong_FromLong */
58#define NEGATE(x) \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000059 do if (Py_Refcnt(x) == 1) Py_Size(x) = -Py_Size(x); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000060 else { PyObject* tmp=PyInt_FromLong(-MEDIUM_VALUE(x)); \
61 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
62 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000063/* For long multiplication, use the O(N**2) school algorithm unless
64 * both operands contain more than KARATSUBA_CUTOFF digits (this
65 * being an internal Python long digit, in base BASE).
66 */
Tim Peters0973b992004-08-29 22:16:50 +000067#define KARATSUBA_CUTOFF 70
68#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000069
Tim Peters47e52ee2004-08-30 02:44:38 +000070/* For exponentiation, use the binary left-to-right algorithm
71 * unless the exponent contains more than FIVEARY_CUTOFF digits.
72 * In that case, do 5 bits at a time. The potential drawback is that
73 * a table of 2**5 intermediate results is computed.
74 */
75#define FIVEARY_CUTOFF 8
76
Guido van Rossume32e0141992-01-19 16:31:05 +000077#define ABS(x) ((x) < 0 ? -(x) : (x))
78
Tim Peters5af4e6c2002-08-12 02:31:19 +000079#undef MIN
80#undef MAX
81#define MAX(x, y) ((x) < (y) ? (y) : (x))
82#define MIN(x, y) ((x) > (y) ? (y) : (x))
83
Guido van Rossume32e0141992-01-19 16:31:05 +000084/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000085static PyLongObject *long_normalize(PyLongObject *);
86static PyLongObject *mul1(PyLongObject *, wdigit);
87static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000088static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Guido van Rossume32e0141992-01-19 16:31:05 +000089
Guido van Rossumc0b618a1997-05-02 03:12:38 +000090#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000091 if (--_Py_Ticker < 0) { \
92 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +000093 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000094 }
95
Guido van Rossumedcc38a1991-05-05 20:09:44 +000096/* Normalize (remove leading zeros from) a long int object.
97 Doesn't attempt to free the storage--in most cases, due to the nature
98 of the algorithms used, this could save at most be one word anyway. */
99
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000100static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000101long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000103 Py_ssize_t j = ABS(Py_Size(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000104 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000105
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000106 while (i > 0 && v->ob_digit[i-1] == 0)
107 --i;
108 if (i != j)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000109 Py_Size(v) = (Py_Size(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000110 return v;
111}
112
113/* Allocate a new long int object with size digits.
114 Return NULL and set exception if we run out of memory. */
115
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000116PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000117_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000118{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000119 PyLongObject *result;
120 /* Can't use sizeof(PyLongObject) here, since the
121 compiler takes padding at the end into account.
122 As the consequence, this would waste 2 bytes on
123 a 32-bit system, and 6 bytes on a 64-bit system.
124 This computation would be incorrect on systems
125 which have padding before the digits; with 16-bit
126 digits this should not happen. */
127 result = PyObject_MALLOC(sizeof(PyVarObject) +
128 size*sizeof(digit));
129 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000130 PyErr_NoMemory();
131 return NULL;
132 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000133 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000134}
135
Tim Peters64b5ce32001-09-10 20:52:51 +0000136PyObject *
137_PyLong_Copy(PyLongObject *src)
138{
139 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000140 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000141
142 assert(src != NULL);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000143 i = Py_Size(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000144 if (i < 0)
145 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000146 if (i < 2) {
147 int ival = src->ob_digit[0];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000148 if (Py_Size(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000149 ival = -ival;
150 CHECK_SMALL_INT(ival);
151 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000152 result = _PyLong_New(i);
153 if (result != NULL) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000154 Py_Size(result) = Py_Size(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000155 while (--i >= 0)
156 result->ob_digit[i] = src->ob_digit[i];
157 }
158 return (PyObject *)result;
159}
160
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000161/* Create a new long int object from a C long int */
162
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000163PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000164PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000165{
Tim Petersce9de2f2001-06-14 04:56:19 +0000166 PyLongObject *v;
167 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
168 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000169 int sign = 1;
170
171 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000172
173 if (ival < 0) {
174 ival = -ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000175 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000176 }
177
Guido van Rossumddefaf32007-01-14 03:31:43 +0000178 /* Fast path for single-digits ints */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000179 if (!(ival>>PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000180 v = _PyLong_New(1);
181 if (v) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000182 Py_Size(v) = sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000183 v->ob_digit[0] = ival;
184 }
185 return (PyObject*)v;
186 }
187
188 /* 2 digits */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000189 if (!(ival >> 2*PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000190 v = _PyLong_New(2);
191 if (v) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000192 Py_Size(v) = 2*sign;
193 v->ob_digit[0] = (digit)ival & PyLong_MASK;
194 v->ob_digit[1] = ival >> PyLong_SHIFT;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000195 }
196 return (PyObject*)v;
197 }
198
199 /* Larger numbers: loop to determine number of digits */
Tim Petersce9de2f2001-06-14 04:56:19 +0000200 t = (unsigned long)ival;
201 while (t) {
202 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000203 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000204 }
205 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000206 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000207 digit *p = v->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000208 Py_Size(v) = ndigits*sign;
Tim Petersce9de2f2001-06-14 04:56:19 +0000209 t = (unsigned long)ival;
210 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000211 *p++ = (digit)(t & PyLong_MASK);
212 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000213 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000214 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000215 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000216}
217
Guido van Rossum53756b11997-01-03 17:14:46 +0000218/* Create a new long int object from a C unsigned long int */
219
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000220PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000221PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000222{
Tim Petersce9de2f2001-06-14 04:56:19 +0000223 PyLongObject *v;
224 unsigned long t;
225 int ndigits = 0;
226
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000227 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000228 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000229 /* Count the number of Python digits. */
230 t = (unsigned long)ival;
231 while (t) {
232 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000233 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000234 }
235 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000236 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000237 digit *p = v->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000238 Py_Size(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000239 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000240 *p++ = (digit)(ival & PyLong_MASK);
241 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000242 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000243 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000245}
246
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000247/* Create a new long int object from a C double */
248
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000249PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000250PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000251{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000252 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000253 double frac;
254 int i, ndig, expo, neg;
255 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000256 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000257 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000258 "cannot convert float infinity to int");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000259 return NULL;
260 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000261 CHECK_SMALL_INT((int)dval);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000262 if (dval < 0.0) {
263 neg = 1;
264 dval = -dval;
265 }
266 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
267 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000268 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000269 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000270 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000271 if (v == NULL)
272 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000273 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000274 for (i = ndig; --i >= 0; ) {
275 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000276 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000277 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000278 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000279 }
280 if (neg)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000281 Py_Size(v) = -(Py_Size(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000282 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000283}
284
Thomas Wouters89f507f2006-12-13 04:49:30 +0000285/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
286 * anything about what happens when a signed integer operation overflows,
287 * and some compilers think they're doing you a favor by being "clever"
288 * then. The bit pattern for the largest postive signed long is
289 * (unsigned long)LONG_MAX, and for the smallest negative signed long
290 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
291 * However, some other compilers warn about applying unary minus to an
292 * unsigned operand. Hence the weird "0-".
293 */
294#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
295#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
296
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000297/* Get a C long int from a long int object.
298 Returns -1 and sets an error condition if overflow occurs. */
299
300long
Tim Peters9f688bf2000-07-07 15:53:28 +0000301PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000302{
Guido van Rossumf7531811998-05-26 14:33:37 +0000303 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000304 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000305 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000306 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000307 Py_ssize_t i;
308 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000309 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000310
Guido van Rossumddefaf32007-01-14 03:31:43 +0000311 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000313 return -1;
314 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000315
316 if (!PyLong_Check(vv)) {
317 PyNumberMethods *nb;
318 if ((nb = vv->ob_type->tp_as_number) == NULL ||
319 nb->nb_int == NULL) {
320 PyErr_SetString(PyExc_TypeError, "an integer is required");
321 return -1;
322 }
323 vv = (*nb->nb_int) (vv);
324 if (vv == NULL)
325 return -1;
326 do_decref = 1;
327 if (!PyLong_Check(vv)) {
328 Py_DECREF(vv);
329 PyErr_SetString(PyExc_TypeError,
330 "nb_int should return int object");
331 return -1;
332 }
333 }
334
Georg Brandl61c31b02007-02-26 14:46:30 +0000335 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000336 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000337 i = Py_Size(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000338
Georg Brandl61c31b02007-02-26 14:46:30 +0000339 switch (i) {
340 case -1:
341 res = -v->ob_digit[0];
342 break;
343 case 0:
344 res = 0;
345 break;
346 case 1:
347 res = v->ob_digit[0];
348 break;
349 default:
350 sign = 1;
351 x = 0;
352 if (i < 0) {
353 sign = -1;
354 i = -(i);
355 }
356 while (--i >= 0) {
357 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000358 x = (x << PyLong_SHIFT) + v->ob_digit[i];
359 if ((x >> PyLong_SHIFT) != prev) {
Georg Brandl61c31b02007-02-26 14:46:30 +0000360 PyErr_SetString(PyExc_OverflowError,
361 "Python int too large to convert to C long");
362 goto exit;
363 }
364 }
365 /* Haven't lost any bits, but casting to long requires extra care
366 * (see comment above).
367 */
368 if (x <= (unsigned long)LONG_MAX) {
369 res = (long)x * sign;
370 }
371 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
372 res = LONG_MIN;
373 }
374 else {
375 PyErr_SetString(PyExc_OverflowError,
376 "Python int too large to convert to C long");
377 }
378 }
379 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000380 if (do_decref) {
381 Py_DECREF(vv);
382 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000383 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000384}
385
Guido van Rossumddefaf32007-01-14 03:31:43 +0000386int
387_PyLong_FitsInLong(PyObject *vv)
388{
389 int size;
390 if (!PyLong_CheckExact(vv)) {
391 PyErr_BadInternalCall();
392 return 0;
393 }
394 /* conservative estimate */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000395 size = Py_Size(vv);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000396 return -2 <= size && size <= 2;
397}
398
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000399/* Get a Py_ssize_t from a long int object.
400 Returns -1 and sets an error condition if overflow occurs. */
401
402Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000403PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000404 register PyLongObject *v;
405 size_t x, prev;
406 Py_ssize_t i;
407 int sign;
408
409 if (vv == NULL || !PyLong_Check(vv)) {
410 PyErr_BadInternalCall();
411 return -1;
412 }
413 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000414 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000415 switch (i) {
416 case -1: return -v->ob_digit[0];
417 case 0: return 0;
418 case 1: return v->ob_digit[0];
419 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000420 sign = 1;
421 x = 0;
422 if (i < 0) {
423 sign = -1;
424 i = -(i);
425 }
426 while (--i >= 0) {
427 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000428 x = (x << PyLong_SHIFT) + v->ob_digit[i];
429 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000430 goto overflow;
431 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000432 /* Haven't lost any bits, but casting to a signed type requires
433 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000434 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000435 if (x <= (size_t)PY_SSIZE_T_MAX) {
436 return (Py_ssize_t)x * sign;
437 }
438 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
439 return PY_SSIZE_T_MIN;
440 }
441 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000442
443 overflow:
444 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000445 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000446 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000447}
448
Guido van Rossumd8c80482002-08-13 00:24:58 +0000449/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000450 Returns -1 and sets an error condition if overflow occurs. */
451
452unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000453PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000454{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000456 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000457 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000458
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000459 if (vv == NULL || !PyLong_Check(vv)) {
460 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000461 return (unsigned long) -1;
462 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000463 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000464 i = Py_Size(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000465 x = 0;
466 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000467 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000468 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000469 return (unsigned long) -1;
470 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000471 switch (i) {
472 case 0: return 0;
473 case 1: return v->ob_digit[0];
474 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000475 while (--i >= 0) {
476 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000477 x = (x << PyLong_SHIFT) + v->ob_digit[i];
478 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000479 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000480 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000481 return (unsigned long) -1;
482 }
483 }
484 return x;
485}
486
487/* Get a C unsigned long int from a long int object.
488 Returns -1 and sets an error condition if overflow occurs. */
489
490size_t
491PyLong_AsSize_t(PyObject *vv)
492{
493 register PyLongObject *v;
494 size_t x, prev;
495 Py_ssize_t i;
496
497 if (vv == NULL || !PyLong_Check(vv)) {
498 PyErr_BadInternalCall();
499 return (unsigned long) -1;
500 }
501 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000502 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000503 x = 0;
504 if (i < 0) {
505 PyErr_SetString(PyExc_OverflowError,
506 "can't convert negative value to size_t");
507 return (size_t) -1;
508 }
509 switch (i) {
510 case 0: return 0;
511 case 1: return v->ob_digit[0];
512 }
513 while (--i >= 0) {
514 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000515 x = (x << PyLong_SHIFT) + v->ob_digit[i];
516 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000517 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000518 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000519 return (unsigned long) -1;
520 }
521 }
522 return x;
523}
524
Thomas Hellera4ea6032003-04-17 18:55:45 +0000525/* Get a C unsigned long int from a long int object, ignoring the high bits.
526 Returns -1 and sets an error condition if an error occurs. */
527
Guido van Rossumddefaf32007-01-14 03:31:43 +0000528static unsigned long
529_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000530{
531 register PyLongObject *v;
532 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000533 Py_ssize_t i;
534 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000535
536 if (vv == NULL || !PyLong_Check(vv)) {
537 PyErr_BadInternalCall();
538 return (unsigned long) -1;
539 }
540 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000541 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000542 switch (i) {
543 case 0: return 0;
544 case 1: return v->ob_digit[0];
545 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000546 sign = 1;
547 x = 0;
548 if (i < 0) {
549 sign = -1;
550 i = -i;
551 }
552 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000553 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000554 }
555 return x * sign;
556}
557
Guido van Rossumddefaf32007-01-14 03:31:43 +0000558unsigned long
559PyLong_AsUnsignedLongMask(register PyObject *op)
560{
561 PyNumberMethods *nb;
562 PyLongObject *lo;
563 unsigned long val;
564
565 if (op && PyLong_Check(op))
566 return _PyLong_AsUnsignedLongMask(op);
567
568 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
569 nb->nb_int == NULL) {
570 PyErr_SetString(PyExc_TypeError, "an integer is required");
571 return (unsigned long)-1;
572 }
573
574 lo = (PyLongObject*) (*nb->nb_int) (op);
575 if (lo == NULL)
576 return (unsigned long)-1;
577 if (PyLong_Check(lo)) {
578 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
579 Py_DECREF(lo);
580 if (PyErr_Occurred())
581 return (unsigned long)-1;
582 return val;
583 }
584 else
585 {
586 Py_DECREF(lo);
587 PyErr_SetString(PyExc_TypeError,
588 "nb_int should return int object");
589 return (unsigned long)-1;
590 }
591}
592
Tim Peters5b8132f2003-01-31 15:52:05 +0000593int
594_PyLong_Sign(PyObject *vv)
595{
596 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000597
598 assert(v != NULL);
599 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000600
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000601 return Py_Size(v) == 0 ? 0 : (Py_Size(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000602}
603
Tim Petersbaefd9e2003-01-28 20:37:45 +0000604size_t
605_PyLong_NumBits(PyObject *vv)
606{
607 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000608 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000609 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000610
611 assert(v != NULL);
612 assert(PyLong_Check(v));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000613 ndigits = ABS(Py_Size(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000614 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
615 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000616 digit msd = v->ob_digit[ndigits - 1];
617
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000618 result = (ndigits - 1) * PyLong_SHIFT;
619 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000620 goto Overflow;
621 do {
622 ++result;
623 if (result == 0)
624 goto Overflow;
625 msd >>= 1;
626 } while (msd);
627 }
628 return result;
629
630Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000631 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000632 "to express in a platform size_t");
633 return (size_t)-1;
634}
635
Tim Peters2a9b3672001-06-11 21:23:58 +0000636PyObject *
637_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
638 int little_endian, int is_signed)
639{
640 const unsigned char* pstartbyte;/* LSB of bytes */
641 int incr; /* direction to move pstartbyte */
642 const unsigned char* pendbyte; /* MSB of bytes */
643 size_t numsignificantbytes; /* number of bytes that matter */
644 size_t ndigits; /* number of Python long digits */
645 PyLongObject* v; /* result */
646 int idigit = 0; /* next free index in v->ob_digit */
647
648 if (n == 0)
649 return PyLong_FromLong(0L);
650
651 if (little_endian) {
652 pstartbyte = bytes;
653 pendbyte = bytes + n - 1;
654 incr = 1;
655 }
656 else {
657 pstartbyte = bytes + n - 1;
658 pendbyte = bytes;
659 incr = -1;
660 }
661
662 if (is_signed)
663 is_signed = *pendbyte >= 0x80;
664
665 /* Compute numsignificantbytes. This consists of finding the most
666 significant byte. Leading 0 bytes are insignficant if the number
667 is positive, and leading 0xff bytes if negative. */
668 {
669 size_t i;
670 const unsigned char* p = pendbyte;
671 const int pincr = -incr; /* search MSB to LSB */
672 const unsigned char insignficant = is_signed ? 0xff : 0x00;
673
674 for (i = 0; i < n; ++i, p += pincr) {
675 if (*p != insignficant)
676 break;
677 }
678 numsignificantbytes = n - i;
679 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
680 actually has 2 significant bytes. OTOH, 0xff0001 ==
681 -0x00ffff, so we wouldn't *need* to bump it there; but we
682 do for 0xffff = -0x0001. To be safe without bothering to
683 check every case, bump it regardless. */
684 if (is_signed && numsignificantbytes < n)
685 ++numsignificantbytes;
686 }
687
688 /* How many Python long digits do we need? We have
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000689 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000690 bits, so it's the ceiling of the quotient. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000691 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000692 if (ndigits > (size_t)INT_MAX)
693 return PyErr_NoMemory();
694 v = _PyLong_New((int)ndigits);
695 if (v == NULL)
696 return NULL;
697
698 /* Copy the bits over. The tricky parts are computing 2's-comp on
699 the fly for signed numbers, and dealing with the mismatch between
700 8-bit bytes and (probably) 15-bit Python digits.*/
701 {
702 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000703 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000704 twodigits accum = 0; /* sliding register */
705 unsigned int accumbits = 0; /* number of bits in accum */
706 const unsigned char* p = pstartbyte;
707
708 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000709 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000710 /* Compute correction for 2's comp, if needed. */
711 if (is_signed) {
712 thisbyte = (0xff ^ thisbyte) + carry;
713 carry = thisbyte >> 8;
714 thisbyte &= 0xff;
715 }
716 /* Because we're going LSB to MSB, thisbyte is
717 more significant than what's already in accum,
718 so needs to be prepended to accum. */
719 accum |= thisbyte << accumbits;
720 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000721 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000722 /* There's enough to fill a Python digit. */
723 assert(idigit < (int)ndigits);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000724 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000725 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000726 accum >>= PyLong_SHIFT;
727 accumbits -= PyLong_SHIFT;
728 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000729 }
730 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000731 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000732 if (accumbits) {
733 assert(idigit < (int)ndigits);
734 v->ob_digit[idigit] = (digit)accum;
735 ++idigit;
736 }
737 }
738
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000739 Py_Size(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000740 return (PyObject *)long_normalize(v);
741}
742
743int
744_PyLong_AsByteArray(PyLongObject* v,
745 unsigned char* bytes, size_t n,
746 int little_endian, int is_signed)
747{
748 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000749 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000750 twodigits accum; /* sliding register */
751 unsigned int accumbits; /* # bits in accum */
752 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
753 twodigits carry; /* for computing 2's-comp */
754 size_t j; /* # bytes filled */
755 unsigned char* p; /* pointer to next byte in bytes */
756 int pincr; /* direction to move p */
757
758 assert(v != NULL && PyLong_Check(v));
759
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000760 if (Py_Size(v) < 0) {
761 ndigits = -(Py_Size(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000762 if (!is_signed) {
763 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000764 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000765 return -1;
766 }
767 do_twos_comp = 1;
768 }
769 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000770 ndigits = Py_Size(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000771 do_twos_comp = 0;
772 }
773
774 if (little_endian) {
775 p = bytes;
776 pincr = 1;
777 }
778 else {
779 p = bytes + n - 1;
780 pincr = -1;
781 }
782
Tim Peters898cf852001-06-13 20:50:08 +0000783 /* Copy over all the Python digits.
784 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000785 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000786 normalized. */
787 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000788 j = 0;
789 accum = 0;
790 accumbits = 0;
791 carry = do_twos_comp ? 1 : 0;
792 for (i = 0; i < ndigits; ++i) {
793 twodigits thisdigit = v->ob_digit[i];
794 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000795 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
796 carry = thisdigit >> PyLong_SHIFT;
797 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000798 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000799 /* Because we're going LSB to MSB, thisdigit is more
800 significant than what's already in accum, so needs to be
801 prepended to accum. */
802 accum |= thisdigit << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000803 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000804
Tim Petersede05092001-06-14 08:53:38 +0000805 /* The most-significant digit may be (probably is) at least
806 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000807 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000808 /* Count # of sign bits -- they needn't be stored,
809 * although for signed conversion we need later to
810 * make sure at least one sign bit gets stored.
811 * First shift conceptual sign bit to real sign bit.
812 */
813 stwodigits s = (stwodigits)(thisdigit <<
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000814 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000815 unsigned int nsignbits = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000816 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000817 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000818 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000819 }
Tim Petersede05092001-06-14 08:53:38 +0000820 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000821 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000822
Tim Peters2a9b3672001-06-11 21:23:58 +0000823 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000824 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000825 if (j >= n)
826 goto Overflow;
827 ++j;
828 *p = (unsigned char)(accum & 0xff);
829 p += pincr;
830 accumbits -= 8;
831 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000832 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000833 }
834
835 /* Store the straggler (if any). */
836 assert(accumbits < 8);
837 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000838 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000839 if (j >= n)
840 goto Overflow;
841 ++j;
842 if (do_twos_comp) {
843 /* Fill leading bits of the byte with sign bits
844 (appropriately pretending that the long had an
845 infinite supply of sign bits). */
846 accum |= (~(twodigits)0) << accumbits;
847 }
848 *p = (unsigned char)(accum & 0xff);
849 p += pincr;
850 }
Tim Peters05607ad2001-06-13 21:01:27 +0000851 else if (j == n && n > 0 && is_signed) {
852 /* The main loop filled the byte array exactly, so the code
853 just above didn't get to ensure there's a sign bit, and the
854 loop below wouldn't add one either. Make sure a sign bit
855 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000856 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000857 int sign_bit_set = msb >= 0x80;
858 assert(accumbits == 0);
859 if (sign_bit_set == do_twos_comp)
860 return 0;
861 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000862 goto Overflow;
863 }
Tim Peters05607ad2001-06-13 21:01:27 +0000864
865 /* Fill remaining bytes with copies of the sign bit. */
866 {
867 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
868 for ( ; j < n; ++j, p += pincr)
869 *p = signbyte;
870 }
871
Tim Peters2a9b3672001-06-11 21:23:58 +0000872 return 0;
873
874Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000875 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000876 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000877
Tim Peters2a9b3672001-06-11 21:23:58 +0000878}
879
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000880double
881_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
882{
883/* NBITS_WANTED should be > the number of bits in a double's precision,
884 but small enough so that 2**NBITS_WANTED is within the normal double
885 range. nbitsneeded is set to 1 less than that because the most-significant
886 Python digit contains at least 1 significant bit, but we don't want to
887 bother counting them (catering to the worst case cheaply).
888
889 57 is one more than VAX-D double precision; I (Tim) don't know of a double
890 format with more precision than that; it's 1 larger so that we add in at
891 least one round bit to stand in for the ignored least-significant bits.
892*/
893#define NBITS_WANTED 57
894 PyLongObject *v;
895 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000896 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000897 Py_ssize_t i;
898 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000899 int nbitsneeded;
900
901 if (vv == NULL || !PyLong_Check(vv)) {
902 PyErr_BadInternalCall();
903 return -1;
904 }
905 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000906 i = Py_Size(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000907 sign = 1;
908 if (i < 0) {
909 sign = -1;
910 i = -(i);
911 }
912 else if (i == 0) {
913 *exponent = 0;
914 return 0.0;
915 }
916 --i;
917 x = (double)v->ob_digit[i];
918 nbitsneeded = NBITS_WANTED - 1;
919 /* Invariant: i Python digits remain unaccounted for. */
920 while (i > 0 && nbitsneeded > 0) {
921 --i;
922 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000923 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000924 }
925 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000926 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000927 *exponent = i;
928 assert(x > 0.0);
929 return x * sign;
930#undef NBITS_WANTED
931}
932
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000933/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000934
935double
Tim Peters9f688bf2000-07-07 15:53:28 +0000936PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000937{
Thomas Wouters553489a2006-02-01 21:32:04 +0000938 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000939 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000940
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000941 if (vv == NULL || !PyLong_Check(vv)) {
942 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000943 return -1;
944 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000945 x = _PyLong_AsScaledDouble(vv, &e);
946 if (x == -1.0 && PyErr_Occurred())
947 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000948 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
949 set correctly after a successful _PyLong_AsScaledDouble() call */
950 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000951 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000952 goto overflow;
953 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000954 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000955 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000956 goto overflow;
957 return x;
958
959overflow:
960 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000961 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000962 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000963}
964
Guido van Rossum78694d91998-09-18 14:14:13 +0000965/* Create a new long (or int) object from a C pointer */
966
967PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000968PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000969{
Tim Peters70128a12001-06-16 08:48:40 +0000970#ifndef HAVE_LONG_LONG
971# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
972#endif
973#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000974# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000975#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000976 /* special-case null pointer */
977 if (!p)
Tim Peters70128a12001-06-16 08:48:40 +0000978 return PyInt_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000979 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000980
Guido van Rossum78694d91998-09-18 14:14:13 +0000981}
982
983/* Get a C pointer from a long object (or an int object in some cases) */
984
985void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000986PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000987{
988 /* This function will allow int or long objects. If vv is neither,
989 then the PyLong_AsLong*() functions will raise the exception:
990 PyExc_SystemError, "bad argument to internal function"
991 */
Tim Peters70128a12001-06-16 08:48:40 +0000992#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000993 long x;
994
Guido van Rossumddefaf32007-01-14 03:31:43 +0000995 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000996 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000997 else
998 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000999#else
Tim Peters70128a12001-06-16 08:48:40 +00001000
1001#ifndef HAVE_LONG_LONG
1002# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1003#endif
1004#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001005# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001006#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001007 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001008
Guido van Rossumddefaf32007-01-14 03:31:43 +00001009 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001010 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001011 else
1012 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001013
1014#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001015
1016 if (x == -1 && PyErr_Occurred())
1017 return NULL;
1018 return (void *)x;
1019}
1020
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001021#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001022
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001023/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001024 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001025 */
1026
Tim Peterscf37dfc2001-06-14 18:42:50 +00001027#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001028
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001029/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001030
1031PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001032PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001033{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001034 PyLongObject *v;
1035 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1036 int ndigits = 0;
1037 int negative = 0;
1038
Guido van Rossumddefaf32007-01-14 03:31:43 +00001039 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001040 if (ival < 0) {
1041 ival = -ival;
1042 negative = 1;
1043 }
1044
1045 /* Count the number of Python digits.
1046 We used to pick 5 ("big enough for anything"), but that's a
1047 waste of time and space given that 5*15 = 75 bits are rarely
1048 needed. */
1049 t = (unsigned PY_LONG_LONG)ival;
1050 while (t) {
1051 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001052 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001053 }
1054 v = _PyLong_New(ndigits);
1055 if (v != NULL) {
1056 digit *p = v->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001057 Py_Size(v) = negative ? -ndigits : ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001058 t = (unsigned PY_LONG_LONG)ival;
1059 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001060 *p++ = (digit)(t & PyLong_MASK);
1061 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001062 }
1063 }
1064 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001065}
1066
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001067/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001068
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001069PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001070PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001071{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001072 PyLongObject *v;
1073 unsigned PY_LONG_LONG t;
1074 int ndigits = 0;
1075
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001076 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001077 return PyLong_FromLong(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001078 /* Count the number of Python digits. */
1079 t = (unsigned PY_LONG_LONG)ival;
1080 while (t) {
1081 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001082 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001083 }
1084 v = _PyLong_New(ndigits);
1085 if (v != NULL) {
1086 digit *p = v->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001087 Py_Size(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001088 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001089 *p++ = (digit)(ival & PyLong_MASK);
1090 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001091 }
1092 }
1093 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001094}
1095
Martin v. Löwis18e16552006-02-15 17:27:45 +00001096/* Create a new long int object from a C Py_ssize_t. */
1097
1098PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001099PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001100{
1101 Py_ssize_t bytes = ival;
1102 int one = 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001103 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001104 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001105 return _PyLong_FromByteArray(
1106 (unsigned char *)&bytes,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001107 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001108}
1109
1110/* Create a new long int object from a C size_t. */
1111
1112PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001113PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114{
1115 size_t bytes = ival;
1116 int one = 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001117 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001118 return PyLong_FromLong(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001119 return _PyLong_FromByteArray(
1120 (unsigned char *)&bytes,
1121 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
1122}
1123
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001124/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001125 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001126
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001127PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001128PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001129{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001130 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001131 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001132 int one = 1;
1133 int res;
1134
Tim Petersd38b1c72001-09-30 05:09:37 +00001135 if (vv == NULL) {
1136 PyErr_BadInternalCall();
1137 return -1;
1138 }
1139 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001140 PyNumberMethods *nb;
1141 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001142 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1143 nb->nb_int == NULL) {
1144 PyErr_SetString(PyExc_TypeError, "an integer is required");
1145 return -1;
1146 }
1147 io = (*nb->nb_int) (vv);
1148 if (io == NULL)
1149 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001150 if (PyLong_Check(io)) {
1151 bytes = PyLong_AsLongLong(io);
1152 Py_DECREF(io);
1153 return bytes;
1154 }
1155 Py_DECREF(io);
1156 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001157 return -1;
1158 }
1159
Guido van Rossumddefaf32007-01-14 03:31:43 +00001160 v = (PyLongObject*)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001161 switch(Py_Size(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001162 case -1: return -v->ob_digit[0];
1163 case 0: return 0;
1164 case 1: return v->ob_digit[0];
1165 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001166 res = _PyLong_AsByteArray(
1167 (PyLongObject *)vv, (unsigned char *)&bytes,
1168 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001169
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001170 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001171 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001172 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001173 else
1174 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001175}
1176
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001177/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001178 Return -1 and set an error if overflow occurs. */
1179
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001180unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001181PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001182{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001183 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001184 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001185 int one = 1;
1186 int res;
1187
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001188 if (vv == NULL || !PyLong_Check(vv)) {
1189 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001190 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001191 }
1192
Guido van Rossumddefaf32007-01-14 03:31:43 +00001193 v = (PyLongObject*)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001194 switch(Py_Size(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001195 case 0: return 0;
1196 case 1: return v->ob_digit[0];
1197 }
1198
Tim Petersd1a7da62001-06-13 00:35:57 +00001199 res = _PyLong_AsByteArray(
1200 (PyLongObject *)vv, (unsigned char *)&bytes,
1201 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001202
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001203 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001204 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001205 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001206 else
1207 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001208}
Tim Petersd1a7da62001-06-13 00:35:57 +00001209
Thomas Hellera4ea6032003-04-17 18:55:45 +00001210/* Get a C unsigned long int from a long int object, ignoring the high bits.
1211 Returns -1 and sets an error condition if an error occurs. */
1212
Guido van Rossumddefaf32007-01-14 03:31:43 +00001213static unsigned PY_LONG_LONG
1214_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001215{
1216 register PyLongObject *v;
1217 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001218 Py_ssize_t i;
1219 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001220
1221 if (vv == NULL || !PyLong_Check(vv)) {
1222 PyErr_BadInternalCall();
1223 return (unsigned long) -1;
1224 }
1225 v = (PyLongObject *)vv;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001226 switch(Py_Size(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001227 case 0: return 0;
1228 case 1: return v->ob_digit[0];
1229 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001230 i = Py_Size(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001231 sign = 1;
1232 x = 0;
1233 if (i < 0) {
1234 sign = -1;
1235 i = -i;
1236 }
1237 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001238 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001239 }
1240 return x * sign;
1241}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001242
1243unsigned PY_LONG_LONG
1244PyLong_AsUnsignedLongLongMask(register PyObject *op)
1245{
1246 PyNumberMethods *nb;
1247 PyLongObject *lo;
1248 unsigned PY_LONG_LONG val;
1249
1250 if (op && PyLong_Check(op))
1251 return _PyLong_AsUnsignedLongLongMask(op);
1252
1253 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1254 nb->nb_int == NULL) {
1255 PyErr_SetString(PyExc_TypeError, "an integer is required");
1256 return (unsigned PY_LONG_LONG)-1;
1257 }
1258
1259 lo = (PyLongObject*) (*nb->nb_int) (op);
1260 if (lo == NULL)
1261 return (unsigned PY_LONG_LONG)-1;
1262 if (PyLong_Check(lo)) {
1263 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1264 Py_DECREF(lo);
1265 if (PyErr_Occurred())
1266 return (unsigned PY_LONG_LONG)-1;
1267 return val;
1268 }
1269 else
1270 {
1271 Py_DECREF(lo);
1272 PyErr_SetString(PyExc_TypeError,
1273 "nb_int should return int object");
1274 return (unsigned PY_LONG_LONG)-1;
1275 }
1276}
Tim Petersd1a7da62001-06-13 00:35:57 +00001277#undef IS_LITTLE_ENDIAN
1278
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001279#endif /* HAVE_LONG_LONG */
1280
Neil Schemenauerba872e22001-01-04 01:46:03 +00001281
1282static int
1283convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001284 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001285 *a = (PyLongObject *) v;
1286 Py_INCREF(v);
1287 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001288 else {
1289 return 0;
1290 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001291 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001292 *b = (PyLongObject *) w;
1293 Py_INCREF(w);
1294 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001295 else {
1296 Py_DECREF(*a);
1297 return 0;
1298 }
1299 return 1;
1300}
1301
1302#define CONVERT_BINOP(v, w, a, b) \
1303 if (!convert_binop(v, w, a, b)) { \
1304 Py_INCREF(Py_NotImplemented); \
1305 return Py_NotImplemented; \
1306 }
1307
Tim Peters877a2122002-08-12 05:09:36 +00001308/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1309 * is modified in place, by adding y to it. Carries are propagated as far as
1310 * x[m-1], and the remaining carry (0 or 1) is returned.
1311 */
1312static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001313v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001314{
1315 int i;
1316 digit carry = 0;
1317
1318 assert(m >= n);
1319 for (i = 0; i < n; ++i) {
1320 carry += x[i] + y[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 for (; carry && i < m; ++i) {
1326 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001327 x[i] = carry & PyLong_MASK;
1328 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001329 assert((carry & 1) == carry);
1330 }
1331 return carry;
1332}
1333
1334/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1335 * is modified in place, by subtracting y from it. Borrows are propagated as
1336 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1337 */
1338static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001339v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001340{
1341 int i;
1342 digit borrow = 0;
1343
1344 assert(m >= n);
1345 for (i = 0; i < n; ++i) {
1346 borrow = x[i] - y[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; /* keep only 1 sign bit */
1350 }
1351 for (; borrow && i < m; ++i) {
1352 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001353 x[i] = borrow & PyLong_MASK;
1354 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001355 borrow &= 1;
1356 }
1357 return borrow;
1358}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001359
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001360/* Multiply by a single digit, ignoring the sign. */
1361
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001362static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001363mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001364{
1365 return muladd1(a, n, (digit)0);
1366}
1367
1368/* Multiply by a single digit and add a single digit, ignoring the sign. */
1369
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001370static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001371muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001372{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001373 Py_ssize_t size_a = ABS(Py_Size(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001374 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001375 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001376 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001377
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001378 if (z == NULL)
1379 return NULL;
1380 for (i = 0; i < size_a; ++i) {
1381 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001382 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1383 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001384 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001385 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001386 return long_normalize(z);
1387}
1388
Tim Peters212e6142001-07-14 12:23:19 +00001389/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1390 in pout, and returning the remainder. pin and pout point at the LSD.
1391 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001392 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001393 immutable. */
1394
1395static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001396inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001397{
1398 twodigits rem = 0;
1399
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001400 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001401 pin += size;
1402 pout += size;
1403 while (--size >= 0) {
1404 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001405 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001406 *--pout = hi = (digit)(rem / n);
1407 rem -= hi * n;
1408 }
1409 return (digit)rem;
1410}
1411
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001412/* Divide a long integer by a digit, returning both the quotient
1413 (as function result) and the remainder (through *prem).
1414 The sign of a is ignored; n should not be zero. */
1415
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001416static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001417divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001418{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001419 const Py_ssize_t size = ABS(Py_Size(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001420 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001421
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001422 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001423 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001424 if (z == NULL)
1425 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001426 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001427 return long_normalize(z);
1428}
1429
1430/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001431 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001432 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001433
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001434PyObject *
1435_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001436{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001437 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001438 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001439 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001440 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001441 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001442 int bits;
1443 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001444
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001445 if (a == NULL || !PyLong_Check(a)) {
1446 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001447 return NULL;
1448 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001449 assert(base >= 2 && base <= 36);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001450 size_a = ABS(Py_Size(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001451
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001452 /* Compute a rough upper bound for the length of the string */
1453 i = base;
1454 bits = 0;
1455 while (i > 1) {
1456 ++bits;
1457 i >>= 1;
1458 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001459 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001460 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001461 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001462 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001463 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001464 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001465 return NULL;
1466 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001467 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001468 if (str == NULL)
1469 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001470 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001471 *p = '\0';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001472 if (Py_Size(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001473 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001474
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001475 if (Py_Size(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001476 *--p = '0';
1477 }
1478 else if ((base & (base - 1)) == 0) {
1479 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001480 twodigits accum = 0;
1481 int accumbits = 0; /* # of bits in accum */
1482 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001483 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001484 while ((i >>= 1) > 1)
1485 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001486
1487 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001488 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001489 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001490 assert(accumbits >= basebits);
1491 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001492 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001493 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001494 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001495 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001496 accumbits -= basebits;
1497 accum >>= basebits;
1498 } while (i < size_a-1 ? accumbits >= basebits :
1499 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001500 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001501 }
1502 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001503 /* Not 0, and base not a power of 2. Divide repeatedly by
1504 base, but for speed use the highest power of base that
1505 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001506 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001507 digit *pin = a->ob_digit;
1508 PyLongObject *scratch;
1509 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001510 digit powbase = base; /* powbase == base ** power */
1511 int power = 1;
1512 for (;;) {
1513 unsigned long newpow = powbase * (unsigned long)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001514 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001515 break;
1516 powbase = (digit)newpow;
1517 ++power;
1518 }
Tim Peters212e6142001-07-14 12:23:19 +00001519
1520 /* Get a scratch area for repeated division. */
1521 scratch = _PyLong_New(size);
1522 if (scratch == NULL) {
1523 Py_DECREF(str);
1524 return NULL;
1525 }
1526
1527 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001528 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001529 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001530 digit rem = inplace_divrem1(scratch->ob_digit,
1531 pin, size, powbase);
1532 pin = scratch->ob_digit; /* no need to use a again */
1533 if (pin[size - 1] == 0)
1534 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001535 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001536 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001537 Py_DECREF(str);
1538 return NULL;
1539 })
Tim Peters212e6142001-07-14 12:23:19 +00001540
1541 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001542 assert(ntostore > 0);
1543 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001544 digit nextrem = (digit)(rem / base);
1545 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001546 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001547 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001548 *--p = c;
1549 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001550 --ntostore;
1551 /* Termination is a bit delicate: must not
1552 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001553 remaining quotient and rem are both 0. */
1554 } while (ntostore && (size || rem));
1555 } while (size != 0);
1556 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001557 }
1558
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001559 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001560 *--p = 'x';
1561 *--p = '0';
1562 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001563 else if (base == 8) {
1564 *--p = 'o';
1565 *--p = '0';
1566 }
1567 else if (base == 2) {
1568 *--p = 'b';
1569 *--p = '0';
1570 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001571 else if (base != 10) {
1572 *--p = '#';
1573 *--p = '0' + base%10;
1574 if (base > 10)
1575 *--p = '0' + base/10;
1576 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001577 if (sign)
1578 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001579 if (p != PyUnicode_AS_UNICODE(str)) {
1580 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001581 assert(p > q);
1582 do {
1583 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001584 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001585 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1586 Py_DECREF(str);
1587 return NULL;
1588 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001589 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001590 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001591}
1592
Thomas Wouters477c8d52006-05-27 19:21:47 +00001593/* Table of digit values for 8-bit string -> integer conversion.
1594 * '0' maps to 0, ..., '9' maps to 9.
1595 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1596 * All other indices map to 37.
1597 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001598 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001599 */
1600int _PyLong_DigitValue[256] = {
1601 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1602 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1603 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1604 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1605 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1606 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1607 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1608 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1609 37, 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 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1612 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1613 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1614 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1615 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1616 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1617};
1618
1619/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001620 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1621 * non-digit (which may be *str!). A normalized long is returned.
1622 * The point to this routine is that it takes time linear in the number of
1623 * string characters.
1624 */
1625static PyLongObject *
1626long_from_binary_base(char **str, int base)
1627{
1628 char *p = *str;
1629 char *start = p;
1630 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001631 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001632 PyLongObject *z;
1633 twodigits accum;
1634 int bits_in_accum;
1635 digit *pdigit;
1636
1637 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1638 n = base;
1639 for (bits_per_char = -1; n; ++bits_per_char)
1640 n >>= 1;
1641 /* n <- total # of bits needed, while setting p to end-of-string */
1642 n = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001643 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001644 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001645 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001646 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1647 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001648 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001649 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001650 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001651 return NULL;
1652 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001653 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001654 z = _PyLong_New(n);
1655 if (z == NULL)
1656 return NULL;
1657 /* Read string from right, and fill in long from left; i.e.,
1658 * from least to most significant in both.
1659 */
1660 accum = 0;
1661 bits_in_accum = 0;
1662 pdigit = z->ob_digit;
1663 while (--p >= start) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001664 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001665 assert(k >= 0 && k < base);
1666 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001667 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001668 if (bits_in_accum >= PyLong_SHIFT) {
1669 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001670 assert(pdigit - z->ob_digit <= (int)n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001671 accum >>= PyLong_SHIFT;
1672 bits_in_accum -= PyLong_SHIFT;
1673 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001674 }
1675 }
1676 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001677 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001678 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001679 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001680 }
1681 while (pdigit - z->ob_digit < n)
1682 *pdigit++ = 0;
1683 return long_normalize(z);
1684}
1685
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001686PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001687PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001688{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001689 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001690 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001691 PyLongObject *z = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001692 PyObject *strobj, *strrepr;
1693 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001694
Guido van Rossum472c04f1996-12-05 21:57:21 +00001695 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001696 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001697 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001698 return NULL;
1699 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001700 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001701 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001702 if (*str == '+')
1703 ++str;
1704 else if (*str == '-') {
1705 ++str;
1706 sign = -1;
1707 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001708 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001709 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001710 if (base == 0) {
1711 if (str[0] != '0')
1712 base = 10;
1713 else if (str[1] == 'x' || str[1] == 'X')
1714 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001715 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001716 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001717 else if (str[1] == 'b' || str[1] == 'B')
1718 base = 2;
1719 else {
1720 /* "old" (C-style) octal literal, now invalid.
1721 it might still be zero though */
1722 error_if_nonzero = 1;
1723 base = 10;
1724 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001725 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001726 if (str[0] == '0' &&
1727 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1728 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1729 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001730 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001731
Guido van Rossume6762971998-06-22 03:54:46 +00001732 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001733 if ((base & (base - 1)) == 0)
1734 z = long_from_binary_base(&str, base);
1735 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001736/***
1737Binary bases can be converted in time linear in the number of digits, because
1738Python's representation base is binary. Other bases (including decimal!) use
1739the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001740
Thomas Wouters477c8d52006-05-27 19:21:47 +00001741First some math: the largest integer that can be expressed in N base-B digits
1742is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1743case number of Python digits needed to hold it is the smallest integer n s.t.
1744
1745 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1746 BASE**n >= B**N [taking logs to base BASE]
1747 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1748
1749The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1750this quickly. A Python long with that much space is reserved near the start,
1751and the result is computed into it.
1752
1753The input string is actually treated as being in base base**i (i.e., i digits
1754are processed at a time), where two more static arrays hold:
1755
1756 convwidth_base[base] = the largest integer i such that base**i <= BASE
1757 convmultmax_base[base] = base ** convwidth_base[base]
1758
1759The first of these is the largest i such that i consecutive input digits
1760must fit in a single Python digit. The second is effectively the input
1761base we're really using.
1762
1763Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1764convmultmax_base[base], the result is "simply"
1765
1766 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1767
1768where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001769
1770Error analysis: as above, the number of Python digits `n` needed is worst-
1771case
1772
1773 n >= N * log(B)/log(BASE)
1774
1775where `N` is the number of input digits in base `B`. This is computed via
1776
1777 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1778
1779below. Two numeric concerns are how much space this can waste, and whether
1780the computed result can be too small. To be concrete, assume BASE = 2**15,
1781which is the default (and it's unlikely anyone changes that).
1782
1783Waste isn't a problem: provided the first input digit isn't 0, the difference
1784between the worst-case input with N digits and the smallest input with N
1785digits is about a factor of B, but B is small compared to BASE so at most
1786one allocated Python digit can remain unused on that count. If
1787N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1788and adding 1 returns a result 1 larger than necessary. However, that can't
1789happen: whenever B is a power of 2, long_from_binary_base() is called
1790instead, and it's impossible for B**i to be an integer power of 2**15 when
1791B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1792an exact integer when B is not a power of 2, since B**i has a prime factor
1793other than 2 in that case, but (2**15)**j's only prime factor is 2).
1794
1795The computed result can be too small if the true value of N*log(B)/log(BASE)
1796is a little bit larger than an exact integer, but due to roundoff errors (in
1797computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1798yields a numeric result a little less than that integer. Unfortunately, "how
1799close can a transcendental function get to an integer over some range?"
1800questions are generally theoretically intractable. Computer analysis via
1801continued fractions is practical: expand log(B)/log(BASE) via continued
1802fractions, giving a sequence i/j of "the best" rational approximations. Then
1803j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1804we can get very close to being in trouble, but very rarely. For example,
180576573 is a denominator in one of the continued-fraction approximations to
1806log(10)/log(2**15), and indeed:
1807
1808 >>> log(10)/log(2**15)*76573
1809 16958.000000654003
1810
1811is very close to an integer. If we were working with IEEE single-precision,
1812rounding errors could kill us. Finding worst cases in IEEE double-precision
1813requires better-than-double-precision log() functions, and Tim didn't bother.
1814Instead the code checks to see whether the allocated space is enough as each
1815new Python digit is added, and copies the whole thing to a larger long if not.
1816This should happen extremely rarely, and in fact I don't have a test case
1817that triggers it(!). Instead the code was tested by artificially allocating
1818just 1 digit at the start, so that the copying code was exercised for every
1819digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001820***/
1821 register twodigits c; /* current input character */
1822 Py_ssize_t size_z;
1823 int i;
1824 int convwidth;
1825 twodigits convmultmax, convmult;
1826 digit *pz, *pzstop;
1827 char* scan;
1828
1829 static double log_base_BASE[37] = {0.0e0,};
1830 static int convwidth_base[37] = {0,};
1831 static twodigits convmultmax_base[37] = {0,};
1832
1833 if (log_base_BASE[base] == 0.0) {
1834 twodigits convmax = base;
1835 int i = 1;
1836
1837 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001838 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001839 for (;;) {
1840 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001841 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001842 break;
1843 convmax = next;
1844 ++i;
1845 }
1846 convmultmax_base[base] = convmax;
1847 assert(i > 0);
1848 convwidth_base[base] = i;
1849 }
1850
1851 /* Find length of the string of numeric characters. */
1852 scan = str;
1853 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1854 ++scan;
1855
1856 /* Create a long object that can contain the largest possible
1857 * integer with this base and length. Note that there's no
1858 * need to initialize z->ob_digit -- no slot is read up before
1859 * being stored into.
1860 */
1861 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001862 /* Uncomment next line to test exceedingly rare copy code */
1863 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001864 assert(size_z > 0);
1865 z = _PyLong_New(size_z);
1866 if (z == NULL)
1867 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001868 Py_Size(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001869
1870 /* `convwidth` consecutive input digits are treated as a single
1871 * digit in base `convmultmax`.
1872 */
1873 convwidth = convwidth_base[base];
1874 convmultmax = convmultmax_base[base];
1875
1876 /* Work ;-) */
1877 while (str < scan) {
1878 /* grab up to convwidth digits from the input string */
1879 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1880 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1881 c = (twodigits)(c * base +
1882 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001883 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001884 }
1885
1886 convmult = convmultmax;
1887 /* Calculate the shift only if we couldn't get
1888 * convwidth digits.
1889 */
1890 if (i != convwidth) {
1891 convmult = base;
1892 for ( ; i > 1; --i)
1893 convmult *= base;
1894 }
1895
1896 /* Multiply z by convmult, and add c. */
1897 pz = z->ob_digit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001898 pzstop = pz + Py_Size(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001899 for (; pz < pzstop; ++pz) {
1900 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001901 *pz = (digit)(c & PyLong_MASK);
1902 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001903 }
1904 /* carry off the current end? */
1905 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001906 assert(c < PyLong_BASE);
1907 if (Py_Size(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001908 *pz = (digit)c;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001909 ++Py_Size(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001910 }
1911 else {
1912 PyLongObject *tmp;
1913 /* Extremely rare. Get more space. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001914 assert(Py_Size(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001915 tmp = _PyLong_New(size_z + 1);
1916 if (tmp == NULL) {
1917 Py_DECREF(z);
1918 return NULL;
1919 }
1920 memcpy(tmp->ob_digit,
1921 z->ob_digit,
1922 sizeof(digit) * size_z);
1923 Py_DECREF(z);
1924 z = tmp;
1925 z->ob_digit[size_z] = (digit)c;
1926 ++size_z;
1927 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001928 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001929 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001930 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001931 if (z == NULL)
1932 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001933 if (error_if_nonzero) {
1934 /* reset the base to 0, else the exception message
1935 doesn't make too much sense */
1936 base = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001937 if (Py_Size(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001938 goto onError;
1939 /* there might still be other problems, therefore base
1940 remains zero here for the same reason */
1941 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001942 if (str == start)
1943 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001944 if (sign < 0)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001945 Py_Size(z) = -(Py_Size(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001946 if (*str == 'L' || *str == 'l')
1947 str++;
1948 while (*str && isspace(Py_CHARMASK(*str)))
1949 str++;
1950 if (*str != '\0')
1951 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001952 if (pend)
1953 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001954 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001955
1956 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001957 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001958 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1959 strobj = PyString_FromStringAndSize(orig_str, slen);
1960 if (strobj == NULL)
1961 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001962 strrepr = PyObject_ReprStr8(strobj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001963 Py_DECREF(strobj);
1964 if (strrepr == NULL)
1965 return NULL;
1966 PyErr_Format(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001967 "invalid literal for int() with base %d: %s",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001968 base, PyString_AS_STRING(strrepr));
1969 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001970 return NULL;
1971}
1972
1973PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001974PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001975{
Walter Dörwald07e14762002-11-06 16:15:14 +00001976 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001977 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001978
Walter Dörwald07e14762002-11-06 16:15:14 +00001979 if (buffer == NULL)
1980 return NULL;
1981
1982 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1983 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001984 return NULL;
1985 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001986 result = PyLong_FromString(buffer, NULL, base);
1987 PyMem_FREE(buffer);
1988 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001989}
1990
Tim Peters9f688bf2000-07-07 15:53:28 +00001991/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001992static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001993 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001994static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00001995static int long_divrem(PyLongObject *, PyLongObject *,
1996 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001997
1998/* Long division with remainder, top-level routine */
1999
Guido van Rossume32e0141992-01-19 16:31:05 +00002000static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002001long_divrem(PyLongObject *a, PyLongObject *b,
2002 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002003{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002004 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002005 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002006
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002007 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002008 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002009 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002010 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002011 }
2012 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002013 (size_a == size_b &&
2014 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002015 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002016 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002017 if (*pdiv == NULL)
2018 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002019 Py_INCREF(a);
2020 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002021 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002022 }
2023 if (size_b == 1) {
2024 digit rem = 0;
2025 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002026 if (z == NULL)
2027 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002028 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002029 if (*prem == NULL) {
2030 Py_DECREF(z);
2031 return -1;
2032 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002033 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002034 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002035 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002036 if (z == NULL)
2037 return -1;
2038 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002039 /* Set the signs.
2040 The quotient z has the sign of a*b;
2041 the remainder r has the sign of a,
2042 so a = b*z + r. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002043 if ((Py_Size(a) < 0) != (Py_Size(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002044 NEGATE(z);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002045 if (Py_Size(a) < 0 && Py_Size(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002046 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002047 *pdiv = z;
2048 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002049}
2050
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002051/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002052
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002053static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002054x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002055{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002056 Py_ssize_t size_v = ABS(Py_Size(v1)), size_w = ABS(Py_Size(w1));
2057 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002058 PyLongObject *v = mul1(v1, d);
2059 PyLongObject *w = mul1(w1, d);
2060 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002061 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002062
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002063 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002064 Py_XDECREF(v);
2065 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002066 return NULL;
2067 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002068
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002069 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002070 assert(Py_Refcnt(v) == 1); /* Since v will be used as accumulator! */
2071 assert(size_w == ABS(Py_Size(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002072
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002073 size_v = ABS(Py_Size(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002074 k = size_v - size_w;
2075 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002076
Thomas Wouters477c8d52006-05-27 19:21:47 +00002077 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002078 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2079 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002080 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002081 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002082
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002083 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002084 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002085 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002086 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002087 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002088 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002089 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002091 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002092 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002093
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002094 while (w->ob_digit[size_w-2]*q >
2095 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002096 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002097 + v->ob_digit[j-1]
2098 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002099 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002100 + v->ob_digit[j-2])
2101 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002102
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002103 for (i = 0; i < size_w && i+k < size_v; ++i) {
2104 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002105 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002106 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002107 + ((twodigits)zz << PyLong_SHIFT);
2108 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002109 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002110 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002111 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002112 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002113
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002114 if (i+k < size_v) {
2115 carry += v->ob_digit[i+k];
2116 v->ob_digit[i+k] = 0;
2117 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002118
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002119 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002120 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002121 else {
2122 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002123 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002124 carry = 0;
2125 for (i = 0; i < size_w && i+k < size_v; ++i) {
2126 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002127 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002128 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2129 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002130 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002131 }
2132 }
2133 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002134
Guido van Rossumc206c761995-01-10 15:23:19 +00002135 if (a == NULL)
2136 *prem = NULL;
2137 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002138 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002139 *prem = divrem1(v, d, &d);
2140 /* d receives the (unused) remainder */
2141 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002142 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002143 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002144 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002145 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002146 Py_DECREF(v);
2147 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002148 return a;
2149}
2150
2151/* Methods */
2152
2153static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002154long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002155{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002156 Py_Type(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002157}
2158
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002159static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002160long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002161{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002162 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002163}
2164
2165static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002166long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002167{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002168 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002169
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002170 if (Py_Size(a) != Py_Size(b)) {
2171 if (ABS(Py_Size(a)) == 0 && ABS(Py_Size(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002172 sign = 0;
2173 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002174 sign = Py_Size(a) - Py_Size(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002175 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002176 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002177 Py_ssize_t i = ABS(Py_Size(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002178 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2179 ;
2180 if (i < 0)
2181 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002182 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002183 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002184 if (Py_Size(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002185 sign = -sign;
2186 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002187 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002188 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002189}
2190
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002191static PyObject *
2192long_richcompare(PyObject *self, PyObject *other, int op)
2193{
2194 PyLongObject *a, *b;
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002195 PyObject *result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002196 CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b);
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002197 result = Py_CmpToRich(op, long_compare(a, b));
2198 Py_DECREF(a);
2199 Py_DECREF(b);
2200 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002201}
2202
Guido van Rossum9bfef441993-03-29 10:43:31 +00002203static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002204long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002205{
2206 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002207 Py_ssize_t i;
2208 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002209
2210 /* This is designed so that Python ints and longs with the
2211 same value hash to the same value, otherwise comparisons
2212 of mapping keys will turn out weird */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002213 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002214 switch(i) {
2215 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2216 case 0: return 0;
2217 case 1: return v->ob_digit[0];
2218 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002219 sign = 1;
2220 x = 0;
2221 if (i < 0) {
2222 sign = -1;
2223 i = -(i);
2224 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002225#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002226 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002227 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002228 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002229 x += v->ob_digit[i];
2230 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002231#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002232 x = x * sign;
2233 if (x == -1)
2234 x = -2;
2235 return x;
2236}
2237
2238
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002239/* Add the absolute values of two long integers. */
2240
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002241static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002242x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002243{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002244 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002245 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002246 int i;
2247 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002248
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002249 /* Ensure a is the larger of the two: */
2250 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002251 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002252 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002253 size_a = size_b;
2254 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002255 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002256 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002257 if (z == NULL)
2258 return NULL;
2259 for (i = 0; i < size_b; ++i) {
2260 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002261 z->ob_digit[i] = carry & PyLong_MASK;
2262 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002263 }
2264 for (; i < size_a; ++i) {
2265 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002266 z->ob_digit[i] = carry & PyLong_MASK;
2267 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002268 }
2269 z->ob_digit[i] = carry;
2270 return long_normalize(z);
2271}
2272
2273/* Subtract the absolute values of two integers. */
2274
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002275static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002276x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002277{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002278 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002279 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002280 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002281 int sign = 1;
2282 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002283
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002284 /* Ensure a is the larger of the two: */
2285 if (size_a < size_b) {
2286 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002287 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002288 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002289 size_a = size_b;
2290 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002291 }
2292 else if (size_a == size_b) {
2293 /* Find highest digit where a and b differ: */
2294 i = size_a;
2295 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2296 ;
2297 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002298 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002299 if (a->ob_digit[i] < b->ob_digit[i]) {
2300 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002301 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002302 }
2303 size_a = size_b = i+1;
2304 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002305 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002306 if (z == NULL)
2307 return NULL;
2308 for (i = 0; i < size_b; ++i) {
2309 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002310 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002311 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002312 z->ob_digit[i] = borrow & PyLong_MASK;
2313 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002314 borrow &= 1; /* Keep only one sign bit */
2315 }
2316 for (; i < size_a; ++i) {
2317 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002318 z->ob_digit[i] = borrow & PyLong_MASK;
2319 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002320 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002321 }
2322 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002323 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002324 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002325 return long_normalize(z);
2326}
2327
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002328static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002329long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002330{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002331 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002332
Neil Schemenauerba872e22001-01-04 01:46:03 +00002333 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2334
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002335 if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002336 PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) +
2337 MEDIUM_VALUE(b));
2338 Py_DECREF(a);
2339 Py_DECREF(b);
2340 return result;
2341 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002342 if (Py_Size(a) < 0) {
2343 if (Py_Size(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002344 z = x_add(a, b);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002345 if (z != NULL && Py_Size(z) != 0)
2346 Py_Size(z) = -(Py_Size(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002347 }
2348 else
2349 z = x_sub(b, a);
2350 }
2351 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002352 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002353 z = x_sub(a, b);
2354 else
2355 z = x_add(a, b);
2356 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002357 Py_DECREF(a);
2358 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002359 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002360}
2361
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002362static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002363long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002364{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002365 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002366
Neil Schemenauerba872e22001-01-04 01:46:03 +00002367 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2368
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002369 if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002370 PyObject* r;
2371 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2372 Py_DECREF(a);
2373 Py_DECREF(b);
2374 return r;
2375 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002376 if (Py_Size(a) < 0) {
2377 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002378 z = x_sub(a, b);
2379 else
2380 z = x_add(a, b);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002381 if (z != NULL && Py_Size(z) != 0)
2382 Py_Size(z) = -(Py_Size(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002383 }
2384 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002385 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002386 z = x_add(a, b);
2387 else
2388 z = x_sub(a, b);
2389 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002390 Py_DECREF(a);
2391 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002392 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002393}
2394
Tim Peters5af4e6c2002-08-12 02:31:19 +00002395/* Grade school multiplication, ignoring the signs.
2396 * Returns the absolute value of the product, or NULL if error.
2397 */
2398static PyLongObject *
2399x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002400{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002401 PyLongObject *z;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002402 Py_ssize_t size_a = ABS(Py_Size(a));
2403 Py_ssize_t size_b = ABS(Py_Size(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002404 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002405
Tim Peters5af4e6c2002-08-12 02:31:19 +00002406 z = _PyLong_New(size_a + size_b);
2407 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002408 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002409
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002410 memset(z->ob_digit, 0, Py_Size(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002411 if (a == b) {
2412 /* Efficient squaring per HAC, Algorithm 14.16:
2413 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2414 * Gives slightly less than a 2x speedup when a == b,
2415 * via exploiting that each entry in the multiplication
2416 * pyramid appears twice (except for the size_a squares).
2417 */
2418 for (i = 0; i < size_a; ++i) {
2419 twodigits carry;
2420 twodigits f = a->ob_digit[i];
2421 digit *pz = z->ob_digit + (i << 1);
2422 digit *pa = a->ob_digit + i + 1;
2423 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002424
Tim Peters0973b992004-08-29 22:16:50 +00002425 SIGCHECK({
2426 Py_DECREF(z);
2427 return NULL;
2428 })
2429
2430 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002431 *pz++ = (digit)(carry & PyLong_MASK);
2432 carry >>= PyLong_SHIFT;
2433 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002434
2435 /* Now f is added in twice in each column of the
2436 * pyramid it appears. Same as adding f<<1 once.
2437 */
2438 f <<= 1;
2439 while (pa < paend) {
2440 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002441 *pz++ = (digit)(carry & PyLong_MASK);
2442 carry >>= PyLong_SHIFT;
2443 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002444 }
2445 if (carry) {
2446 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002447 *pz++ = (digit)(carry & PyLong_MASK);
2448 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002449 }
2450 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002451 *pz += (digit)(carry & PyLong_MASK);
2452 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002453 }
Tim Peters0973b992004-08-29 22:16:50 +00002454 }
2455 else { /* a is not the same as b -- gradeschool long mult */
2456 for (i = 0; i < size_a; ++i) {
2457 twodigits carry = 0;
2458 twodigits f = a->ob_digit[i];
2459 digit *pz = z->ob_digit + i;
2460 digit *pb = b->ob_digit;
2461 digit *pbend = b->ob_digit + size_b;
2462
2463 SIGCHECK({
2464 Py_DECREF(z);
2465 return NULL;
2466 })
2467
2468 while (pb < pbend) {
2469 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002470 *pz++ = (digit)(carry & PyLong_MASK);
2471 carry >>= PyLong_SHIFT;
2472 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002473 }
2474 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002475 *pz += (digit)(carry & PyLong_MASK);
2476 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002477 }
2478 }
Tim Peters44121a62002-08-12 06:17:58 +00002479 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002480}
2481
2482/* A helper for Karatsuba multiplication (k_mul).
2483 Takes a long "n" and an integer "size" representing the place to
2484 split, and sets low and high such that abs(n) == (high << size) + low,
2485 viewing the shift as being by digits. The sign bit is ignored, and
2486 the return values are >= 0.
2487 Returns 0 on success, -1 on failure.
2488*/
2489static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002490kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002491{
2492 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002493 Py_ssize_t size_lo, size_hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002494 const Py_ssize_t size_n = ABS(Py_Size(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002495
2496 size_lo = MIN(size_n, size);
2497 size_hi = size_n - size_lo;
2498
2499 if ((hi = _PyLong_New(size_hi)) == NULL)
2500 return -1;
2501 if ((lo = _PyLong_New(size_lo)) == NULL) {
2502 Py_DECREF(hi);
2503 return -1;
2504 }
2505
2506 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2507 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2508
2509 *high = long_normalize(hi);
2510 *low = long_normalize(lo);
2511 return 0;
2512}
2513
Tim Peters60004642002-08-12 22:01:34 +00002514static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2515
Tim Peters5af4e6c2002-08-12 02:31:19 +00002516/* Karatsuba multiplication. Ignores the input signs, and returns the
2517 * absolute value of the product (or NULL if error).
2518 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2519 */
2520static PyLongObject *
2521k_mul(PyLongObject *a, PyLongObject *b)
2522{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002523 Py_ssize_t asize = ABS(Py_Size(a));
2524 Py_ssize_t bsize = ABS(Py_Size(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002525 PyLongObject *ah = NULL;
2526 PyLongObject *al = NULL;
2527 PyLongObject *bh = NULL;
2528 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002529 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002530 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002531 Py_ssize_t shift; /* the number of digits we split off */
2532 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002533
Tim Peters5af4e6c2002-08-12 02:31:19 +00002534 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2535 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2536 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002537 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002538 * By picking X to be a power of 2, "*X" is just shifting, and it's
2539 * been reduced to 3 multiplies on numbers half the size.
2540 */
2541
Tim Petersfc07e562002-08-12 02:54:10 +00002542 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002543 * is largest.
2544 */
Tim Peters738eda72002-08-12 15:08:20 +00002545 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002546 t1 = a;
2547 a = b;
2548 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002549
2550 i = asize;
2551 asize = bsize;
2552 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002553 }
2554
2555 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002556 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2557 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002558 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002559 return _PyLong_New(0);
2560 else
2561 return x_mul(a, b);
2562 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002563
Tim Peters60004642002-08-12 22:01:34 +00002564 /* If a is small compared to b, splitting on b gives a degenerate
2565 * case with ah==0, and Karatsuba may be (even much) less efficient
2566 * than "grade school" then. However, we can still win, by viewing
2567 * b as a string of "big digits", each of width a->ob_size. That
2568 * leads to a sequence of balanced calls to k_mul.
2569 */
2570 if (2 * asize <= bsize)
2571 return k_lopsided_mul(a, b);
2572
Tim Petersd6974a52002-08-13 20:37:51 +00002573 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002574 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002575 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002576 assert(Py_Size(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002577
Tim Peters0973b992004-08-29 22:16:50 +00002578 if (a == b) {
2579 bh = ah;
2580 bl = al;
2581 Py_INCREF(bh);
2582 Py_INCREF(bl);
2583 }
2584 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002585
Tim Petersd64c1de2002-08-12 17:36:03 +00002586 /* The plan:
2587 * 1. Allocate result space (asize + bsize digits: that's always
2588 * enough).
2589 * 2. Compute ah*bh, and copy into result at 2*shift.
2590 * 3. Compute al*bl, and copy into result at 0. Note that this
2591 * can't overlap with #2.
2592 * 4. Subtract al*bl from the result, starting at shift. This may
2593 * underflow (borrow out of the high digit), but we don't care:
2594 * we're effectively doing unsigned arithmetic mod
2595 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2596 * borrows and carries out of the high digit can be ignored.
2597 * 5. Subtract ah*bh from the result, starting at shift.
2598 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2599 * at shift.
2600 */
2601
2602 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002603 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002604 if (ret == NULL) goto fail;
2605#ifdef Py_DEBUG
2606 /* Fill with trash, to catch reference to uninitialized digits. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002607 memset(ret->ob_digit, 0xDF, Py_Size(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002608#endif
Tim Peters44121a62002-08-12 06:17:58 +00002609
Tim Petersd64c1de2002-08-12 17:36:03 +00002610 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002611 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002612 assert(Py_Size(t1) >= 0);
2613 assert(2*shift + Py_Size(t1) <= Py_Size(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002614 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002615 Py_Size(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002616
2617 /* Zero-out the digits higher than the ah*bh copy. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002618 i = Py_Size(ret) - 2*shift - Py_Size(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002619 if (i)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002620 memset(ret->ob_digit + 2*shift + Py_Size(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002621 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002622
Tim Petersd64c1de2002-08-12 17:36:03 +00002623 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002624 if ((t2 = k_mul(al, bl)) == NULL) {
2625 Py_DECREF(t1);
2626 goto fail;
2627 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002628 assert(Py_Size(t2) >= 0);
2629 assert(Py_Size(t2) <= 2*shift); /* no overlap with high digits */
2630 memcpy(ret->ob_digit, t2->ob_digit, Py_Size(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002631
2632 /* Zero out remaining digits. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002633 i = 2*shift - Py_Size(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002634 if (i)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002635 memset(ret->ob_digit + Py_Size(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002636
Tim Petersd64c1de2002-08-12 17:36:03 +00002637 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2638 * because it's fresher in cache.
2639 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002640 i = Py_Size(ret) - shift; /* # digits after shift */
2641 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_Size(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002642 Py_DECREF(t2);
2643
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002644 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_Size(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002645 Py_DECREF(t1);
2646
Tim Petersd64c1de2002-08-12 17:36:03 +00002647 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002648 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2649 Py_DECREF(ah);
2650 Py_DECREF(al);
2651 ah = al = NULL;
2652
Tim Peters0973b992004-08-29 22:16:50 +00002653 if (a == b) {
2654 t2 = t1;
2655 Py_INCREF(t2);
2656 }
2657 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002658 Py_DECREF(t1);
2659 goto fail;
2660 }
2661 Py_DECREF(bh);
2662 Py_DECREF(bl);
2663 bh = bl = NULL;
2664
Tim Peters738eda72002-08-12 15:08:20 +00002665 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002666 Py_DECREF(t1);
2667 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002668 if (t3 == NULL) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002669 assert(Py_Size(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002670
Tim Petersd6974a52002-08-13 20:37:51 +00002671 /* Add t3. It's not obvious why we can't run out of room here.
2672 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002673 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002674 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_Size(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002675 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002676
Tim Peters5af4e6c2002-08-12 02:31:19 +00002677 return long_normalize(ret);
2678
2679 fail:
2680 Py_XDECREF(ret);
2681 Py_XDECREF(ah);
2682 Py_XDECREF(al);
2683 Py_XDECREF(bh);
2684 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002685 return NULL;
2686}
2687
Tim Petersd6974a52002-08-13 20:37:51 +00002688/* (*) Why adding t3 can't "run out of room" above.
2689
Tim Petersab86c2b2002-08-15 20:06:00 +00002690Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2691to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002692
Tim Petersab86c2b2002-08-15 20:06:00 +000026931. For any integer i, i = c(i/2) + f(i/2). In particular,
2694 bsize = c(bsize/2) + f(bsize/2).
26952. shift = f(bsize/2)
26963. asize <= bsize
26974. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2698 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002699
Tim Petersab86c2b2002-08-15 20:06:00 +00002700We allocated asize + bsize result digits, and add t3 into them at an offset
2701of shift. This leaves asize+bsize-shift allocated digit positions for t3
2702to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2703asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002704
Tim Petersab86c2b2002-08-15 20:06:00 +00002705bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2706at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002707
Tim Petersab86c2b2002-08-15 20:06:00 +00002708If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2709digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2710most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002711
Tim Petersab86c2b2002-08-15 20:06:00 +00002712The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002713
Tim Petersab86c2b2002-08-15 20:06:00 +00002714 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002715
Tim Petersab86c2b2002-08-15 20:06:00 +00002716and we have asize + c(bsize/2) available digit positions. We need to show
2717this is always enough. An instance of c(bsize/2) cancels out in both, so
2718the question reduces to whether asize digits is enough to hold
2719(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2720then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2721asize 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 +00002722digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002723asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002724c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2725is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2726bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002727
Tim Peters48d52c02002-08-14 17:07:32 +00002728Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2729clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2730ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002731*/
2732
Tim Peters60004642002-08-12 22:01:34 +00002733/* b has at least twice the digits of a, and a is big enough that Karatsuba
2734 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2735 * of slices, each with a->ob_size digits, and multiply the slices by a,
2736 * one at a time. This gives k_mul balanced inputs to work with, and is
2737 * also cache-friendly (we compute one double-width slice of the result
2738 * at a time, then move on, never bactracking except for the helpful
2739 * single-width slice overlap between successive partial sums).
2740 */
2741static PyLongObject *
2742k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2743{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002744 const Py_ssize_t asize = ABS(Py_Size(a));
2745 Py_ssize_t bsize = ABS(Py_Size(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002746 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002747 PyLongObject *ret;
2748 PyLongObject *bslice = NULL;
2749
2750 assert(asize > KARATSUBA_CUTOFF);
2751 assert(2 * asize <= bsize);
2752
2753 /* Allocate result space, and zero it out. */
2754 ret = _PyLong_New(asize + bsize);
2755 if (ret == NULL)
2756 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002757 memset(ret->ob_digit, 0, Py_Size(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002758
2759 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002760 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002761 if (bslice == NULL)
2762 goto fail;
2763
2764 nbdone = 0;
2765 while (bsize > 0) {
2766 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002767 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002768
2769 /* Multiply the next slice of b by a. */
2770 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2771 nbtouse * sizeof(digit));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002772 Py_Size(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002773 product = k_mul(a, bslice);
2774 if (product == NULL)
2775 goto fail;
2776
2777 /* Add into result. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002778 (void)v_iadd(ret->ob_digit + nbdone, Py_Size(ret) - nbdone,
2779 product->ob_digit, Py_Size(product));
Tim Peters60004642002-08-12 22:01:34 +00002780 Py_DECREF(product);
2781
2782 bsize -= nbtouse;
2783 nbdone += nbtouse;
2784 }
2785
2786 Py_DECREF(bslice);
2787 return long_normalize(ret);
2788
2789 fail:
2790 Py_DECREF(ret);
2791 Py_XDECREF(bslice);
2792 return NULL;
2793}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002794
2795static PyObject *
2796long_mul(PyLongObject *v, PyLongObject *w)
2797{
2798 PyLongObject *a, *b, *z;
2799
2800 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002801 Py_INCREF(Py_NotImplemented);
2802 return Py_NotImplemented;
2803 }
2804
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002805 if (ABS(Py_Size(v)) <= 1 && ABS(Py_Size(w)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002806 PyObject *r;
2807 r = PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w));
2808 Py_DECREF(a);
2809 Py_DECREF(b);
2810 return r;
2811 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002812
Tim Petersd64c1de2002-08-12 17:36:03 +00002813 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002814 /* Negate if exactly one of the inputs is negative. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002815 if (((Py_Size(a) ^ Py_Size(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002816 NEGATE(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002817 Py_DECREF(a);
2818 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002819 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002820}
2821
Guido van Rossume32e0141992-01-19 16:31:05 +00002822/* The / and % operators are now defined in terms of divmod().
2823 The expression a mod b has the value a - b*floor(a/b).
2824 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002825 |a| by |b|, with the sign of a. This is also expressed
2826 as a - b*trunc(a/b), if trunc truncates towards zero.
2827 Some examples:
2828 a b a rem b a mod b
2829 13 10 3 3
2830 -13 10 -3 7
2831 13 -10 3 -7
2832 -13 -10 -3 -3
2833 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002834 have different signs. We then subtract one from the 'div'
2835 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002836
Tim Peters47e52ee2004-08-30 02:44:38 +00002837/* Compute
2838 * *pdiv, *pmod = divmod(v, w)
2839 * NULL can be passed for pdiv or pmod, in which case that part of
2840 * the result is simply thrown away. The caller owns a reference to
2841 * each of these it requests (does not pass NULL for).
2842 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002843static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002844l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002845 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002846{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002847 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002848
Guido van Rossume32e0141992-01-19 16:31:05 +00002849 if (long_divrem(v, w, &div, &mod) < 0)
2850 return -1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002851 if ((Py_Size(mod) < 0 && Py_Size(w) > 0) ||
2852 (Py_Size(mod) > 0 && Py_Size(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002853 PyLongObject *temp;
2854 PyLongObject *one;
2855 temp = (PyLongObject *) long_add(mod, w);
2856 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002857 mod = temp;
2858 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002859 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002860 return -1;
2861 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002862 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002863 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002864 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2865 Py_DECREF(mod);
2866 Py_DECREF(div);
2867 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002868 return -1;
2869 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002870 Py_DECREF(one);
2871 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002872 div = temp;
2873 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002874 if (pdiv != NULL)
2875 *pdiv = div;
2876 else
2877 Py_DECREF(div);
2878
2879 if (pmod != NULL)
2880 *pmod = mod;
2881 else
2882 Py_DECREF(mod);
2883
Guido van Rossume32e0141992-01-19 16:31:05 +00002884 return 0;
2885}
2886
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002887static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002888long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002889{
Tim Peters47e52ee2004-08-30 02:44:38 +00002890 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002891
2892 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002893 if (l_divmod(a, b, &div, NULL) < 0)
2894 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002895 Py_DECREF(a);
2896 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002897 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002898}
2899
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002900static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002901long_true_divide(PyObject *v, PyObject *w)
2902{
Tim Peterse2a60002001-09-04 06:17:36 +00002903 PyLongObject *a, *b;
2904 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002905 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002906
2907 CONVERT_BINOP(v, w, &a, &b);
2908 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2909 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002910 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2911 Py_DECREF(a);
2912 Py_DECREF(b);
2913 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002914 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002915 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2916 but should really be set correctly after sucessful calls to
2917 _PyLong_AsScaledDouble() */
2918 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002919
2920 if (bd == 0.0) {
2921 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002922 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002923 return NULL;
2924 }
2925
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002926 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002927 ad /= bd; /* overflow/underflow impossible here */
2928 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002929 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002930 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002931 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002932 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002933 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002934 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002935 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002936 goto overflow;
2937 return PyFloat_FromDouble(ad);
2938
2939overflow:
2940 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002941 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002942 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002943
Tim Peters20dab9f2001-09-04 05:31:47 +00002944}
2945
2946static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002947long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002948{
Tim Peters47e52ee2004-08-30 02:44:38 +00002949 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002950
2951 CONVERT_BINOP(v, w, &a, &b);
2952
Tim Peters47e52ee2004-08-30 02:44:38 +00002953 if (l_divmod(a, b, NULL, &mod) < 0)
2954 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002955 Py_DECREF(a);
2956 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002957 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002958}
2959
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002960static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002961long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002962{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002963 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002964 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002965
2966 CONVERT_BINOP(v, w, &a, &b);
2967
2968 if (l_divmod(a, b, &div, &mod) < 0) {
2969 Py_DECREF(a);
2970 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002971 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002972 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002973 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002974 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002975 PyTuple_SetItem(z, 0, (PyObject *) div);
2976 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002977 }
2978 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002979 Py_DECREF(div);
2980 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002981 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002982 Py_DECREF(a);
2983 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002984 return z;
2985}
2986
Tim Peters47e52ee2004-08-30 02:44:38 +00002987/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002988static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002989long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002990{
Tim Peters47e52ee2004-08-30 02:44:38 +00002991 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2992 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002993
Tim Peters47e52ee2004-08-30 02:44:38 +00002994 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002995 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002996 PyLongObject *temp = NULL;
2997
2998 /* 5-ary values. If the exponent is large enough, table is
2999 * precomputed so that table[i] == a**i % c for i in range(32).
3000 */
3001 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3002 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3003
3004 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003005 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003006 if (PyLong_Check(x)) {
3007 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003008 Py_INCREF(x);
3009 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003010 else if (x == Py_None)
3011 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003012 else {
3013 Py_DECREF(a);
3014 Py_DECREF(b);
3015 Py_INCREF(Py_NotImplemented);
3016 return Py_NotImplemented;
3017 }
Tim Peters4c483c42001-09-05 06:24:58 +00003018
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003019 if (Py_Size(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003020 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003021 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003022 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003023 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003024 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003025 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003026 /* else return a float. This works because we know
3027 that this calls float_pow() which converts its
3028 arguments to double. */
3029 Py_DECREF(a);
3030 Py_DECREF(b);
3031 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003032 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003033 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003034
3035 if (c) {
3036 /* if modulus == 0:
3037 raise ValueError() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003038 if (Py_Size(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003039 PyErr_SetString(PyExc_ValueError,
3040 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003041 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003042 }
3043
3044 /* if modulus < 0:
3045 negativeOutput = True
3046 modulus = -modulus */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003047 if (Py_Size(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003048 negativeOutput = 1;
3049 temp = (PyLongObject *)_PyLong_Copy(c);
3050 if (temp == NULL)
3051 goto Error;
3052 Py_DECREF(c);
3053 c = temp;
3054 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003055 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003056 }
3057
3058 /* if modulus == 1:
3059 return 0 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003060 if ((Py_Size(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003061 z = (PyLongObject *)PyLong_FromLong(0L);
3062 goto Done;
3063 }
3064
3065 /* if base < 0:
3066 base = base % modulus
3067 Having the base positive just makes things easier. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003068 if (Py_Size(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003069 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003070 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003071 Py_DECREF(a);
3072 a = temp;
3073 temp = NULL;
3074 }
3075 }
3076
3077 /* At this point a, b, and c are guaranteed non-negative UNLESS
3078 c is NULL, in which case a may be negative. */
3079
3080 z = (PyLongObject *)PyLong_FromLong(1L);
3081 if (z == NULL)
3082 goto Error;
3083
3084 /* Perform a modular reduction, X = X % c, but leave X alone if c
3085 * is NULL.
3086 */
3087#define REDUCE(X) \
3088 if (c != NULL) { \
3089 if (l_divmod(X, c, NULL, &temp) < 0) \
3090 goto Error; \
3091 Py_XDECREF(X); \
3092 X = temp; \
3093 temp = NULL; \
3094 }
3095
3096 /* Multiply two values, then reduce the result:
3097 result = X*Y % c. If c is NULL, skip the mod. */
3098#define MULT(X, Y, result) \
3099{ \
3100 temp = (PyLongObject *)long_mul(X, Y); \
3101 if (temp == NULL) \
3102 goto Error; \
3103 Py_XDECREF(result); \
3104 result = temp; \
3105 temp = NULL; \
3106 REDUCE(result) \
3107}
3108
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003109 if (Py_Size(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003110 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3111 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003112 for (i = Py_Size(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003113 digit bi = b->ob_digit[i];
3114
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003115 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003116 MULT(z, z, z)
3117 if (bi & j)
3118 MULT(z, a, z)
3119 }
3120 }
3121 }
3122 else {
3123 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3124 Py_INCREF(z); /* still holds 1L */
3125 table[0] = z;
3126 for (i = 1; i < 32; ++i)
3127 MULT(table[i-1], a, table[i])
3128
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003129 for (i = Py_Size(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003130 const digit bi = b->ob_digit[i];
3131
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003132 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003133 const int index = (bi >> j) & 0x1f;
3134 for (k = 0; k < 5; ++k)
3135 MULT(z, z, z)
3136 if (index)
3137 MULT(z, table[index], z)
3138 }
3139 }
3140 }
3141
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003142 if (negativeOutput && (Py_Size(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003143 temp = (PyLongObject *)long_sub(z, c);
3144 if (temp == NULL)
3145 goto Error;
3146 Py_DECREF(z);
3147 z = temp;
3148 temp = NULL;
3149 }
3150 goto Done;
3151
3152 Error:
3153 if (z != NULL) {
3154 Py_DECREF(z);
3155 z = NULL;
3156 }
3157 /* fall through */
3158 Done:
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003159 if (Py_Size(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003160 for (i = 0; i < 32; ++i)
3161 Py_XDECREF(table[i]);
3162 }
Tim Petersde7990b2005-07-17 23:45:23 +00003163 Py_DECREF(a);
3164 Py_DECREF(b);
3165 Py_XDECREF(c);
3166 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003167 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003168}
3169
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003170static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003171long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003172{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003173 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003174 PyLongObject *x;
3175 PyLongObject *w;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003176 if (ABS(Py_Size(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003177 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003178 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003179 if (w == NULL)
3180 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003181 x = (PyLongObject *) long_add(v, w);
3182 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003183 if (x == NULL)
3184 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003185 Py_Size(x) = -(Py_Size(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003186 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003187}
3188
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003189static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003190long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003191{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003192 PyLongObject *z;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003193 if (ABS(Py_Size(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003194 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003195 z = (PyLongObject *)_PyLong_Copy(v);
3196 if (z != NULL)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003197 Py_Size(z) = -(Py_Size(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003198 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003199}
3200
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003201static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003202long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003203{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003204 if (Py_Size(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003205 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003206 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003207 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003208}
3209
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003210static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003211long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003212{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003213 return ABS(Py_Size(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003214}
3215
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003216static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003217long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003218{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003219 PyLongObject *a, *b;
3220 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003221 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003222 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003223 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003224
Neil Schemenauerba872e22001-01-04 01:46:03 +00003225 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3226
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003227 if (Py_Size(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003228 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003229 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003230 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003231 if (a1 == NULL)
3232 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003233 a2 = (PyLongObject *) long_rshift(a1, b);
3234 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003235 if (a2 == NULL)
3236 goto rshift_error;
3237 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003238 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003239 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003240 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003241
Neil Schemenauerba872e22001-01-04 01:46:03 +00003242 shiftby = PyLong_AsLong((PyObject *)b);
3243 if (shiftby == -1L && PyErr_Occurred())
3244 goto rshift_error;
3245 if (shiftby < 0) {
3246 PyErr_SetString(PyExc_ValueError,
3247 "negative shift count");
3248 goto rshift_error;
3249 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003250 wordshift = shiftby / PyLong_SHIFT;
3251 newsize = ABS(Py_Size(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003252 if (newsize <= 0) {
3253 z = _PyLong_New(0);
3254 Py_DECREF(a);
3255 Py_DECREF(b);
3256 return (PyObject *)z;
3257 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003258 loshift = shiftby % PyLong_SHIFT;
3259 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003260 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003261 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003262 z = _PyLong_New(newsize);
3263 if (z == NULL)
3264 goto rshift_error;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003265 if (Py_Size(a) < 0)
3266 Py_Size(z) = -(Py_Size(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003267 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3268 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3269 if (i+1 < newsize)
3270 z->ob_digit[i] |=
3271 (a->ob_digit[j+1] << hishift) & himask;
3272 }
3273 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003274 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003275rshift_error:
3276 Py_DECREF(a);
3277 Py_DECREF(b);
3278 return (PyObject *) z;
3279
Guido van Rossumc6913e71991-11-19 20:26:46 +00003280}
3281
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003282static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003283long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003284{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003285 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003286 PyLongObject *a, *b;
3287 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003288 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003289 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003290 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003291
Neil Schemenauerba872e22001-01-04 01:46:03 +00003292 CONVERT_BINOP(v, w, &a, &b);
3293
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003294 shiftby = PyLong_AsLong((PyObject *)b);
3295 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003296 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003297 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003298 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003299 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003300 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003301 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003302 PyErr_SetString(PyExc_ValueError,
3303 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003304 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003305 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003306 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3307 wordshift = (int)shiftby / PyLong_SHIFT;
3308 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003309
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003310 oldsize = ABS(Py_Size(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003311 newsize = oldsize + wordshift;
3312 if (remshift)
3313 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003314 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003315 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003316 goto lshift_error;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003317 if (Py_Size(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003318 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003319 for (i = 0; i < wordshift; i++)
3320 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003321 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003322 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003323 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003324 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3325 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003326 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003327 if (remshift)
3328 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003329 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003330 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003331 z = long_normalize(z);
3332lshift_error:
3333 Py_DECREF(a);
3334 Py_DECREF(b);
3335 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003336}
3337
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003338
3339/* Bitwise and/xor/or operations */
3340
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003341static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003342long_bitwise(PyLongObject *a,
3343 int op, /* '&', '|', '^' */
3344 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003345{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003346 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003347 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003348 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003349 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003350 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003351 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003352 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003353
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003354 if (Py_Size(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003355 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003356 if (a == NULL)
3357 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003358 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003359 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003360 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003361 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003362 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003363 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003364 if (Py_Size(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003365 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003366 if (b == NULL) {
3367 Py_DECREF(a);
3368 return NULL;
3369 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003370 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003371 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003372 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003373 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003374 maskb = 0;
3375 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003376
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003377 negz = 0;
3378 switch (op) {
3379 case '^':
3380 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003381 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003382 negz = -1;
3383 }
3384 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003385 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003386 if (maska && maskb) {
3387 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003388 maska ^= PyLong_MASK;
3389 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003390 negz = -1;
3391 }
3392 break;
3393 case '|':
3394 if (maska || maskb) {
3395 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003396 maska ^= PyLong_MASK;
3397 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003398 negz = -1;
3399 }
3400 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003401 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003402
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003403 /* JRH: The original logic here was to allocate the result value (z)
3404 as the longer of the two operands. However, there are some cases
3405 where the result is guaranteed to be shorter than that: AND of two
3406 positives, OR of two negatives: use the shorter number. AND with
3407 mixed signs: use the positive number. OR with mixed signs: use the
3408 negative number. After the transformations above, op will be '&'
3409 iff one of these cases applies, and mask will be non-0 for operands
3410 whose length should be ignored.
3411 */
3412
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003413 size_a = Py_Size(a);
3414 size_b = Py_Size(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003415 size_z = op == '&'
3416 ? (maska
3417 ? size_b
3418 : (maskb ? size_a : MIN(size_a, size_b)))
3419 : MAX(size_a, size_b);
3420 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003421 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003422 Py_DECREF(a);
3423 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003424 return NULL;
3425 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003426
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003427 for (i = 0; i < size_z; ++i) {
3428 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3429 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3430 switch (op) {
3431 case '&': z->ob_digit[i] = diga & digb; break;
3432 case '|': z->ob_digit[i] = diga | digb; break;
3433 case '^': z->ob_digit[i] = diga ^ digb; break;
3434 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003435 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003436
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003437 Py_DECREF(a);
3438 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003439 z = long_normalize(z);
3440 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003441 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003442 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003443 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003444 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003445}
3446
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003447static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003448long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003449{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003450 PyLongObject *a, *b;
3451 PyObject *c;
3452 CONVERT_BINOP(v, w, &a, &b);
3453 c = long_bitwise(a, '&', b);
3454 Py_DECREF(a);
3455 Py_DECREF(b);
3456 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003457}
3458
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003459static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003460long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003461{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003462 PyLongObject *a, *b;
3463 PyObject *c;
3464 CONVERT_BINOP(v, w, &a, &b);
3465 c = long_bitwise(a, '^', b);
3466 Py_DECREF(a);
3467 Py_DECREF(b);
3468 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003469}
3470
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003471static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003472long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003473{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003474 PyLongObject *a, *b;
3475 PyObject *c;
3476 CONVERT_BINOP(v, w, &a, &b);
3477 c = long_bitwise(a, '|', b);
3478 Py_DECREF(a);
3479 Py_DECREF(b);
3480 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003481}
3482
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003483static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003484long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003485{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003486 if (PyLong_CheckExact(v))
3487 Py_INCREF(v);
3488 else
3489 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003490 return v;
3491}
3492
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003493static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003494long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003495{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003496 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003497 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003498 if (result == -1.0 && PyErr_Occurred())
3499 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003500 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003501}
3502
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003503static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003504long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003505
Tim Peters6d6c1a32001-08-02 04:15:00 +00003506static PyObject *
3507long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3508{
3509 PyObject *x = NULL;
3510 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003511 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003512
Guido van Rossumbef14172001-08-29 15:47:46 +00003513 if (type != &PyLong_Type)
3514 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003515 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003516 &x, &base))
3517 return NULL;
3518 if (x == NULL)
3519 return PyLong_FromLong(0L);
3520 if (base == -909)
3521 return PyNumber_Long(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003522 else if (PyString_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003523 /* Since PyLong_FromString doesn't have a length parameter,
3524 * check here for possible NULs in the string. */
Guido van Rossum4581ae52007-05-22 21:56:47 +00003525 char *string;
3526 int size;
3527 if (PyBytes_Check(x)) {
3528 string = PyBytes_AS_STRING(x);
3529 size = PyBytes_GET_SIZE(x);
3530 }
3531 else {
3532 string = PyString_AS_STRING(x);
3533 size = PyString_GET_SIZE(x);
3534 }
3535 if (strlen(string) != size) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003536 /* create a repr() of the input string,
3537 * just like PyLong_FromString does. */
3538 PyObject *srepr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00003539 srepr = PyObject_ReprStr8(x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003540 if (srepr == NULL)
3541 return NULL;
3542 PyErr_Format(PyExc_ValueError,
3543 "invalid literal for int() with base %d: %s",
3544 base, PyString_AS_STRING(srepr));
3545 Py_DECREF(srepr);
3546 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003547 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003548 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003549 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003550 else if (PyUnicode_Check(x))
3551 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3552 PyUnicode_GET_SIZE(x),
3553 base);
3554 else {
3555 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003556 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003557 return NULL;
3558 }
3559}
3560
Guido van Rossumbef14172001-08-29 15:47:46 +00003561/* Wimpy, slow approach to tp_new calls for subtypes of long:
3562 first create a regular long from whatever arguments we got,
3563 then allocate a subtype instance and initialize it from
3564 the regular long. The regular long is then thrown away.
3565*/
3566static PyObject *
3567long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3568{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003569 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003570 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003571
3572 assert(PyType_IsSubtype(type, &PyLong_Type));
3573 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3574 if (tmp == NULL)
3575 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003576 assert(PyLong_CheckExact(tmp));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003577 n = Py_Size(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003578 if (n < 0)
3579 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003580 newobj = (PyLongObject *)type->tp_alloc(type, n);
3581 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003582 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003583 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003584 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003585 assert(PyLong_Check(newobj));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003586 Py_Size(newobj) = Py_Size(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003587 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003588 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003589 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003590 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003591}
3592
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003593static PyObject *
3594long_getnewargs(PyLongObject *v)
3595{
3596 return Py_BuildValue("(N)", _PyLong_Copy(v));
3597}
3598
Guido van Rossumb43daf72007-08-01 18:08:08 +00003599static PyObject *
3600long_getN(PyLongObject *v, void *context) {
3601 return PyLong_FromLong((intptr_t)context);
3602}
3603
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003604static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003605 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3606 "Returns self, the complex conjugate of any int."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003607 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3608 {NULL, NULL} /* sentinel */
3609};
3610
Guido van Rossumb43daf72007-08-01 18:08:08 +00003611static PyGetSetDef long_getset[] = {
3612 {"real",
3613 (getter)long_long, (setter)NULL,
3614 "the real part of a complex number",
3615 NULL},
3616 {"imag",
3617 (getter)long_getN, (setter)NULL,
3618 "the imaginary part of a complex number",
3619 (void*)0},
3620 {"numerator",
3621 (getter)long_long, (setter)NULL,
3622 "the numerator of a rational number in lowest terms",
3623 NULL},
3624 {"denominator",
3625 (getter)long_getN, (setter)NULL,
3626 "the denominator of a rational number in lowest terms",
3627 (void*)1},
3628 {NULL} /* Sentinel */
3629};
3630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003631PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003632"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003633\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003634Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003635point argument will be truncated towards zero (this does not include a\n\
3636string representation of a floating point number!) When converting a\n\
3637string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003638converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003640static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003641 (binaryfunc) long_add, /*nb_add*/
3642 (binaryfunc) long_sub, /*nb_subtract*/
3643 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003644 long_mod, /*nb_remainder*/
3645 long_divmod, /*nb_divmod*/
3646 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003647 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003648 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003649 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003650 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003651 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003652 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003653 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003654 long_and, /*nb_and*/
3655 long_xor, /*nb_xor*/
3656 long_or, /*nb_or*/
Neal Norwitzca810462006-08-29 07:57:59 +00003657 0, /*nb_coerce*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003658 long_long, /*nb_int*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003659 long_long, /*nb_long*/
3660 long_float, /*nb_float*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003661 0, /*nb_oct*/ /* not used */
3662 0, /*nb_hex*/ /* not used */
Guido van Rossum4668b002001-08-08 05:00:18 +00003663 0, /* nb_inplace_add */
3664 0, /* nb_inplace_subtract */
3665 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003666 0, /* nb_inplace_remainder */
3667 0, /* nb_inplace_power */
3668 0, /* nb_inplace_lshift */
3669 0, /* nb_inplace_rshift */
3670 0, /* nb_inplace_and */
3671 0, /* nb_inplace_xor */
3672 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003673 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003674 long_true_divide, /* nb_true_divide */
3675 0, /* nb_inplace_floor_divide */
3676 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003677 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003678};
3679
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003680PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003681 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003682 "int", /* tp_name */
3683 /* See _PyLong_New for why this isn't
3684 sizeof(PyLongObject) - sizeof(digit) */
3685 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003686 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003687 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688 0, /* tp_print */
3689 0, /* tp_getattr */
3690 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003691 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003692 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693 &long_as_number, /* tp_as_number */
3694 0, /* tp_as_sequence */
3695 0, /* tp_as_mapping */
3696 (hashfunc)long_hash, /* tp_hash */
3697 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003698 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003699 PyObject_GenericGetAttr, /* tp_getattro */
3700 0, /* tp_setattro */
3701 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003702 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3703 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003704 long_doc, /* tp_doc */
3705 0, /* tp_traverse */
3706 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003707 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003708 0, /* tp_weaklistoffset */
3709 0, /* tp_iter */
3710 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003711 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003712 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003713 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714 0, /* tp_base */
3715 0, /* tp_dict */
3716 0, /* tp_descr_get */
3717 0, /* tp_descr_set */
3718 0, /* tp_dictoffset */
3719 0, /* tp_init */
3720 0, /* tp_alloc */
3721 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003722 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003723};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003724
3725int
3726_PyLong_Init(void)
3727{
3728#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3729 int ival;
3730 PyLongObject *v = small_ints;
3731 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3732 PyObject_INIT(v, &PyLong_Type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003733 Py_Size(v) = -1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003734 v->ob_digit[0] = -ival;
3735 }
3736 for (; ival < NSMALLPOSINTS; ival++, v++) {
3737 PyObject_INIT(v, &PyLong_Type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003738 Py_Size(v) = ival ? 1 : 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003739 v->ob_digit[0] = ival;
3740 }
3741#endif
3742 return 1;
3743}
3744
3745void
3746PyLong_Fini(void)
3747{
3748#if 0
3749 int i;
3750 /* This is currently not needed; the small integers
3751 are statically allocated */
3752#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3753 PyIntObject **q;
3754
3755 i = NSMALLNEGINTS + NSMALLPOSINTS;
3756 q = small_ints;
3757 while (--i >= 0) {
3758 Py_XDECREF(*q);
3759 *q++ = NULL;
3760 }
3761#endif
3762#endif
3763}