blob: ddf359d0eac2a136c6d7490cc4f9081e21f05120 [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;
Guido van Rossum25236212007-08-22 23:28:23 +00001692 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001693 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;
Guido van Rossum25236212007-08-22 23:28:23 +00001959 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001960 if (strobj == NULL)
1961 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001962 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00001963 "invalid literal for int() with base %d: %R",
1964 base, strobj);
1965 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001966 return NULL;
1967}
1968
1969PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001970PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001971{
Walter Dörwald07e14762002-11-06 16:15:14 +00001972 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001973 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001974
Walter Dörwald07e14762002-11-06 16:15:14 +00001975 if (buffer == NULL)
1976 return NULL;
1977
1978 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1979 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001980 return NULL;
1981 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001982 result = PyLong_FromString(buffer, NULL, base);
1983 PyMem_FREE(buffer);
1984 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001985}
1986
Tim Peters9f688bf2000-07-07 15:53:28 +00001987/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001988static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001989 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00001990static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00001991static int long_divrem(PyLongObject *, PyLongObject *,
1992 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001993
1994/* Long division with remainder, top-level routine */
1995
Guido van Rossume32e0141992-01-19 16:31:05 +00001996static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001997long_divrem(PyLongObject *a, PyLongObject *b,
1998 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001999{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002000 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002001 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002002
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002003 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002004 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002005 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002006 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002007 }
2008 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002009 (size_a == size_b &&
2010 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002011 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002012 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002013 if (*pdiv == NULL)
2014 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002015 Py_INCREF(a);
2016 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002017 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002018 }
2019 if (size_b == 1) {
2020 digit rem = 0;
2021 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002022 if (z == NULL)
2023 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002024 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002025 if (*prem == NULL) {
2026 Py_DECREF(z);
2027 return -1;
2028 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002029 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002030 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002031 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002032 if (z == NULL)
2033 return -1;
2034 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002035 /* Set the signs.
2036 The quotient z has the sign of a*b;
2037 the remainder r has the sign of a,
2038 so a = b*z + r. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002039 if ((Py_Size(a) < 0) != (Py_Size(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002040 NEGATE(z);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002041 if (Py_Size(a) < 0 && Py_Size(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002042 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002043 *pdiv = z;
2044 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002045}
2046
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002047/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002048
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002049static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002050x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002051{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002052 Py_ssize_t size_v = ABS(Py_Size(v1)), size_w = ABS(Py_Size(w1));
2053 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002054 PyLongObject *v = mul1(v1, d);
2055 PyLongObject *w = mul1(w1, d);
2056 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002057 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002058
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002059 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002060 Py_XDECREF(v);
2061 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002062 return NULL;
2063 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002064
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002065 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002066 assert(Py_Refcnt(v) == 1); /* Since v will be used as accumulator! */
2067 assert(size_w == ABS(Py_Size(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002068
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002069 size_v = ABS(Py_Size(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002070 k = size_v - size_w;
2071 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002072
Thomas Wouters477c8d52006-05-27 19:21:47 +00002073 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002074 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2075 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002076 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002077 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002078
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002079 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002080 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002081 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002082 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002083 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002084 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002085 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002086 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002087 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002088 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002089
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090 while (w->ob_digit[size_w-2]*q >
2091 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002092 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002093 + v->ob_digit[j-1]
2094 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002095 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002096 + v->ob_digit[j-2])
2097 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002098
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002099 for (i = 0; i < size_w && i+k < size_v; ++i) {
2100 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002101 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002102 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002103 + ((twodigits)zz << PyLong_SHIFT);
2104 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002105 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002106 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002107 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002108 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002109
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002110 if (i+k < size_v) {
2111 carry += v->ob_digit[i+k];
2112 v->ob_digit[i+k] = 0;
2113 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002114
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002115 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002116 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002117 else {
2118 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002119 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002120 carry = 0;
2121 for (i = 0; i < size_w && i+k < size_v; ++i) {
2122 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002123 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002124 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2125 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002126 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002127 }
2128 }
2129 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002130
Guido van Rossumc206c761995-01-10 15:23:19 +00002131 if (a == NULL)
2132 *prem = NULL;
2133 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002134 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002135 *prem = divrem1(v, d, &d);
2136 /* d receives the (unused) remainder */
2137 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002138 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002139 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002140 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002141 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002142 Py_DECREF(v);
2143 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002144 return a;
2145}
2146
2147/* Methods */
2148
2149static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002150long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002151{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002152 Py_Type(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002153}
2154
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002155static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002156long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002157{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002158 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002159}
2160
2161static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002162long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002163{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002164 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002165
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002166 if (Py_Size(a) != Py_Size(b)) {
2167 if (ABS(Py_Size(a)) == 0 && ABS(Py_Size(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002168 sign = 0;
2169 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002170 sign = Py_Size(a) - Py_Size(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002171 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002172 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002173 Py_ssize_t i = ABS(Py_Size(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002174 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2175 ;
2176 if (i < 0)
2177 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002178 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002179 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002180 if (Py_Size(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002181 sign = -sign;
2182 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002183 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002184 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002185}
2186
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002187static PyObject *
2188long_richcompare(PyObject *self, PyObject *other, int op)
2189{
2190 PyLongObject *a, *b;
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002191 PyObject *result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002192 CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b);
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002193 result = Py_CmpToRich(op, long_compare(a, b));
2194 Py_DECREF(a);
2195 Py_DECREF(b);
2196 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002197}
2198
Guido van Rossum9bfef441993-03-29 10:43:31 +00002199static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002200long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002201{
2202 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002203 Py_ssize_t i;
2204 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002205
2206 /* This is designed so that Python ints and longs with the
2207 same value hash to the same value, otherwise comparisons
2208 of mapping keys will turn out weird */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002209 i = Py_Size(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002210 switch(i) {
2211 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2212 case 0: return 0;
2213 case 1: return v->ob_digit[0];
2214 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002215 sign = 1;
2216 x = 0;
2217 if (i < 0) {
2218 sign = -1;
2219 i = -(i);
2220 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002221#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002222 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002223 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002224 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002225 x += v->ob_digit[i];
2226 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002227#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002228 x = x * sign;
2229 if (x == -1)
2230 x = -2;
2231 return x;
2232}
2233
2234
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002235/* Add the absolute values of two long integers. */
2236
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002237static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002238x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002239{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002240 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002241 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002242 int i;
2243 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002244
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002245 /* Ensure a is the larger of the two: */
2246 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002247 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002248 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002249 size_a = size_b;
2250 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002251 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002252 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002253 if (z == NULL)
2254 return NULL;
2255 for (i = 0; i < size_b; ++i) {
2256 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002257 z->ob_digit[i] = carry & PyLong_MASK;
2258 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002259 }
2260 for (; i < size_a; ++i) {
2261 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002262 z->ob_digit[i] = carry & PyLong_MASK;
2263 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002264 }
2265 z->ob_digit[i] = carry;
2266 return long_normalize(z);
2267}
2268
2269/* Subtract the absolute values of two integers. */
2270
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002271static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002272x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002273{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002274 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002275 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002276 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002277 int sign = 1;
2278 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002279
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002280 /* Ensure a is the larger of the two: */
2281 if (size_a < size_b) {
2282 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002283 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002284 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002285 size_a = size_b;
2286 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002287 }
2288 else if (size_a == size_b) {
2289 /* Find highest digit where a and b differ: */
2290 i = size_a;
2291 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2292 ;
2293 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002294 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002295 if (a->ob_digit[i] < b->ob_digit[i]) {
2296 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002297 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002298 }
2299 size_a = size_b = i+1;
2300 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002301 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002302 if (z == NULL)
2303 return NULL;
2304 for (i = 0; i < size_b; ++i) {
2305 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002306 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002307 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002308 z->ob_digit[i] = borrow & PyLong_MASK;
2309 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002310 borrow &= 1; /* Keep only one sign bit */
2311 }
2312 for (; i < size_a; ++i) {
2313 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002314 z->ob_digit[i] = borrow & PyLong_MASK;
2315 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002316 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002317 }
2318 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002319 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002320 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002321 return long_normalize(z);
2322}
2323
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002324static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002325long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002326{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002327 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002328
Neil Schemenauerba872e22001-01-04 01:46:03 +00002329 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2330
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002331 if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002332 PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) +
2333 MEDIUM_VALUE(b));
2334 Py_DECREF(a);
2335 Py_DECREF(b);
2336 return result;
2337 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002338 if (Py_Size(a) < 0) {
2339 if (Py_Size(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002340 z = x_add(a, b);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002341 if (z != NULL && Py_Size(z) != 0)
2342 Py_Size(z) = -(Py_Size(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002343 }
2344 else
2345 z = x_sub(b, a);
2346 }
2347 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002348 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002349 z = x_sub(a, b);
2350 else
2351 z = x_add(a, b);
2352 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002353 Py_DECREF(a);
2354 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002355 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002356}
2357
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002358static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002359long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002360{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002361 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002362
Neil Schemenauerba872e22001-01-04 01:46:03 +00002363 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2364
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002365 if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002366 PyObject* r;
2367 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2368 Py_DECREF(a);
2369 Py_DECREF(b);
2370 return r;
2371 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002372 if (Py_Size(a) < 0) {
2373 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002374 z = x_sub(a, b);
2375 else
2376 z = x_add(a, b);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002377 if (z != NULL && Py_Size(z) != 0)
2378 Py_Size(z) = -(Py_Size(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002379 }
2380 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002381 if (Py_Size(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002382 z = x_add(a, b);
2383 else
2384 z = x_sub(a, b);
2385 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002386 Py_DECREF(a);
2387 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002388 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002389}
2390
Tim Peters5af4e6c2002-08-12 02:31:19 +00002391/* Grade school multiplication, ignoring the signs.
2392 * Returns the absolute value of the product, or NULL if error.
2393 */
2394static PyLongObject *
2395x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002396{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002397 PyLongObject *z;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002398 Py_ssize_t size_a = ABS(Py_Size(a));
2399 Py_ssize_t size_b = ABS(Py_Size(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002400 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002401
Tim Peters5af4e6c2002-08-12 02:31:19 +00002402 z = _PyLong_New(size_a + size_b);
2403 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002404 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002405
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002406 memset(z->ob_digit, 0, Py_Size(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002407 if (a == b) {
2408 /* Efficient squaring per HAC, Algorithm 14.16:
2409 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2410 * Gives slightly less than a 2x speedup when a == b,
2411 * via exploiting that each entry in the multiplication
2412 * pyramid appears twice (except for the size_a squares).
2413 */
2414 for (i = 0; i < size_a; ++i) {
2415 twodigits carry;
2416 twodigits f = a->ob_digit[i];
2417 digit *pz = z->ob_digit + (i << 1);
2418 digit *pa = a->ob_digit + i + 1;
2419 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002420
Tim Peters0973b992004-08-29 22:16:50 +00002421 SIGCHECK({
2422 Py_DECREF(z);
2423 return NULL;
2424 })
2425
2426 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002427 *pz++ = (digit)(carry & PyLong_MASK);
2428 carry >>= PyLong_SHIFT;
2429 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002430
2431 /* Now f is added in twice in each column of the
2432 * pyramid it appears. Same as adding f<<1 once.
2433 */
2434 f <<= 1;
2435 while (pa < paend) {
2436 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002437 *pz++ = (digit)(carry & PyLong_MASK);
2438 carry >>= PyLong_SHIFT;
2439 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002440 }
2441 if (carry) {
2442 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002443 *pz++ = (digit)(carry & PyLong_MASK);
2444 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002445 }
2446 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002447 *pz += (digit)(carry & PyLong_MASK);
2448 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002449 }
Tim Peters0973b992004-08-29 22:16:50 +00002450 }
2451 else { /* a is not the same as b -- gradeschool long mult */
2452 for (i = 0; i < size_a; ++i) {
2453 twodigits carry = 0;
2454 twodigits f = a->ob_digit[i];
2455 digit *pz = z->ob_digit + i;
2456 digit *pb = b->ob_digit;
2457 digit *pbend = b->ob_digit + size_b;
2458
2459 SIGCHECK({
2460 Py_DECREF(z);
2461 return NULL;
2462 })
2463
2464 while (pb < pbend) {
2465 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002466 *pz++ = (digit)(carry & PyLong_MASK);
2467 carry >>= PyLong_SHIFT;
2468 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002469 }
2470 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002471 *pz += (digit)(carry & PyLong_MASK);
2472 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002473 }
2474 }
Tim Peters44121a62002-08-12 06:17:58 +00002475 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002476}
2477
2478/* A helper for Karatsuba multiplication (k_mul).
2479 Takes a long "n" and an integer "size" representing the place to
2480 split, and sets low and high such that abs(n) == (high << size) + low,
2481 viewing the shift as being by digits. The sign bit is ignored, and
2482 the return values are >= 0.
2483 Returns 0 on success, -1 on failure.
2484*/
2485static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002486kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002487{
2488 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002489 Py_ssize_t size_lo, size_hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002490 const Py_ssize_t size_n = ABS(Py_Size(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002491
2492 size_lo = MIN(size_n, size);
2493 size_hi = size_n - size_lo;
2494
2495 if ((hi = _PyLong_New(size_hi)) == NULL)
2496 return -1;
2497 if ((lo = _PyLong_New(size_lo)) == NULL) {
2498 Py_DECREF(hi);
2499 return -1;
2500 }
2501
2502 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2503 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2504
2505 *high = long_normalize(hi);
2506 *low = long_normalize(lo);
2507 return 0;
2508}
2509
Tim Peters60004642002-08-12 22:01:34 +00002510static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2511
Tim Peters5af4e6c2002-08-12 02:31:19 +00002512/* Karatsuba multiplication. Ignores the input signs, and returns the
2513 * absolute value of the product (or NULL if error).
2514 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2515 */
2516static PyLongObject *
2517k_mul(PyLongObject *a, PyLongObject *b)
2518{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002519 Py_ssize_t asize = ABS(Py_Size(a));
2520 Py_ssize_t bsize = ABS(Py_Size(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002521 PyLongObject *ah = NULL;
2522 PyLongObject *al = NULL;
2523 PyLongObject *bh = NULL;
2524 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002525 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002526 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002527 Py_ssize_t shift; /* the number of digits we split off */
2528 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002529
Tim Peters5af4e6c2002-08-12 02:31:19 +00002530 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2531 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2532 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002533 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002534 * By picking X to be a power of 2, "*X" is just shifting, and it's
2535 * been reduced to 3 multiplies on numbers half the size.
2536 */
2537
Tim Petersfc07e562002-08-12 02:54:10 +00002538 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002539 * is largest.
2540 */
Tim Peters738eda72002-08-12 15:08:20 +00002541 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002542 t1 = a;
2543 a = b;
2544 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002545
2546 i = asize;
2547 asize = bsize;
2548 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002549 }
2550
2551 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002552 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2553 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002554 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002555 return _PyLong_New(0);
2556 else
2557 return x_mul(a, b);
2558 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002559
Tim Peters60004642002-08-12 22:01:34 +00002560 /* If a is small compared to b, splitting on b gives a degenerate
2561 * case with ah==0, and Karatsuba may be (even much) less efficient
2562 * than "grade school" then. However, we can still win, by viewing
2563 * b as a string of "big digits", each of width a->ob_size. That
2564 * leads to a sequence of balanced calls to k_mul.
2565 */
2566 if (2 * asize <= bsize)
2567 return k_lopsided_mul(a, b);
2568
Tim Petersd6974a52002-08-13 20:37:51 +00002569 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002570 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002571 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002572 assert(Py_Size(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002573
Tim Peters0973b992004-08-29 22:16:50 +00002574 if (a == b) {
2575 bh = ah;
2576 bl = al;
2577 Py_INCREF(bh);
2578 Py_INCREF(bl);
2579 }
2580 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002581
Tim Petersd64c1de2002-08-12 17:36:03 +00002582 /* The plan:
2583 * 1. Allocate result space (asize + bsize digits: that's always
2584 * enough).
2585 * 2. Compute ah*bh, and copy into result at 2*shift.
2586 * 3. Compute al*bl, and copy into result at 0. Note that this
2587 * can't overlap with #2.
2588 * 4. Subtract al*bl from the result, starting at shift. This may
2589 * underflow (borrow out of the high digit), but we don't care:
2590 * we're effectively doing unsigned arithmetic mod
2591 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2592 * borrows and carries out of the high digit can be ignored.
2593 * 5. Subtract ah*bh from the result, starting at shift.
2594 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2595 * at shift.
2596 */
2597
2598 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002599 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002600 if (ret == NULL) goto fail;
2601#ifdef Py_DEBUG
2602 /* Fill with trash, to catch reference to uninitialized digits. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002603 memset(ret->ob_digit, 0xDF, Py_Size(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002604#endif
Tim Peters44121a62002-08-12 06:17:58 +00002605
Tim Petersd64c1de2002-08-12 17:36:03 +00002606 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002607 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002608 assert(Py_Size(t1) >= 0);
2609 assert(2*shift + Py_Size(t1) <= Py_Size(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002610 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002611 Py_Size(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002612
2613 /* Zero-out the digits higher than the ah*bh copy. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002614 i = Py_Size(ret) - 2*shift - Py_Size(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002615 if (i)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002616 memset(ret->ob_digit + 2*shift + Py_Size(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002617 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002618
Tim Petersd64c1de2002-08-12 17:36:03 +00002619 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002620 if ((t2 = k_mul(al, bl)) == NULL) {
2621 Py_DECREF(t1);
2622 goto fail;
2623 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002624 assert(Py_Size(t2) >= 0);
2625 assert(Py_Size(t2) <= 2*shift); /* no overlap with high digits */
2626 memcpy(ret->ob_digit, t2->ob_digit, Py_Size(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002627
2628 /* Zero out remaining digits. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002629 i = 2*shift - Py_Size(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002630 if (i)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002631 memset(ret->ob_digit + Py_Size(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002632
Tim Petersd64c1de2002-08-12 17:36:03 +00002633 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2634 * because it's fresher in cache.
2635 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002636 i = Py_Size(ret) - shift; /* # digits after shift */
2637 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_Size(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002638 Py_DECREF(t2);
2639
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002640 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_Size(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002641 Py_DECREF(t1);
2642
Tim Petersd64c1de2002-08-12 17:36:03 +00002643 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002644 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2645 Py_DECREF(ah);
2646 Py_DECREF(al);
2647 ah = al = NULL;
2648
Tim Peters0973b992004-08-29 22:16:50 +00002649 if (a == b) {
2650 t2 = t1;
2651 Py_INCREF(t2);
2652 }
2653 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002654 Py_DECREF(t1);
2655 goto fail;
2656 }
2657 Py_DECREF(bh);
2658 Py_DECREF(bl);
2659 bh = bl = NULL;
2660
Tim Peters738eda72002-08-12 15:08:20 +00002661 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002662 Py_DECREF(t1);
2663 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002664 if (t3 == NULL) goto fail;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002665 assert(Py_Size(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002666
Tim Petersd6974a52002-08-13 20:37:51 +00002667 /* Add t3. It's not obvious why we can't run out of room here.
2668 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002669 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002670 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_Size(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002671 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002672
Tim Peters5af4e6c2002-08-12 02:31:19 +00002673 return long_normalize(ret);
2674
2675 fail:
2676 Py_XDECREF(ret);
2677 Py_XDECREF(ah);
2678 Py_XDECREF(al);
2679 Py_XDECREF(bh);
2680 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002681 return NULL;
2682}
2683
Tim Petersd6974a52002-08-13 20:37:51 +00002684/* (*) Why adding t3 can't "run out of room" above.
2685
Tim Petersab86c2b2002-08-15 20:06:00 +00002686Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2687to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002688
Tim Petersab86c2b2002-08-15 20:06:00 +000026891. For any integer i, i = c(i/2) + f(i/2). In particular,
2690 bsize = c(bsize/2) + f(bsize/2).
26912. shift = f(bsize/2)
26923. asize <= bsize
26934. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2694 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002695
Tim Petersab86c2b2002-08-15 20:06:00 +00002696We allocated asize + bsize result digits, and add t3 into them at an offset
2697of shift. This leaves asize+bsize-shift allocated digit positions for t3
2698to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2699asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002700
Tim Petersab86c2b2002-08-15 20:06:00 +00002701bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2702at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002703
Tim Petersab86c2b2002-08-15 20:06:00 +00002704If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2705digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2706most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002707
Tim Petersab86c2b2002-08-15 20:06:00 +00002708The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002709
Tim Petersab86c2b2002-08-15 20:06:00 +00002710 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002711
Tim Petersab86c2b2002-08-15 20:06:00 +00002712and we have asize + c(bsize/2) available digit positions. We need to show
2713this is always enough. An instance of c(bsize/2) cancels out in both, so
2714the question reduces to whether asize digits is enough to hold
2715(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2716then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2717asize 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 +00002718digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002719asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002720c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2721is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2722bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002723
Tim Peters48d52c02002-08-14 17:07:32 +00002724Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2725clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2726ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002727*/
2728
Tim Peters60004642002-08-12 22:01:34 +00002729/* b has at least twice the digits of a, and a is big enough that Karatsuba
2730 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2731 * of slices, each with a->ob_size digits, and multiply the slices by a,
2732 * one at a time. This gives k_mul balanced inputs to work with, and is
2733 * also cache-friendly (we compute one double-width slice of the result
2734 * at a time, then move on, never bactracking except for the helpful
2735 * single-width slice overlap between successive partial sums).
2736 */
2737static PyLongObject *
2738k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2739{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002740 const Py_ssize_t asize = ABS(Py_Size(a));
2741 Py_ssize_t bsize = ABS(Py_Size(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002742 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002743 PyLongObject *ret;
2744 PyLongObject *bslice = NULL;
2745
2746 assert(asize > KARATSUBA_CUTOFF);
2747 assert(2 * asize <= bsize);
2748
2749 /* Allocate result space, and zero it out. */
2750 ret = _PyLong_New(asize + bsize);
2751 if (ret == NULL)
2752 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002753 memset(ret->ob_digit, 0, Py_Size(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002754
2755 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002756 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002757 if (bslice == NULL)
2758 goto fail;
2759
2760 nbdone = 0;
2761 while (bsize > 0) {
2762 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002763 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002764
2765 /* Multiply the next slice of b by a. */
2766 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2767 nbtouse * sizeof(digit));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002768 Py_Size(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002769 product = k_mul(a, bslice);
2770 if (product == NULL)
2771 goto fail;
2772
2773 /* Add into result. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002774 (void)v_iadd(ret->ob_digit + nbdone, Py_Size(ret) - nbdone,
2775 product->ob_digit, Py_Size(product));
Tim Peters60004642002-08-12 22:01:34 +00002776 Py_DECREF(product);
2777
2778 bsize -= nbtouse;
2779 nbdone += nbtouse;
2780 }
2781
2782 Py_DECREF(bslice);
2783 return long_normalize(ret);
2784
2785 fail:
2786 Py_DECREF(ret);
2787 Py_XDECREF(bslice);
2788 return NULL;
2789}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002790
2791static PyObject *
2792long_mul(PyLongObject *v, PyLongObject *w)
2793{
2794 PyLongObject *a, *b, *z;
2795
2796 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002797 Py_INCREF(Py_NotImplemented);
2798 return Py_NotImplemented;
2799 }
2800
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002801 if (ABS(Py_Size(v)) <= 1 && ABS(Py_Size(w)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002802 PyObject *r;
2803 r = PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w));
2804 Py_DECREF(a);
2805 Py_DECREF(b);
2806 return r;
2807 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002808
Tim Petersd64c1de2002-08-12 17:36:03 +00002809 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002810 /* Negate if exactly one of the inputs is negative. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002811 if (((Py_Size(a) ^ Py_Size(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002812 NEGATE(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002813 Py_DECREF(a);
2814 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002815 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002816}
2817
Guido van Rossume32e0141992-01-19 16:31:05 +00002818/* The / and % operators are now defined in terms of divmod().
2819 The expression a mod b has the value a - b*floor(a/b).
2820 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002821 |a| by |b|, with the sign of a. This is also expressed
2822 as a - b*trunc(a/b), if trunc truncates towards zero.
2823 Some examples:
2824 a b a rem b a mod b
2825 13 10 3 3
2826 -13 10 -3 7
2827 13 -10 3 -7
2828 -13 -10 -3 -3
2829 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002830 have different signs. We then subtract one from the 'div'
2831 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002832
Tim Peters47e52ee2004-08-30 02:44:38 +00002833/* Compute
2834 * *pdiv, *pmod = divmod(v, w)
2835 * NULL can be passed for pdiv or pmod, in which case that part of
2836 * the result is simply thrown away. The caller owns a reference to
2837 * each of these it requests (does not pass NULL for).
2838 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002839static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002840l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002841 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002842{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002843 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002844
Guido van Rossume32e0141992-01-19 16:31:05 +00002845 if (long_divrem(v, w, &div, &mod) < 0)
2846 return -1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002847 if ((Py_Size(mod) < 0 && Py_Size(w) > 0) ||
2848 (Py_Size(mod) > 0 && Py_Size(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002849 PyLongObject *temp;
2850 PyLongObject *one;
2851 temp = (PyLongObject *) long_add(mod, w);
2852 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002853 mod = temp;
2854 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002855 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002856 return -1;
2857 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002858 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002859 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002860 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2861 Py_DECREF(mod);
2862 Py_DECREF(div);
2863 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002864 return -1;
2865 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002866 Py_DECREF(one);
2867 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002868 div = temp;
2869 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002870 if (pdiv != NULL)
2871 *pdiv = div;
2872 else
2873 Py_DECREF(div);
2874
2875 if (pmod != NULL)
2876 *pmod = mod;
2877 else
2878 Py_DECREF(mod);
2879
Guido van Rossume32e0141992-01-19 16:31:05 +00002880 return 0;
2881}
2882
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002883static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002884long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002885{
Tim Peters47e52ee2004-08-30 02:44:38 +00002886 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002887
2888 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002889 if (l_divmod(a, b, &div, NULL) < 0)
2890 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002891 Py_DECREF(a);
2892 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002893 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002894}
2895
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002896static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002897long_true_divide(PyObject *v, PyObject *w)
2898{
Tim Peterse2a60002001-09-04 06:17:36 +00002899 PyLongObject *a, *b;
2900 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002901 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002902
2903 CONVERT_BINOP(v, w, &a, &b);
2904 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2905 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002906 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2907 Py_DECREF(a);
2908 Py_DECREF(b);
2909 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002910 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002911 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2912 but should really be set correctly after sucessful calls to
2913 _PyLong_AsScaledDouble() */
2914 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002915
2916 if (bd == 0.0) {
2917 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002918 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002919 return NULL;
2920 }
2921
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002922 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002923 ad /= bd; /* overflow/underflow impossible here */
2924 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002925 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002926 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002927 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002928 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002929 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002930 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002931 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002932 goto overflow;
2933 return PyFloat_FromDouble(ad);
2934
2935overflow:
2936 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002937 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002938 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002939
Tim Peters20dab9f2001-09-04 05:31:47 +00002940}
2941
2942static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002943long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002944{
Tim Peters47e52ee2004-08-30 02:44:38 +00002945 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002946
2947 CONVERT_BINOP(v, w, &a, &b);
2948
Tim Peters47e52ee2004-08-30 02:44:38 +00002949 if (l_divmod(a, b, NULL, &mod) < 0)
2950 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002951 Py_DECREF(a);
2952 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002953 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002954}
2955
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002956static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002957long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002958{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002959 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002960 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002961
2962 CONVERT_BINOP(v, w, &a, &b);
2963
2964 if (l_divmod(a, b, &div, &mod) < 0) {
2965 Py_DECREF(a);
2966 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002967 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002968 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002969 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002970 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002971 PyTuple_SetItem(z, 0, (PyObject *) div);
2972 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002973 }
2974 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002975 Py_DECREF(div);
2976 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002977 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002978 Py_DECREF(a);
2979 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002980 return z;
2981}
2982
Tim Peters47e52ee2004-08-30 02:44:38 +00002983/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002984static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002985long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002986{
Tim Peters47e52ee2004-08-30 02:44:38 +00002987 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2988 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002989
Tim Peters47e52ee2004-08-30 02:44:38 +00002990 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002991 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002992 PyLongObject *temp = NULL;
2993
2994 /* 5-ary values. If the exponent is large enough, table is
2995 * precomputed so that table[i] == a**i % c for i in range(32).
2996 */
2997 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2998 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2999
3000 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003001 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003002 if (PyLong_Check(x)) {
3003 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003004 Py_INCREF(x);
3005 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003006 else if (x == Py_None)
3007 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003008 else {
3009 Py_DECREF(a);
3010 Py_DECREF(b);
3011 Py_INCREF(Py_NotImplemented);
3012 return Py_NotImplemented;
3013 }
Tim Peters4c483c42001-09-05 06:24:58 +00003014
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003015 if (Py_Size(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003016 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003017 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003018 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003019 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003020 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003021 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003022 /* else return a float. This works because we know
3023 that this calls float_pow() which converts its
3024 arguments to double. */
3025 Py_DECREF(a);
3026 Py_DECREF(b);
3027 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003028 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003029 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003030
3031 if (c) {
3032 /* if modulus == 0:
3033 raise ValueError() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003034 if (Py_Size(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003035 PyErr_SetString(PyExc_ValueError,
3036 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003037 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003038 }
3039
3040 /* if modulus < 0:
3041 negativeOutput = True
3042 modulus = -modulus */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003043 if (Py_Size(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003044 negativeOutput = 1;
3045 temp = (PyLongObject *)_PyLong_Copy(c);
3046 if (temp == NULL)
3047 goto Error;
3048 Py_DECREF(c);
3049 c = temp;
3050 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003051 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003052 }
3053
3054 /* if modulus == 1:
3055 return 0 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003056 if ((Py_Size(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003057 z = (PyLongObject *)PyLong_FromLong(0L);
3058 goto Done;
3059 }
3060
3061 /* if base < 0:
3062 base = base % modulus
3063 Having the base positive just makes things easier. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003064 if (Py_Size(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003065 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003066 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003067 Py_DECREF(a);
3068 a = temp;
3069 temp = NULL;
3070 }
3071 }
3072
3073 /* At this point a, b, and c are guaranteed non-negative UNLESS
3074 c is NULL, in which case a may be negative. */
3075
3076 z = (PyLongObject *)PyLong_FromLong(1L);
3077 if (z == NULL)
3078 goto Error;
3079
3080 /* Perform a modular reduction, X = X % c, but leave X alone if c
3081 * is NULL.
3082 */
3083#define REDUCE(X) \
3084 if (c != NULL) { \
3085 if (l_divmod(X, c, NULL, &temp) < 0) \
3086 goto Error; \
3087 Py_XDECREF(X); \
3088 X = temp; \
3089 temp = NULL; \
3090 }
3091
3092 /* Multiply two values, then reduce the result:
3093 result = X*Y % c. If c is NULL, skip the mod. */
3094#define MULT(X, Y, result) \
3095{ \
3096 temp = (PyLongObject *)long_mul(X, Y); \
3097 if (temp == NULL) \
3098 goto Error; \
3099 Py_XDECREF(result); \
3100 result = temp; \
3101 temp = NULL; \
3102 REDUCE(result) \
3103}
3104
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003105 if (Py_Size(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003106 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3107 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003108 for (i = Py_Size(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003109 digit bi = b->ob_digit[i];
3110
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003111 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003112 MULT(z, z, z)
3113 if (bi & j)
3114 MULT(z, a, z)
3115 }
3116 }
3117 }
3118 else {
3119 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3120 Py_INCREF(z); /* still holds 1L */
3121 table[0] = z;
3122 for (i = 1; i < 32; ++i)
3123 MULT(table[i-1], a, table[i])
3124
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003125 for (i = Py_Size(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003126 const digit bi = b->ob_digit[i];
3127
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003128 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003129 const int index = (bi >> j) & 0x1f;
3130 for (k = 0; k < 5; ++k)
3131 MULT(z, z, z)
3132 if (index)
3133 MULT(z, table[index], z)
3134 }
3135 }
3136 }
3137
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003138 if (negativeOutput && (Py_Size(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003139 temp = (PyLongObject *)long_sub(z, c);
3140 if (temp == NULL)
3141 goto Error;
3142 Py_DECREF(z);
3143 z = temp;
3144 temp = NULL;
3145 }
3146 goto Done;
3147
3148 Error:
3149 if (z != NULL) {
3150 Py_DECREF(z);
3151 z = NULL;
3152 }
3153 /* fall through */
3154 Done:
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003155 if (Py_Size(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003156 for (i = 0; i < 32; ++i)
3157 Py_XDECREF(table[i]);
3158 }
Tim Petersde7990b2005-07-17 23:45:23 +00003159 Py_DECREF(a);
3160 Py_DECREF(b);
3161 Py_XDECREF(c);
3162 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003163 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003164}
3165
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003166static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003167long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003168{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003169 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003170 PyLongObject *x;
3171 PyLongObject *w;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003172 if (ABS(Py_Size(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003173 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003174 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003175 if (w == NULL)
3176 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003177 x = (PyLongObject *) long_add(v, w);
3178 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003179 if (x == NULL)
3180 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003181 Py_Size(x) = -(Py_Size(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003182 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003183}
3184
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003185static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003186long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003187{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003188 PyLongObject *z;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003189 if (ABS(Py_Size(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003190 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003191 z = (PyLongObject *)_PyLong_Copy(v);
3192 if (z != NULL)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003193 Py_Size(z) = -(Py_Size(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003194 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003195}
3196
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003197static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003198long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003199{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003200 if (Py_Size(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003201 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003202 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003203 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003204}
3205
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003206static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003207long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003208{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003209 return ABS(Py_Size(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003210}
3211
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003212static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003213long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003214{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003215 PyLongObject *a, *b;
3216 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003217 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003218 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003219 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003220
Neil Schemenauerba872e22001-01-04 01:46:03 +00003221 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3222
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003223 if (Py_Size(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003224 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003225 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003226 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003227 if (a1 == NULL)
3228 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003229 a2 = (PyLongObject *) long_rshift(a1, b);
3230 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003231 if (a2 == NULL)
3232 goto rshift_error;
3233 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003234 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003235 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003236 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003237
Neil Schemenauerba872e22001-01-04 01:46:03 +00003238 shiftby = PyLong_AsLong((PyObject *)b);
3239 if (shiftby == -1L && PyErr_Occurred())
3240 goto rshift_error;
3241 if (shiftby < 0) {
3242 PyErr_SetString(PyExc_ValueError,
3243 "negative shift count");
3244 goto rshift_error;
3245 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003246 wordshift = shiftby / PyLong_SHIFT;
3247 newsize = ABS(Py_Size(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003248 if (newsize <= 0) {
3249 z = _PyLong_New(0);
3250 Py_DECREF(a);
3251 Py_DECREF(b);
3252 return (PyObject *)z;
3253 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003254 loshift = shiftby % PyLong_SHIFT;
3255 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003256 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003257 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003258 z = _PyLong_New(newsize);
3259 if (z == NULL)
3260 goto rshift_error;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003261 if (Py_Size(a) < 0)
3262 Py_Size(z) = -(Py_Size(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003263 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3264 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3265 if (i+1 < newsize)
3266 z->ob_digit[i] |=
3267 (a->ob_digit[j+1] << hishift) & himask;
3268 }
3269 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003270 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003271rshift_error:
3272 Py_DECREF(a);
3273 Py_DECREF(b);
3274 return (PyObject *) z;
3275
Guido van Rossumc6913e71991-11-19 20:26:46 +00003276}
3277
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003278static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003279long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003280{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003281 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003282 PyLongObject *a, *b;
3283 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003284 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003285 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003286 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003287
Neil Schemenauerba872e22001-01-04 01:46:03 +00003288 CONVERT_BINOP(v, w, &a, &b);
3289
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003290 shiftby = PyLong_AsLong((PyObject *)b);
3291 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003292 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003293 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003294 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003295 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003296 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003297 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003298 PyErr_SetString(PyExc_ValueError,
3299 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003300 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003301 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003302 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3303 wordshift = (int)shiftby / PyLong_SHIFT;
3304 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003305
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003306 oldsize = ABS(Py_Size(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003307 newsize = oldsize + wordshift;
3308 if (remshift)
3309 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003310 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003311 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003312 goto lshift_error;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003313 if (Py_Size(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003314 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003315 for (i = 0; i < wordshift; i++)
3316 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003317 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003318 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003319 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003320 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3321 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003322 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003323 if (remshift)
3324 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003325 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003326 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003327 z = long_normalize(z);
3328lshift_error:
3329 Py_DECREF(a);
3330 Py_DECREF(b);
3331 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003332}
3333
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003334
3335/* Bitwise and/xor/or operations */
3336
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003337static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003338long_bitwise(PyLongObject *a,
3339 int op, /* '&', '|', '^' */
3340 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003341{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003342 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003343 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003344 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003345 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003346 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003347 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003348 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003349
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003350 if (Py_Size(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003351 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003352 if (a == NULL)
3353 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003354 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003355 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003356 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003357 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003358 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003359 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003360 if (Py_Size(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003361 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003362 if (b == NULL) {
3363 Py_DECREF(a);
3364 return NULL;
3365 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003366 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003367 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003368 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003369 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003370 maskb = 0;
3371 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003372
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003373 negz = 0;
3374 switch (op) {
3375 case '^':
3376 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003377 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003378 negz = -1;
3379 }
3380 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003381 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003382 if (maska && maskb) {
3383 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003384 maska ^= PyLong_MASK;
3385 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003386 negz = -1;
3387 }
3388 break;
3389 case '|':
3390 if (maska || maskb) {
3391 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003392 maska ^= PyLong_MASK;
3393 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003394 negz = -1;
3395 }
3396 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003397 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003398
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003399 /* JRH: The original logic here was to allocate the result value (z)
3400 as the longer of the two operands. However, there are some cases
3401 where the result is guaranteed to be shorter than that: AND of two
3402 positives, OR of two negatives: use the shorter number. AND with
3403 mixed signs: use the positive number. OR with mixed signs: use the
3404 negative number. After the transformations above, op will be '&'
3405 iff one of these cases applies, and mask will be non-0 for operands
3406 whose length should be ignored.
3407 */
3408
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003409 size_a = Py_Size(a);
3410 size_b = Py_Size(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003411 size_z = op == '&'
3412 ? (maska
3413 ? size_b
3414 : (maskb ? size_a : MIN(size_a, size_b)))
3415 : MAX(size_a, size_b);
3416 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003417 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003418 Py_DECREF(a);
3419 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003420 return NULL;
3421 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003422
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003423 for (i = 0; i < size_z; ++i) {
3424 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3425 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3426 switch (op) {
3427 case '&': z->ob_digit[i] = diga & digb; break;
3428 case '|': z->ob_digit[i] = diga | digb; break;
3429 case '^': z->ob_digit[i] = diga ^ digb; break;
3430 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003431 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003432
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003433 Py_DECREF(a);
3434 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003435 z = long_normalize(z);
3436 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003437 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003438 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003439 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003440 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003441}
3442
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003443static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003444long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003445{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003446 PyLongObject *a, *b;
3447 PyObject *c;
3448 CONVERT_BINOP(v, w, &a, &b);
3449 c = long_bitwise(a, '&', b);
3450 Py_DECREF(a);
3451 Py_DECREF(b);
3452 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003453}
3454
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003455static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003456long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003457{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003458 PyLongObject *a, *b;
3459 PyObject *c;
3460 CONVERT_BINOP(v, w, &a, &b);
3461 c = long_bitwise(a, '^', b);
3462 Py_DECREF(a);
3463 Py_DECREF(b);
3464 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003465}
3466
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003467static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003468long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003469{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003470 PyLongObject *a, *b;
3471 PyObject *c;
3472 CONVERT_BINOP(v, w, &a, &b);
3473 c = long_bitwise(a, '|', b);
3474 Py_DECREF(a);
3475 Py_DECREF(b);
3476 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003477}
3478
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003479static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003480long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003481{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003482 if (PyLong_CheckExact(v))
3483 Py_INCREF(v);
3484 else
3485 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003486 return v;
3487}
3488
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003489static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003490long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003491{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003492 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003493 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003494 if (result == -1.0 && PyErr_Occurred())
3495 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003496 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003497}
3498
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003499static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003500long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003501
Tim Peters6d6c1a32001-08-02 04:15:00 +00003502static PyObject *
3503long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3504{
3505 PyObject *x = NULL;
3506 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003507 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003508
Guido van Rossumbef14172001-08-29 15:47:46 +00003509 if (type != &PyLong_Type)
3510 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003511 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003512 &x, &base))
3513 return NULL;
3514 if (x == NULL)
3515 return PyLong_FromLong(0L);
3516 if (base == -909)
3517 return PyNumber_Long(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003518 else if (PyString_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003519 /* Since PyLong_FromString doesn't have a length parameter,
3520 * check here for possible NULs in the string. */
Guido van Rossum4581ae52007-05-22 21:56:47 +00003521 char *string;
3522 int size;
3523 if (PyBytes_Check(x)) {
3524 string = PyBytes_AS_STRING(x);
3525 size = PyBytes_GET_SIZE(x);
3526 }
3527 else {
3528 string = PyString_AS_STRING(x);
3529 size = PyString_GET_SIZE(x);
3530 }
3531 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003532 /* We only see this if there's a null byte in x,
3533 x is a str8 or a bytes, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003534 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003535 "invalid literal for int() with base %d: %R",
3536 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003537 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003538 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003539 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003540 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003541 else if (PyUnicode_Check(x))
3542 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3543 PyUnicode_GET_SIZE(x),
3544 base);
3545 else {
3546 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003547 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003548 return NULL;
3549 }
3550}
3551
Guido van Rossumbef14172001-08-29 15:47:46 +00003552/* Wimpy, slow approach to tp_new calls for subtypes of long:
3553 first create a regular long from whatever arguments we got,
3554 then allocate a subtype instance and initialize it from
3555 the regular long. The regular long is then thrown away.
3556*/
3557static PyObject *
3558long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3559{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003560 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003561 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003562
3563 assert(PyType_IsSubtype(type, &PyLong_Type));
3564 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3565 if (tmp == NULL)
3566 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003567 assert(PyLong_CheckExact(tmp));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003568 n = Py_Size(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003569 if (n < 0)
3570 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003571 newobj = (PyLongObject *)type->tp_alloc(type, n);
3572 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003573 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003574 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003575 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003576 assert(PyLong_Check(newobj));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003577 Py_Size(newobj) = Py_Size(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003578 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003579 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003580 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003581 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003582}
3583
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003584static PyObject *
3585long_getnewargs(PyLongObject *v)
3586{
3587 return Py_BuildValue("(N)", _PyLong_Copy(v));
3588}
3589
Guido van Rossumb43daf72007-08-01 18:08:08 +00003590static PyObject *
3591long_getN(PyLongObject *v, void *context) {
3592 return PyLong_FromLong((intptr_t)context);
3593}
3594
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003595static PyObject *
3596long_round(PyObject *self, PyObject *args)
3597{
3598#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
3599 int ndigits = UNDEF_NDIGITS;
3600 double x;
3601 PyObject *res;
3602
3603 if (!PyArg_ParseTuple(args, "|i", &ndigits))
3604 return NULL;
3605
3606 if (ndigits == UNDEF_NDIGITS)
3607 return long_long(self);
3608
3609 /* If called with two args, defer to float.__round__(). */
3610 x = PyLong_AsDouble(self);
3611 if (x == -1.0 && PyErr_Occurred())
3612 return NULL;
3613 self = PyFloat_FromDouble(x);
3614 if (self == NULL)
3615 return NULL;
3616 res = PyObject_CallMethod(self, "__round__", "i", ndigits);
3617 Py_DECREF(self);
3618 return res;
3619#undef UNDEF_NDIGITS
3620}
3621
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003622static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003623 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3624 "Returns self, the complex conjugate of any int."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003625 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3626 "Truncating an Integral returns itself."},
3627 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3628 "Flooring an Integral returns itself."},
3629 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3630 "Ceiling of an Integral returns itself."},
3631 {"__round__", (PyCFunction)long_round, METH_VARARGS,
3632 "Rounding an Integral returns itself.\n"
3633 "Rounding with an ndigits arguments defers to float.__round__."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003634 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3635 {NULL, NULL} /* sentinel */
3636};
3637
Guido van Rossumb43daf72007-08-01 18:08:08 +00003638static PyGetSetDef long_getset[] = {
3639 {"real",
3640 (getter)long_long, (setter)NULL,
3641 "the real part of a complex number",
3642 NULL},
3643 {"imag",
3644 (getter)long_getN, (setter)NULL,
3645 "the imaginary part of a complex number",
3646 (void*)0},
3647 {"numerator",
3648 (getter)long_long, (setter)NULL,
3649 "the numerator of a rational number in lowest terms",
3650 NULL},
3651 {"denominator",
3652 (getter)long_getN, (setter)NULL,
3653 "the denominator of a rational number in lowest terms",
3654 (void*)1},
3655 {NULL} /* Sentinel */
3656};
3657
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003658PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003659"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003660\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003661Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003662point argument will be truncated towards zero (this does not include a\n\
3663string representation of a floating point number!) When converting a\n\
3664string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003665converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003666
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003667static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003668 (binaryfunc) long_add, /*nb_add*/
3669 (binaryfunc) long_sub, /*nb_subtract*/
3670 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003671 long_mod, /*nb_remainder*/
3672 long_divmod, /*nb_divmod*/
3673 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003674 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003675 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003676 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003677 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003678 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003679 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003680 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003681 long_and, /*nb_and*/
3682 long_xor, /*nb_xor*/
3683 long_or, /*nb_or*/
Neal Norwitzca810462006-08-29 07:57:59 +00003684 0, /*nb_coerce*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003685 long_long, /*nb_int*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003686 long_long, /*nb_long*/
3687 long_float, /*nb_float*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003688 0, /*nb_oct*/ /* not used */
3689 0, /*nb_hex*/ /* not used */
Guido van Rossum4668b002001-08-08 05:00:18 +00003690 0, /* nb_inplace_add */
3691 0, /* nb_inplace_subtract */
3692 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003693 0, /* nb_inplace_remainder */
3694 0, /* nb_inplace_power */
3695 0, /* nb_inplace_lshift */
3696 0, /* nb_inplace_rshift */
3697 0, /* nb_inplace_and */
3698 0, /* nb_inplace_xor */
3699 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003700 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003701 long_true_divide, /* nb_true_divide */
3702 0, /* nb_inplace_floor_divide */
3703 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003704 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003705};
3706
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003707PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003708 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003709 "int", /* tp_name */
3710 /* See _PyLong_New for why this isn't
3711 sizeof(PyLongObject) - sizeof(digit) */
3712 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003713 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003714 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003715 0, /* tp_print */
3716 0, /* tp_getattr */
3717 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003718 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003719 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003720 &long_as_number, /* tp_as_number */
3721 0, /* tp_as_sequence */
3722 0, /* tp_as_mapping */
3723 (hashfunc)long_hash, /* tp_hash */
3724 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003725 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726 PyObject_GenericGetAttr, /* tp_getattro */
3727 0, /* tp_setattro */
3728 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003729 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3730 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003731 long_doc, /* tp_doc */
3732 0, /* tp_traverse */
3733 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003734 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003735 0, /* tp_weaklistoffset */
3736 0, /* tp_iter */
3737 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003738 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003739 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003740 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003741 0, /* tp_base */
3742 0, /* tp_dict */
3743 0, /* tp_descr_get */
3744 0, /* tp_descr_set */
3745 0, /* tp_dictoffset */
3746 0, /* tp_init */
3747 0, /* tp_alloc */
3748 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003749 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003750};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003751
3752int
3753_PyLong_Init(void)
3754{
3755#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3756 int ival;
3757 PyLongObject *v = small_ints;
3758 for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
3759 PyObject_INIT(v, &PyLong_Type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003760 Py_Size(v) = -1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003761 v->ob_digit[0] = -ival;
3762 }
3763 for (; ival < NSMALLPOSINTS; ival++, v++) {
3764 PyObject_INIT(v, &PyLong_Type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003765 Py_Size(v) = ival ? 1 : 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003766 v->ob_digit[0] = ival;
3767 }
3768#endif
3769 return 1;
3770}
3771
3772void
3773PyLong_Fini(void)
3774{
3775#if 0
3776 int i;
3777 /* This is currently not needed; the small integers
3778 are statically allocated */
3779#if NSMALLNEGINTS + NSMALLPOSINTS > 0
3780 PyIntObject **q;
3781
3782 i = NSMALLNEGINTS + NSMALLPOSINTS;
3783 q = small_ints;
3784 while (--i >= 0) {
3785 Py_XDECREF(*q);
3786 *q++ = NULL;
3787 }
3788#endif
3789#endif
3790}