blob: 0578b0e9af3a947e17618fdb8826474fb58571d1 [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"
Mark Dickinsonefc82f72009-03-20 15:51:55 +00007#include "structseq.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008
Mark Dickinson6736cf82009-04-20 21:13:33 +00009#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000011#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000012
Tim Peters5af4e6c2002-08-12 02:31:19 +000013/* For long multiplication, use the O(N**2) school algorithm unless
14 * both operands contain more than KARATSUBA_CUTOFF digits (this
Christian Heimes7f39c9f2008-01-25 12:18:43 +000015 * being an internal Python long digit, in base PyLong_BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000016 */
Tim Peters0973b992004-08-29 22:16:50 +000017#define KARATSUBA_CUTOFF 70
18#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000019
Tim Peters47e52ee2004-08-30 02:44:38 +000020/* For exponentiation, use the binary left-to-right algorithm
21 * unless the exponent contains more than FIVEARY_CUTOFF digits.
22 * In that case, do 5 bits at a time. The potential drawback is that
23 * a table of 2**5 intermediate results is computed.
24 */
25#define FIVEARY_CUTOFF 8
26
Guido van Rossume32e0141992-01-19 16:31:05 +000027#define ABS(x) ((x) < 0 ? -(x) : (x))
28
Tim Peters5af4e6c2002-08-12 02:31:19 +000029#undef MIN
30#undef MAX
31#define MAX(x, y) ((x) < (y) ? (y) : (x))
32#define MIN(x, y) ((x) > (y) ? (y) : (x))
33
Guido van Rossumc0b618a1997-05-02 03:12:38 +000034#define SIGCHECK(PyTryBlock) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000035 if (--_Py_Ticker < 0) { \
36 _Py_Ticker = _Py_CheckInterval; \
37 if (PyErr_CheckSignals()) PyTryBlock \
38 }
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000039
Guido van Rossumedcc38a1991-05-05 20:09:44 +000040/* Normalize (remove leading zeros from) a long int object.
41 Doesn't attempt to free the storage--in most cases, due to the nature
42 of the algorithms used, this could save at most be one word anyway. */
43
Guido van Rossumc0b618a1997-05-02 03:12:38 +000044static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000045long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000046{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000047 Py_ssize_t j = ABS(Py_SIZE(v));
48 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +000049
Antoine Pitrouc83ea132010-05-09 14:46:46 +000050 while (i > 0 && v->ob_digit[i-1] == 0)
51 --i;
52 if (i != j)
53 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
54 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +000055}
56
57/* Allocate a new long int object with size digits.
58 Return NULL and set exception if we run out of memory. */
59
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000060#define MAX_LONG_DIGITS \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000061 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000062
Guido van Rossumc0b618a1997-05-02 03:12:38 +000063PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000064_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000065{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000066 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
67 PyErr_SetString(PyExc_OverflowError,
68 "too many digits in integer");
69 return NULL;
70 }
71 /* coverity[ampersand_in_size] */
72 /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect
73 overflow */
74 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000075}
76
Tim Peters64b5ce32001-09-10 20:52:51 +000077PyObject *
78_PyLong_Copy(PyLongObject *src)
79{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000080 PyLongObject *result;
81 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000082
Antoine Pitrouc83ea132010-05-09 14:46:46 +000083 assert(src != NULL);
84 i = src->ob_size;
85 if (i < 0)
86 i = -(i);
87 result = _PyLong_New(i);
88 if (result != NULL) {
89 result->ob_size = src->ob_size;
90 while (--i >= 0)
91 result->ob_digit[i] = src->ob_digit[i];
92 }
93 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +000094}
95
Guido van Rossumedcc38a1991-05-05 20:09:44 +000096/* Create a new long int object from a C long int */
97
Guido van Rossumc0b618a1997-05-02 03:12:38 +000098PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000099PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000100{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000101 PyLongObject *v;
102 unsigned long abs_ival;
103 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
104 int ndigits = 0;
105 int negative = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000106
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000107 if (ival < 0) {
108 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
109 ANSI C says that the result of -ival is undefined when ival
110 == LONG_MIN. Hence the following workaround. */
111 abs_ival = (unsigned long)(-1-ival) + 1;
112 negative = 1;
113 }
114 else {
115 abs_ival = (unsigned long)ival;
116 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000117
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000118 /* Count the number of Python digits.
119 We used to pick 5 ("big enough for anything"), but that's a
120 waste of time and space given that 5*15 = 75 bits are rarely
121 needed. */
122 t = abs_ival;
123 while (t) {
124 ++ndigits;
125 t >>= PyLong_SHIFT;
126 }
127 v = _PyLong_New(ndigits);
128 if (v != NULL) {
129 digit *p = v->ob_digit;
130 v->ob_size = negative ? -ndigits : ndigits;
131 t = abs_ival;
132 while (t) {
133 *p++ = (digit)(t & PyLong_MASK);
134 t >>= PyLong_SHIFT;
135 }
136 }
137 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000138}
139
Guido van Rossum53756b11997-01-03 17:14:46 +0000140/* Create a new long int object from a C unsigned long int */
141
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000143PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000144{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000145 PyLongObject *v;
146 unsigned long t;
147 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000148
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000149 /* Count the number of Python digits. */
150 t = (unsigned long)ival;
151 while (t) {
152 ++ndigits;
153 t >>= PyLong_SHIFT;
154 }
155 v = _PyLong_New(ndigits);
156 if (v != NULL) {
157 digit *p = v->ob_digit;
158 Py_SIZE(v) = ndigits;
159 while (ival) {
160 *p++ = (digit)(ival & PyLong_MASK);
161 ival >>= PyLong_SHIFT;
162 }
163 }
164 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000165}
166
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000167/* Create a new long int object from a C double */
168
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000169PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000171{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000172 PyLongObject *v;
173 double frac;
174 int i, ndig, expo, neg;
175 neg = 0;
176 if (Py_IS_INFINITY(dval)) {
177 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000178 "cannot convert float infinity to integer");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000179 return NULL;
180 }
181 if (Py_IS_NAN(dval)) {
182 PyErr_SetString(PyExc_ValueError,
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000183 "cannot convert float NaN to integer");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000184 return NULL;
185 }
186 if (dval < 0.0) {
187 neg = 1;
188 dval = -dval;
189 }
190 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
191 if (expo <= 0)
192 return PyLong_FromLong(0L);
193 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
194 v = _PyLong_New(ndig);
195 if (v == NULL)
196 return NULL;
197 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
198 for (i = ndig; --i >= 0; ) {
199 digit bits = (digit)frac;
200 v->ob_digit[i] = bits;
201 frac = frac - (double)bits;
202 frac = ldexp(frac, PyLong_SHIFT);
203 }
204 if (neg)
205 Py_SIZE(v) = -(Py_SIZE(v));
206 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000207}
208
Armin Rigo7ccbca92006-10-04 12:17:45 +0000209/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
210 * anything about what happens when a signed integer operation overflows,
211 * and some compilers think they're doing you a favor by being "clever"
212 * then. The bit pattern for the largest postive signed long is
213 * (unsigned long)LONG_MAX, and for the smallest negative signed long
214 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
215 * However, some other compilers warn about applying unary minus to an
216 * unsigned operand. Hence the weird "0-".
217 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000218#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
219#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Armin Rigo7ccbca92006-10-04 12:17:45 +0000220
Mark Dickinsone31d3002009-12-21 11:21:25 +0000221/* Get a C long int from a Python long or Python int object.
222 On overflow, returns -1 and sets *overflow to 1 or -1 depending
223 on the sign of the result. Otherwise *overflow is 0.
224
225 For other errors (e.g., type error), returns -1 and sets an error
226 condition.
227*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000228
229long
Mark Dickinsone31d3002009-12-21 11:21:25 +0000230PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000231{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000232 /* This version by Tim Peters */
233 register PyLongObject *v;
234 unsigned long x, prev;
235 long res;
236 Py_ssize_t i;
237 int sign;
238 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000239
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000240 *overflow = 0;
241 if (vv == NULL) {
242 PyErr_BadInternalCall();
243 return -1;
244 }
Guido van Rossumf7531811998-05-26 14:33:37 +0000245
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000246 if(PyInt_Check(vv))
247 return PyInt_AsLong(vv);
Mark Dickinsone31d3002009-12-21 11:21:25 +0000248
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000249 if (!PyLong_Check(vv)) {
250 PyNumberMethods *nb;
251 nb = vv->ob_type->tp_as_number;
252 if (nb == NULL || nb->nb_int == NULL) {
253 PyErr_SetString(PyExc_TypeError,
254 "an integer is required");
255 return -1;
256 }
257 vv = (*nb->nb_int) (vv);
258 if (vv == NULL)
259 return -1;
260 do_decref = 1;
261 if(PyInt_Check(vv)) {
262 res = PyInt_AsLong(vv);
263 goto exit;
264 }
265 if (!PyLong_Check(vv)) {
266 Py_DECREF(vv);
267 PyErr_SetString(PyExc_TypeError,
268 "nb_int should return int object");
269 return -1;
270 }
271 }
Mark Dickinsone31d3002009-12-21 11:21:25 +0000272
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000273 res = -1;
274 v = (PyLongObject *)vv;
275 i = Py_SIZE(v);
Mark Dickinsone31d3002009-12-21 11:21:25 +0000276
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000277 switch (i) {
278 case -1:
279 res = -(sdigit)v->ob_digit[0];
280 break;
281 case 0:
282 res = 0;
283 break;
284 case 1:
285 res = v->ob_digit[0];
286 break;
287 default:
288 sign = 1;
289 x = 0;
290 if (i < 0) {
291 sign = -1;
292 i = -(i);
293 }
294 while (--i >= 0) {
295 prev = x;
296 x = (x << PyLong_SHIFT) + v->ob_digit[i];
297 if ((x >> PyLong_SHIFT) != prev) {
298 *overflow = sign;
299 goto exit;
300 }
301 }
302 /* Haven't lost any bits, but casting to long requires extra
303 * care (see comment above).
304 */
305 if (x <= (unsigned long)LONG_MAX) {
306 res = (long)x * sign;
307 }
308 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
309 res = LONG_MIN;
310 }
311 else {
312 *overflow = sign;
313 /* res is already set to -1 */
314 }
315 }
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000316 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000317 if (do_decref) {
318 Py_DECREF(vv);
319 }
320 return res;
Mark Dickinsone31d3002009-12-21 11:21:25 +0000321}
322
323/* Get a C long int from a long int object.
324 Returns -1 and sets an error condition if overflow occurs. */
325
326long
327PyLong_AsLong(PyObject *obj)
328{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000329 int overflow;
330 long result = PyLong_AsLongAndOverflow(obj, &overflow);
331 if (overflow) {
332 /* XXX: could be cute and give a different
333 message for overflow == -1 */
334 PyErr_SetString(PyExc_OverflowError,
335 "Python int too large to convert to C long");
336 }
337 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000338}
339
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000340/* Get a Py_ssize_t from a long int object.
341 Returns -1 and sets an error condition if overflow occurs. */
342
343Py_ssize_t
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000344PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000345 register PyLongObject *v;
346 size_t x, prev;
347 Py_ssize_t i;
348 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000349
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000350 if (vv == NULL || !PyLong_Check(vv)) {
351 PyErr_BadInternalCall();
352 return -1;
353 }
354 v = (PyLongObject *)vv;
355 i = v->ob_size;
356 sign = 1;
357 x = 0;
358 if (i < 0) {
359 sign = -1;
360 i = -(i);
361 }
362 while (--i >= 0) {
363 prev = x;
364 x = (x << PyLong_SHIFT) | v->ob_digit[i];
365 if ((x >> PyLong_SHIFT) != prev)
366 goto overflow;
367 }
368 /* Haven't lost any bits, but casting to a signed type requires
369 * extra care (see comment above).
370 */
371 if (x <= (size_t)PY_SSIZE_T_MAX) {
372 return (Py_ssize_t)x * sign;
373 }
374 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
375 return PY_SSIZE_T_MIN;
376 }
377 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000378
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000379 overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000380 PyErr_SetString(PyExc_OverflowError,
381 "long int too large to convert to int");
382 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000383}
384
Guido van Rossumd8c80482002-08-13 00:24:58 +0000385/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000386 Returns -1 and sets an error condition if overflow occurs. */
387
388unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000389PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000390{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000391 register PyLongObject *v;
392 unsigned long x, prev;
393 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000394
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000395 if (vv == NULL || !PyLong_Check(vv)) {
396 if (vv != NULL && PyInt_Check(vv)) {
397 long val = PyInt_AsLong(vv);
398 if (val < 0) {
399 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000400 "can't convert negative value "
401 "to unsigned long");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000402 return (unsigned long) -1;
403 }
404 return val;
405 }
406 PyErr_BadInternalCall();
407 return (unsigned long) -1;
408 }
409 v = (PyLongObject *)vv;
410 i = Py_SIZE(v);
411 x = 0;
412 if (i < 0) {
413 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000414 "can't convert negative value to unsigned long");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000415 return (unsigned long) -1;
416 }
417 while (--i >= 0) {
418 prev = x;
419 x = (x << PyLong_SHIFT) | v->ob_digit[i];
420 if ((x >> PyLong_SHIFT) != prev) {
421 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000422 "long int too large to convert");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000423 return (unsigned long) -1;
424 }
425 }
426 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000427}
428
Thomas Hellera4ea6032003-04-17 18:55:45 +0000429/* Get a C unsigned long int from a long int object, ignoring the high bits.
430 Returns -1 and sets an error condition if an error occurs. */
431
432unsigned long
433PyLong_AsUnsignedLongMask(PyObject *vv)
434{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000435 register PyLongObject *v;
436 unsigned long x;
437 Py_ssize_t i;
438 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000439
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000440 if (vv == NULL || !PyLong_Check(vv)) {
441 if (vv != NULL && PyInt_Check(vv))
442 return PyInt_AsUnsignedLongMask(vv);
443 PyErr_BadInternalCall();
444 return (unsigned long) -1;
445 }
446 v = (PyLongObject *)vv;
447 i = v->ob_size;
448 sign = 1;
449 x = 0;
450 if (i < 0) {
451 sign = -1;
452 i = -i;
453 }
454 while (--i >= 0) {
455 x = (x << PyLong_SHIFT) | v->ob_digit[i];
456 }
457 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000458}
459
Tim Peters5b8132f2003-01-31 15:52:05 +0000460int
461_PyLong_Sign(PyObject *vv)
462{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000463 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000464
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000465 assert(v != NULL);
466 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000467
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000468 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000469}
470
Tim Petersbaefd9e2003-01-28 20:37:45 +0000471size_t
472_PyLong_NumBits(PyObject *vv)
473{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000474 PyLongObject *v = (PyLongObject *)vv;
475 size_t result = 0;
476 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000477
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000478 assert(v != NULL);
479 assert(PyLong_Check(v));
480 ndigits = ABS(Py_SIZE(v));
481 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
482 if (ndigits > 0) {
483 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000484
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000485 result = (ndigits - 1) * PyLong_SHIFT;
486 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
487 goto Overflow;
488 do {
489 ++result;
490 if (result == 0)
491 goto Overflow;
492 msd >>= 1;
493 } while (msd);
494 }
495 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000496
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000497 Overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000498 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
499 "to express in a platform size_t");
500 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000501}
502
Tim Peters2a9b3672001-06-11 21:23:58 +0000503PyObject *
504_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000505 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000506{
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000507 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000508 int incr; /* direction to move pstartbyte */
509 const unsigned char* pendbyte; /* MSB of bytes */
510 size_t numsignificantbytes; /* number of bytes that matter */
511 Py_ssize_t ndigits; /* number of Python long digits */
512 PyLongObject* v; /* result */
513 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000514
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000515 if (n == 0)
516 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000517
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000518 if (little_endian) {
519 pstartbyte = bytes;
520 pendbyte = bytes + n - 1;
521 incr = 1;
522 }
523 else {
524 pstartbyte = bytes + n - 1;
525 pendbyte = bytes;
526 incr = -1;
527 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000528
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000529 if (is_signed)
530 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000531
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000532 /* Compute numsignificantbytes. This consists of finding the most
533 significant byte. Leading 0 bytes are insignficant if the number
534 is positive, and leading 0xff bytes if negative. */
535 {
536 size_t i;
537 const unsigned char* p = pendbyte;
538 const int pincr = -incr; /* search MSB to LSB */
539 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000540
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000541 for (i = 0; i < n; ++i, p += pincr) {
542 if (*p != insignficant)
543 break;
544 }
545 numsignificantbytes = n - i;
546 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
547 actually has 2 significant bytes. OTOH, 0xff0001 ==
548 -0x00ffff, so we wouldn't *need* to bump it there; but we
549 do for 0xffff = -0x0001. To be safe without bothering to
550 check every case, bump it regardless. */
551 if (is_signed && numsignificantbytes < n)
552 ++numsignificantbytes;
553 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000554
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000555 /* How many Python long digits do we need? We have
556 8*numsignificantbytes bits, and each Python long digit has
557 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
558 /* catch overflow before it happens */
559 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
560 PyErr_SetString(PyExc_OverflowError,
561 "byte array too long to convert to int");
562 return NULL;
563 }
564 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
565 v = _PyLong_New(ndigits);
566 if (v == NULL)
567 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000568
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000569 /* Copy the bits over. The tricky parts are computing 2's-comp on
570 the fly for signed numbers, and dealing with the mismatch between
571 8-bit bytes and (probably) 15-bit Python digits.*/
572 {
573 size_t i;
574 twodigits carry = 1; /* for 2's-comp calculation */
575 twodigits accum = 0; /* sliding register */
576 unsigned int accumbits = 0; /* number of bits in accum */
577 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000578
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000579 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
580 twodigits thisbyte = *p;
581 /* Compute correction for 2's comp, if needed. */
582 if (is_signed) {
583 thisbyte = (0xff ^ thisbyte) + carry;
584 carry = thisbyte >> 8;
585 thisbyte &= 0xff;
586 }
587 /* Because we're going LSB to MSB, thisbyte is
588 more significant than what's already in accum,
589 so needs to be prepended to accum. */
590 accum |= (twodigits)thisbyte << accumbits;
591 accumbits += 8;
592 if (accumbits >= PyLong_SHIFT) {
593 /* There's enough to fill a Python digit. */
594 assert(idigit < ndigits);
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000595 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000596 ++idigit;
597 accum >>= PyLong_SHIFT;
598 accumbits -= PyLong_SHIFT;
599 assert(accumbits < PyLong_SHIFT);
600 }
601 }
602 assert(accumbits < PyLong_SHIFT);
603 if (accumbits) {
604 assert(idigit < ndigits);
605 v->ob_digit[idigit] = (digit)accum;
606 ++idigit;
607 }
608 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000609
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000610 Py_SIZE(v) = is_signed ? -idigit : idigit;
611 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000612}
613
614int
615_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000616 unsigned char* bytes, size_t n,
617 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000618{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000619 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000620 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000621 twodigits accum; /* sliding register */
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000622 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000623 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
624 digit carry; /* for computing 2's-comp */
625 size_t j; /* # bytes filled */
626 unsigned char* p; /* pointer to next byte in bytes */
627 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000628
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000629 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000630
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000631 if (Py_SIZE(v) < 0) {
632 ndigits = -(Py_SIZE(v));
633 if (!is_signed) {
634 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000635 "can't convert negative long to unsigned");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000636 return -1;
637 }
638 do_twos_comp = 1;
639 }
640 else {
641 ndigits = Py_SIZE(v);
642 do_twos_comp = 0;
643 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000644
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000645 if (little_endian) {
646 p = bytes;
647 pincr = 1;
648 }
649 else {
650 p = bytes + n - 1;
651 pincr = -1;
652 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000653
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000654 /* Copy over all the Python digits.
655 It's crucial that every Python digit except for the MSD contribute
656 exactly PyLong_SHIFT bits to the total, so first assert that the long is
657 normalized. */
658 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
659 j = 0;
660 accum = 0;
661 accumbits = 0;
662 carry = do_twos_comp ? 1 : 0;
663 for (i = 0; i < ndigits; ++i) {
664 digit thisdigit = v->ob_digit[i];
665 if (do_twos_comp) {
666 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
667 carry = thisdigit >> PyLong_SHIFT;
668 thisdigit &= PyLong_MASK;
669 }
670 /* Because we're going LSB to MSB, thisdigit is more
671 significant than what's already in accum, so needs to be
672 prepended to accum. */
673 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000674
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000675 /* The most-significant digit may be (probably is) at least
676 partly empty. */
677 if (i == ndigits - 1) {
678 /* Count # of sign bits -- they needn't be stored,
679 * although for signed conversion we need later to
680 * make sure at least one sign bit gets stored. */
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000681 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000682 while (s != 0) {
683 s >>= 1;
684 accumbits++;
685 }
686 }
687 else
688 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000689
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000690 /* Store as many bytes as possible. */
691 while (accumbits >= 8) {
692 if (j >= n)
693 goto Overflow;
694 ++j;
695 *p = (unsigned char)(accum & 0xff);
696 p += pincr;
697 accumbits -= 8;
698 accum >>= 8;
699 }
700 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000701
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000702 /* Store the straggler (if any). */
703 assert(accumbits < 8);
704 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
705 if (accumbits > 0) {
706 if (j >= n)
707 goto Overflow;
708 ++j;
709 if (do_twos_comp) {
710 /* Fill leading bits of the byte with sign bits
711 (appropriately pretending that the long had an
712 infinite supply of sign bits). */
713 accum |= (~(twodigits)0) << accumbits;
714 }
715 *p = (unsigned char)(accum & 0xff);
716 p += pincr;
717 }
718 else if (j == n && n > 0 && is_signed) {
719 /* The main loop filled the byte array exactly, so the code
720 just above didn't get to ensure there's a sign bit, and the
721 loop below wouldn't add one either. Make sure a sign bit
722 exists. */
723 unsigned char msb = *(p - pincr);
724 int sign_bit_set = msb >= 0x80;
725 assert(accumbits == 0);
726 if (sign_bit_set == do_twos_comp)
727 return 0;
728 else
729 goto Overflow;
730 }
Tim Peters05607ad2001-06-13 21:01:27 +0000731
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000732 /* Fill remaining bytes with copies of the sign bit. */
733 {
734 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
735 for ( ; j < n; ++j, p += pincr)
736 *p = signbyte;
737 }
Tim Peters05607ad2001-06-13 21:01:27 +0000738
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000739 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000740
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000741 Overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000742 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
743 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000744
Tim Peters2a9b3672001-06-11 21:23:58 +0000745}
746
Guido van Rossum78694d91998-09-18 14:14:13 +0000747/* Create a new long (or int) object from a C pointer */
748
749PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000750PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000751{
Tim Peters70128a12001-06-16 08:48:40 +0000752#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000753 if ((long)p < 0)
754 return PyLong_FromUnsignedLong((unsigned long)p);
755 return PyInt_FromLong((long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000756#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000757
Tim Peters70128a12001-06-16 08:48:40 +0000758#ifndef HAVE_LONG_LONG
759# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
760#endif
761#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000762# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000763#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000764 /* optimize null pointers */
765 if (p == NULL)
766 return PyInt_FromLong(0);
767 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000768
769#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000770}
771
772/* Get a C pointer from a long object (or an int object in some cases) */
773
774void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000775PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000776{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000777 /* This function will allow int or long objects. If vv is neither,
778 then the PyLong_AsLong*() functions will raise the exception:
779 PyExc_SystemError, "bad argument to internal function"
780 */
Tim Peters70128a12001-06-16 08:48:40 +0000781#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000782 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000783
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000784 if (PyInt_Check(vv))
785 x = PyInt_AS_LONG(vv);
786 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
787 x = PyLong_AsLong(vv);
788 else
789 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000790#else
Tim Peters70128a12001-06-16 08:48:40 +0000791
792#ifndef HAVE_LONG_LONG
793# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
794#endif
795#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000796# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000797#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000798 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000799
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000800 if (PyInt_Check(vv))
801 x = PyInt_AS_LONG(vv);
802 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
803 x = PyLong_AsLongLong(vv);
804 else
805 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000806
807#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000808
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000809 if (x == -1 && PyErr_Occurred())
810 return NULL;
811 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000812}
813
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000814#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000815
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000816/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000817 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000818 */
819
Tim Peterscf37dfc2001-06-14 18:42:50 +0000820#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000821#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000822
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000823/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000824
825PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000826PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000827{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000828 PyLongObject *v;
829 unsigned PY_LONG_LONG abs_ival;
830 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
831 int ndigits = 0;
832 int negative = 0;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000833
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000834 if (ival < 0) {
835 /* avoid signed overflow on negation; see comments
836 in PyLong_FromLong above. */
837 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
838 negative = 1;
839 }
840 else {
841 abs_ival = (unsigned PY_LONG_LONG)ival;
842 }
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000843
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000844 /* Count the number of Python digits.
845 We used to pick 5 ("big enough for anything"), but that's a
846 waste of time and space given that 5*15 = 75 bits are rarely
847 needed. */
848 t = abs_ival;
849 while (t) {
850 ++ndigits;
851 t >>= PyLong_SHIFT;
852 }
853 v = _PyLong_New(ndigits);
854 if (v != NULL) {
855 digit *p = v->ob_digit;
856 Py_SIZE(v) = negative ? -ndigits : ndigits;
857 t = abs_ival;
858 while (t) {
859 *p++ = (digit)(t & PyLong_MASK);
860 t >>= PyLong_SHIFT;
861 }
862 }
863 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000864}
865
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000866/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000867
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000868PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000869PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000870{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000871 PyLongObject *v;
872 unsigned PY_LONG_LONG t;
873 int ndigits = 0;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000874
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000875 /* Count the number of Python digits. */
876 t = (unsigned PY_LONG_LONG)ival;
877 while (t) {
878 ++ndigits;
879 t >>= PyLong_SHIFT;
880 }
881 v = _PyLong_New(ndigits);
882 if (v != NULL) {
883 digit *p = v->ob_digit;
884 Py_SIZE(v) = ndigits;
885 while (ival) {
886 *p++ = (digit)(ival & PyLong_MASK);
887 ival >>= PyLong_SHIFT;
888 }
889 }
890 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000891}
892
Martin v. Löwis18e16552006-02-15 17:27:45 +0000893/* Create a new long int object from a C Py_ssize_t. */
894
895PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000896PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000897{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000898 Py_ssize_t bytes = ival;
899 int one = 1;
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000900 return _PyLong_FromByteArray((unsigned char *)&bytes,
901 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000902}
903
904/* Create a new long int object from a C size_t. */
905
906PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000907PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000908{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000909 size_t bytes = ival;
910 int one = 1;
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000911 return _PyLong_FromByteArray((unsigned char *)&bytes,
912 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000913}
914
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000915/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000916 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000917
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000918PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000919PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000920{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000921 PY_LONG_LONG bytes;
922 int one = 1;
923 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +0000924
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000925 if (vv == NULL) {
926 PyErr_BadInternalCall();
927 return -1;
928 }
929 if (!PyLong_Check(vv)) {
930 PyNumberMethods *nb;
931 PyObject *io;
932 if (PyInt_Check(vv))
933 return (PY_LONG_LONG)PyInt_AsLong(vv);
934 if ((nb = vv->ob_type->tp_as_number) == NULL ||
935 nb->nb_int == NULL) {
936 PyErr_SetString(PyExc_TypeError, "an integer is required");
937 return -1;
938 }
939 io = (*nb->nb_int) (vv);
940 if (io == NULL)
941 return -1;
942 if (PyInt_Check(io)) {
943 bytes = PyInt_AsLong(io);
944 Py_DECREF(io);
945 return bytes;
946 }
947 if (PyLong_Check(io)) {
948 bytes = PyLong_AsLongLong(io);
949 Py_DECREF(io);
950 return bytes;
951 }
952 Py_DECREF(io);
953 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
954 return -1;
955 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000956
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000957 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
958 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000959
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000960 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
961 if (res < 0)
962 return (PY_LONG_LONG)-1;
963 else
964 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000965}
966
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000967/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000968 Return -1 and set an error if overflow occurs. */
969
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000970unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000971PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000972{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000973 unsigned PY_LONG_LONG bytes;
974 int one = 1;
975 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +0000976
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000977 if (vv == NULL || !PyLong_Check(vv)) {
978 PyErr_BadInternalCall();
979 return (unsigned PY_LONG_LONG)-1;
980 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000981
Mark Dickinsonfda8d112010-05-09 20:30:29 +0000982 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
983 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000984
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000985 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
986 if (res < 0)
987 return (unsigned PY_LONG_LONG)res;
988 else
989 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000990}
Tim Petersd1a7da62001-06-13 00:35:57 +0000991
Thomas Hellera4ea6032003-04-17 18:55:45 +0000992/* Get a C unsigned long int from a long int object, ignoring the high bits.
993 Returns -1 and sets an error condition if an error occurs. */
994
995unsigned PY_LONG_LONG
996PyLong_AsUnsignedLongLongMask(PyObject *vv)
997{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000998 register PyLongObject *v;
999 unsigned PY_LONG_LONG x;
1000 Py_ssize_t i;
1001 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001002
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001003 if (vv == NULL || !PyLong_Check(vv)) {
1004 PyErr_BadInternalCall();
1005 return (unsigned long) -1;
1006 }
1007 v = (PyLongObject *)vv;
1008 i = v->ob_size;
1009 sign = 1;
1010 x = 0;
1011 if (i < 0) {
1012 sign = -1;
1013 i = -i;
1014 }
1015 while (--i >= 0) {
1016 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1017 }
1018 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001019}
Mark Dickinsona36507c2010-01-30 10:08:33 +00001020
1021/* Get a C long long int from a Python long or Python int object.
1022 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1023 on the sign of the result. Otherwise *overflow is 0.
1024
1025 For other errors (e.g., type error), returns -1 and sets an error
1026 condition.
1027*/
1028
1029PY_LONG_LONG
1030PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1031{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001032 /* This version by Tim Peters */
1033 register PyLongObject *v;
1034 unsigned PY_LONG_LONG x, prev;
1035 PY_LONG_LONG res;
1036 Py_ssize_t i;
1037 int sign;
1038 int do_decref = 0; /* if nb_int was called */
Mark Dickinsona36507c2010-01-30 10:08:33 +00001039
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001040 *overflow = 0;
1041 if (vv == NULL) {
1042 PyErr_BadInternalCall();
1043 return -1;
1044 }
Mark Dickinsona36507c2010-01-30 10:08:33 +00001045
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001046 if (PyInt_Check(vv))
1047 return PyInt_AsLong(vv);
Mark Dickinsona36507c2010-01-30 10:08:33 +00001048
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001049 if (!PyLong_Check(vv)) {
1050 PyNumberMethods *nb;
1051 nb = vv->ob_type->tp_as_number;
1052 if (nb == NULL || nb->nb_int == NULL) {
1053 PyErr_SetString(PyExc_TypeError,
1054 "an integer is required");
1055 return -1;
1056 }
1057 vv = (*nb->nb_int) (vv);
1058 if (vv == NULL)
1059 return -1;
1060 do_decref = 1;
1061 if(PyInt_Check(vv)) {
1062 res = PyInt_AsLong(vv);
1063 goto exit;
1064 }
1065 if (!PyLong_Check(vv)) {
1066 Py_DECREF(vv);
1067 PyErr_SetString(PyExc_TypeError,
1068 "nb_int should return int object");
1069 return -1;
1070 }
1071 }
Mark Dickinsona36507c2010-01-30 10:08:33 +00001072
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001073 res = -1;
1074 v = (PyLongObject *)vv;
1075 i = Py_SIZE(v);
Mark Dickinsona36507c2010-01-30 10:08:33 +00001076
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001077 switch (i) {
1078 case -1:
1079 res = -(sdigit)v->ob_digit[0];
1080 break;
1081 case 0:
1082 res = 0;
1083 break;
1084 case 1:
1085 res = v->ob_digit[0];
1086 break;
1087 default:
1088 sign = 1;
1089 x = 0;
1090 if (i < 0) {
1091 sign = -1;
1092 i = -(i);
1093 }
1094 while (--i >= 0) {
1095 prev = x;
1096 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1097 if ((x >> PyLong_SHIFT) != prev) {
1098 *overflow = sign;
1099 goto exit;
1100 }
1101 }
1102 /* Haven't lost any bits, but casting to long requires extra
1103 * care (see comment above).
1104 */
1105 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1106 res = (PY_LONG_LONG)x * sign;
1107 }
1108 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1109 res = PY_LLONG_MIN;
1110 }
1111 else {
1112 *overflow = sign;
1113 /* res is already set to -1 */
1114 }
1115 }
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001116 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001117 if (do_decref) {
1118 Py_DECREF(vv);
1119 }
1120 return res;
Mark Dickinsona36507c2010-01-30 10:08:33 +00001121}
1122
Tim Petersd1a7da62001-06-13 00:35:57 +00001123#undef IS_LITTLE_ENDIAN
1124
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001125#endif /* HAVE_LONG_LONG */
1126
Neil Schemenauerba872e22001-01-04 01:46:03 +00001127
1128static int
1129convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001130 if (PyLong_Check(v)) {
1131 *a = (PyLongObject *) v;
1132 Py_INCREF(v);
1133 }
1134 else if (PyInt_Check(v)) {
1135 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1136 }
1137 else {
1138 return 0;
1139 }
1140 if (PyLong_Check(w)) {
1141 *b = (PyLongObject *) w;
1142 Py_INCREF(w);
1143 }
1144 else if (PyInt_Check(w)) {
1145 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1146 }
1147 else {
1148 Py_DECREF(*a);
1149 return 0;
1150 }
1151 return 1;
Neil Schemenauerba872e22001-01-04 01:46:03 +00001152}
1153
1154#define CONVERT_BINOP(v, w, a, b) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001155 if (!convert_binop(v, w, a, b)) { \
1156 Py_INCREF(Py_NotImplemented); \
1157 return Py_NotImplemented; \
1158 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001159
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001160/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1161 2**k if d is nonzero, else 0. */
1162
1163static const unsigned char BitLengthTable[32] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001164 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1165 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001166};
1167
1168static int
1169bits_in_digit(digit d)
1170{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001171 int d_bits = 0;
1172 while (d >= 32) {
1173 d_bits += 6;
1174 d >>= 6;
1175 }
1176 d_bits += (int)BitLengthTable[d];
1177 return d_bits;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001178}
1179
Tim Peters877a2122002-08-12 05:09:36 +00001180/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1181 * is modified in place, by adding y to it. Carries are propagated as far as
1182 * x[m-1], and the remaining carry (0 or 1) is returned.
1183 */
1184static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001185v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001186{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001187 Py_ssize_t i;
1188 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001189
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001190 assert(m >= n);
1191 for (i = 0; i < n; ++i) {
1192 carry += x[i] + y[i];
1193 x[i] = carry & PyLong_MASK;
1194 carry >>= PyLong_SHIFT;
1195 assert((carry & 1) == carry);
1196 }
1197 for (; carry && i < m; ++i) {
1198 carry += x[i];
1199 x[i] = carry & PyLong_MASK;
1200 carry >>= PyLong_SHIFT;
1201 assert((carry & 1) == carry);
1202 }
1203 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001204}
1205
1206/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1207 * is modified in place, by subtracting y from it. Borrows are propagated as
1208 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1209 */
1210static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001211v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001212{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001213 Py_ssize_t i;
1214 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001215
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001216 assert(m >= n);
1217 for (i = 0; i < n; ++i) {
1218 borrow = x[i] - y[i] - borrow;
1219 x[i] = borrow & PyLong_MASK;
1220 borrow >>= PyLong_SHIFT;
1221 borrow &= 1; /* keep only 1 sign bit */
1222 }
1223 for (; borrow && i < m; ++i) {
1224 borrow = x[i] - borrow;
1225 x[i] = borrow & PyLong_MASK;
1226 borrow >>= PyLong_SHIFT;
1227 borrow &= 1;
1228 }
1229 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001230}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001231
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001232/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1233 * result in z[0:m], and return the d bits shifted out of the top.
1234 */
1235static digit
1236v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001237{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001238 Py_ssize_t i;
1239 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001240
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001241 assert(0 <= d && d < PyLong_SHIFT);
1242 for (i=0; i < m; i++) {
1243 twodigits acc = (twodigits)a[i] << d | carry;
1244 z[i] = (digit)acc & PyLong_MASK;
1245 carry = (digit)(acc >> PyLong_SHIFT);
1246 }
1247 return carry;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001248}
1249
1250/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1251 * result in z[0:m], and return the d bits shifted out of the bottom.
1252 */
1253static digit
1254v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1255{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001256 Py_ssize_t i;
1257 digit carry = 0;
1258 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001259
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001260 assert(0 <= d && d < PyLong_SHIFT);
1261 for (i=m; i-- > 0;) {
1262 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1263 carry = (digit)acc & mask;
1264 z[i] = (digit)(acc >> d);
1265 }
1266 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001267}
1268
Tim Peters212e6142001-07-14 12:23:19 +00001269/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1270 in pout, and returning the remainder. pin and pout point at the LSD.
1271 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Eric Smith5e527eb2008-02-10 01:36:53 +00001272 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001273 immutable. */
1274
1275static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001276inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001277{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001278 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001279
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001280 assert(n > 0 && n <= PyLong_MASK);
1281 pin += size;
1282 pout += size;
1283 while (--size >= 0) {
1284 digit hi;
1285 rem = (rem << PyLong_SHIFT) | *--pin;
1286 *--pout = hi = (digit)(rem / n);
1287 rem -= (twodigits)hi * n;
1288 }
1289 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001290}
1291
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001292/* Divide a long integer by a digit, returning both the quotient
1293 (as function result) and the remainder (through *prem).
1294 The sign of a is ignored; n should not be zero. */
1295
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001296static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001297divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001298{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001299 const Py_ssize_t size = ABS(Py_SIZE(a));
1300 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001301
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001302 assert(n > 0 && n <= PyLong_MASK);
1303 z = _PyLong_New(size);
1304 if (z == NULL)
1305 return NULL;
1306 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1307 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001308}
1309
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001310/* Convert a long integer to a base 10 string. Returns a new non-shared
1311 string. (Return value is non-shared so that callers can modify the
1312 returned value if necessary.) */
1313
1314static PyObject *
1315long_to_decimal_string(PyObject *aa, int addL)
1316{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001317 PyLongObject *scratch, *a;
1318 PyObject *str;
1319 Py_ssize_t size, strlen, size_a, i, j;
1320 digit *pout, *pin, rem, tenpow;
1321 char *p;
1322 int negative;
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001323
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001324 a = (PyLongObject *)aa;
1325 if (a == NULL || !PyLong_Check(a)) {
1326 PyErr_BadInternalCall();
1327 return NULL;
1328 }
1329 size_a = ABS(Py_SIZE(a));
1330 negative = Py_SIZE(a) < 0;
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001331
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001332 /* quick and dirty upper bound for the number of digits
1333 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001334
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001335 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001336
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001337 But log2(a) < size_a * PyLong_SHIFT, and
1338 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1339 > 3 * _PyLong_DECIMAL_SHIFT
1340 */
1341 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1342 PyErr_SetString(PyExc_OverflowError,
1343 "long is too large to format");
1344 return NULL;
1345 }
1346 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1347 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1348 scratch = _PyLong_New(size);
1349 if (scratch == NULL)
1350 return NULL;
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001351
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001352 /* convert array of base _PyLong_BASE digits in pin to an array of
1353 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1354 Volume 2 (3rd edn), section 4.4, Method 1b). */
1355 pin = a->ob_digit;
1356 pout = scratch->ob_digit;
1357 size = 0;
1358 for (i = size_a; --i >= 0; ) {
1359 digit hi = pin[i];
1360 for (j = 0; j < size; j++) {
1361 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1362 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1363 pout[j] = (digit)(z - (twodigits)hi *
1364 _PyLong_DECIMAL_BASE);
1365 }
1366 while (hi) {
1367 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1368 hi /= _PyLong_DECIMAL_BASE;
1369 }
1370 /* check for keyboard interrupt */
1371 SIGCHECK({
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001372 Py_DECREF(scratch);
1373 return NULL;
1374 })
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001375 }
1376 /* pout should have at least one digit, so that the case when a = 0
1377 works correctly */
1378 if (size == 0)
1379 pout[size++] = 0;
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001380
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001381 /* calculate exact length of output string, and allocate */
1382 strlen = (addL != 0) + negative +
1383 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1384 tenpow = 10;
1385 rem = pout[size-1];
1386 while (rem >= tenpow) {
1387 tenpow *= 10;
1388 strlen++;
1389 }
1390 str = PyString_FromStringAndSize(NULL, strlen);
1391 if (str == NULL) {
1392 Py_DECREF(scratch);
1393 return NULL;
1394 }
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001395
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001396 /* fill the string right-to-left */
1397 p = PyString_AS_STRING(str) + strlen;
1398 *p = '\0';
1399 if (addL)
1400 *--p = 'L';
1401 /* pout[0] through pout[size-2] contribute exactly
1402 _PyLong_DECIMAL_SHIFT digits each */
1403 for (i=0; i < size - 1; i++) {
1404 rem = pout[i];
1405 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1406 *--p = '0' + rem % 10;
1407 rem /= 10;
1408 }
1409 }
1410 /* pout[size-1]: always produce at least one decimal digit */
1411 rem = pout[i];
1412 do {
1413 *--p = '0' + rem % 10;
1414 rem /= 10;
1415 } while (rem != 0);
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001416
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001417 /* and sign */
1418 if (negative)
1419 *--p = '-';
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001420
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001421 /* check we've counted correctly */
1422 assert(p == PyString_AS_STRING(str));
1423 Py_DECREF(scratch);
1424 return (PyObject *)str;
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001425}
1426
Eric Smith5e527eb2008-02-10 01:36:53 +00001427/* Convert the long to a string object with given base,
1428 appending a base prefix of 0[box] if base is 2, 8 or 16.
1429 Add a trailing "L" if addL is non-zero.
1430 If newstyle is zero, then use the pre-2.6 behavior of octal having
1431 a leading "0", instead of the prefix "0o" */
1432PyAPI_FUNC(PyObject *)
1433_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001434{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001435 register PyLongObject *a = (PyLongObject *)aa;
1436 PyStringObject *str;
1437 Py_ssize_t i, sz;
1438 Py_ssize_t size_a;
1439 char *p;
1440 int bits;
1441 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001442
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001443 if (base == 10)
1444 return long_to_decimal_string((PyObject *)a, addL);
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001445
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001446 if (a == NULL || !PyLong_Check(a)) {
1447 PyErr_BadInternalCall();
1448 return NULL;
1449 }
1450 assert(base >= 2 && base <= 36);
1451 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001452
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001453 /* Compute a rough upper bound for the length of the string */
1454 i = base;
1455 bits = 0;
1456 while (i > 1) {
1457 ++bits;
1458 i >>= 1;
1459 }
1460 i = 5 + (addL ? 1 : 0);
1461 /* ensure we don't get signed overflow in sz calculation */
1462 if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {
1463 PyErr_SetString(PyExc_OverflowError,
1464 "long is too large to format");
1465 return NULL;
1466 }
1467 sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;
1468 assert(sz >= 0);
1469 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
1470 if (str == NULL)
1471 return NULL;
1472 p = PyString_AS_STRING(str) + sz;
1473 *p = '\0';
1474 if (addL)
1475 *--p = 'L';
1476 if (a->ob_size < 0)
1477 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001478
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001479 if (a->ob_size == 0) {
1480 *--p = '0';
1481 }
1482 else if ((base & (base - 1)) == 0) {
1483 /* JRH: special case for power-of-2 bases */
1484 twodigits accum = 0;
1485 int accumbits = 0; /* # of bits in accum */
1486 int basebits = 1; /* # of bits in base-1 */
1487 i = base;
1488 while ((i >>= 1) > 1)
1489 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001490
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001491 for (i = 0; i < size_a; ++i) {
1492 accum |= (twodigits)a->ob_digit[i] << accumbits;
1493 accumbits += PyLong_SHIFT;
1494 assert(accumbits >= basebits);
1495 do {
1496 char cdigit = (char)(accum & (base - 1));
1497 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1498 assert(p > PyString_AS_STRING(str));
1499 *--p = cdigit;
1500 accumbits -= basebits;
1501 accum >>= basebits;
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001502 } while (i < size_a-1 ? accumbits >= basebits : accum > 0);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001503 }
1504 }
1505 else {
1506 /* Not 0, and base not a power of 2. Divide repeatedly by
1507 base, but for speed use the highest power of base that
1508 fits in a digit. */
1509 Py_ssize_t size = size_a;
1510 digit *pin = a->ob_digit;
1511 PyLongObject *scratch;
1512 /* powbasw <- largest power of base that fits in a digit. */
1513 digit powbase = base; /* powbase == base ** power */
1514 int power = 1;
1515 for (;;) {
1516 twodigits newpow = powbase * (twodigits)base;
1517 if (newpow >> PyLong_SHIFT)
1518 /* doesn't fit in a digit */
1519 break;
1520 powbase = (digit)newpow;
1521 ++power;
1522 }
Tim Peters212e6142001-07-14 12:23:19 +00001523
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001524 /* Get a scratch area for repeated division. */
1525 scratch = _PyLong_New(size);
1526 if (scratch == NULL) {
1527 Py_DECREF(str);
1528 return NULL;
1529 }
Tim Peters212e6142001-07-14 12:23:19 +00001530
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001531 /* Repeatedly divide by powbase. */
1532 do {
1533 int ntostore = power;
1534 digit rem = inplace_divrem1(scratch->ob_digit,
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001535 pin, size, powbase);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001536 pin = scratch->ob_digit; /* no need to use a again */
1537 if (pin[size - 1] == 0)
1538 --size;
1539 SIGCHECK({
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001540 Py_DECREF(scratch);
1541 Py_DECREF(str);
1542 return NULL;
1543 })
Tim Peters212e6142001-07-14 12:23:19 +00001544
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001545 /* Break rem into digits. */
1546 assert(ntostore > 0);
1547 do {
1548 digit nextrem = (digit)(rem / base);
1549 char c = (char)(rem - nextrem * base);
1550 assert(p > PyString_AS_STRING(str));
1551 c += (c < 10) ? '0' : 'a'-10;
1552 *--p = c;
1553 rem = nextrem;
1554 --ntostore;
1555 /* Termination is a bit delicate: must not
1556 store leading zeroes, so must get out if
1557 remaining quotient and rem are both 0. */
1558 } while (ntostore && (size || rem));
1559 } while (size != 0);
1560 Py_DECREF(scratch);
1561 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001562
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001563 if (base == 2) {
1564 *--p = 'b';
1565 *--p = '0';
1566 }
1567 else if (base == 8) {
1568 if (newstyle) {
1569 *--p = 'o';
1570 *--p = '0';
1571 }
1572 else
1573 if (size_a != 0)
1574 *--p = '0';
1575 }
1576 else if (base == 16) {
1577 *--p = 'x';
1578 *--p = '0';
1579 }
1580 else if (base != 10) {
1581 *--p = '#';
1582 *--p = '0' + base%10;
1583 if (base > 10)
1584 *--p = '0' + base/10;
1585 }
1586 if (sign)
1587 *--p = sign;
1588 if (p != PyString_AS_STRING(str)) {
1589 char *q = PyString_AS_STRING(str);
1590 assert(p > q);
1591 do {
1592 } while ((*q++ = *p++) != '\0');
1593 q--;
1594 _PyString_Resize((PyObject **)&str,
1595 (Py_ssize_t) (q - PyString_AS_STRING(str)));
1596 }
1597 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001598}
1599
Tim Petersda53afa2006-05-25 17:34:03 +00001600/* Table of digit values for 8-bit string -> integer conversion.
1601 * '0' maps to 0, ..., '9' maps to 9.
1602 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1603 * All other indices map to 37.
1604 * Note that when converting a base B string, a char c is a legitimate
1605 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1606 */
1607int _PyLong_DigitValue[256] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001608 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1609 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1610 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1611 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1612 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1613 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1614 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1615 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1616 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1617 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1618 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1619 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1620 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1621 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1622 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1623 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Tim Peters696cf432006-05-24 21:10:40 +00001624};
1625
1626/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001627 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1628 * non-digit (which may be *str!). A normalized long is returned.
1629 * The point to this routine is that it takes time linear in the number of
1630 * string characters.
1631 */
1632static PyLongObject *
1633long_from_binary_base(char **str, int base)
1634{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001635 char *p = *str;
1636 char *start = p;
1637 int bits_per_char;
1638 Py_ssize_t n;
1639 PyLongObject *z;
1640 twodigits accum;
1641 int bits_in_accum;
1642 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001643
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001644 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1645 n = base;
1646 for (bits_per_char = -1; n; ++bits_per_char)
1647 n >>= 1;
1648 /* n <- total # of bits needed, while setting p to end-of-string */
1649 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1650 ++p;
1651 *str = p;
1652 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1653 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1654 if (n / bits_per_char < p - start) {
1655 PyErr_SetString(PyExc_ValueError,
1656 "long string too large to convert");
1657 return NULL;
1658 }
1659 n = n / PyLong_SHIFT;
1660 z = _PyLong_New(n);
1661 if (z == NULL)
1662 return NULL;
1663 /* Read string from right, and fill in long from left; i.e.,
1664 * from least to most significant in both.
1665 */
1666 accum = 0;
1667 bits_in_accum = 0;
1668 pdigit = z->ob_digit;
1669 while (--p >= start) {
1670 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
1671 assert(k >= 0 && k < base);
1672 accum |= (twodigits)k << bits_in_accum;
1673 bits_in_accum += bits_per_char;
1674 if (bits_in_accum >= PyLong_SHIFT) {
1675 *pdigit++ = (digit)(accum & PyLong_MASK);
1676 assert(pdigit - z->ob_digit <= n);
1677 accum >>= PyLong_SHIFT;
1678 bits_in_accum -= PyLong_SHIFT;
1679 assert(bits_in_accum < PyLong_SHIFT);
1680 }
1681 }
1682 if (bits_in_accum) {
1683 assert(bits_in_accum <= PyLong_SHIFT);
1684 *pdigit++ = (digit)accum;
1685 assert(pdigit - z->ob_digit <= n);
1686 }
1687 while (pdigit - z->ob_digit < n)
1688 *pdigit++ = 0;
1689 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001690}
1691
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001692PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001693PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001694{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001695 int sign = 1;
1696 char *start, *orig_str = str;
1697 PyLongObject *z;
1698 PyObject *strobj, *strrepr;
1699 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001700
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001701 if ((base != 0 && base < 2) || base > 36) {
1702 PyErr_SetString(PyExc_ValueError,
1703 "long() arg 2 must be >= 2 and <= 36");
1704 return NULL;
1705 }
1706 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1707 str++;
1708 if (*str == '+')
1709 ++str;
1710 else if (*str == '-') {
1711 ++str;
1712 sign = -1;
1713 }
1714 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1715 str++;
1716 if (base == 0) {
1717 /* No base given. Deduce the base from the contents
1718 of the string */
1719 if (str[0] != '0')
1720 base = 10;
1721 else if (str[1] == 'x' || str[1] == 'X')
1722 base = 16;
1723 else if (str[1] == 'o' || str[1] == 'O')
1724 base = 8;
1725 else if (str[1] == 'b' || str[1] == 'B')
1726 base = 2;
1727 else
1728 /* "old" (C-style) octal literal, still valid in
1729 2.x, although illegal in 3.x */
1730 base = 8;
1731 }
1732 /* Whether or not we were deducing the base, skip leading chars
1733 as needed */
1734 if (str[0] == '0' &&
1735 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1736 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1737 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1738 str += 2;
Tim Peters696cf432006-05-24 21:10:40 +00001739
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001740 start = str;
1741 if ((base & (base - 1)) == 0)
1742 z = long_from_binary_base(&str, base);
1743 else {
Tim Peters696cf432006-05-24 21:10:40 +00001744/***
1745Binary bases can be converted in time linear in the number of digits, because
1746Python's representation base is binary. Other bases (including decimal!) use
1747the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001748
Tim Peters696cf432006-05-24 21:10:40 +00001749First some math: the largest integer that can be expressed in N base-B digits
1750is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1751case number of Python digits needed to hold it is the smallest integer n s.t.
1752
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001753 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1754 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1755 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001756
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001757The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so
1758we can compute this quickly. A Python long with that much space is reserved
1759near the start, and the result is computed into it.
Tim Peters696cf432006-05-24 21:10:40 +00001760
1761The input string is actually treated as being in base base**i (i.e., i digits
1762are processed at a time), where two more static arrays hold:
1763
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001764 convwidth_base[base] = the largest integer i such that
1765 base**i <= PyLong_BASE
Tim Peters696cf432006-05-24 21:10:40 +00001766 convmultmax_base[base] = base ** convwidth_base[base]
1767
1768The first of these is the largest i such that i consecutive input digits
1769must fit in a single Python digit. The second is effectively the input
1770base we're really using.
1771
1772Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1773convmultmax_base[base], the result is "simply"
1774
1775 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1776
1777where B = convmultmax_base[base].
Tim Peters9faa3ed2006-05-30 15:53:34 +00001778
1779Error analysis: as above, the number of Python digits `n` needed is worst-
1780case
1781
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001782 n >= N * log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001783
1784where `N` is the number of input digits in base `B`. This is computed via
1785
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001786 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001787
1788below. Two numeric concerns are how much space this can waste, and whether
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001789the computed result can be too small. To be concrete, assume PyLong_BASE =
17902**15, which is the default (and it's unlikely anyone changes that).
Tim Peters9faa3ed2006-05-30 15:53:34 +00001791
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001792Waste isn't a problem: provided the first input digit isn't 0, the difference
Tim Peters9faa3ed2006-05-30 15:53:34 +00001793between the worst-case input with N digits and the smallest input with N
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001794digits is about a factor of B, but B is small compared to PyLong_BASE so at
1795most one allocated Python digit can remain unused on that count. If
1796N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating
1797that and adding 1 returns a result 1 larger than necessary. However, that
1798can't happen: whenever B is a power of 2, long_from_binary_base() is called
1799instead, and it's impossible for B**i to be an integer power of 2**15 when B
1800is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be
Tim Peters9faa3ed2006-05-30 15:53:34 +00001801an exact integer when B is not a power of 2, since B**i has a prime factor
1802other than 2 in that case, but (2**15)**j's only prime factor is 2).
1803
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001804The computed result can be too small if the true value of
1805N*log(B)/log(PyLong_BASE) is a little bit larger than an exact integer, but
1806due to roundoff errors (in computing log(B), log(PyLong_BASE), their quotient,
1807and/or multiplying that by N) yields a numeric result a little less than that
1808integer. Unfortunately, "how close can a transcendental function get to an
1809integer over some range?" questions are generally theoretically intractable.
1810Computer analysis via continued fractions is practical: expand
1811log(B)/log(PyLong_BASE) via continued fractions, giving a sequence i/j of "the
1812best" rational approximations. Then j*log(B)/log(PyLong_BASE) is
1813approximately equal to (the integer) i. This shows that we can get very close
1814to being in trouble, but very rarely. For example, 76573 is a denominator in
1815one of the continued-fraction approximations to log(10)/log(2**15), and
1816indeed:
Tim Peters9faa3ed2006-05-30 15:53:34 +00001817
1818 >>> log(10)/log(2**15)*76573
1819 16958.000000654003
1820
1821is very close to an integer. If we were working with IEEE single-precision,
1822rounding errors could kill us. Finding worst cases in IEEE double-precision
1823requires better-than-double-precision log() functions, and Tim didn't bother.
1824Instead the code checks to see whether the allocated space is enough as each
1825new Python digit is added, and copies the whole thing to a larger long if not.
1826This should happen extremely rarely, and in fact I don't have a test case
1827that triggers it(!). Instead the code was tested by artificially allocating
1828just 1 digit at the start, so that the copying code was exercised for every
1829digit beyond the first.
Tim Peters696cf432006-05-24 21:10:40 +00001830***/
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001831 register twodigits c; /* current input character */
1832 Py_ssize_t size_z;
1833 int i;
1834 int convwidth;
1835 twodigits convmultmax, convmult;
1836 digit *pz, *pzstop;
1837 char* scan;
Tim Peters696cf432006-05-24 21:10:40 +00001838
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001839 static double log_base_PyLong_BASE[37] = {0.0e0,};
1840 static int convwidth_base[37] = {0,};
1841 static twodigits convmultmax_base[37] = {0,};
Tim Peters696cf432006-05-24 21:10:40 +00001842
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001843 if (log_base_PyLong_BASE[base] == 0.0) {
1844 twodigits convmax = base;
1845 int i = 1;
Tim Peters696cf432006-05-24 21:10:40 +00001846
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001847 log_base_PyLong_BASE[base] = (log((double)base) /
1848 log((double)PyLong_BASE));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001849 for (;;) {
1850 twodigits next = convmax * base;
1851 if (next > PyLong_BASE)
1852 break;
1853 convmax = next;
1854 ++i;
1855 }
1856 convmultmax_base[base] = convmax;
1857 assert(i > 0);
1858 convwidth_base[base] = i;
1859 }
Tim Peters696cf432006-05-24 21:10:40 +00001860
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001861 /* Find length of the string of numeric characters. */
1862 scan = str;
1863 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1864 ++scan;
Tim Peters696cf432006-05-24 21:10:40 +00001865
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001866 /* Create a long object that can contain the largest possible
1867 * integer with this base and length. Note that there's no
1868 * need to initialize z->ob_digit -- no slot is read up before
1869 * being stored into.
1870 */
1871 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
1872 /* Uncomment next line to test exceedingly rare copy code */
1873 /* size_z = 1; */
1874 assert(size_z > 0);
1875 z = _PyLong_New(size_z);
1876 if (z == NULL)
1877 return NULL;
1878 Py_SIZE(z) = 0;
Tim Peters696cf432006-05-24 21:10:40 +00001879
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001880 /* `convwidth` consecutive input digits are treated as a single
1881 * digit in base `convmultmax`.
1882 */
1883 convwidth = convwidth_base[base];
1884 convmultmax = convmultmax_base[base];
Tim Peters696cf432006-05-24 21:10:40 +00001885
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001886 /* Work ;-) */
1887 while (str < scan) {
1888 /* grab up to convwidth digits from the input string */
1889 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1890 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1891 c = (twodigits)(c * base +
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001892 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001893 assert(c < PyLong_BASE);
1894 }
Tim Peters696cf432006-05-24 21:10:40 +00001895
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001896 convmult = convmultmax;
1897 /* Calculate the shift only if we couldn't get
1898 * convwidth digits.
1899 */
1900 if (i != convwidth) {
1901 convmult = base;
1902 for ( ; i > 1; --i)
1903 convmult *= base;
1904 }
Tim Peters696cf432006-05-24 21:10:40 +00001905
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001906 /* Multiply z by convmult, and add c. */
1907 pz = z->ob_digit;
1908 pzstop = pz + Py_SIZE(z);
1909 for (; pz < pzstop; ++pz) {
1910 c += (twodigits)*pz * convmult;
1911 *pz = (digit)(c & PyLong_MASK);
1912 c >>= PyLong_SHIFT;
1913 }
1914 /* carry off the current end? */
1915 if (c) {
1916 assert(c < PyLong_BASE);
1917 if (Py_SIZE(z) < size_z) {
1918 *pz = (digit)c;
1919 ++Py_SIZE(z);
1920 }
1921 else {
1922 PyLongObject *tmp;
1923 /* Extremely rare. Get more space. */
1924 assert(Py_SIZE(z) == size_z);
1925 tmp = _PyLong_New(size_z + 1);
1926 if (tmp == NULL) {
1927 Py_DECREF(z);
1928 return NULL;
1929 }
1930 memcpy(tmp->ob_digit,
1931 z->ob_digit,
1932 sizeof(digit) * size_z);
1933 Py_DECREF(z);
1934 z = tmp;
1935 z->ob_digit[size_z] = (digit)c;
1936 ++size_z;
1937 }
1938 }
1939 }
1940 }
1941 if (z == NULL)
1942 return NULL;
1943 if (str == start)
1944 goto onError;
1945 if (sign < 0)
1946 Py_SIZE(z) = -(Py_SIZE(z));
1947 if (*str == 'L' || *str == 'l')
1948 str++;
1949 while (*str && isspace(Py_CHARMASK(*str)))
1950 str++;
1951 if (*str != '\0')
1952 goto onError;
1953 if (pend)
1954 *pend = str;
1955 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001956
Mark Dickinsonfda8d112010-05-09 20:30:29 +00001957 onError:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001958 Py_XDECREF(z);
1959 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1960 strobj = PyString_FromStringAndSize(orig_str, slen);
1961 if (strobj == NULL)
1962 return NULL;
1963 strrepr = PyObject_Repr(strobj);
1964 Py_DECREF(strobj);
1965 if (strrepr == NULL)
1966 return NULL;
1967 PyErr_Format(PyExc_ValueError,
1968 "invalid literal for long() with base %d: %s",
1969 base, PyString_AS_STRING(strrepr));
1970 Py_DECREF(strrepr);
1971 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001972}
1973
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001974#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001975PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001976PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001977{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001978 PyObject *result;
1979 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001980
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001981 if (buffer == NULL)
1982 return NULL;
Walter Dörwald07e14762002-11-06 16:15:14 +00001983
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001984 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1985 PyMem_FREE(buffer);
1986 return NULL;
1987 }
1988 result = PyLong_FromString(buffer, NULL, base);
1989 PyMem_FREE(buffer);
1990 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001991}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001992#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001993
Tim Peters9f688bf2000-07-07 15:53:28 +00001994/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001995static PyLongObject *x_divrem
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001996 (PyLongObject *, PyLongObject *, PyLongObject **);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001997static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001998
1999/* Long division with remainder, top-level routine */
2000
Guido van Rossume32e0141992-01-19 16:31:05 +00002001static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002002long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002003 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002004{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002005 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2006 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002007
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002008 if (size_b == 0) {
2009 PyErr_SetString(PyExc_ZeroDivisionError,
2010 "long division or modulo by zero");
2011 return -1;
2012 }
2013 if (size_a < size_b ||
2014 (size_a == size_b &&
2015 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2016 /* |a| < |b|. */
2017 *pdiv = _PyLong_New(0);
2018 if (*pdiv == NULL)
2019 return -1;
2020 Py_INCREF(a);
2021 *prem = (PyLongObject *) a;
2022 return 0;
2023 }
2024 if (size_b == 1) {
2025 digit rem = 0;
2026 z = divrem1(a, b->ob_digit[0], &rem);
2027 if (z == NULL)
2028 return -1;
2029 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2030 if (*prem == NULL) {
2031 Py_DECREF(z);
2032 return -1;
2033 }
2034 }
2035 else {
2036 z = x_divrem(a, b, prem);
2037 if (z == NULL)
2038 return -1;
2039 }
2040 /* Set the signs.
2041 The quotient z has the sign of a*b;
2042 the remainder r has the sign of a,
2043 so a = b*z + r. */
2044 if ((a->ob_size < 0) != (b->ob_size < 0))
2045 z->ob_size = -(z->ob_size);
2046 if (a->ob_size < 0 && (*prem)->ob_size != 0)
2047 (*prem)->ob_size = -((*prem)->ob_size);
2048 *pdiv = z;
2049 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002050}
2051
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002052/* Unsigned long division with remainder -- the algorithm. The arguments v1
2053 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002054
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002055static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002056x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002057{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002058 PyLongObject *v, *w, *a;
2059 Py_ssize_t i, k, size_v, size_w;
2060 int d;
2061 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2062 twodigits vv;
2063 sdigit zhi;
2064 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002065
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002066 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2067 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2068 handle the special case when the initial estimate q for a quotient
2069 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2070 that won't overflow a digit. */
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002071
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002072 /* allocate space; w will also be used to hold the final remainder */
2073 size_v = ABS(Py_SIZE(v1));
2074 size_w = ABS(Py_SIZE(w1));
2075 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2076 v = _PyLong_New(size_v+1);
2077 if (v == NULL) {
2078 *prem = NULL;
2079 return NULL;
2080 }
2081 w = _PyLong_New(size_w);
2082 if (w == NULL) {
2083 Py_DECREF(v);
2084 *prem = NULL;
2085 return NULL;
2086 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002087
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002088 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2089 shift v1 left by the same amount. Results go into w and v. */
2090 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2091 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2092 assert(carry == 0);
2093 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2094 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2095 v->ob_digit[size_v] = carry;
2096 size_v++;
2097 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002098
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002099 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2100 at most (and usually exactly) k = size_v - size_w digits. */
2101 k = size_v - size_w;
2102 assert(k >= 0);
2103 a = _PyLong_New(k);
2104 if (a == NULL) {
2105 Py_DECREF(w);
2106 Py_DECREF(v);
2107 *prem = NULL;
2108 return NULL;
2109 }
2110 v0 = v->ob_digit;
2111 w0 = w->ob_digit;
2112 wm1 = w0[size_w-1];
2113 wm2 = w0[size_w-2];
2114 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2115 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2116 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002117
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002118 SIGCHECK({
Mark Dickinsonfda8d112010-05-09 20:30:29 +00002119 Py_DECREF(a);
2120 Py_DECREF(w);
2121 Py_DECREF(v);
2122 *prem = NULL;
2123 return NULL;
2124 })
Tim Peters5af4e6c2002-08-12 02:31:19 +00002125
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002126 /* estimate quotient digit q; may overestimate by 1 (rare) */
2127 vtop = vk[size_w];
2128 assert(vtop <= wm1);
2129 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2130 q = (digit)(vv / wm1);
2131 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2132 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2133 | vk[size_w-2])) {
2134 --q;
2135 r += wm1;
2136 if (r >= PyLong_BASE)
2137 break;
2138 }
2139 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002140
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002141 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2142 zhi = 0;
2143 for (i = 0; i < size_w; ++i) {
2144 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2145 -PyLong_BASE * q <= z < PyLong_BASE */
2146 z = (sdigit)vk[i] + zhi -
2147 (stwodigits)q * (stwodigits)w0[i];
2148 vk[i] = (digit)z & PyLong_MASK;
2149 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinsonfda8d112010-05-09 20:30:29 +00002150 z, PyLong_SHIFT);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002151 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002152
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002153 /* add w back if q was too large (this branch taken rarely) */
2154 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2155 if ((sdigit)vtop + zhi < 0) {
2156 carry = 0;
2157 for (i = 0; i < size_w; ++i) {
2158 carry += vk[i] + w0[i];
2159 vk[i] = carry & PyLong_MASK;
2160 carry >>= PyLong_SHIFT;
2161 }
2162 --q;
2163 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002164
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002165 /* store quotient digit */
2166 assert(q < PyLong_BASE);
2167 *--ak = q;
2168 }
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002169
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002170 /* unshift remainder; we reuse w to store the result */
2171 carry = v_rshift(w0, v0, size_w, d);
2172 assert(carry==0);
2173 Py_DECREF(v);
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002174
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002175 *prem = long_normalize(w);
2176 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002177}
2178
Mark Dickinsond3e32322010-01-02 14:45:40 +00002179/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2180 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2181 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2182 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2183 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2184 -1.0. */
2185
2186/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2187#if DBL_MANT_DIG == 53
2188#define EXP2_DBL_MANT_DIG 9007199254740992.0
2189#else
2190#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2191#endif
2192
2193double
2194_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2195{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002196 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2197 /* See below for why x_digits is always large enough. */
2198 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2199 double dx;
2200 /* Correction term for round-half-to-even rounding. For a digit x,
2201 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2202 multiple of 4, rounding ties to a multiple of 8. */
2203 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinsond3e32322010-01-02 14:45:40 +00002204
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002205 a_size = ABS(Py_SIZE(a));
2206 if (a_size == 0) {
2207 /* Special case for 0: significand 0.0, exponent 0. */
2208 *e = 0;
2209 return 0.0;
2210 }
2211 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2212 /* The following is an overflow-free version of the check
2213 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2214 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2215 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2216 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinsonfda8d112010-05-09 20:30:29 +00002217 goto overflow;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002218 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinsond3e32322010-01-02 14:45:40 +00002219
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002220 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2221 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinsond3e32322010-01-02 14:45:40 +00002222
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002223 Number of digits needed for result: write // for floor division.
2224 Then if shifting left, we end up using
Mark Dickinsond3e32322010-01-02 14:45:40 +00002225
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002226 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinsond3e32322010-01-02 14:45:40 +00002227
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002228 digits. If shifting right, we use
Mark Dickinsond3e32322010-01-02 14:45:40 +00002229
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002230 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinsond3e32322010-01-02 14:45:40 +00002231
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002232 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2233 the inequalities
Mark Dickinsond3e32322010-01-02 14:45:40 +00002234
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002235 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2236 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2237 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinsond3e32322010-01-02 14:45:40 +00002238
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002239 valid for any integers m and n, we find that x_size satisfies
Mark Dickinsond3e32322010-01-02 14:45:40 +00002240
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002241 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinsond3e32322010-01-02 14:45:40 +00002242
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002243 in both cases.
2244 */
2245 if (a_bits <= DBL_MANT_DIG + 2) {
2246 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2247 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2248 x_size = 0;
2249 while (x_size < shift_digits)
2250 x_digits[x_size++] = 0;
2251 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2252 (int)shift_bits);
2253 x_size += a_size;
2254 x_digits[x_size++] = rem;
2255 }
2256 else {
2257 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2258 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2259 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2260 a_size - shift_digits, (int)shift_bits);
2261 x_size = a_size - shift_digits;
2262 /* For correct rounding below, we need the least significant
2263 bit of x to be 'sticky' for this shift: if any of the bits
2264 shifted out was nonzero, we set the least significant bit
2265 of x. */
2266 if (rem)
2267 x_digits[0] |= 1;
2268 else
2269 while (shift_digits > 0)
2270 if (a->ob_digit[--shift_digits]) {
2271 x_digits[0] |= 1;
2272 break;
2273 }
2274 }
Mark Dickinsonfda8d112010-05-09 20:30:29 +00002275 assert(1 <= x_size &&
2276 x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
Mark Dickinsond3e32322010-01-02 14:45:40 +00002277
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002278 /* Round, and convert to double. */
2279 x_digits[0] += half_even_correction[x_digits[0] & 7];
2280 dx = x_digits[--x_size];
2281 while (x_size > 0)
2282 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinsond3e32322010-01-02 14:45:40 +00002283
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002284 /* Rescale; make correction if result is 1.0. */
2285 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2286 if (dx == 1.0) {
2287 if (a_bits == PY_SSIZE_T_MAX)
2288 goto overflow;
2289 dx = 0.5;
2290 a_bits += 1;
2291 }
Mark Dickinsond3e32322010-01-02 14:45:40 +00002292
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002293 *e = a_bits;
2294 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinsond3e32322010-01-02 14:45:40 +00002295
2296 overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002297 /* exponent > PY_SSIZE_T_MAX */
2298 PyErr_SetString(PyExc_OverflowError,
2299 "huge integer: number of bits overflows a Py_ssize_t");
2300 *e = 0;
2301 return -1.0;
Mark Dickinsond3e32322010-01-02 14:45:40 +00002302}
2303
2304/* Get a C double from a long int object. Rounds to the nearest double,
2305 using the round-half-to-even rule in the case of a tie. */
2306
2307double
2308PyLong_AsDouble(PyObject *v)
2309{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002310 Py_ssize_t exponent;
2311 double x;
Mark Dickinsond3e32322010-01-02 14:45:40 +00002312
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002313 if (v == NULL || !PyLong_Check(v)) {
2314 PyErr_BadInternalCall();
2315 return -1.0;
2316 }
2317 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2318 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2319 PyErr_SetString(PyExc_OverflowError,
2320 "long int too large to convert to float");
2321 return -1.0;
2322 }
2323 return ldexp(x, (int)exponent);
Mark Dickinsond3e32322010-01-02 14:45:40 +00002324}
2325
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002326/* Methods */
2327
2328static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002329long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002330{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002331 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002332}
2333
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002334static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002335long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002336{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002337 return _PyLong_Format(v, 10, 1, 0);
Fred Drake121ee271999-12-23 15:41:28 +00002338}
2339
2340static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002341long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00002342{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002343 return _PyLong_Format(v, 10, 0, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002344}
2345
2346static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002347long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002348{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002349 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002350
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002351 if (Py_SIZE(a) != Py_SIZE(b)) {
2352 sign = Py_SIZE(a) - Py_SIZE(b);
2353 }
2354 else {
2355 Py_ssize_t i = ABS(Py_SIZE(a));
2356 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2357 ;
2358 if (i < 0)
2359 sign = 0;
2360 else {
2361 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2362 if (Py_SIZE(a) < 0)
2363 sign = -sign;
2364 }
2365 }
2366 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002367}
2368
Guido van Rossum9bfef441993-03-29 10:43:31 +00002369static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002370long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002371{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002372 unsigned long x;
2373 Py_ssize_t i;
2374 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002375
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002376 /* This is designed so that Python ints and longs with the
2377 same value hash to the same value, otherwise comparisons
2378 of mapping keys will turn out weird */
2379 i = v->ob_size;
2380 sign = 1;
2381 x = 0;
2382 if (i < 0) {
2383 sign = -1;
2384 i = -(i);
2385 }
2386 /* The following loop produces a C unsigned long x such that x is
2387 congruent to the absolute value of v modulo ULONG_MAX. The
2388 resulting x is nonzero if and only if v is. */
2389 while (--i >= 0) {
2390 /* Force a native long #-bits (32 or 64) circular shift */
2391 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
2392 x += v->ob_digit[i];
2393 /* If the addition above overflowed we compensate by
2394 incrementing. This preserves the value modulo
2395 ULONG_MAX. */
2396 if (x < v->ob_digit[i])
2397 x++;
2398 }
2399 x = x * sign;
2400 if (x == (unsigned long)-1)
2401 x = (unsigned long)-2;
2402 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002403}
2404
2405
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002406/* Add the absolute values of two long integers. */
2407
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002408static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002409x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002410{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002411 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2412 PyLongObject *z;
2413 Py_ssize_t i;
2414 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002415
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002416 /* Ensure a is the larger of the two: */
2417 if (size_a < size_b) {
2418 { PyLongObject *temp = a; a = b; b = temp; }
2419 { Py_ssize_t size_temp = size_a;
Mark Dickinsonfda8d112010-05-09 20:30:29 +00002420 size_a = size_b;
2421 size_b = size_temp; }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002422 }
2423 z = _PyLong_New(size_a+1);
2424 if (z == NULL)
2425 return NULL;
2426 for (i = 0; i < size_b; ++i) {
2427 carry += a->ob_digit[i] + b->ob_digit[i];
2428 z->ob_digit[i] = carry & PyLong_MASK;
2429 carry >>= PyLong_SHIFT;
2430 }
2431 for (; i < size_a; ++i) {
2432 carry += a->ob_digit[i];
2433 z->ob_digit[i] = carry & PyLong_MASK;
2434 carry >>= PyLong_SHIFT;
2435 }
2436 z->ob_digit[i] = carry;
2437 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002438}
2439
2440/* Subtract the absolute values of two integers. */
2441
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002442static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002443x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002444{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002445 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2446 PyLongObject *z;
2447 Py_ssize_t i;
2448 int sign = 1;
2449 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002450
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002451 /* Ensure a is the larger of the two: */
2452 if (size_a < size_b) {
2453 sign = -1;
2454 { PyLongObject *temp = a; a = b; b = temp; }
2455 { Py_ssize_t size_temp = size_a;
Mark Dickinsonfda8d112010-05-09 20:30:29 +00002456 size_a = size_b;
2457 size_b = size_temp; }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002458 }
2459 else if (size_a == size_b) {
2460 /* Find highest digit where a and b differ: */
2461 i = size_a;
2462 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2463 ;
2464 if (i < 0)
2465 return _PyLong_New(0);
2466 if (a->ob_digit[i] < b->ob_digit[i]) {
2467 sign = -1;
2468 { PyLongObject *temp = a; a = b; b = temp; }
2469 }
2470 size_a = size_b = i+1;
2471 }
2472 z = _PyLong_New(size_a);
2473 if (z == NULL)
2474 return NULL;
2475 for (i = 0; i < size_b; ++i) {
2476 /* The following assumes unsigned arithmetic
2477 works module 2**N for some N>PyLong_SHIFT. */
2478 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2479 z->ob_digit[i] = borrow & PyLong_MASK;
2480 borrow >>= PyLong_SHIFT;
2481 borrow &= 1; /* Keep only one sign bit */
2482 }
2483 for (; i < size_a; ++i) {
2484 borrow = a->ob_digit[i] - borrow;
2485 z->ob_digit[i] = borrow & PyLong_MASK;
2486 borrow >>= PyLong_SHIFT;
2487 borrow &= 1; /* Keep only one sign bit */
2488 }
2489 assert(borrow == 0);
2490 if (sign < 0)
2491 z->ob_size = -(z->ob_size);
2492 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002493}
2494
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002495static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002496long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002497{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002498 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002499
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002500 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002501
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002502 if (a->ob_size < 0) {
2503 if (b->ob_size < 0) {
2504 z = x_add(a, b);
2505 if (z != NULL && z->ob_size != 0)
2506 z->ob_size = -(z->ob_size);
2507 }
2508 else
2509 z = x_sub(b, a);
2510 }
2511 else {
2512 if (b->ob_size < 0)
2513 z = x_sub(a, b);
2514 else
2515 z = x_add(a, b);
2516 }
2517 Py_DECREF(a);
2518 Py_DECREF(b);
2519 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002520}
2521
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002522static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002523long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002524{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002525 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002526
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002527 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002528
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002529 if (a->ob_size < 0) {
2530 if (b->ob_size < 0)
2531 z = x_sub(a, b);
2532 else
2533 z = x_add(a, b);
2534 if (z != NULL && z->ob_size != 0)
2535 z->ob_size = -(z->ob_size);
2536 }
2537 else {
2538 if (b->ob_size < 0)
2539 z = x_add(a, b);
2540 else
2541 z = x_sub(a, b);
2542 }
2543 Py_DECREF(a);
2544 Py_DECREF(b);
2545 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002546}
2547
Tim Peters5af4e6c2002-08-12 02:31:19 +00002548/* Grade school multiplication, ignoring the signs.
2549 * Returns the absolute value of the product, or NULL if error.
2550 */
2551static PyLongObject *
2552x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002553{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002554 PyLongObject *z;
2555 Py_ssize_t size_a = ABS(Py_SIZE(a));
2556 Py_ssize_t size_b = ABS(Py_SIZE(b));
2557 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002558
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002559 z = _PyLong_New(size_a + size_b);
2560 if (z == NULL)
2561 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002562
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002563 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2564 if (a == b) {
2565 /* Efficient squaring per HAC, Algorithm 14.16:
2566 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2567 * Gives slightly less than a 2x speedup when a == b,
2568 * via exploiting that each entry in the multiplication
2569 * pyramid appears twice (except for the size_a squares).
2570 */
2571 for (i = 0; i < size_a; ++i) {
2572 twodigits carry;
2573 twodigits f = a->ob_digit[i];
2574 digit *pz = z->ob_digit + (i << 1);
2575 digit *pa = a->ob_digit + i + 1;
2576 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002577
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002578 SIGCHECK({
Mark Dickinsonfda8d112010-05-09 20:30:29 +00002579 Py_DECREF(z);
2580 return NULL;
2581 })
Tim Peters0973b992004-08-29 22:16:50 +00002582
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002583 carry = *pz + f * f;
2584 *pz++ = (digit)(carry & PyLong_MASK);
2585 carry >>= PyLong_SHIFT;
2586 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002587
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002588 /* Now f is added in twice in each column of the
2589 * pyramid it appears. Same as adding f<<1 once.
2590 */
2591 f <<= 1;
2592 while (pa < paend) {
2593 carry += *pz + *pa++ * f;
2594 *pz++ = (digit)(carry & PyLong_MASK);
2595 carry >>= PyLong_SHIFT;
2596 assert(carry <= (PyLong_MASK << 1));
2597 }
2598 if (carry) {
2599 carry += *pz;
2600 *pz++ = (digit)(carry & PyLong_MASK);
2601 carry >>= PyLong_SHIFT;
2602 }
2603 if (carry)
2604 *pz += (digit)(carry & PyLong_MASK);
2605 assert((carry >> PyLong_SHIFT) == 0);
2606 }
2607 }
2608 else { /* a is not the same as b -- gradeschool long mult */
2609 for (i = 0; i < size_a; ++i) {
2610 twodigits carry = 0;
2611 twodigits f = a->ob_digit[i];
2612 digit *pz = z->ob_digit + i;
2613 digit *pb = b->ob_digit;
2614 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002615
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002616 SIGCHECK({
Mark Dickinsonfda8d112010-05-09 20:30:29 +00002617 Py_DECREF(z);
2618 return NULL;
2619 })
Tim Peters0973b992004-08-29 22:16:50 +00002620
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002621 while (pb < pbend) {
2622 carry += *pz + *pb++ * f;
2623 *pz++ = (digit)(carry & PyLong_MASK);
2624 carry >>= PyLong_SHIFT;
2625 assert(carry <= PyLong_MASK);
2626 }
2627 if (carry)
2628 *pz += (digit)(carry & PyLong_MASK);
2629 assert((carry >> PyLong_SHIFT) == 0);
2630 }
2631 }
2632 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002633}
2634
2635/* A helper for Karatsuba multiplication (k_mul).
2636 Takes a long "n" and an integer "size" representing the place to
2637 split, and sets low and high such that abs(n) == (high << size) + low,
2638 viewing the shift as being by digits. The sign bit is ignored, and
2639 the return values are >= 0.
2640 Returns 0 on success, -1 on failure.
2641*/
2642static int
Mark Dickinsonfda8d112010-05-09 20:30:29 +00002643kmul_split(PyLongObject *n,
2644 Py_ssize_t size,
2645 PyLongObject **high,
2646 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002647{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002648 PyLongObject *hi, *lo;
2649 Py_ssize_t size_lo, size_hi;
2650 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002651
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002652 size_lo = MIN(size_n, size);
2653 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002654
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002655 if ((hi = _PyLong_New(size_hi)) == NULL)
2656 return -1;
2657 if ((lo = _PyLong_New(size_lo)) == NULL) {
2658 Py_DECREF(hi);
2659 return -1;
2660 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002661
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002662 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2663 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002664
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002665 *high = long_normalize(hi);
2666 *low = long_normalize(lo);
2667 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002668}
2669
Tim Peters60004642002-08-12 22:01:34 +00002670static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2671
Tim Peters5af4e6c2002-08-12 02:31:19 +00002672/* Karatsuba multiplication. Ignores the input signs, and returns the
2673 * absolute value of the product (or NULL if error).
2674 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2675 */
2676static PyLongObject *
2677k_mul(PyLongObject *a, PyLongObject *b)
2678{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002679 Py_ssize_t asize = ABS(Py_SIZE(a));
2680 Py_ssize_t bsize = ABS(Py_SIZE(b));
2681 PyLongObject *ah = NULL;
2682 PyLongObject *al = NULL;
2683 PyLongObject *bh = NULL;
2684 PyLongObject *bl = NULL;
2685 PyLongObject *ret = NULL;
2686 PyLongObject *t1, *t2, *t3;
2687 Py_ssize_t shift; /* the number of digits we split off */
2688 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002689
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002690 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2691 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2692 * Then the original product is
2693 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2694 * By picking X to be a power of 2, "*X" is just shifting, and it's
2695 * been reduced to 3 multiplies on numbers half the size.
2696 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002697
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002698 /* We want to split based on the larger number; fiddle so that b
2699 * is largest.
2700 */
2701 if (asize > bsize) {
2702 t1 = a;
2703 a = b;
2704 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002705
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002706 i = asize;
2707 asize = bsize;
2708 bsize = i;
2709 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002710
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002711 /* Use gradeschool math when either number is too small. */
2712 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2713 if (asize <= i) {
2714 if (asize == 0)
2715 return _PyLong_New(0);
2716 else
2717 return x_mul(a, b);
2718 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002719
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002720 /* If a is small compared to b, splitting on b gives a degenerate
2721 * case with ah==0, and Karatsuba may be (even much) less efficient
2722 * than "grade school" then. However, we can still win, by viewing
2723 * b as a string of "big digits", each of width a->ob_size. That
2724 * leads to a sequence of balanced calls to k_mul.
2725 */
2726 if (2 * asize <= bsize)
2727 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002728
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002729 /* Split a & b into hi & lo pieces. */
2730 shift = bsize >> 1;
2731 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2732 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002733
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002734 if (a == b) {
2735 bh = ah;
2736 bl = al;
2737 Py_INCREF(bh);
2738 Py_INCREF(bl);
2739 }
2740 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002741
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002742 /* The plan:
2743 * 1. Allocate result space (asize + bsize digits: that's always
2744 * enough).
2745 * 2. Compute ah*bh, and copy into result at 2*shift.
2746 * 3. Compute al*bl, and copy into result at 0. Note that this
2747 * can't overlap with #2.
2748 * 4. Subtract al*bl from the result, starting at shift. This may
2749 * underflow (borrow out of the high digit), but we don't care:
2750 * we're effectively doing unsigned arithmetic mod
2751 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
2752 * borrows and carries out of the high digit can be ignored.
2753 * 5. Subtract ah*bh from the result, starting at shift.
2754 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2755 * at shift.
2756 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002757
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002758 /* 1. Allocate result space. */
2759 ret = _PyLong_New(asize + bsize);
2760 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002761#ifdef Py_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002762 /* Fill with trash, to catch reference to uninitialized digits. */
2763 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002764#endif
Tim Peters44121a62002-08-12 06:17:58 +00002765
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002766 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2767 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2768 assert(Py_SIZE(t1) >= 0);
2769 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
2770 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2771 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002772
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002773 /* Zero-out the digits higher than the ah*bh copy. */
2774 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
2775 if (i)
2776 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
2777 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002778
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002779 /* 3. t2 <- al*bl, and copy into the low digits. */
2780 if ((t2 = k_mul(al, bl)) == NULL) {
2781 Py_DECREF(t1);
2782 goto fail;
2783 }
2784 assert(Py_SIZE(t2) >= 0);
2785 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2786 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002787
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002788 /* Zero out remaining digits. */
2789 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
2790 if (i)
2791 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002792
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002793 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2794 * because it's fresher in cache.
2795 */
2796 i = Py_SIZE(ret) - shift; /* # digits after shift */
2797 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
2798 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002799
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002800 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
2801 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00002802
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002803 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
2804 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2805 Py_DECREF(ah);
2806 Py_DECREF(al);
2807 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002808
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002809 if (a == b) {
2810 t2 = t1;
2811 Py_INCREF(t2);
2812 }
2813 else if ((t2 = x_add(bh, bl)) == NULL) {
2814 Py_DECREF(t1);
2815 goto fail;
2816 }
2817 Py_DECREF(bh);
2818 Py_DECREF(bl);
2819 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002820
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002821 t3 = k_mul(t1, t2);
2822 Py_DECREF(t1);
2823 Py_DECREF(t2);
2824 if (t3 == NULL) goto fail;
2825 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002826
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002827 /* Add t3. It's not obvious why we can't run out of room here.
2828 * See the (*) comment after this function.
2829 */
2830 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
2831 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002832
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002833 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002834
Mark Dickinsonfda8d112010-05-09 20:30:29 +00002835 fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002836 Py_XDECREF(ret);
2837 Py_XDECREF(ah);
2838 Py_XDECREF(al);
2839 Py_XDECREF(bh);
2840 Py_XDECREF(bl);
2841 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002842}
2843
Tim Petersd6974a52002-08-13 20:37:51 +00002844/* (*) Why adding t3 can't "run out of room" above.
2845
Tim Petersab86c2b2002-08-15 20:06:00 +00002846Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2847to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002848
Tim Petersab86c2b2002-08-15 20:06:00 +000028491. For any integer i, i = c(i/2) + f(i/2). In particular,
2850 bsize = c(bsize/2) + f(bsize/2).
28512. shift = f(bsize/2)
28523. asize <= bsize
28534. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2854 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002855
Tim Petersab86c2b2002-08-15 20:06:00 +00002856We allocated asize + bsize result digits, and add t3 into them at an offset
2857of shift. This leaves asize+bsize-shift allocated digit positions for t3
2858to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2859asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002860
Tim Petersab86c2b2002-08-15 20:06:00 +00002861bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2862at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002863
Tim Petersab86c2b2002-08-15 20:06:00 +00002864If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2865digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2866most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002867
Tim Petersab86c2b2002-08-15 20:06:00 +00002868The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002869
Tim Petersab86c2b2002-08-15 20:06:00 +00002870 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002871
Tim Petersab86c2b2002-08-15 20:06:00 +00002872and we have asize + c(bsize/2) available digit positions. We need to show
2873this is always enough. An instance of c(bsize/2) cancels out in both, so
2874the question reduces to whether asize digits is enough to hold
2875(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2876then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2877asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002878digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002879asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002880c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2881is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2882bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002883
Tim Peters48d52c02002-08-14 17:07:32 +00002884Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2885clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2886ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002887*/
2888
Tim Peters60004642002-08-12 22:01:34 +00002889/* b has at least twice the digits of a, and a is big enough that Karatsuba
2890 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2891 * of slices, each with a->ob_size digits, and multiply the slices by a,
2892 * one at a time. This gives k_mul balanced inputs to work with, and is
2893 * also cache-friendly (we compute one double-width slice of the result
2894 * at a time, then move on, never bactracking except for the helpful
2895 * single-width slice overlap between successive partial sums).
2896 */
2897static PyLongObject *
2898k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2899{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002900 const Py_ssize_t asize = ABS(Py_SIZE(a));
2901 Py_ssize_t bsize = ABS(Py_SIZE(b));
2902 Py_ssize_t nbdone; /* # of b digits already multiplied */
2903 PyLongObject *ret;
2904 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00002905
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002906 assert(asize > KARATSUBA_CUTOFF);
2907 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00002908
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002909 /* Allocate result space, and zero it out. */
2910 ret = _PyLong_New(asize + bsize);
2911 if (ret == NULL)
2912 return NULL;
2913 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002914
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002915 /* Successive slices of b are copied into bslice. */
2916 bslice = _PyLong_New(asize);
2917 if (bslice == NULL)
2918 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00002919
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002920 nbdone = 0;
2921 while (bsize > 0) {
2922 PyLongObject *product;
2923 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002924
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002925 /* Multiply the next slice of b by a. */
2926 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2927 nbtouse * sizeof(digit));
2928 Py_SIZE(bslice) = nbtouse;
2929 product = k_mul(a, bslice);
2930 if (product == NULL)
2931 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00002932
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002933 /* Add into result. */
2934 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2935 product->ob_digit, Py_SIZE(product));
2936 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00002937
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002938 bsize -= nbtouse;
2939 nbdone += nbtouse;
2940 }
Tim Peters60004642002-08-12 22:01:34 +00002941
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002942 Py_DECREF(bslice);
2943 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00002944
Mark Dickinsonfda8d112010-05-09 20:30:29 +00002945 fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002946 Py_DECREF(ret);
2947 Py_XDECREF(bslice);
2948 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00002949}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002950
2951static PyObject *
2952long_mul(PyLongObject *v, PyLongObject *w)
2953{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002954 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002955
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002956 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
2957 Py_INCREF(Py_NotImplemented);
2958 return Py_NotImplemented;
2959 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002960
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002961 z = k_mul(a, b);
2962 /* Negate if exactly one of the inputs is negative. */
2963 if (((a->ob_size ^ b->ob_size) < 0) && z)
2964 z->ob_size = -(z->ob_size);
2965 Py_DECREF(a);
2966 Py_DECREF(b);
2967 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002968}
2969
Guido van Rossume32e0141992-01-19 16:31:05 +00002970/* The / and % operators are now defined in terms of divmod().
2971 The expression a mod b has the value a - b*floor(a/b).
2972 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002973 |a| by |b|, with the sign of a. This is also expressed
2974 as a - b*trunc(a/b), if trunc truncates towards zero.
2975 Some examples:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002976 a b a rem b a mod b
2977 13 10 3 3
2978 -13 10 -3 7
2979 13 -10 3 -7
2980 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002981 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002982 have different signs. We then subtract one from the 'div'
2983 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002984
Tim Peters47e52ee2004-08-30 02:44:38 +00002985/* Compute
2986 * *pdiv, *pmod = divmod(v, w)
2987 * NULL can be passed for pdiv or pmod, in which case that part of
2988 * the result is simply thrown away. The caller owns a reference to
2989 * each of these it requests (does not pass NULL for).
2990 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002991static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002992l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002993 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002994{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002995 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002996
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002997 if (long_divrem(v, w, &div, &mod) < 0)
2998 return -1;
2999 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3000 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3001 PyLongObject *temp;
3002 PyLongObject *one;
3003 temp = (PyLongObject *) long_add(mod, w);
3004 Py_DECREF(mod);
3005 mod = temp;
3006 if (mod == NULL) {
3007 Py_DECREF(div);
3008 return -1;
3009 }
3010 one = (PyLongObject *) PyLong_FromLong(1L);
3011 if (one == NULL ||
3012 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3013 Py_DECREF(mod);
3014 Py_DECREF(div);
3015 Py_XDECREF(one);
3016 return -1;
3017 }
3018 Py_DECREF(one);
3019 Py_DECREF(div);
3020 div = temp;
3021 }
3022 if (pdiv != NULL)
3023 *pdiv = div;
3024 else
3025 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003026
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003027 if (pmod != NULL)
3028 *pmod = mod;
3029 else
3030 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003031
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003032 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003033}
3034
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003035static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003036long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00003037{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003038 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003039
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003040 CONVERT_BINOP(v, w, &a, &b);
3041 if (l_divmod(a, b, &div, NULL) < 0)
3042 div = NULL;
3043 Py_DECREF(a);
3044 Py_DECREF(b);
3045 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003046}
3047
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003048static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00003049long_classic_div(PyObject *v, PyObject *w)
3050{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003051 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00003052
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003053 CONVERT_BINOP(v, w, &a, &b);
3054 if (Py_DivisionWarningFlag &&
3055 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
3056 div = NULL;
3057 else if (l_divmod(a, b, &div, NULL) < 0)
3058 div = NULL;
3059 Py_DECREF(a);
3060 Py_DECREF(b);
3061 return (PyObject *)div;
Guido van Rossum393661d2001-08-31 17:40:15 +00003062}
3063
Mark Dickinson46572832009-12-27 14:55:57 +00003064/* PyLong/PyLong -> float, with correctly rounded result. */
3065
3066#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3067#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3068
Guido van Rossum393661d2001-08-31 17:40:15 +00003069static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00003070long_true_divide(PyObject *v, PyObject *w)
3071{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003072 PyLongObject *a, *b, *x;
3073 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3074 digit mask, low;
3075 int inexact, negate, a_is_small, b_is_small;
3076 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003077
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003078 CONVERT_BINOP(v, w, &a, &b);
Tim Peterse2a60002001-09-04 06:17:36 +00003079
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003080 /*
3081 Method in a nutshell:
Mark Dickinson46572832009-12-27 14:55:57 +00003082
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003083 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3084 1. choose a suitable integer 'shift'
3085 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3086 3. adjust x for correct rounding
3087 4. convert x to a double dx with the same value
3088 5. return ldexp(dx, shift).
Mark Dickinson46572832009-12-27 14:55:57 +00003089
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003090 In more detail:
Mark Dickinson46572832009-12-27 14:55:57 +00003091
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003092 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3093 returns either 0.0 or -0.0, depending on the sign of b. For a and
3094 b both nonzero, ignore signs of a and b, and add the sign back in
3095 at the end. Now write a_bits and b_bits for the bit lengths of a
3096 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3097 for b). Then
Mark Dickinson46572832009-12-27 14:55:57 +00003098
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003099 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinson46572832009-12-27 14:55:57 +00003100
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003101 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3102 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3103 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3104 the way, we can assume that
Mark Dickinson46572832009-12-27 14:55:57 +00003105
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003106 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinson46572832009-12-27 14:55:57 +00003107
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003108 1. The integer 'shift' is chosen so that x has the right number of
3109 bits for a double, plus two or three extra bits that will be used
3110 in the rounding decisions. Writing a_bits and b_bits for the
3111 number of significant bits in a and b respectively, a
3112 straightforward formula for shift is:
Mark Dickinson46572832009-12-27 14:55:57 +00003113
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003114 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinson46572832009-12-27 14:55:57 +00003115
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003116 This is fine in the usual case, but if a/b is smaller than the
3117 smallest normal float then it can lead to double rounding on an
3118 IEEE 754 platform, giving incorrectly rounded results. So we
3119 adjust the formula slightly. The actual formula used is:
Mark Dickinson46572832009-12-27 14:55:57 +00003120
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003121 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinson46572832009-12-27 14:55:57 +00003122
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003123 2. The quantity x is computed by first shifting a (left -shift bits
3124 if shift <= 0, right shift bits if shift > 0) and then dividing by
3125 b. For both the shift and the division, we keep track of whether
3126 the result is inexact, in a flag 'inexact'; this information is
3127 needed at the rounding stage.
Mark Dickinson46572832009-12-27 14:55:57 +00003128
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003129 With the choice of shift above, together with our assumption that
3130 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3131 that x >= 1.
Mark Dickinson46572832009-12-27 14:55:57 +00003132
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003133 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3134 this with an exactly representable float of the form
Mark Dickinson46572832009-12-27 14:55:57 +00003135
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003136 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinson46572832009-12-27 14:55:57 +00003137
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003138 For float representability, we need x/2**extra_bits <
3139 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3140 DBL_MANT_DIG. This translates to the condition:
Mark Dickinson46572832009-12-27 14:55:57 +00003141
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003142 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinson46572832009-12-27 14:55:57 +00003143
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003144 To round, we just modify the bottom digit of x in-place; this can
3145 end up giving a digit with value > PyLONG_MASK, but that's not a
3146 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinson46572832009-12-27 14:55:57 +00003147
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003148 With the original choices for shift above, extra_bits will always
3149 be 2 or 3. Then rounding under the round-half-to-even rule, we
3150 round up iff the most significant of the extra bits is 1, and
3151 either: (a) the computation of x in step 2 had an inexact result,
3152 or (b) at least one other of the extra bits is 1, or (c) the least
3153 significant bit of x (above those to be rounded) is 1.
Mark Dickinson46572832009-12-27 14:55:57 +00003154
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003155 4. Conversion to a double is straightforward; all floating-point
3156 operations involved in the conversion are exact, so there's no
3157 danger of rounding errors.
Mark Dickinson46572832009-12-27 14:55:57 +00003158
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003159 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3160 The result will always be exactly representable as a double, except
3161 in the case that it overflows. To avoid dependence on the exact
3162 behaviour of ldexp on overflow, we check for overflow before
3163 applying ldexp. The result of ldexp is adjusted for sign before
3164 returning.
3165 */
Mark Dickinson46572832009-12-27 14:55:57 +00003166
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003167 /* Reduce to case where a and b are both positive. */
3168 a_size = ABS(Py_SIZE(a));
3169 b_size = ABS(Py_SIZE(b));
3170 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3171 if (b_size == 0) {
3172 PyErr_SetString(PyExc_ZeroDivisionError,
3173 "division by zero");
3174 goto error;
3175 }
3176 if (a_size == 0)
3177 goto underflow_or_zero;
Mark Dickinson46572832009-12-27 14:55:57 +00003178
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003179 /* Fast path for a and b small (exactly representable in a double).
3180 Relies on floating-point division being correctly rounded; results
3181 may be subject to double rounding on x86 machines that operate with
3182 the x87 FPU set to 64-bit precision. */
3183 a_is_small = a_size <= MANT_DIG_DIGITS ||
3184 (a_size == MANT_DIG_DIGITS+1 &&
3185 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3186 b_is_small = b_size <= MANT_DIG_DIGITS ||
3187 (b_size == MANT_DIG_DIGITS+1 &&
3188 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3189 if (a_is_small && b_is_small) {
3190 double da, db;
3191 da = a->ob_digit[--a_size];
3192 while (a_size > 0)
3193 da = da * PyLong_BASE + a->ob_digit[--a_size];
3194 db = b->ob_digit[--b_size];
3195 while (b_size > 0)
3196 db = db * PyLong_BASE + b->ob_digit[--b_size];
3197 result = da / db;
3198 goto success;
3199 }
Tim Peterse2a60002001-09-04 06:17:36 +00003200
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003201 /* Catch obvious cases of underflow and overflow */
3202 diff = a_size - b_size;
3203 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3204 /* Extreme overflow */
3205 goto overflow;
3206 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3207 /* Extreme underflow */
3208 goto underflow_or_zero;
3209 /* Next line is now safe from overflowing a Py_ssize_t */
3210 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3211 bits_in_digit(b->ob_digit[b_size - 1]);
3212 /* Now diff = a_bits - b_bits. */
3213 if (diff > DBL_MAX_EXP)
3214 goto overflow;
3215 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3216 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003217
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003218 /* Choose value for shift; see comments for step 1 above. */
3219 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinson46572832009-12-27 14:55:57 +00003220
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003221 inexact = 0;
Mark Dickinson46572832009-12-27 14:55:57 +00003222
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003223 /* x = abs(a * 2**-shift) */
3224 if (shift <= 0) {
3225 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3226 digit rem;
3227 /* x = a << -shift */
3228 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3229 /* In practice, it's probably impossible to end up
3230 here. Both a and b would have to be enormous,
3231 using close to SIZE_T_MAX bytes of memory each. */
3232 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonfda8d112010-05-09 20:30:29 +00003233 "intermediate overflow during division");
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003234 goto error;
3235 }
3236 x = _PyLong_New(a_size + shift_digits + 1);
3237 if (x == NULL)
3238 goto error;
3239 for (i = 0; i < shift_digits; i++)
3240 x->ob_digit[i] = 0;
3241 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3242 a_size, -shift % PyLong_SHIFT);
3243 x->ob_digit[a_size + shift_digits] = rem;
3244 }
3245 else {
3246 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3247 digit rem;
3248 /* x = a >> shift */
3249 assert(a_size >= shift_digits);
3250 x = _PyLong_New(a_size - shift_digits);
3251 if (x == NULL)
3252 goto error;
3253 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3254 a_size - shift_digits, shift % PyLong_SHIFT);
3255 /* set inexact if any of the bits shifted out is nonzero */
3256 if (rem)
3257 inexact = 1;
3258 while (!inexact && shift_digits > 0)
3259 if (a->ob_digit[--shift_digits])
3260 inexact = 1;
3261 }
3262 long_normalize(x);
3263 x_size = Py_SIZE(x);
Mark Dickinson46572832009-12-27 14:55:57 +00003264
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003265 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3266 reference to x, so it's safe to modify it in-place. */
3267 if (b_size == 1) {
3268 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3269 b->ob_digit[0]);
3270 long_normalize(x);
3271 if (rem)
3272 inexact = 1;
3273 }
3274 else {
3275 PyLongObject *div, *rem;
3276 div = x_divrem(x, b, &rem);
3277 Py_DECREF(x);
3278 x = div;
3279 if (x == NULL)
3280 goto error;
3281 if (Py_SIZE(rem))
3282 inexact = 1;
3283 Py_DECREF(rem);
3284 }
3285 x_size = ABS(Py_SIZE(x));
3286 assert(x_size > 0); /* result of division is never zero */
3287 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinson46572832009-12-27 14:55:57 +00003288
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003289 /* The number of extra bits that have to be rounded away. */
3290 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3291 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinson46572832009-12-27 14:55:57 +00003292
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003293 /* Round by directly modifying the low digit of x. */
3294 mask = (digit)1 << (extra_bits - 1);
3295 low = x->ob_digit[0] | inexact;
3296 if (low & mask && low & (3*mask-1))
3297 low += mask;
3298 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinson46572832009-12-27 14:55:57 +00003299
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003300 /* Convert x to a double dx; the conversion is exact. */
3301 dx = x->ob_digit[--x_size];
3302 while (x_size > 0)
3303 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3304 Py_DECREF(x);
Mark Dickinson46572832009-12-27 14:55:57 +00003305
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003306 /* Check whether ldexp result will overflow a double. */
3307 if (shift + x_bits >= DBL_MAX_EXP &&
3308 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3309 goto overflow;
3310 result = ldexp(dx, (int)shift);
Mark Dickinson46572832009-12-27 14:55:57 +00003311
3312 success:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003313 Py_DECREF(a);
3314 Py_DECREF(b);
3315 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinson46572832009-12-27 14:55:57 +00003316
3317 underflow_or_zero:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003318 Py_DECREF(a);
3319 Py_DECREF(b);
3320 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinson46572832009-12-27 14:55:57 +00003321
3322 overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003323 PyErr_SetString(PyExc_OverflowError,
3324 "integer division result too large for a float");
Mark Dickinson46572832009-12-27 14:55:57 +00003325 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003326 Py_DECREF(a);
3327 Py_DECREF(b);
3328 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003329}
3330
3331static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003332long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00003333{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003334 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003335
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003336 CONVERT_BINOP(v, w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003337
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003338 if (l_divmod(a, b, NULL, &mod) < 0)
3339 mod = NULL;
3340 Py_DECREF(a);
3341 Py_DECREF(b);
3342 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003343}
3344
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003345static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003346long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003347{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003348 PyLongObject *a, *b, *div, *mod;
3349 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003350
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003351 CONVERT_BINOP(v, w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003352
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003353 if (l_divmod(a, b, &div, &mod) < 0) {
3354 Py_DECREF(a);
3355 Py_DECREF(b);
3356 return NULL;
3357 }
3358 z = PyTuple_New(2);
3359 if (z != NULL) {
3360 PyTuple_SetItem(z, 0, (PyObject *) div);
3361 PyTuple_SetItem(z, 1, (PyObject *) mod);
3362 }
3363 else {
3364 Py_DECREF(div);
3365 Py_DECREF(mod);
3366 }
3367 Py_DECREF(a);
3368 Py_DECREF(b);
3369 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003370}
3371
Tim Peters47e52ee2004-08-30 02:44:38 +00003372/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003373static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003374long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003375{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003376 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3377 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003378
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003379 PyLongObject *z = NULL; /* accumulated result */
3380 Py_ssize_t i, j, k; /* counters */
3381 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003382
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003383 /* 5-ary values. If the exponent is large enough, table is
3384 * precomputed so that table[i] == a**i % c for i in range(32).
3385 */
3386 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3387 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003388
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003389 /* a, b, c = v, w, x */
3390 CONVERT_BINOP(v, w, &a, &b);
3391 if (PyLong_Check(x)) {
3392 c = (PyLongObject *)x;
3393 Py_INCREF(x);
3394 }
3395 else if (PyInt_Check(x)) {
3396 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
3397 if (c == NULL)
3398 goto Error;
3399 }
3400 else if (x == Py_None)
3401 c = NULL;
3402 else {
3403 Py_DECREF(a);
3404 Py_DECREF(b);
3405 Py_INCREF(Py_NotImplemented);
3406 return Py_NotImplemented;
3407 }
Tim Peters4c483c42001-09-05 06:24:58 +00003408
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003409 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3410 if (c) {
3411 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinsonfda8d112010-05-09 20:30:29 +00003412 "cannot be negative when 3rd argument specified");
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003413 goto Error;
3414 }
3415 else {
3416 /* else return a float. This works because we know
3417 that this calls float_pow() which converts its
3418 arguments to double. */
3419 Py_DECREF(a);
3420 Py_DECREF(b);
3421 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3422 }
3423 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003424
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003425 if (c) {
3426 /* if modulus == 0:
3427 raise ValueError() */
3428 if (Py_SIZE(c) == 0) {
3429 PyErr_SetString(PyExc_ValueError,
3430 "pow() 3rd argument cannot be 0");
3431 goto Error;
3432 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003433
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003434 /* if modulus < 0:
3435 negativeOutput = True
3436 modulus = -modulus */
3437 if (Py_SIZE(c) < 0) {
3438 negativeOutput = 1;
3439 temp = (PyLongObject *)_PyLong_Copy(c);
3440 if (temp == NULL)
3441 goto Error;
3442 Py_DECREF(c);
3443 c = temp;
3444 temp = NULL;
3445 c->ob_size = - c->ob_size;
3446 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003447
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003448 /* if modulus == 1:
3449 return 0 */
3450 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3451 z = (PyLongObject *)PyLong_FromLong(0L);
3452 goto Done;
3453 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003454
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003455 /* if base < 0:
3456 base = base % modulus
3457 Having the base positive just makes things easier. */
3458 if (Py_SIZE(a) < 0) {
3459 if (l_divmod(a, c, NULL, &temp) < 0)
3460 goto Error;
3461 Py_DECREF(a);
3462 a = temp;
3463 temp = NULL;
3464 }
3465 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003466
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003467 /* At this point a, b, and c are guaranteed non-negative UNLESS
3468 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003469
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003470 z = (PyLongObject *)PyLong_FromLong(1L);
3471 if (z == NULL)
3472 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003473
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003474 /* Perform a modular reduction, X = X % c, but leave X alone if c
3475 * is NULL.
3476 */
3477#define REDUCE(X) \
3478 if (c != NULL) { \
3479 if (l_divmod(X, c, NULL, &temp) < 0) \
3480 goto Error; \
3481 Py_XDECREF(X); \
3482 X = temp; \
3483 temp = NULL; \
3484 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003485
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003486 /* Multiply two values, then reduce the result:
3487 result = X*Y % c. If c is NULL, skip the mod. */
3488#define MULT(X, Y, result) \
3489{ \
3490 temp = (PyLongObject *)long_mul(X, Y); \
3491 if (temp == NULL) \
3492 goto Error; \
3493 Py_XDECREF(result); \
3494 result = temp; \
3495 temp = NULL; \
3496 REDUCE(result) \
Tim Peters47e52ee2004-08-30 02:44:38 +00003497}
3498
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003499 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3500 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3501 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3502 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3503 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003504
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003505 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
3506 MULT(z, z, z)
3507 if (bi & j)
3508 MULT(z, a, z)
3509 }
3510 }
3511 }
3512 else {
3513 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3514 Py_INCREF(z); /* still holds 1L */
3515 table[0] = z;
3516 for (i = 1; i < 32; ++i)
3517 MULT(table[i-1], a, table[i])
Tim Peters47e52ee2004-08-30 02:44:38 +00003518
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003519 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3520 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003521
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003522 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3523 const int index = (bi >> j) & 0x1f;
3524 for (k = 0; k < 5; ++k)
3525 MULT(z, z, z)
3526 if (index)
3527 MULT(z, table[index], z)
3528 }
3529 }
3530 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003532 if (negativeOutput && (Py_SIZE(z) != 0)) {
3533 temp = (PyLongObject *)long_sub(z, c);
3534 if (temp == NULL)
3535 goto Error;
3536 Py_DECREF(z);
3537 z = temp;
3538 temp = NULL;
3539 }
3540 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003541
Mark Dickinsonfda8d112010-05-09 20:30:29 +00003542 Error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003543 if (z != NULL) {
3544 Py_DECREF(z);
3545 z = NULL;
3546 }
3547 /* fall through */
Mark Dickinsonfda8d112010-05-09 20:30:29 +00003548 Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003549 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3550 for (i = 0; i < 32; ++i)
3551 Py_XDECREF(table[i]);
3552 }
3553 Py_DECREF(a);
3554 Py_DECREF(b);
3555 Py_XDECREF(c);
3556 Py_XDECREF(temp);
3557 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003558}
3559
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003560static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003561long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003562{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003563 /* Implement ~x as -(x+1) */
3564 PyLongObject *x;
3565 PyLongObject *w;
3566 w = (PyLongObject *)PyLong_FromLong(1L);
3567 if (w == NULL)
3568 return NULL;
3569 x = (PyLongObject *) long_add(v, w);
3570 Py_DECREF(w);
3571 if (x == NULL)
3572 return NULL;
3573 Py_SIZE(x) = -(Py_SIZE(x));
3574 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003575}
3576
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003577static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003578long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003579{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003580 PyLongObject *z;
3581 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
3582 /* -0 == 0 */
3583 Py_INCREF(v);
3584 return (PyObject *) v;
3585 }
3586 z = (PyLongObject *)_PyLong_Copy(v);
3587 if (z != NULL)
3588 z->ob_size = -(v->ob_size);
3589 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003590}
3591
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003592static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003593long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003594{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003595 if (v->ob_size < 0)
3596 return long_neg(v);
3597 else
3598 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003599}
3600
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003601static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003602long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003603{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003604 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003605}
3606
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003607static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003608long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003609{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003610 PyLongObject *a, *b;
3611 PyLongObject *z = NULL;
3612 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3613 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003614
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003615 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003616
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003617 if (Py_SIZE(a) < 0) {
3618 /* Right shifting negative numbers is harder */
3619 PyLongObject *a1, *a2;
3620 a1 = (PyLongObject *) long_invert(a);
3621 if (a1 == NULL)
3622 goto rshift_error;
3623 a2 = (PyLongObject *) long_rshift(a1, b);
3624 Py_DECREF(a1);
3625 if (a2 == NULL)
3626 goto rshift_error;
3627 z = (PyLongObject *) long_invert(a2);
3628 Py_DECREF(a2);
3629 }
3630 else {
3631 shiftby = PyLong_AsSsize_t((PyObject *)b);
3632 if (shiftby == -1L && PyErr_Occurred())
3633 goto rshift_error;
3634 if (shiftby < 0) {
3635 PyErr_SetString(PyExc_ValueError,
3636 "negative shift count");
3637 goto rshift_error;
3638 }
3639 wordshift = shiftby / PyLong_SHIFT;
3640 newsize = ABS(Py_SIZE(a)) - wordshift;
3641 if (newsize <= 0) {
3642 z = _PyLong_New(0);
3643 Py_DECREF(a);
3644 Py_DECREF(b);
3645 return (PyObject *)z;
3646 }
3647 loshift = shiftby % PyLong_SHIFT;
3648 hishift = PyLong_SHIFT - loshift;
3649 lomask = ((digit)1 << hishift) - 1;
3650 himask = PyLong_MASK ^ lomask;
3651 z = _PyLong_New(newsize);
3652 if (z == NULL)
3653 goto rshift_error;
3654 if (Py_SIZE(a) < 0)
3655 Py_SIZE(z) = -(Py_SIZE(z));
3656 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3657 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3658 if (i+1 < newsize)
Mark Dickinsonfda8d112010-05-09 20:30:29 +00003659 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003660 }
3661 z = long_normalize(z);
3662 }
Mark Dickinsonfda8d112010-05-09 20:30:29 +00003663 rshift_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003664 Py_DECREF(a);
3665 Py_DECREF(b);
3666 return (PyObject *) z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003667
Guido van Rossumc6913e71991-11-19 20:26:46 +00003668}
3669
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003670static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003671long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003672{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003673 /* This version due to Tim Peters */
3674 PyLongObject *a, *b;
3675 PyLongObject *z = NULL;
3676 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3677 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003678
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003679 CONVERT_BINOP(v, w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003680
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003681 shiftby = PyLong_AsSsize_t((PyObject *)b);
3682 if (shiftby == -1L && PyErr_Occurred())
3683 goto lshift_error;
3684 if (shiftby < 0) {
3685 PyErr_SetString(PyExc_ValueError, "negative shift count");
3686 goto lshift_error;
3687 }
3688 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3689 wordshift = shiftby / PyLong_SHIFT;
3690 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003691
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003692 oldsize = ABS(a->ob_size);
3693 newsize = oldsize + wordshift;
3694 if (remshift)
3695 ++newsize;
3696 z = _PyLong_New(newsize);
3697 if (z == NULL)
3698 goto lshift_error;
3699 if (a->ob_size < 0)
3700 z->ob_size = -(z->ob_size);
3701 for (i = 0; i < wordshift; i++)
3702 z->ob_digit[i] = 0;
3703 accum = 0;
3704 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3705 accum |= (twodigits)a->ob_digit[j] << remshift;
3706 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3707 accum >>= PyLong_SHIFT;
3708 }
3709 if (remshift)
3710 z->ob_digit[newsize-1] = (digit)accum;
3711 else
3712 assert(!accum);
3713 z = long_normalize(z);
Mark Dickinsonfda8d112010-05-09 20:30:29 +00003714 lshift_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003715 Py_DECREF(a);
3716 Py_DECREF(b);
3717 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003718}
3719
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003720/* Compute two's complement of digit vector a[0:m], writing result to
3721 z[0:m]. The digit vector a need not be normalized, but should not
3722 be entirely zero. a and z may point to the same digit vector. */
3723
3724static void
3725v_complement(digit *z, digit *a, Py_ssize_t m)
3726{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003727 Py_ssize_t i;
3728 digit carry = 1;
3729 for (i = 0; i < m; ++i) {
3730 carry += a[i] ^ PyLong_MASK;
3731 z[i] = carry & PyLong_MASK;
3732 carry >>= PyLong_SHIFT;
3733 }
3734 assert(carry == 0);
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003735}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003736
3737/* Bitwise and/xor/or operations */
3738
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003739static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003740long_bitwise(PyLongObject *a,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003741 int op, /* '&', '|', '^' */
Mark Dickinsonfda8d112010-05-09 20:30:29 +00003742 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003743{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003744 int nega, negb, negz;
3745 Py_ssize_t size_a, size_b, size_z, i;
3746 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003747
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003748 /* Bitwise operations for negative numbers operate as though
3749 on a two's complement representation. So convert arguments
3750 from sign-magnitude to two's complement, and convert the
3751 result back to sign-magnitude at the end. */
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003752
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003753 /* If a is negative, replace it by its two's complement. */
3754 size_a = ABS(Py_SIZE(a));
3755 nega = Py_SIZE(a) < 0;
3756 if (nega) {
3757 z = _PyLong_New(size_a);
3758 if (z == NULL)
3759 return NULL;
3760 v_complement(z->ob_digit, a->ob_digit, size_a);
3761 a = z;
3762 }
3763 else
3764 /* Keep reference count consistent. */
3765 Py_INCREF(a);
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003766
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003767 /* Same for b. */
3768 size_b = ABS(Py_SIZE(b));
3769 negb = Py_SIZE(b) < 0;
3770 if (negb) {
3771 z = _PyLong_New(size_b);
3772 if (z == NULL) {
3773 Py_DECREF(a);
3774 return NULL;
3775 }
3776 v_complement(z->ob_digit, b->ob_digit, size_b);
3777 b = z;
3778 }
3779 else
3780 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003781
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003782 /* Swap a and b if necessary to ensure size_a >= size_b. */
3783 if (size_a < size_b) {
3784 z = a; a = b; b = z;
3785 size_z = size_a; size_a = size_b; size_b = size_z;
3786 negz = nega; nega = negb; negb = negz;
3787 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003788
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003789 /* JRH: The original logic here was to allocate the result value (z)
3790 as the longer of the two operands. However, there are some cases
3791 where the result is guaranteed to be shorter than that: AND of two
3792 positives, OR of two negatives: use the shorter number. AND with
3793 mixed signs: use the positive number. OR with mixed signs: use the
3794 negative number.
3795 */
3796 switch (op) {
3797 case '^':
3798 negz = nega ^ negb;
3799 size_z = size_a;
3800 break;
3801 case '&':
3802 negz = nega & negb;
3803 size_z = negb ? size_a : size_b;
3804 break;
3805 case '|':
3806 negz = nega | negb;
3807 size_z = negb ? size_b : size_a;
3808 break;
3809 default:
3810 PyErr_BadArgument();
3811 return NULL;
3812 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003813
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003814 /* We allow an extra digit if z is negative, to make sure that
3815 the final two's complement of z doesn't overflow. */
3816 z = _PyLong_New(size_z + negz);
3817 if (z == NULL) {
3818 Py_DECREF(a);
3819 Py_DECREF(b);
3820 return NULL;
3821 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003822
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003823 /* Compute digits for overlap of a and b. */
3824 switch(op) {
3825 case '&':
3826 for (i = 0; i < size_b; ++i)
3827 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
3828 break;
3829 case '|':
3830 for (i = 0; i < size_b; ++i)
3831 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
3832 break;
3833 case '^':
3834 for (i = 0; i < size_b; ++i)
3835 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
3836 break;
3837 default:
3838 PyErr_BadArgument();
3839 return NULL;
3840 }
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003841
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003842 /* Copy any remaining digits of a, inverting if necessary. */
3843 if (op == '^' && negb)
3844 for (; i < size_z; ++i)
3845 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
3846 else if (i < size_z)
3847 memcpy(&z->ob_digit[i], &a->ob_digit[i],
3848 (size_z-i)*sizeof(digit));
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003849
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003850 /* Complement result if negative. */
3851 if (negz) {
3852 Py_SIZE(z) = -(Py_SIZE(z));
3853 z->ob_digit[size_z] = PyLong_MASK;
3854 v_complement(z->ob_digit, z->ob_digit, size_z+1);
3855 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003856
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003857 Py_DECREF(a);
3858 Py_DECREF(b);
3859 return (PyObject *)long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003860}
3861
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003862static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003863long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003864{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003865 PyLongObject *a, *b;
3866 PyObject *c;
3867 CONVERT_BINOP(v, w, &a, &b);
3868 c = long_bitwise(a, '&', b);
3869 Py_DECREF(a);
3870 Py_DECREF(b);
3871 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003872}
3873
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003874static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003875long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003876{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003877 PyLongObject *a, *b;
3878 PyObject *c;
3879 CONVERT_BINOP(v, w, &a, &b);
3880 c = long_bitwise(a, '^', b);
3881 Py_DECREF(a);
3882 Py_DECREF(b);
3883 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003884}
3885
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003886static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003887long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003888{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003889 PyLongObject *a, *b;
3890 PyObject *c;
3891 CONVERT_BINOP(v, w, &a, &b);
3892 c = long_bitwise(a, '|', b);
3893 Py_DECREF(a);
3894 Py_DECREF(b);
3895 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003896}
3897
Guido van Rossum234f9421993-06-17 12:35:49 +00003898static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003899long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003900{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003901 if (PyInt_Check(*pw)) {
3902 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
3903 if (*pw == NULL)
3904 return -1;
3905 Py_INCREF(*pv);
3906 return 0;
3907 }
3908 else if (PyLong_Check(*pw)) {
3909 Py_INCREF(*pv);
3910 Py_INCREF(*pw);
3911 return 0;
3912 }
3913 return 1; /* Can't do it */
Guido van Rossume6eefc21992-08-14 12:06:52 +00003914}
3915
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003916static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003917long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003918{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003919 if (PyLong_CheckExact(v))
3920 Py_INCREF(v);
3921 else
3922 v = _PyLong_Copy((PyLongObject *)v);
3923 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003924}
3925
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003926static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003927long_int(PyObject *v)
3928{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003929 long x;
3930 x = PyLong_AsLong(v);
3931 if (PyErr_Occurred()) {
3932 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
Mark Dickinsonfda8d112010-05-09 20:30:29 +00003933 PyErr_Clear();
3934 if (PyLong_CheckExact(v)) {
3935 Py_INCREF(v);
3936 return v;
3937 }
3938 else
3939 return _PyLong_Copy((PyLongObject *)v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003940 }
3941 else
3942 return NULL;
3943 }
3944 return PyInt_FromLong(x);
Walter Dörwaldf1715402002-11-19 20:49:15 +00003945}
3946
3947static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003948long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003949{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003950 double result;
3951 result = PyLong_AsDouble(v);
3952 if (result == -1.0 && PyErr_Occurred())
3953 return NULL;
3954 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003955}
3956
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003957static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003958long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003959{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003960 return _PyLong_Format(v, 8, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003961}
3962
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003963static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003964long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003965{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003966 return _PyLong_Format(v, 16, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003967}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003968
3969static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003970long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003971
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972static PyObject *
3973long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3974{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003975 PyObject *x = NULL;
3976 int base = -909; /* unlikely! */
3977 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003979 if (type != &PyLong_Type)
3980 return long_subtype_new(type, args, kwds); /* Wimp out */
3981 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3982 &x, &base))
3983 return NULL;
3984 if (x == NULL)
3985 return PyLong_FromLong(0L);
3986 if (base == -909)
3987 return PyNumber_Long(x);
3988 else if (PyString_Check(x)) {
3989 /* Since PyLong_FromString doesn't have a length parameter,
3990 * check here for possible NULs in the string. */
3991 char *string = PyString_AS_STRING(x);
3992 if (strlen(string) != (size_t)PyString_Size(x)) {
3993 /* create a repr() of the input string,
3994 * just like PyLong_FromString does. */
3995 PyObject *srepr;
3996 srepr = PyObject_Repr(x);
3997 if (srepr == NULL)
3998 return NULL;
3999 PyErr_Format(PyExc_ValueError,
Mark Dickinsonfda8d112010-05-09 20:30:29 +00004000 "invalid literal for long() with base %d: %s",
4001 base, PyString_AS_STRING(srepr));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004002 Py_DECREF(srepr);
4003 return NULL;
4004 }
4005 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
4006 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004007#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004008 else if (PyUnicode_Check(x))
4009 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4010 PyUnicode_GET_SIZE(x),
4011 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004012#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004013 else {
4014 PyErr_SetString(PyExc_TypeError,
Mark Dickinsonfda8d112010-05-09 20:30:29 +00004015 "long() can't convert non-string with explicit base");
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004016 return NULL;
4017 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004018}
4019
Guido van Rossumbef14172001-08-29 15:47:46 +00004020/* Wimpy, slow approach to tp_new calls for subtypes of long:
4021 first create a regular long from whatever arguments we got,
4022 then allocate a subtype instance and initialize it from
4023 the regular long. The regular long is then thrown away.
4024*/
4025static PyObject *
4026long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4027{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004028 PyLongObject *tmp, *newobj;
4029 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004030
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004031 assert(PyType_IsSubtype(type, &PyLong_Type));
4032 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4033 if (tmp == NULL)
4034 return NULL;
4035 assert(PyLong_CheckExact(tmp));
4036 n = Py_SIZE(tmp);
4037 if (n < 0)
4038 n = -n;
4039 newobj = (PyLongObject *)type->tp_alloc(type, n);
4040 if (newobj == NULL) {
4041 Py_DECREF(tmp);
4042 return NULL;
4043 }
4044 assert(PyLong_Check(newobj));
4045 Py_SIZE(newobj) = Py_SIZE(tmp);
4046 for (i = 0; i < n; i++)
4047 newobj->ob_digit[i] = tmp->ob_digit[i];
4048 Py_DECREF(tmp);
4049 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004050}
4051
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004052static PyObject *
4053long_getnewargs(PyLongObject *v)
4054{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004055 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004056}
4057
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004058static PyObject *
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004059long_get0(PyLongObject *v, void *context) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004060 return PyLong_FromLong(0L);
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004061}
4062
4063static PyObject *
4064long_get1(PyLongObject *v, void *context) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004065 return PyLong_FromLong(1L);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004066}
4067
Eric Smitha9f7d622008-02-17 19:46:49 +00004068static PyObject *
4069long__format__(PyObject *self, PyObject *args)
4070{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004071 PyObject *format_spec;
Eric Smitha9f7d622008-02-17 19:46:49 +00004072
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004073 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
4074 return NULL;
4075 if (PyBytes_Check(format_spec))
4076 return _PyLong_FormatAdvanced(self,
4077 PyBytes_AS_STRING(format_spec),
4078 PyBytes_GET_SIZE(format_spec));
4079 if (PyUnicode_Check(format_spec)) {
4080 /* Convert format_spec to a str */
4081 PyObject *result;
4082 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00004083
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004084 if (str_spec == NULL)
4085 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00004086
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004087 result = _PyLong_FormatAdvanced(self,
4088 PyBytes_AS_STRING(str_spec),
4089 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00004090
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004091 Py_DECREF(str_spec);
4092 return result;
4093 }
4094 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
4095 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00004096}
4097
Robert Schuppenies51df0642008-06-01 16:16:17 +00004098static PyObject *
4099long_sizeof(PyLongObject *v)
4100{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004101 Py_ssize_t res;
Robert Schuppenies51df0642008-06-01 16:16:17 +00004102
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004103 res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);
4104 return PyInt_FromSsize_t(res);
Robert Schuppenies51df0642008-06-01 16:16:17 +00004105}
4106
Mark Dickinson1a707982008-12-17 16:14:37 +00004107static PyObject *
4108long_bit_length(PyLongObject *v)
4109{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004110 PyLongObject *result, *x, *y;
4111 Py_ssize_t ndigits, msd_bits = 0;
4112 digit msd;
Mark Dickinson1a707982008-12-17 16:14:37 +00004113
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004114 assert(v != NULL);
4115 assert(PyLong_Check(v));
Mark Dickinson1a707982008-12-17 16:14:37 +00004116
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004117 ndigits = ABS(Py_SIZE(v));
4118 if (ndigits == 0)
4119 return PyInt_FromLong(0);
Mark Dickinson1a707982008-12-17 16:14:37 +00004120
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004121 msd = v->ob_digit[ndigits-1];
4122 while (msd >= 32) {
4123 msd_bits += 6;
4124 msd >>= 6;
4125 }
4126 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson1a707982008-12-17 16:14:37 +00004127
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004128 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4129 return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson1a707982008-12-17 16:14:37 +00004130
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004131 /* expression above may overflow; use Python integers instead */
4132 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4133 if (result == NULL)
4134 return NULL;
4135 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4136 if (x == NULL)
4137 goto error;
4138 y = (PyLongObject *)long_mul(result, x);
4139 Py_DECREF(x);
4140 if (y == NULL)
4141 goto error;
4142 Py_DECREF(result);
4143 result = y;
Mark Dickinson1a707982008-12-17 16:14:37 +00004144
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004145 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4146 if (x == NULL)
4147 goto error;
4148 y = (PyLongObject *)long_add(result, x);
4149 Py_DECREF(x);
4150 if (y == NULL)
4151 goto error;
4152 Py_DECREF(result);
4153 result = y;
Mark Dickinson1a707982008-12-17 16:14:37 +00004154
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004155 return (PyObject *)result;
Mark Dickinson1a707982008-12-17 16:14:37 +00004156
Mark Dickinsonfda8d112010-05-09 20:30:29 +00004157 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004158 Py_DECREF(result);
4159 return NULL;
Mark Dickinson1a707982008-12-17 16:14:37 +00004160}
4161
4162PyDoc_STRVAR(long_bit_length_doc,
4163"long.bit_length() -> int or long\n\
4164\n\
4165Number of bits necessary to represent self in binary.\n\
4166>>> bin(37L)\n\
4167'0b100101'\n\
4168>>> (37L).bit_length()\n\
41696");
4170
Christian Heimes6f341092008-04-18 23:13:07 +00004171#if 0
4172static PyObject *
4173long_is_finite(PyObject *v)
4174{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004175 Py_RETURN_TRUE;
Christian Heimes6f341092008-04-18 23:13:07 +00004176}
4177#endif
4178
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004179static PyMethodDef long_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004180 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4181 "Returns self, the complex conjugate of any long."},
4182 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4183 long_bit_length_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00004184#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004185 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4186 "Returns always True."},
Christian Heimes6f341092008-04-18 23:13:07 +00004187#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004188 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4189 "Truncating an Integral returns itself."},
4190 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4191 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4192 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4193 "Returns size in memory, in bytes"},
4194 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004195};
4196
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004197static PyGetSetDef long_getset[] = {
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004198 {"real",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004199 (getter)long_long, (setter)NULL,
4200 "the real part of a complex number",
4201 NULL},
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004202 {"imag",
4203 (getter)long_get0, (setter)NULL,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004204 "the imaginary part of a complex number",
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004205 NULL},
4206 {"numerator",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004207 (getter)long_long, (setter)NULL,
4208 "the numerator of a rational number in lowest terms",
4209 NULL},
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004210 {"denominator",
4211 (getter)long_get1, (setter)NULL,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004212 "the denominator of a rational number in lowest terms",
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004213 NULL},
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004214 {NULL} /* Sentinel */
4215};
4216
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004217PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00004218"long(x[, base]) -> integer\n\
4219\n\
4220Convert a string or number to a long integer, if possible. A floating\n\
4221point argument will be truncated towards zero (this does not include a\n\
4222string representation of a floating point number!) When converting a\n\
4223string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004224converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004225
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004226static PyNumberMethods long_as_number = {
Mark Dickinsonfda8d112010-05-09 20:30:29 +00004227 (binaryfunc)long_add, /*nb_add*/
4228 (binaryfunc)long_sub, /*nb_subtract*/
4229 (binaryfunc)long_mul, /*nb_multiply*/
4230 long_classic_div, /*nb_divide*/
4231 long_mod, /*nb_remainder*/
4232 long_divmod, /*nb_divmod*/
4233 long_pow, /*nb_power*/
4234 (unaryfunc)long_neg, /*nb_negative*/
4235 (unaryfunc)long_long, /*tp_positive*/
4236 (unaryfunc)long_abs, /*tp_absolute*/
4237 (inquiry)long_nonzero, /*tp_nonzero*/
4238 (unaryfunc)long_invert, /*nb_invert*/
4239 long_lshift, /*nb_lshift*/
4240 (binaryfunc)long_rshift, /*nb_rshift*/
4241 long_and, /*nb_and*/
4242 long_xor, /*nb_xor*/
4243 long_or, /*nb_or*/
4244 long_coerce, /*nb_coerce*/
4245 long_int, /*nb_int*/
4246 long_long, /*nb_long*/
4247 long_float, /*nb_float*/
4248 long_oct, /*nb_oct*/
4249 long_hex, /*nb_hex*/
4250 0, /* nb_inplace_add */
4251 0, /* nb_inplace_subtract */
4252 0, /* nb_inplace_multiply */
4253 0, /* nb_inplace_divide */
4254 0, /* nb_inplace_remainder */
4255 0, /* nb_inplace_power */
4256 0, /* nb_inplace_lshift */
4257 0, /* nb_inplace_rshift */
4258 0, /* nb_inplace_and */
4259 0, /* nb_inplace_xor */
4260 0, /* nb_inplace_or */
4261 long_div, /* nb_floor_divide */
4262 long_true_divide, /* nb_true_divide */
4263 0, /* nb_inplace_floor_divide */
4264 0, /* nb_inplace_true_divide */
4265 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004266};
4267
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004268PyTypeObject PyLong_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004269 PyObject_HEAD_INIT(&PyType_Type)
4270 0, /* ob_size */
4271 "long", /* tp_name */
4272 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4273 sizeof(digit), /* tp_itemsize */
4274 long_dealloc, /* tp_dealloc */
4275 0, /* tp_print */
4276 0, /* tp_getattr */
4277 0, /* tp_setattr */
4278 (cmpfunc)long_compare, /* tp_compare */
4279 long_repr, /* tp_repr */
4280 &long_as_number, /* tp_as_number */
4281 0, /* tp_as_sequence */
4282 0, /* tp_as_mapping */
4283 (hashfunc)long_hash, /* tp_hash */
4284 0, /* tp_call */
4285 long_str, /* tp_str */
4286 PyObject_GenericGetAttr, /* tp_getattro */
4287 0, /* tp_setattro */
4288 0, /* tp_as_buffer */
4289 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Mark Dickinsonfda8d112010-05-09 20:30:29 +00004290 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004291 long_doc, /* tp_doc */
4292 0, /* tp_traverse */
4293 0, /* tp_clear */
4294 0, /* tp_richcompare */
4295 0, /* tp_weaklistoffset */
4296 0, /* tp_iter */
4297 0, /* tp_iternext */
4298 long_methods, /* tp_methods */
4299 0, /* tp_members */
4300 long_getset, /* tp_getset */
4301 0, /* tp_base */
4302 0, /* tp_dict */
4303 0, /* tp_descr_get */
4304 0, /* tp_descr_set */
4305 0, /* tp_dictoffset */
4306 0, /* tp_init */
4307 0, /* tp_alloc */
4308 long_new, /* tp_new */
Mark Dickinsonfda8d112010-05-09 20:30:29 +00004309 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004310};
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004311
4312static PyTypeObject Long_InfoType;
4313
4314PyDoc_STRVAR(long_info__doc__,
4315"sys.long_info\n\
4316\n\
4317A struct sequence that holds information about Python's\n\
4318internal representation of integers. The attributes are read only.");
4319
4320static PyStructSequence_Field long_info_fields[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004321 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinsonfda8d112010-05-09 20:30:29 +00004322 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004323 {NULL, NULL}
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004324};
4325
4326static PyStructSequence_Desc long_info_desc = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004327 "sys.long_info", /* name */
4328 long_info__doc__, /* doc */
4329 long_info_fields, /* fields */
Mark Dickinsonfda8d112010-05-09 20:30:29 +00004330 2 /* number of fields */
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004331};
4332
4333PyObject *
4334PyLong_GetInfo(void)
4335{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004336 PyObject* long_info;
4337 int field = 0;
4338 long_info = PyStructSequence_New(&Long_InfoType);
4339 if (long_info == NULL)
4340 return NULL;
4341 PyStructSequence_SET_ITEM(long_info, field++,
4342 PyInt_FromLong(PyLong_SHIFT));
4343 PyStructSequence_SET_ITEM(long_info, field++,
4344 PyInt_FromLong(sizeof(digit)));
4345 if (PyErr_Occurred()) {
4346 Py_CLEAR(long_info);
4347 return NULL;
4348 }
4349 return long_info;
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004350}
4351
4352int
4353_PyLong_Init(void)
4354{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004355 /* initialize long_info */
4356 if (Long_InfoType.tp_name == 0)
4357 PyStructSequence_InitType(&Long_InfoType, &long_info_desc);
4358 return 1;
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004359}