blob: 698a6db2c77bf91b99966d4f48f6aec58af8bfe0 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003/* Long (arbitrary precision) integer object implementation */
4
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00005/* XXX The functional organization of this file is terrible */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00008#include "longintrepr.h"
Mark Dickinsonefc82f72009-03-20 15:51:55 +00009#include "structseq.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +000010
Mark Dickinson6736cf82009-04-20 21:13:33 +000011#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000012#include <ctype.h>
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000013#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000014
Tim Peters5af4e6c2002-08-12 02:31:19 +000015/* For long multiplication, use the O(N**2) school algorithm unless
16 * both operands contain more than KARATSUBA_CUTOFF digits (this
Christian Heimes7f39c9f2008-01-25 12:18:43 +000017 * being an internal Python long digit, in base PyLong_BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000018 */
Tim Peters0973b992004-08-29 22:16:50 +000019#define KARATSUBA_CUTOFF 70
20#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000021
Tim Peters47e52ee2004-08-30 02:44:38 +000022/* For exponentiation, use the binary left-to-right algorithm
23 * unless the exponent contains more than FIVEARY_CUTOFF digits.
24 * In that case, do 5 bits at a time. The potential drawback is that
25 * a table of 2**5 intermediate results is computed.
26 */
27#define FIVEARY_CUTOFF 8
28
Guido van Rossume32e0141992-01-19 16:31:05 +000029#define ABS(x) ((x) < 0 ? -(x) : (x))
30
Tim Peters5af4e6c2002-08-12 02:31:19 +000031#undef MIN
32#undef MAX
33#define MAX(x, y) ((x) < (y) ? (y) : (x))
34#define MIN(x, y) ((x) > (y) ? (y) : (x))
35
Guido van Rossumc0b618a1997-05-02 03:12:38 +000036#define SIGCHECK(PyTryBlock) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000037 if (--_Py_Ticker < 0) { \
38 _Py_Ticker = _Py_CheckInterval; \
39 if (PyErr_CheckSignals()) PyTryBlock \
40 }
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000041
Guido van Rossumedcc38a1991-05-05 20:09:44 +000042/* Normalize (remove leading zeros from) a long int object.
43 Doesn't attempt to free the storage--in most cases, due to the nature
44 of the algorithms used, this could save at most be one word anyway. */
45
Guido van Rossumc0b618a1997-05-02 03:12:38 +000046static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000047long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000048{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000049 Py_ssize_t j = ABS(Py_SIZE(v));
50 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +000051
Antoine Pitrouc83ea132010-05-09 14:46:46 +000052 while (i > 0 && v->ob_digit[i-1] == 0)
53 --i;
54 if (i != j)
55 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
56 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +000057}
58
59/* Allocate a new long int object with size digits.
60 Return NULL and set exception if we run out of memory. */
61
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000062#define MAX_LONG_DIGITS \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000063 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000064
Guido van Rossumc0b618a1997-05-02 03:12:38 +000065PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000066_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000067{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000068 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
69 PyErr_SetString(PyExc_OverflowError,
70 "too many digits in integer");
71 return NULL;
72 }
73 /* coverity[ampersand_in_size] */
74 /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect
75 overflow */
76 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000077}
78
Tim Peters64b5ce32001-09-10 20:52:51 +000079PyObject *
80_PyLong_Copy(PyLongObject *src)
81{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000082 PyLongObject *result;
83 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000084
Antoine Pitrouc83ea132010-05-09 14:46:46 +000085 assert(src != NULL);
86 i = src->ob_size;
87 if (i < 0)
88 i = -(i);
89 result = _PyLong_New(i);
90 if (result != NULL) {
91 result->ob_size = src->ob_size;
92 while (--i >= 0)
93 result->ob_digit[i] = src->ob_digit[i];
94 }
95 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +000096}
97
Guido van Rossumedcc38a1991-05-05 20:09:44 +000098/* Create a new long int object from a C long int */
99
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000100PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000101PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000103 PyLongObject *v;
104 unsigned long abs_ival;
105 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
106 int ndigits = 0;
107 int negative = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000108
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000109 if (ival < 0) {
110 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
111 ANSI C says that the result of -ival is undefined when ival
112 == LONG_MIN. Hence the following workaround. */
113 abs_ival = (unsigned long)(-1-ival) + 1;
114 negative = 1;
115 }
116 else {
117 abs_ival = (unsigned long)ival;
118 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000119
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000120 /* Count the number of Python digits.
121 We used to pick 5 ("big enough for anything"), but that's a
122 waste of time and space given that 5*15 = 75 bits are rarely
123 needed. */
124 t = abs_ival;
125 while (t) {
126 ++ndigits;
127 t >>= PyLong_SHIFT;
128 }
129 v = _PyLong_New(ndigits);
130 if (v != NULL) {
131 digit *p = v->ob_digit;
132 v->ob_size = negative ? -ndigits : ndigits;
133 t = abs_ival;
134 while (t) {
135 *p++ = (digit)(t & PyLong_MASK);
136 t >>= PyLong_SHIFT;
137 }
138 }
139 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000140}
141
Guido van Rossum53756b11997-01-03 17:14:46 +0000142/* Create a new long int object from a C unsigned long int */
143
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000144PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000145PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000146{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000147 PyLongObject *v;
148 unsigned long t;
149 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000150
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000151 /* Count the number of Python digits. */
152 t = (unsigned long)ival;
153 while (t) {
154 ++ndigits;
155 t >>= PyLong_SHIFT;
156 }
157 v = _PyLong_New(ndigits);
158 if (v != NULL) {
159 digit *p = v->ob_digit;
160 Py_SIZE(v) = ndigits;
161 while (ival) {
162 *p++ = (digit)(ival & PyLong_MASK);
163 ival >>= PyLong_SHIFT;
164 }
165 }
166 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000167}
168
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000169/* Create a new long int object from a C double */
170
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000172PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000173{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000174 PyLongObject *v;
175 double frac;
176 int i, ndig, expo, neg;
177 neg = 0;
178 if (Py_IS_INFINITY(dval)) {
179 PyErr_SetString(PyExc_OverflowError,
180 "cannot convert float infinity to integer");
181 return NULL;
182 }
183 if (Py_IS_NAN(dval)) {
184 PyErr_SetString(PyExc_ValueError,
185 "cannot convert float NaN to integer");
186 return NULL;
187 }
188 if (dval < 0.0) {
189 neg = 1;
190 dval = -dval;
191 }
192 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
193 if (expo <= 0)
194 return PyLong_FromLong(0L);
195 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
196 v = _PyLong_New(ndig);
197 if (v == NULL)
198 return NULL;
199 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
200 for (i = ndig; --i >= 0; ) {
201 digit bits = (digit)frac;
202 v->ob_digit[i] = bits;
203 frac = frac - (double)bits;
204 frac = ldexp(frac, PyLong_SHIFT);
205 }
206 if (neg)
207 Py_SIZE(v) = -(Py_SIZE(v));
208 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000209}
210
Armin Rigo7ccbca92006-10-04 12:17:45 +0000211/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
212 * anything about what happens when a signed integer operation overflows,
213 * and some compilers think they're doing you a favor by being "clever"
214 * then. The bit pattern for the largest postive signed long is
215 * (unsigned long)LONG_MAX, and for the smallest negative signed long
216 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
217 * However, some other compilers warn about applying unary minus to an
218 * unsigned operand. Hence the weird "0-".
219 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000220#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
221#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Armin Rigo7ccbca92006-10-04 12:17:45 +0000222
Mark Dickinsone31d3002009-12-21 11:21:25 +0000223/* Get a C long int from a Python long or Python int object.
224 On overflow, returns -1 and sets *overflow to 1 or -1 depending
225 on the sign of the result. Otherwise *overflow is 0.
226
227 For other errors (e.g., type error), returns -1 and sets an error
228 condition.
229*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000230
231long
Mark Dickinsone31d3002009-12-21 11:21:25 +0000232PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000233{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000234 /* This version by Tim Peters */
235 register PyLongObject *v;
236 unsigned long x, prev;
237 long res;
238 Py_ssize_t i;
239 int sign;
240 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000241
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000242 *overflow = 0;
243 if (vv == NULL) {
244 PyErr_BadInternalCall();
245 return -1;
246 }
Guido van Rossumf7531811998-05-26 14:33:37 +0000247
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000248 if(PyInt_Check(vv))
249 return PyInt_AsLong(vv);
Mark Dickinsone31d3002009-12-21 11:21:25 +0000250
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000251 if (!PyLong_Check(vv)) {
252 PyNumberMethods *nb;
253 nb = vv->ob_type->tp_as_number;
254 if (nb == NULL || nb->nb_int == NULL) {
255 PyErr_SetString(PyExc_TypeError,
256 "an integer is required");
257 return -1;
258 }
259 vv = (*nb->nb_int) (vv);
260 if (vv == NULL)
261 return -1;
262 do_decref = 1;
263 if(PyInt_Check(vv)) {
264 res = PyInt_AsLong(vv);
265 goto exit;
266 }
267 if (!PyLong_Check(vv)) {
268 Py_DECREF(vv);
269 PyErr_SetString(PyExc_TypeError,
270 "nb_int should return int object");
271 return -1;
272 }
273 }
Mark Dickinsone31d3002009-12-21 11:21:25 +0000274
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000275 res = -1;
276 v = (PyLongObject *)vv;
277 i = Py_SIZE(v);
Mark Dickinsone31d3002009-12-21 11:21:25 +0000278
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000279 switch (i) {
280 case -1:
281 res = -(sdigit)v->ob_digit[0];
282 break;
283 case 0:
284 res = 0;
285 break;
286 case 1:
287 res = v->ob_digit[0];
288 break;
289 default:
290 sign = 1;
291 x = 0;
292 if (i < 0) {
293 sign = -1;
294 i = -(i);
295 }
296 while (--i >= 0) {
297 prev = x;
298 x = (x << PyLong_SHIFT) + v->ob_digit[i];
299 if ((x >> PyLong_SHIFT) != prev) {
300 *overflow = sign;
301 goto exit;
302 }
303 }
304 /* Haven't lost any bits, but casting to long requires extra
305 * care (see comment above).
306 */
307 if (x <= (unsigned long)LONG_MAX) {
308 res = (long)x * sign;
309 }
310 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
311 res = LONG_MIN;
312 }
313 else {
314 *overflow = sign;
315 /* res is already set to -1 */
316 }
317 }
Mark Dickinsone31d3002009-12-21 11:21:25 +0000318 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000319 if (do_decref) {
320 Py_DECREF(vv);
321 }
322 return res;
Mark Dickinsone31d3002009-12-21 11:21:25 +0000323}
324
325/* Get a C long int from a long int object.
326 Returns -1 and sets an error condition if overflow occurs. */
327
328long
329PyLong_AsLong(PyObject *obj)
330{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000331 int overflow;
332 long result = PyLong_AsLongAndOverflow(obj, &overflow);
333 if (overflow) {
334 /* XXX: could be cute and give a different
335 message for overflow == -1 */
336 PyErr_SetString(PyExc_OverflowError,
337 "Python int too large to convert to C long");
338 }
339 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000340}
341
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000342/* Get a Py_ssize_t from a long int object.
343 Returns -1 and sets an error condition if overflow occurs. */
344
345Py_ssize_t
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000346PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000347 register PyLongObject *v;
348 size_t x, prev;
349 Py_ssize_t i;
350 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000351
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000352 if (vv == NULL || !PyLong_Check(vv)) {
353 PyErr_BadInternalCall();
354 return -1;
355 }
356 v = (PyLongObject *)vv;
357 i = v->ob_size;
358 sign = 1;
359 x = 0;
360 if (i < 0) {
361 sign = -1;
362 i = -(i);
363 }
364 while (--i >= 0) {
365 prev = x;
366 x = (x << PyLong_SHIFT) | v->ob_digit[i];
367 if ((x >> PyLong_SHIFT) != prev)
368 goto overflow;
369 }
370 /* Haven't lost any bits, but casting to a signed type requires
371 * extra care (see comment above).
372 */
373 if (x <= (size_t)PY_SSIZE_T_MAX) {
374 return (Py_ssize_t)x * sign;
375 }
376 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
377 return PY_SSIZE_T_MIN;
378 }
379 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000380
381 overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000382 PyErr_SetString(PyExc_OverflowError,
383 "long int too large to convert to int");
384 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000385}
386
Guido van Rossumd8c80482002-08-13 00:24:58 +0000387/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000388 Returns -1 and sets an error condition if overflow occurs. */
389
390unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000391PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000392{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000393 register PyLongObject *v;
394 unsigned long x, prev;
395 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000396
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000397 if (vv == NULL || !PyLong_Check(vv)) {
398 if (vv != NULL && PyInt_Check(vv)) {
399 long val = PyInt_AsLong(vv);
400 if (val < 0) {
401 PyErr_SetString(PyExc_OverflowError,
402 "can't convert negative value to unsigned long");
403 return (unsigned long) -1;
404 }
405 return val;
406 }
407 PyErr_BadInternalCall();
408 return (unsigned long) -1;
409 }
410 v = (PyLongObject *)vv;
411 i = Py_SIZE(v);
412 x = 0;
413 if (i < 0) {
414 PyErr_SetString(PyExc_OverflowError,
415 "can't convert negative value to unsigned long");
416 return (unsigned long) -1;
417 }
418 while (--i >= 0) {
419 prev = x;
420 x = (x << PyLong_SHIFT) | v->ob_digit[i];
421 if ((x >> PyLong_SHIFT) != prev) {
422 PyErr_SetString(PyExc_OverflowError,
423 "long int too large to convert");
424 return (unsigned long) -1;
425 }
426 }
427 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000428}
429
Thomas Hellera4ea6032003-04-17 18:55:45 +0000430/* Get a C unsigned long int from a long int object, ignoring the high bits.
431 Returns -1 and sets an error condition if an error occurs. */
432
433unsigned long
434PyLong_AsUnsignedLongMask(PyObject *vv)
435{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000436 register PyLongObject *v;
437 unsigned long x;
438 Py_ssize_t i;
439 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000440
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000441 if (vv == NULL || !PyLong_Check(vv)) {
442 if (vv != NULL && PyInt_Check(vv))
443 return PyInt_AsUnsignedLongMask(vv);
444 PyErr_BadInternalCall();
445 return (unsigned long) -1;
446 }
447 v = (PyLongObject *)vv;
448 i = v->ob_size;
449 sign = 1;
450 x = 0;
451 if (i < 0) {
452 sign = -1;
453 i = -i;
454 }
455 while (--i >= 0) {
456 x = (x << PyLong_SHIFT) | v->ob_digit[i];
457 }
458 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000459}
460
Tim Peters5b8132f2003-01-31 15:52:05 +0000461int
462_PyLong_Sign(PyObject *vv)
463{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000464 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000465
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000466 assert(v != NULL);
467 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000468
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000469 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000470}
471
Tim Petersbaefd9e2003-01-28 20:37:45 +0000472size_t
473_PyLong_NumBits(PyObject *vv)
474{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000475 PyLongObject *v = (PyLongObject *)vv;
476 size_t result = 0;
477 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000478
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000479 assert(v != NULL);
480 assert(PyLong_Check(v));
481 ndigits = ABS(Py_SIZE(v));
482 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
483 if (ndigits > 0) {
484 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000485
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000486 result = (ndigits - 1) * PyLong_SHIFT;
487 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
488 goto Overflow;
489 do {
490 ++result;
491 if (result == 0)
492 goto Overflow;
493 msd >>= 1;
494 } while (msd);
495 }
496 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000497
498Overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000499 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
500 "to express in a platform size_t");
501 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000502}
503
Tim Peters2a9b3672001-06-11 21:23:58 +0000504PyObject *
505_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000506 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000507{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000508 const unsigned char* pstartbyte;/* LSB of bytes */
509 int incr; /* direction to move pstartbyte */
510 const unsigned char* pendbyte; /* MSB of bytes */
511 size_t numsignificantbytes; /* number of bytes that matter */
512 Py_ssize_t ndigits; /* number of Python long digits */
513 PyLongObject* v; /* result */
514 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000515
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000516 if (n == 0)
517 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000518
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000519 if (little_endian) {
520 pstartbyte = bytes;
521 pendbyte = bytes + n - 1;
522 incr = 1;
523 }
524 else {
525 pstartbyte = bytes + n - 1;
526 pendbyte = bytes;
527 incr = -1;
528 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000529
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000530 if (is_signed)
531 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000532
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000533 /* Compute numsignificantbytes. This consists of finding the most
534 significant byte. Leading 0 bytes are insignficant if the number
535 is positive, and leading 0xff bytes if negative. */
536 {
537 size_t i;
538 const unsigned char* p = pendbyte;
539 const int pincr = -incr; /* search MSB to LSB */
540 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000541
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000542 for (i = 0; i < n; ++i, p += pincr) {
543 if (*p != insignficant)
544 break;
545 }
546 numsignificantbytes = n - i;
547 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
548 actually has 2 significant bytes. OTOH, 0xff0001 ==
549 -0x00ffff, so we wouldn't *need* to bump it there; but we
550 do for 0xffff = -0x0001. To be safe without bothering to
551 check every case, bump it regardless. */
552 if (is_signed && numsignificantbytes < n)
553 ++numsignificantbytes;
554 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000555
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000556 /* How many Python long digits do we need? We have
557 8*numsignificantbytes bits, and each Python long digit has
558 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
559 /* catch overflow before it happens */
560 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
561 PyErr_SetString(PyExc_OverflowError,
562 "byte array too long to convert to int");
563 return NULL;
564 }
565 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
566 v = _PyLong_New(ndigits);
567 if (v == NULL)
568 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000569
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000570 /* Copy the bits over. The tricky parts are computing 2's-comp on
571 the fly for signed numbers, and dealing with the mismatch between
572 8-bit bytes and (probably) 15-bit Python digits.*/
573 {
574 size_t i;
575 twodigits carry = 1; /* for 2's-comp calculation */
576 twodigits accum = 0; /* sliding register */
577 unsigned int accumbits = 0; /* number of bits in accum */
578 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000579
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000580 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
581 twodigits thisbyte = *p;
582 /* Compute correction for 2's comp, if needed. */
583 if (is_signed) {
584 thisbyte = (0xff ^ thisbyte) + carry;
585 carry = thisbyte >> 8;
586 thisbyte &= 0xff;
587 }
588 /* Because we're going LSB to MSB, thisbyte is
589 more significant than what's already in accum,
590 so needs to be prepended to accum. */
591 accum |= (twodigits)thisbyte << accumbits;
592 accumbits += 8;
593 if (accumbits >= PyLong_SHIFT) {
594 /* There's enough to fill a Python digit. */
595 assert(idigit < ndigits);
596 v->ob_digit[idigit] = (digit)(accum &
597 PyLong_MASK);
598 ++idigit;
599 accum >>= PyLong_SHIFT;
600 accumbits -= PyLong_SHIFT;
601 assert(accumbits < PyLong_SHIFT);
602 }
603 }
604 assert(accumbits < PyLong_SHIFT);
605 if (accumbits) {
606 assert(idigit < ndigits);
607 v->ob_digit[idigit] = (digit)accum;
608 ++idigit;
609 }
610 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000611
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000612 Py_SIZE(v) = is_signed ? -idigit : idigit;
613 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000614}
615
616int
617_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000618 unsigned char* bytes, size_t n,
619 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000620{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000621 Py_ssize_t i; /* index into v->ob_digit */
622 Py_ssize_t ndigits; /* |v->ob_size| */
623 twodigits accum; /* sliding register */
624 unsigned int accumbits; /* # bits in accum */
625 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
626 digit carry; /* for computing 2's-comp */
627 size_t j; /* # bytes filled */
628 unsigned char* p; /* pointer to next byte in bytes */
629 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000630
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000631 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000632
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000633 if (Py_SIZE(v) < 0) {
634 ndigits = -(Py_SIZE(v));
635 if (!is_signed) {
636 PyErr_SetString(PyExc_OverflowError,
637 "can't convert negative long to unsigned");
638 return -1;
639 }
640 do_twos_comp = 1;
641 }
642 else {
643 ndigits = Py_SIZE(v);
644 do_twos_comp = 0;
645 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000646
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000647 if (little_endian) {
648 p = bytes;
649 pincr = 1;
650 }
651 else {
652 p = bytes + n - 1;
653 pincr = -1;
654 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000655
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000656 /* Copy over all the Python digits.
657 It's crucial that every Python digit except for the MSD contribute
658 exactly PyLong_SHIFT bits to the total, so first assert that the long is
659 normalized. */
660 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
661 j = 0;
662 accum = 0;
663 accumbits = 0;
664 carry = do_twos_comp ? 1 : 0;
665 for (i = 0; i < ndigits; ++i) {
666 digit thisdigit = v->ob_digit[i];
667 if (do_twos_comp) {
668 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
669 carry = thisdigit >> PyLong_SHIFT;
670 thisdigit &= PyLong_MASK;
671 }
672 /* Because we're going LSB to MSB, thisdigit is more
673 significant than what's already in accum, so needs to be
674 prepended to accum. */
675 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000676
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000677 /* The most-significant digit may be (probably is) at least
678 partly empty. */
679 if (i == ndigits - 1) {
680 /* Count # of sign bits -- they needn't be stored,
681 * although for signed conversion we need later to
682 * make sure at least one sign bit gets stored. */
683 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
684 thisdigit;
685 while (s != 0) {
686 s >>= 1;
687 accumbits++;
688 }
689 }
690 else
691 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000692
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000693 /* Store as many bytes as possible. */
694 while (accumbits >= 8) {
695 if (j >= n)
696 goto Overflow;
697 ++j;
698 *p = (unsigned char)(accum & 0xff);
699 p += pincr;
700 accumbits -= 8;
701 accum >>= 8;
702 }
703 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000704
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000705 /* Store the straggler (if any). */
706 assert(accumbits < 8);
707 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
708 if (accumbits > 0) {
709 if (j >= n)
710 goto Overflow;
711 ++j;
712 if (do_twos_comp) {
713 /* Fill leading bits of the byte with sign bits
714 (appropriately pretending that the long had an
715 infinite supply of sign bits). */
716 accum |= (~(twodigits)0) << accumbits;
717 }
718 *p = (unsigned char)(accum & 0xff);
719 p += pincr;
720 }
721 else if (j == n && n > 0 && is_signed) {
722 /* The main loop filled the byte array exactly, so the code
723 just above didn't get to ensure there's a sign bit, and the
724 loop below wouldn't add one either. Make sure a sign bit
725 exists. */
726 unsigned char msb = *(p - pincr);
727 int sign_bit_set = msb >= 0x80;
728 assert(accumbits == 0);
729 if (sign_bit_set == do_twos_comp)
730 return 0;
731 else
732 goto Overflow;
733 }
Tim Peters05607ad2001-06-13 21:01:27 +0000734
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000735 /* Fill remaining bytes with copies of the sign bit. */
736 {
737 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
738 for ( ; j < n; ++j, p += pincr)
739 *p = signbyte;
740 }
Tim Peters05607ad2001-06-13 21:01:27 +0000741
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000742 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000743
744Overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000745 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
746 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000747
Tim Peters2a9b3672001-06-11 21:23:58 +0000748}
749
Guido van Rossum78694d91998-09-18 14:14:13 +0000750/* Create a new long (or int) object from a C pointer */
751
752PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000753PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000754{
Tim Peters70128a12001-06-16 08:48:40 +0000755#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000756 if ((long)p < 0)
757 return PyLong_FromUnsignedLong((unsigned long)p);
758 return PyInt_FromLong((long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000759#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000760
Tim Peters70128a12001-06-16 08:48:40 +0000761#ifndef HAVE_LONG_LONG
762# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
763#endif
764#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000765# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000766#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000767 /* optimize null pointers */
768 if (p == NULL)
769 return PyInt_FromLong(0);
770 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000771
772#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000773}
774
775/* Get a C pointer from a long object (or an int object in some cases) */
776
777void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000778PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000779{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000780 /* This function will allow int or long objects. If vv is neither,
781 then the PyLong_AsLong*() functions will raise the exception:
782 PyExc_SystemError, "bad argument to internal function"
783 */
Tim Peters70128a12001-06-16 08:48:40 +0000784#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000785 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000786
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000787 if (PyInt_Check(vv))
788 x = PyInt_AS_LONG(vv);
789 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
790 x = PyLong_AsLong(vv);
791 else
792 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000793#else
Tim Peters70128a12001-06-16 08:48:40 +0000794
795#ifndef HAVE_LONG_LONG
796# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
797#endif
798#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000799# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000800#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000801 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000802
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000803 if (PyInt_Check(vv))
804 x = PyInt_AS_LONG(vv);
805 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
806 x = PyLong_AsLongLong(vv);
807 else
808 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000809
810#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000811
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000812 if (x == -1 && PyErr_Occurred())
813 return NULL;
814 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000815}
816
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000817#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000818
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000819/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000820 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000821 */
822
Tim Peterscf37dfc2001-06-14 18:42:50 +0000823#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000824#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000825
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000826/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000827
828PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000829PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000830{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000831 PyLongObject *v;
832 unsigned PY_LONG_LONG abs_ival;
833 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
834 int ndigits = 0;
835 int negative = 0;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000836
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000837 if (ival < 0) {
838 /* avoid signed overflow on negation; see comments
839 in PyLong_FromLong above. */
840 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
841 negative = 1;
842 }
843 else {
844 abs_ival = (unsigned PY_LONG_LONG)ival;
845 }
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000846
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000847 /* Count the number of Python digits.
848 We used to pick 5 ("big enough for anything"), but that's a
849 waste of time and space given that 5*15 = 75 bits are rarely
850 needed. */
851 t = abs_ival;
852 while (t) {
853 ++ndigits;
854 t >>= PyLong_SHIFT;
855 }
856 v = _PyLong_New(ndigits);
857 if (v != NULL) {
858 digit *p = v->ob_digit;
859 Py_SIZE(v) = negative ? -ndigits : ndigits;
860 t = abs_ival;
861 while (t) {
862 *p++ = (digit)(t & PyLong_MASK);
863 t >>= PyLong_SHIFT;
864 }
865 }
866 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000867}
868
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000869/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000870
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000871PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000872PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000873{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 PyLongObject *v;
875 unsigned PY_LONG_LONG t;
876 int ndigits = 0;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000877
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000878 /* Count the number of Python digits. */
879 t = (unsigned PY_LONG_LONG)ival;
880 while (t) {
881 ++ndigits;
882 t >>= PyLong_SHIFT;
883 }
884 v = _PyLong_New(ndigits);
885 if (v != NULL) {
886 digit *p = v->ob_digit;
887 Py_SIZE(v) = ndigits;
888 while (ival) {
889 *p++ = (digit)(ival & PyLong_MASK);
890 ival >>= PyLong_SHIFT;
891 }
892 }
893 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000894}
895
Martin v. Löwis18e16552006-02-15 17:27:45 +0000896/* Create a new long int object from a C Py_ssize_t. */
897
898PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000899PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000900{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000901 Py_ssize_t bytes = ival;
902 int one = 1;
903 return _PyLong_FromByteArray(
904 (unsigned char *)&bytes,
905 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000906}
907
908/* Create a new long int object from a C size_t. */
909
910PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000911PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000912{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000913 size_t bytes = ival;
914 int one = 1;
915 return _PyLong_FromByteArray(
916 (unsigned char *)&bytes,
917 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000918}
919
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000920/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000921 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000922
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000923PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000924PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000925{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000926 PY_LONG_LONG bytes;
927 int one = 1;
928 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +0000929
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000930 if (vv == NULL) {
931 PyErr_BadInternalCall();
932 return -1;
933 }
934 if (!PyLong_Check(vv)) {
935 PyNumberMethods *nb;
936 PyObject *io;
937 if (PyInt_Check(vv))
938 return (PY_LONG_LONG)PyInt_AsLong(vv);
939 if ((nb = vv->ob_type->tp_as_number) == NULL ||
940 nb->nb_int == NULL) {
941 PyErr_SetString(PyExc_TypeError, "an integer is required");
942 return -1;
943 }
944 io = (*nb->nb_int) (vv);
945 if (io == NULL)
946 return -1;
947 if (PyInt_Check(io)) {
948 bytes = PyInt_AsLong(io);
949 Py_DECREF(io);
950 return bytes;
951 }
952 if (PyLong_Check(io)) {
953 bytes = PyLong_AsLongLong(io);
954 Py_DECREF(io);
955 return bytes;
956 }
957 Py_DECREF(io);
958 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
959 return -1;
960 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000961
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000962 res = _PyLong_AsByteArray(
963 (PyLongObject *)vv, (unsigned char *)&bytes,
964 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000965
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000966 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
967 if (res < 0)
968 return (PY_LONG_LONG)-1;
969 else
970 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000971}
972
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000973/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000974 Return -1 and set an error if overflow occurs. */
975
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000976unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000977PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000978{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000979 unsigned PY_LONG_LONG bytes;
980 int one = 1;
981 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +0000982
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000983 if (vv == NULL || !PyLong_Check(vv)) {
984 PyErr_BadInternalCall();
985 return (unsigned PY_LONG_LONG)-1;
986 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000987
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000988 res = _PyLong_AsByteArray(
989 (PyLongObject *)vv, (unsigned char *)&bytes,
990 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000991
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000992 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
993 if (res < 0)
994 return (unsigned PY_LONG_LONG)res;
995 else
996 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000997}
Tim Petersd1a7da62001-06-13 00:35:57 +0000998
Thomas Hellera4ea6032003-04-17 18:55:45 +0000999/* Get a C unsigned long int from a long int object, ignoring the high bits.
1000 Returns -1 and sets an error condition if an error occurs. */
1001
1002unsigned PY_LONG_LONG
1003PyLong_AsUnsignedLongLongMask(PyObject *vv)
1004{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001005 register PyLongObject *v;
1006 unsigned PY_LONG_LONG x;
1007 Py_ssize_t i;
1008 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001009
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001010 if (vv == NULL || !PyLong_Check(vv)) {
1011 PyErr_BadInternalCall();
1012 return (unsigned long) -1;
1013 }
1014 v = (PyLongObject *)vv;
1015 i = v->ob_size;
1016 sign = 1;
1017 x = 0;
1018 if (i < 0) {
1019 sign = -1;
1020 i = -i;
1021 }
1022 while (--i >= 0) {
1023 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1024 }
1025 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001026}
Mark Dickinsona36507c2010-01-30 10:08:33 +00001027
1028/* Get a C long long int from a Python long or Python int object.
1029 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1030 on the sign of the result. Otherwise *overflow is 0.
1031
1032 For other errors (e.g., type error), returns -1 and sets an error
1033 condition.
1034*/
1035
1036PY_LONG_LONG
1037PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1038{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001039 /* This version by Tim Peters */
1040 register PyLongObject *v;
1041 unsigned PY_LONG_LONG x, prev;
1042 PY_LONG_LONG res;
1043 Py_ssize_t i;
1044 int sign;
1045 int do_decref = 0; /* if nb_int was called */
Mark Dickinsona36507c2010-01-30 10:08:33 +00001046
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001047 *overflow = 0;
1048 if (vv == NULL) {
1049 PyErr_BadInternalCall();
1050 return -1;
1051 }
Mark Dickinsona36507c2010-01-30 10:08:33 +00001052
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001053 if (PyInt_Check(vv))
1054 return PyInt_AsLong(vv);
Mark Dickinsona36507c2010-01-30 10:08:33 +00001055
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001056 if (!PyLong_Check(vv)) {
1057 PyNumberMethods *nb;
1058 nb = vv->ob_type->tp_as_number;
1059 if (nb == NULL || nb->nb_int == NULL) {
1060 PyErr_SetString(PyExc_TypeError,
1061 "an integer is required");
1062 return -1;
1063 }
1064 vv = (*nb->nb_int) (vv);
1065 if (vv == NULL)
1066 return -1;
1067 do_decref = 1;
1068 if(PyInt_Check(vv)) {
1069 res = PyInt_AsLong(vv);
1070 goto exit;
1071 }
1072 if (!PyLong_Check(vv)) {
1073 Py_DECREF(vv);
1074 PyErr_SetString(PyExc_TypeError,
1075 "nb_int should return int object");
1076 return -1;
1077 }
1078 }
Mark Dickinsona36507c2010-01-30 10:08:33 +00001079
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001080 res = -1;
1081 v = (PyLongObject *)vv;
1082 i = Py_SIZE(v);
Mark Dickinsona36507c2010-01-30 10:08:33 +00001083
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001084 switch (i) {
1085 case -1:
1086 res = -(sdigit)v->ob_digit[0];
1087 break;
1088 case 0:
1089 res = 0;
1090 break;
1091 case 1:
1092 res = v->ob_digit[0];
1093 break;
1094 default:
1095 sign = 1;
1096 x = 0;
1097 if (i < 0) {
1098 sign = -1;
1099 i = -(i);
1100 }
1101 while (--i >= 0) {
1102 prev = x;
1103 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1104 if ((x >> PyLong_SHIFT) != prev) {
1105 *overflow = sign;
1106 goto exit;
1107 }
1108 }
1109 /* Haven't lost any bits, but casting to long requires extra
1110 * care (see comment above).
1111 */
1112 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1113 res = (PY_LONG_LONG)x * sign;
1114 }
1115 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1116 res = PY_LLONG_MIN;
1117 }
1118 else {
1119 *overflow = sign;
1120 /* res is already set to -1 */
1121 }
1122 }
Mark Dickinsona36507c2010-01-30 10:08:33 +00001123 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001124 if (do_decref) {
1125 Py_DECREF(vv);
1126 }
1127 return res;
Mark Dickinsona36507c2010-01-30 10:08:33 +00001128}
1129
Tim Petersd1a7da62001-06-13 00:35:57 +00001130#undef IS_LITTLE_ENDIAN
1131
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001132#endif /* HAVE_LONG_LONG */
1133
Neil Schemenauerba872e22001-01-04 01:46:03 +00001134
1135static int
1136convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001137 if (PyLong_Check(v)) {
1138 *a = (PyLongObject *) v;
1139 Py_INCREF(v);
1140 }
1141 else if (PyInt_Check(v)) {
1142 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1143 }
1144 else {
1145 return 0;
1146 }
1147 if (PyLong_Check(w)) {
1148 *b = (PyLongObject *) w;
1149 Py_INCREF(w);
1150 }
1151 else if (PyInt_Check(w)) {
1152 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1153 }
1154 else {
1155 Py_DECREF(*a);
1156 return 0;
1157 }
1158 return 1;
Neil Schemenauerba872e22001-01-04 01:46:03 +00001159}
1160
1161#define CONVERT_BINOP(v, w, a, b) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001162 if (!convert_binop(v, w, a, b)) { \
1163 Py_INCREF(Py_NotImplemented); \
1164 return Py_NotImplemented; \
1165 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001166
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001167/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1168 2**k if d is nonzero, else 0. */
1169
1170static const unsigned char BitLengthTable[32] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001171 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1172 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001173};
1174
1175static int
1176bits_in_digit(digit d)
1177{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001178 int d_bits = 0;
1179 while (d >= 32) {
1180 d_bits += 6;
1181 d >>= 6;
1182 }
1183 d_bits += (int)BitLengthTable[d];
1184 return d_bits;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001185}
1186
Tim Peters877a2122002-08-12 05:09:36 +00001187/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1188 * is modified in place, by adding y to it. Carries are propagated as far as
1189 * x[m-1], and the remaining carry (0 or 1) is returned.
1190 */
1191static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001192v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001193{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001194 Py_ssize_t i;
1195 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001196
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001197 assert(m >= n);
1198 for (i = 0; i < n; ++i) {
1199 carry += x[i] + y[i];
1200 x[i] = carry & PyLong_MASK;
1201 carry >>= PyLong_SHIFT;
1202 assert((carry & 1) == carry);
1203 }
1204 for (; carry && i < m; ++i) {
1205 carry += x[i];
1206 x[i] = carry & PyLong_MASK;
1207 carry >>= PyLong_SHIFT;
1208 assert((carry & 1) == carry);
1209 }
1210 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001211}
1212
1213/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1214 * is modified in place, by subtracting y from it. Borrows are propagated as
1215 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1216 */
1217static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001218v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001219{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001220 Py_ssize_t i;
1221 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001222
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001223 assert(m >= n);
1224 for (i = 0; i < n; ++i) {
1225 borrow = x[i] - y[i] - borrow;
1226 x[i] = borrow & PyLong_MASK;
1227 borrow >>= PyLong_SHIFT;
1228 borrow &= 1; /* keep only 1 sign bit */
1229 }
1230 for (; borrow && i < m; ++i) {
1231 borrow = x[i] - borrow;
1232 x[i] = borrow & PyLong_MASK;
1233 borrow >>= PyLong_SHIFT;
1234 borrow &= 1;
1235 }
1236 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001237}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001238
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001239/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1240 * result in z[0:m], and return the d bits shifted out of the top.
1241 */
1242static digit
1243v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001244{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001245 Py_ssize_t i;
1246 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001247
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001248 assert(0 <= d && d < PyLong_SHIFT);
1249 for (i=0; i < m; i++) {
1250 twodigits acc = (twodigits)a[i] << d | carry;
1251 z[i] = (digit)acc & PyLong_MASK;
1252 carry = (digit)(acc >> PyLong_SHIFT);
1253 }
1254 return carry;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001255}
1256
1257/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1258 * result in z[0:m], and return the d bits shifted out of the bottom.
1259 */
1260static digit
1261v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1262{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001263 Py_ssize_t i;
1264 digit carry = 0;
1265 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001266
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001267 assert(0 <= d && d < PyLong_SHIFT);
1268 for (i=m; i-- > 0;) {
1269 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1270 carry = (digit)acc & mask;
1271 z[i] = (digit)(acc >> d);
1272 }
1273 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001274}
1275
Tim Peters212e6142001-07-14 12:23:19 +00001276/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1277 in pout, and returning the remainder. pin and pout point at the LSD.
1278 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Eric Smith5e527eb2008-02-10 01:36:53 +00001279 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001280 immutable. */
1281
1282static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001283inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001284{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001285 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001286
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001287 assert(n > 0 && n <= PyLong_MASK);
1288 pin += size;
1289 pout += size;
1290 while (--size >= 0) {
1291 digit hi;
1292 rem = (rem << PyLong_SHIFT) | *--pin;
1293 *--pout = hi = (digit)(rem / n);
1294 rem -= (twodigits)hi * n;
1295 }
1296 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001297}
1298
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001299/* Divide a long integer by a digit, returning both the quotient
1300 (as function result) and the remainder (through *prem).
1301 The sign of a is ignored; n should not be zero. */
1302
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001303static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001304divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001305{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001306 const Py_ssize_t size = ABS(Py_SIZE(a));
1307 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001308
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001309 assert(n > 0 && n <= PyLong_MASK);
1310 z = _PyLong_New(size);
1311 if (z == NULL)
1312 return NULL;
1313 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1314 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001315}
1316
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001317/* Convert a long integer to a base 10 string. Returns a new non-shared
1318 string. (Return value is non-shared so that callers can modify the
1319 returned value if necessary.) */
1320
1321static PyObject *
1322long_to_decimal_string(PyObject *aa, int addL)
1323{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001324 PyLongObject *scratch, *a;
1325 PyObject *str;
1326 Py_ssize_t size, strlen, size_a, i, j;
1327 digit *pout, *pin, rem, tenpow;
1328 char *p;
1329 int negative;
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001330
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001331 a = (PyLongObject *)aa;
1332 if (a == NULL || !PyLong_Check(a)) {
1333 PyErr_BadInternalCall();
1334 return NULL;
1335 }
1336 size_a = ABS(Py_SIZE(a));
1337 negative = Py_SIZE(a) < 0;
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001338
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001339 /* quick and dirty upper bound for the number of digits
1340 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001341
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001342 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001343
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001344 But log2(a) < size_a * PyLong_SHIFT, and
1345 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1346 > 3 * _PyLong_DECIMAL_SHIFT
1347 */
1348 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1349 PyErr_SetString(PyExc_OverflowError,
1350 "long is too large to format");
1351 return NULL;
1352 }
1353 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1354 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1355 scratch = _PyLong_New(size);
1356 if (scratch == NULL)
1357 return NULL;
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001358
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001359 /* convert array of base _PyLong_BASE digits in pin to an array of
1360 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1361 Volume 2 (3rd edn), section 4.4, Method 1b). */
1362 pin = a->ob_digit;
1363 pout = scratch->ob_digit;
1364 size = 0;
1365 for (i = size_a; --i >= 0; ) {
1366 digit hi = pin[i];
1367 for (j = 0; j < size; j++) {
1368 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1369 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1370 pout[j] = (digit)(z - (twodigits)hi *
1371 _PyLong_DECIMAL_BASE);
1372 }
1373 while (hi) {
1374 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1375 hi /= _PyLong_DECIMAL_BASE;
1376 }
1377 /* check for keyboard interrupt */
1378 SIGCHECK({
1379 Py_DECREF(scratch);
1380 return NULL;
1381 })
1382 }
1383 /* pout should have at least one digit, so that the case when a = 0
1384 works correctly */
1385 if (size == 0)
1386 pout[size++] = 0;
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001387
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001388 /* calculate exact length of output string, and allocate */
1389 strlen = (addL != 0) + negative +
1390 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1391 tenpow = 10;
1392 rem = pout[size-1];
1393 while (rem >= tenpow) {
1394 tenpow *= 10;
1395 strlen++;
1396 }
1397 str = PyString_FromStringAndSize(NULL, strlen);
1398 if (str == NULL) {
1399 Py_DECREF(scratch);
1400 return NULL;
1401 }
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001402
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001403 /* fill the string right-to-left */
1404 p = PyString_AS_STRING(str) + strlen;
1405 *p = '\0';
1406 if (addL)
1407 *--p = 'L';
1408 /* pout[0] through pout[size-2] contribute exactly
1409 _PyLong_DECIMAL_SHIFT digits each */
1410 for (i=0; i < size - 1; i++) {
1411 rem = pout[i];
1412 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1413 *--p = '0' + rem % 10;
1414 rem /= 10;
1415 }
1416 }
1417 /* pout[size-1]: always produce at least one decimal digit */
1418 rem = pout[i];
1419 do {
1420 *--p = '0' + rem % 10;
1421 rem /= 10;
1422 } while (rem != 0);
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001423
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001424 /* and sign */
1425 if (negative)
1426 *--p = '-';
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001427
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001428 /* check we've counted correctly */
1429 assert(p == PyString_AS_STRING(str));
1430 Py_DECREF(scratch);
1431 return (PyObject *)str;
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001432}
1433
Eric Smith5e527eb2008-02-10 01:36:53 +00001434/* Convert the long to a string object with given base,
1435 appending a base prefix of 0[box] if base is 2, 8 or 16.
1436 Add a trailing "L" if addL is non-zero.
1437 If newstyle is zero, then use the pre-2.6 behavior of octal having
1438 a leading "0", instead of the prefix "0o" */
1439PyAPI_FUNC(PyObject *)
1440_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001441{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001442 register PyLongObject *a = (PyLongObject *)aa;
1443 PyStringObject *str;
1444 Py_ssize_t i, sz;
1445 Py_ssize_t size_a;
1446 char *p;
1447 int bits;
1448 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001449
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001450 if (base == 10)
1451 return long_to_decimal_string((PyObject *)a, addL);
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001452
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001453 if (a == NULL || !PyLong_Check(a)) {
1454 PyErr_BadInternalCall();
1455 return NULL;
1456 }
1457 assert(base >= 2 && base <= 36);
1458 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001459
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001460 /* Compute a rough upper bound for the length of the string */
1461 i = base;
1462 bits = 0;
1463 while (i > 1) {
1464 ++bits;
1465 i >>= 1;
1466 }
1467 i = 5 + (addL ? 1 : 0);
1468 /* ensure we don't get signed overflow in sz calculation */
1469 if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {
1470 PyErr_SetString(PyExc_OverflowError,
1471 "long is too large to format");
1472 return NULL;
1473 }
1474 sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;
1475 assert(sz >= 0);
1476 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
1477 if (str == NULL)
1478 return NULL;
1479 p = PyString_AS_STRING(str) + sz;
1480 *p = '\0';
1481 if (addL)
1482 *--p = 'L';
1483 if (a->ob_size < 0)
1484 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001485
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001486 if (a->ob_size == 0) {
1487 *--p = '0';
1488 }
1489 else if ((base & (base - 1)) == 0) {
1490 /* JRH: special case for power-of-2 bases */
1491 twodigits accum = 0;
1492 int accumbits = 0; /* # of bits in accum */
1493 int basebits = 1; /* # of bits in base-1 */
1494 i = base;
1495 while ((i >>= 1) > 1)
1496 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001497
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001498 for (i = 0; i < size_a; ++i) {
1499 accum |= (twodigits)a->ob_digit[i] << accumbits;
1500 accumbits += PyLong_SHIFT;
1501 assert(accumbits >= basebits);
1502 do {
1503 char cdigit = (char)(accum & (base - 1));
1504 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1505 assert(p > PyString_AS_STRING(str));
1506 *--p = cdigit;
1507 accumbits -= basebits;
1508 accum >>= basebits;
1509 } while (i < size_a-1 ? accumbits >= basebits :
1510 accum > 0);
1511 }
1512 }
1513 else {
1514 /* Not 0, and base not a power of 2. Divide repeatedly by
1515 base, but for speed use the highest power of base that
1516 fits in a digit. */
1517 Py_ssize_t size = size_a;
1518 digit *pin = a->ob_digit;
1519 PyLongObject *scratch;
1520 /* powbasw <- largest power of base that fits in a digit. */
1521 digit powbase = base; /* powbase == base ** power */
1522 int power = 1;
1523 for (;;) {
1524 twodigits newpow = powbase * (twodigits)base;
1525 if (newpow >> PyLong_SHIFT)
1526 /* doesn't fit in a digit */
1527 break;
1528 powbase = (digit)newpow;
1529 ++power;
1530 }
Tim Peters212e6142001-07-14 12:23:19 +00001531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001532 /* Get a scratch area for repeated division. */
1533 scratch = _PyLong_New(size);
1534 if (scratch == NULL) {
1535 Py_DECREF(str);
1536 return NULL;
1537 }
Tim Peters212e6142001-07-14 12:23:19 +00001538
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001539 /* Repeatedly divide by powbase. */
1540 do {
1541 int ntostore = power;
1542 digit rem = inplace_divrem1(scratch->ob_digit,
1543 pin, size, powbase);
1544 pin = scratch->ob_digit; /* no need to use a again */
1545 if (pin[size - 1] == 0)
1546 --size;
1547 SIGCHECK({
1548 Py_DECREF(scratch);
1549 Py_DECREF(str);
1550 return NULL;
1551 })
Tim Peters212e6142001-07-14 12:23:19 +00001552
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001553 /* Break rem into digits. */
1554 assert(ntostore > 0);
1555 do {
1556 digit nextrem = (digit)(rem / base);
1557 char c = (char)(rem - nextrem * base);
1558 assert(p > PyString_AS_STRING(str));
1559 c += (c < 10) ? '0' : 'a'-10;
1560 *--p = c;
1561 rem = nextrem;
1562 --ntostore;
1563 /* Termination is a bit delicate: must not
1564 store leading zeroes, so must get out if
1565 remaining quotient and rem are both 0. */
1566 } while (ntostore && (size || rem));
1567 } while (size != 0);
1568 Py_DECREF(scratch);
1569 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001570
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001571 if (base == 2) {
1572 *--p = 'b';
1573 *--p = '0';
1574 }
1575 else if (base == 8) {
1576 if (newstyle) {
1577 *--p = 'o';
1578 *--p = '0';
1579 }
1580 else
1581 if (size_a != 0)
1582 *--p = '0';
1583 }
1584 else if (base == 16) {
1585 *--p = 'x';
1586 *--p = '0';
1587 }
1588 else if (base != 10) {
1589 *--p = '#';
1590 *--p = '0' + base%10;
1591 if (base > 10)
1592 *--p = '0' + base/10;
1593 }
1594 if (sign)
1595 *--p = sign;
1596 if (p != PyString_AS_STRING(str)) {
1597 char *q = PyString_AS_STRING(str);
1598 assert(p > q);
1599 do {
1600 } while ((*q++ = *p++) != '\0');
1601 q--;
1602 _PyString_Resize((PyObject **)&str,
1603 (Py_ssize_t) (q - PyString_AS_STRING(str)));
1604 }
1605 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001606}
1607
Tim Petersda53afa2006-05-25 17:34:03 +00001608/* Table of digit values for 8-bit string -> integer conversion.
1609 * '0' maps to 0, ..., '9' maps to 9.
1610 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1611 * All other indices map to 37.
1612 * Note that when converting a base B string, a char c is a legitimate
1613 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1614 */
1615int _PyLong_DigitValue[256] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001616 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 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1620 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1621 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1622 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1623 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1624 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1625 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1626 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1627 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1628 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1629 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1630 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1631 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Tim Peters696cf432006-05-24 21:10:40 +00001632};
1633
1634/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001635 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1636 * non-digit (which may be *str!). A normalized long is returned.
1637 * The point to this routine is that it takes time linear in the number of
1638 * string characters.
1639 */
1640static PyLongObject *
1641long_from_binary_base(char **str, int base)
1642{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001643 char *p = *str;
1644 char *start = p;
1645 int bits_per_char;
1646 Py_ssize_t n;
1647 PyLongObject *z;
1648 twodigits accum;
1649 int bits_in_accum;
1650 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001651
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001652 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1653 n = base;
1654 for (bits_per_char = -1; n; ++bits_per_char)
1655 n >>= 1;
1656 /* n <- total # of bits needed, while setting p to end-of-string */
1657 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1658 ++p;
1659 *str = p;
1660 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1661 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1662 if (n / bits_per_char < p - start) {
1663 PyErr_SetString(PyExc_ValueError,
1664 "long string too large to convert");
1665 return NULL;
1666 }
1667 n = n / PyLong_SHIFT;
1668 z = _PyLong_New(n);
1669 if (z == NULL)
1670 return NULL;
1671 /* Read string from right, and fill in long from left; i.e.,
1672 * from least to most significant in both.
1673 */
1674 accum = 0;
1675 bits_in_accum = 0;
1676 pdigit = z->ob_digit;
1677 while (--p >= start) {
1678 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
1679 assert(k >= 0 && k < base);
1680 accum |= (twodigits)k << bits_in_accum;
1681 bits_in_accum += bits_per_char;
1682 if (bits_in_accum >= PyLong_SHIFT) {
1683 *pdigit++ = (digit)(accum & PyLong_MASK);
1684 assert(pdigit - z->ob_digit <= n);
1685 accum >>= PyLong_SHIFT;
1686 bits_in_accum -= PyLong_SHIFT;
1687 assert(bits_in_accum < PyLong_SHIFT);
1688 }
1689 }
1690 if (bits_in_accum) {
1691 assert(bits_in_accum <= PyLong_SHIFT);
1692 *pdigit++ = (digit)accum;
1693 assert(pdigit - z->ob_digit <= n);
1694 }
1695 while (pdigit - z->ob_digit < n)
1696 *pdigit++ = 0;
1697 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001698}
1699
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001700PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001701PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001702{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001703 int sign = 1;
1704 char *start, *orig_str = str;
1705 PyLongObject *z;
1706 PyObject *strobj, *strrepr;
1707 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001708
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001709 if ((base != 0 && base < 2) || base > 36) {
1710 PyErr_SetString(PyExc_ValueError,
1711 "long() arg 2 must be >= 2 and <= 36");
1712 return NULL;
1713 }
1714 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1715 str++;
1716 if (*str == '+')
1717 ++str;
1718 else if (*str == '-') {
1719 ++str;
1720 sign = -1;
1721 }
1722 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1723 str++;
1724 if (base == 0) {
1725 /* No base given. Deduce the base from the contents
1726 of the string */
1727 if (str[0] != '0')
1728 base = 10;
1729 else if (str[1] == 'x' || str[1] == 'X')
1730 base = 16;
1731 else if (str[1] == 'o' || str[1] == 'O')
1732 base = 8;
1733 else if (str[1] == 'b' || str[1] == 'B')
1734 base = 2;
1735 else
1736 /* "old" (C-style) octal literal, still valid in
1737 2.x, although illegal in 3.x */
1738 base = 8;
1739 }
1740 /* Whether or not we were deducing the base, skip leading chars
1741 as needed */
1742 if (str[0] == '0' &&
1743 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1744 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1745 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1746 str += 2;
Tim Peters696cf432006-05-24 21:10:40 +00001747
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001748 start = str;
1749 if ((base & (base - 1)) == 0)
1750 z = long_from_binary_base(&str, base);
1751 else {
Tim Peters696cf432006-05-24 21:10:40 +00001752/***
1753Binary bases can be converted in time linear in the number of digits, because
1754Python's representation base is binary. Other bases (including decimal!) use
1755the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001756
Tim Peters696cf432006-05-24 21:10:40 +00001757First some math: the largest integer that can be expressed in N base-B digits
1758is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1759case number of Python digits needed to hold it is the smallest integer n s.t.
1760
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001761 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1762 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1763 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001764
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001765The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute
Tim Peters696cf432006-05-24 21:10:40 +00001766this quickly. A Python long with that much space is reserved near the start,
1767and the result is computed into it.
1768
1769The input string is actually treated as being in base base**i (i.e., i digits
1770are processed at a time), where two more static arrays hold:
1771
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001772 convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE
Tim Peters696cf432006-05-24 21:10:40 +00001773 convmultmax_base[base] = base ** convwidth_base[base]
1774
1775The first of these is the largest i such that i consecutive input digits
1776must fit in a single Python digit. The second is effectively the input
1777base we're really using.
1778
1779Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1780convmultmax_base[base], the result is "simply"
1781
1782 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1783
1784where B = convmultmax_base[base].
Tim Peters9faa3ed2006-05-30 15:53:34 +00001785
1786Error analysis: as above, the number of Python digits `n` needed is worst-
1787case
1788
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001789 n >= N * log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001790
1791where `N` is the number of input digits in base `B`. This is computed via
1792
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001793 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001794
1795below. Two numeric concerns are how much space this can waste, and whether
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001796the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15,
Tim Peters9faa3ed2006-05-30 15:53:34 +00001797which is the default (and it's unlikely anyone changes that).
1798
1799Waste isn't a problem: provided the first input digit isn't 0, the difference
1800between the worst-case input with N digits and the smallest input with N
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001801digits is about a factor of B, but B is small compared to PyLong_BASE so at most
Tim Peters9faa3ed2006-05-30 15:53:34 +00001802one allocated Python digit can remain unused on that count. If
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001803N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001804and adding 1 returns a result 1 larger than necessary. However, that can't
1805happen: whenever B is a power of 2, long_from_binary_base() is called
1806instead, and it's impossible for B**i to be an integer power of 2**15 when
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001807B is 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 +00001808an exact integer when B is not a power of 2, since B**i has a prime factor
1809other than 2 in that case, but (2**15)**j's only prime factor is 2).
1810
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001811The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001812is a little bit larger than an exact integer, but due to roundoff errors (in
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001813computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001814yields a numeric result a little less than that integer. Unfortunately, "how
1815close can a transcendental function get to an integer over some range?"
1816questions are generally theoretically intractable. Computer analysis via
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001817continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued
Tim Peters9faa3ed2006-05-30 15:53:34 +00001818fractions, giving a sequence i/j of "the best" rational approximations. Then
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001819j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001820we can get very close to being in trouble, but very rarely. For example,
182176573 is a denominator in one of the continued-fraction approximations to
1822log(10)/log(2**15), and indeed:
1823
1824 >>> log(10)/log(2**15)*76573
1825 16958.000000654003
1826
1827is very close to an integer. If we were working with IEEE single-precision,
1828rounding errors could kill us. Finding worst cases in IEEE double-precision
1829requires better-than-double-precision log() functions, and Tim didn't bother.
1830Instead the code checks to see whether the allocated space is enough as each
1831new Python digit is added, and copies the whole thing to a larger long if not.
1832This should happen extremely rarely, and in fact I don't have a test case
1833that triggers it(!). Instead the code was tested by artificially allocating
1834just 1 digit at the start, so that the copying code was exercised for every
1835digit beyond the first.
Tim Peters696cf432006-05-24 21:10:40 +00001836***/
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001837 register twodigits c; /* current input character */
1838 Py_ssize_t size_z;
1839 int i;
1840 int convwidth;
1841 twodigits convmultmax, convmult;
1842 digit *pz, *pzstop;
1843 char* scan;
Tim Peters696cf432006-05-24 21:10:40 +00001844
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001845 static double log_base_PyLong_BASE[37] = {0.0e0,};
1846 static int convwidth_base[37] = {0,};
1847 static twodigits convmultmax_base[37] = {0,};
Tim Peters696cf432006-05-24 21:10:40 +00001848
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001849 if (log_base_PyLong_BASE[base] == 0.0) {
1850 twodigits convmax = base;
1851 int i = 1;
Tim Peters696cf432006-05-24 21:10:40 +00001852
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001853 log_base_PyLong_BASE[base] = log((double)base) /
1854 log((double)PyLong_BASE);
1855 for (;;) {
1856 twodigits next = convmax * base;
1857 if (next > PyLong_BASE)
1858 break;
1859 convmax = next;
1860 ++i;
1861 }
1862 convmultmax_base[base] = convmax;
1863 assert(i > 0);
1864 convwidth_base[base] = i;
1865 }
Tim Peters696cf432006-05-24 21:10:40 +00001866
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001867 /* Find length of the string of numeric characters. */
1868 scan = str;
1869 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1870 ++scan;
Tim Peters696cf432006-05-24 21:10:40 +00001871
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001872 /* Create a long object that can contain the largest possible
1873 * integer with this base and length. Note that there's no
1874 * need to initialize z->ob_digit -- no slot is read up before
1875 * being stored into.
1876 */
1877 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
1878 /* Uncomment next line to test exceedingly rare copy code */
1879 /* size_z = 1; */
1880 assert(size_z > 0);
1881 z = _PyLong_New(size_z);
1882 if (z == NULL)
1883 return NULL;
1884 Py_SIZE(z) = 0;
Tim Peters696cf432006-05-24 21:10:40 +00001885
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001886 /* `convwidth` consecutive input digits are treated as a single
1887 * digit in base `convmultmax`.
1888 */
1889 convwidth = convwidth_base[base];
1890 convmultmax = convmultmax_base[base];
Tim Peters696cf432006-05-24 21:10:40 +00001891
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001892 /* Work ;-) */
1893 while (str < scan) {
1894 /* grab up to convwidth digits from the input string */
1895 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1896 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1897 c = (twodigits)(c * base +
1898 _PyLong_DigitValue[Py_CHARMASK(*str)]);
1899 assert(c < PyLong_BASE);
1900 }
Tim Peters696cf432006-05-24 21:10:40 +00001901
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001902 convmult = convmultmax;
1903 /* Calculate the shift only if we couldn't get
1904 * convwidth digits.
1905 */
1906 if (i != convwidth) {
1907 convmult = base;
1908 for ( ; i > 1; --i)
1909 convmult *= base;
1910 }
Tim Peters696cf432006-05-24 21:10:40 +00001911
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001912 /* Multiply z by convmult, and add c. */
1913 pz = z->ob_digit;
1914 pzstop = pz + Py_SIZE(z);
1915 for (; pz < pzstop; ++pz) {
1916 c += (twodigits)*pz * convmult;
1917 *pz = (digit)(c & PyLong_MASK);
1918 c >>= PyLong_SHIFT;
1919 }
1920 /* carry off the current end? */
1921 if (c) {
1922 assert(c < PyLong_BASE);
1923 if (Py_SIZE(z) < size_z) {
1924 *pz = (digit)c;
1925 ++Py_SIZE(z);
1926 }
1927 else {
1928 PyLongObject *tmp;
1929 /* Extremely rare. Get more space. */
1930 assert(Py_SIZE(z) == size_z);
1931 tmp = _PyLong_New(size_z + 1);
1932 if (tmp == NULL) {
1933 Py_DECREF(z);
1934 return NULL;
1935 }
1936 memcpy(tmp->ob_digit,
1937 z->ob_digit,
1938 sizeof(digit) * size_z);
1939 Py_DECREF(z);
1940 z = tmp;
1941 z->ob_digit[size_z] = (digit)c;
1942 ++size_z;
1943 }
1944 }
1945 }
1946 }
1947 if (z == NULL)
1948 return NULL;
1949 if (str == start)
1950 goto onError;
1951 if (sign < 0)
1952 Py_SIZE(z) = -(Py_SIZE(z));
1953 if (*str == 'L' || *str == 'l')
1954 str++;
1955 while (*str && isspace(Py_CHARMASK(*str)))
1956 str++;
1957 if (*str != '\0')
1958 goto onError;
1959 if (pend)
1960 *pend = str;
1961 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001962
1963 onError:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001964 Py_XDECREF(z);
1965 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1966 strobj = PyString_FromStringAndSize(orig_str, slen);
1967 if (strobj == NULL)
1968 return NULL;
1969 strrepr = PyObject_Repr(strobj);
1970 Py_DECREF(strobj);
1971 if (strrepr == NULL)
1972 return NULL;
1973 PyErr_Format(PyExc_ValueError,
1974 "invalid literal for long() with base %d: %s",
1975 base, PyString_AS_STRING(strrepr));
1976 Py_DECREF(strrepr);
1977 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001978}
1979
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001980#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001981PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001982PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001983{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001984 PyObject *result;
1985 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001986
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001987 if (buffer == NULL)
1988 return NULL;
Walter Dörwald07e14762002-11-06 16:15:14 +00001989
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001990 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1991 PyMem_FREE(buffer);
1992 return NULL;
1993 }
1994 result = PyLong_FromString(buffer, NULL, base);
1995 PyMem_FREE(buffer);
1996 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001997}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001998#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001999
Tim Peters9f688bf2000-07-07 15:53:28 +00002000/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002001static PyLongObject *x_divrem
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002002 (PyLongObject *, PyLongObject *, PyLongObject **);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002003static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002004
2005/* Long division with remainder, top-level routine */
2006
Guido van Rossume32e0141992-01-19 16:31:05 +00002007static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002008long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002009 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002010{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002011 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2012 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002013
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002014 if (size_b == 0) {
2015 PyErr_SetString(PyExc_ZeroDivisionError,
2016 "long division or modulo by zero");
2017 return -1;
2018 }
2019 if (size_a < size_b ||
2020 (size_a == size_b &&
2021 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2022 /* |a| < |b|. */
2023 *pdiv = _PyLong_New(0);
2024 if (*pdiv == NULL)
2025 return -1;
2026 Py_INCREF(a);
2027 *prem = (PyLongObject *) a;
2028 return 0;
2029 }
2030 if (size_b == 1) {
2031 digit rem = 0;
2032 z = divrem1(a, b->ob_digit[0], &rem);
2033 if (z == NULL)
2034 return -1;
2035 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2036 if (*prem == NULL) {
2037 Py_DECREF(z);
2038 return -1;
2039 }
2040 }
2041 else {
2042 z = x_divrem(a, b, prem);
2043 if (z == NULL)
2044 return -1;
2045 }
2046 /* Set the signs.
2047 The quotient z has the sign of a*b;
2048 the remainder r has the sign of a,
2049 so a = b*z + r. */
2050 if ((a->ob_size < 0) != (b->ob_size < 0))
2051 z->ob_size = -(z->ob_size);
2052 if (a->ob_size < 0 && (*prem)->ob_size != 0)
2053 (*prem)->ob_size = -((*prem)->ob_size);
2054 *pdiv = z;
2055 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002056}
2057
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002058/* Unsigned long division with remainder -- the algorithm. The arguments v1
2059 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002060
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002061static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002062x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002063{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002064 PyLongObject *v, *w, *a;
2065 Py_ssize_t i, k, size_v, size_w;
2066 int d;
2067 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2068 twodigits vv;
2069 sdigit zhi;
2070 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002071
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002072 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2073 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2074 handle the special case when the initial estimate q for a quotient
2075 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2076 that won't overflow a digit. */
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002077
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002078 /* allocate space; w will also be used to hold the final remainder */
2079 size_v = ABS(Py_SIZE(v1));
2080 size_w = ABS(Py_SIZE(w1));
2081 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2082 v = _PyLong_New(size_v+1);
2083 if (v == NULL) {
2084 *prem = NULL;
2085 return NULL;
2086 }
2087 w = _PyLong_New(size_w);
2088 if (w == NULL) {
2089 Py_DECREF(v);
2090 *prem = NULL;
2091 return NULL;
2092 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002094 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2095 shift v1 left by the same amount. Results go into w and v. */
2096 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2097 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2098 assert(carry == 0);
2099 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2100 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2101 v->ob_digit[size_v] = carry;
2102 size_v++;
2103 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002104
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002105 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2106 at most (and usually exactly) k = size_v - size_w digits. */
2107 k = size_v - size_w;
2108 assert(k >= 0);
2109 a = _PyLong_New(k);
2110 if (a == NULL) {
2111 Py_DECREF(w);
2112 Py_DECREF(v);
2113 *prem = NULL;
2114 return NULL;
2115 }
2116 v0 = v->ob_digit;
2117 w0 = w->ob_digit;
2118 wm1 = w0[size_w-1];
2119 wm2 = w0[size_w-2];
2120 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2121 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2122 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002123
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002124 SIGCHECK({
2125 Py_DECREF(a);
2126 Py_DECREF(w);
2127 Py_DECREF(v);
2128 *prem = NULL;
2129 return NULL;
2130 })
Tim Peters5af4e6c2002-08-12 02:31:19 +00002131
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002132 /* estimate quotient digit q; may overestimate by 1 (rare) */
2133 vtop = vk[size_w];
2134 assert(vtop <= wm1);
2135 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2136 q = (digit)(vv / wm1);
2137 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2138 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2139 | vk[size_w-2])) {
2140 --q;
2141 r += wm1;
2142 if (r >= PyLong_BASE)
2143 break;
2144 }
2145 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002146
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002147 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2148 zhi = 0;
2149 for (i = 0; i < size_w; ++i) {
2150 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2151 -PyLong_BASE * q <= z < PyLong_BASE */
2152 z = (sdigit)vk[i] + zhi -
2153 (stwodigits)q * (stwodigits)w0[i];
2154 vk[i] = (digit)z & PyLong_MASK;
2155 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
2156 z, PyLong_SHIFT);
2157 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002158
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002159 /* add w back if q was too large (this branch taken rarely) */
2160 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2161 if ((sdigit)vtop + zhi < 0) {
2162 carry = 0;
2163 for (i = 0; i < size_w; ++i) {
2164 carry += vk[i] + w0[i];
2165 vk[i] = carry & PyLong_MASK;
2166 carry >>= PyLong_SHIFT;
2167 }
2168 --q;
2169 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002170
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002171 /* store quotient digit */
2172 assert(q < PyLong_BASE);
2173 *--ak = q;
2174 }
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002175
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002176 /* unshift remainder; we reuse w to store the result */
2177 carry = v_rshift(w0, v0, size_w, d);
2178 assert(carry==0);
2179 Py_DECREF(v);
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002180
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002181 *prem = long_normalize(w);
2182 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002183}
2184
Mark Dickinsond3e32322010-01-02 14:45:40 +00002185/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2186 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2187 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2188 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2189 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2190 -1.0. */
2191
2192/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2193#if DBL_MANT_DIG == 53
2194#define EXP2_DBL_MANT_DIG 9007199254740992.0
2195#else
2196#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2197#endif
2198
2199double
2200_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2201{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002202 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2203 /* See below for why x_digits is always large enough. */
2204 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2205 double dx;
2206 /* Correction term for round-half-to-even rounding. For a digit x,
2207 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2208 multiple of 4, rounding ties to a multiple of 8. */
2209 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinsond3e32322010-01-02 14:45:40 +00002210
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002211 a_size = ABS(Py_SIZE(a));
2212 if (a_size == 0) {
2213 /* Special case for 0: significand 0.0, exponent 0. */
2214 *e = 0;
2215 return 0.0;
2216 }
2217 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2218 /* The following is an overflow-free version of the check
2219 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2220 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2221 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2222 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
2223 goto overflow;
2224 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinsond3e32322010-01-02 14:45:40 +00002225
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002226 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2227 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinsond3e32322010-01-02 14:45:40 +00002228
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002229 Number of digits needed for result: write // for floor division.
2230 Then if shifting left, we end up using
Mark Dickinsond3e32322010-01-02 14:45:40 +00002231
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002232 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinsond3e32322010-01-02 14:45:40 +00002233
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002234 digits. If shifting right, we use
Mark Dickinsond3e32322010-01-02 14:45:40 +00002235
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002236 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinsond3e32322010-01-02 14:45:40 +00002237
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002238 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2239 the inequalities
Mark Dickinsond3e32322010-01-02 14:45:40 +00002240
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002241 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2242 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2243 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinsond3e32322010-01-02 14:45:40 +00002244
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002245 valid for any integers m and n, we find that x_size satisfies
Mark Dickinsond3e32322010-01-02 14:45:40 +00002246
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002247 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinsond3e32322010-01-02 14:45:40 +00002248
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002249 in both cases.
2250 */
2251 if (a_bits <= DBL_MANT_DIG + 2) {
2252 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2253 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2254 x_size = 0;
2255 while (x_size < shift_digits)
2256 x_digits[x_size++] = 0;
2257 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2258 (int)shift_bits);
2259 x_size += a_size;
2260 x_digits[x_size++] = rem;
2261 }
2262 else {
2263 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2264 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2265 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2266 a_size - shift_digits, (int)shift_bits);
2267 x_size = a_size - shift_digits;
2268 /* For correct rounding below, we need the least significant
2269 bit of x to be 'sticky' for this shift: if any of the bits
2270 shifted out was nonzero, we set the least significant bit
2271 of x. */
2272 if (rem)
2273 x_digits[0] |= 1;
2274 else
2275 while (shift_digits > 0)
2276 if (a->ob_digit[--shift_digits]) {
2277 x_digits[0] |= 1;
2278 break;
2279 }
2280 }
2281 assert(1 <= x_size && x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
Mark Dickinsond3e32322010-01-02 14:45:40 +00002282
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002283 /* Round, and convert to double. */
2284 x_digits[0] += half_even_correction[x_digits[0] & 7];
2285 dx = x_digits[--x_size];
2286 while (x_size > 0)
2287 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinsond3e32322010-01-02 14:45:40 +00002288
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002289 /* Rescale; make correction if result is 1.0. */
2290 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2291 if (dx == 1.0) {
2292 if (a_bits == PY_SSIZE_T_MAX)
2293 goto overflow;
2294 dx = 0.5;
2295 a_bits += 1;
2296 }
Mark Dickinsond3e32322010-01-02 14:45:40 +00002297
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002298 *e = a_bits;
2299 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinsond3e32322010-01-02 14:45:40 +00002300
2301 overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002302 /* exponent > PY_SSIZE_T_MAX */
2303 PyErr_SetString(PyExc_OverflowError,
2304 "huge integer: number of bits overflows a Py_ssize_t");
2305 *e = 0;
2306 return -1.0;
Mark Dickinsond3e32322010-01-02 14:45:40 +00002307}
2308
2309/* Get a C double from a long int object. Rounds to the nearest double,
2310 using the round-half-to-even rule in the case of a tie. */
2311
2312double
2313PyLong_AsDouble(PyObject *v)
2314{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002315 Py_ssize_t exponent;
2316 double x;
Mark Dickinsond3e32322010-01-02 14:45:40 +00002317
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002318 if (v == NULL || !PyLong_Check(v)) {
2319 PyErr_BadInternalCall();
2320 return -1.0;
2321 }
2322 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2323 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2324 PyErr_SetString(PyExc_OverflowError,
2325 "long int too large to convert to float");
2326 return -1.0;
2327 }
2328 return ldexp(x, (int)exponent);
Mark Dickinsond3e32322010-01-02 14:45:40 +00002329}
2330
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002331/* Methods */
2332
2333static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002334long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002335{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002336 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002337}
2338
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002339static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002340long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002341{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002342 return _PyLong_Format(v, 10, 1, 0);
Fred Drake121ee271999-12-23 15:41:28 +00002343}
2344
2345static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002346long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00002347{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002348 return _PyLong_Format(v, 10, 0, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002349}
2350
2351static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002352long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002353{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002354 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002355
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002356 if (Py_SIZE(a) != Py_SIZE(b)) {
2357 sign = Py_SIZE(a) - Py_SIZE(b);
2358 }
2359 else {
2360 Py_ssize_t i = ABS(Py_SIZE(a));
2361 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2362 ;
2363 if (i < 0)
2364 sign = 0;
2365 else {
2366 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2367 if (Py_SIZE(a) < 0)
2368 sign = -sign;
2369 }
2370 }
2371 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002372}
2373
Guido van Rossum9bfef441993-03-29 10:43:31 +00002374static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002375long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002376{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002377 unsigned long x;
2378 Py_ssize_t i;
2379 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002380
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002381 /* This is designed so that Python ints and longs with the
2382 same value hash to the same value, otherwise comparisons
2383 of mapping keys will turn out weird */
2384 i = v->ob_size;
2385 sign = 1;
2386 x = 0;
2387 if (i < 0) {
2388 sign = -1;
2389 i = -(i);
2390 }
2391 /* The following loop produces a C unsigned long x such that x is
2392 congruent to the absolute value of v modulo ULONG_MAX. The
2393 resulting x is nonzero if and only if v is. */
2394 while (--i >= 0) {
2395 /* Force a native long #-bits (32 or 64) circular shift */
2396 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
2397 x += v->ob_digit[i];
2398 /* If the addition above overflowed we compensate by
2399 incrementing. This preserves the value modulo
2400 ULONG_MAX. */
2401 if (x < v->ob_digit[i])
2402 x++;
2403 }
2404 x = x * sign;
2405 if (x == (unsigned long)-1)
2406 x = (unsigned long)-2;
2407 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002408}
2409
2410
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002411/* Add the absolute values of two long integers. */
2412
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002413static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002414x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002415{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002416 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2417 PyLongObject *z;
2418 Py_ssize_t i;
2419 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002420
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002421 /* Ensure a is the larger of the two: */
2422 if (size_a < size_b) {
2423 { PyLongObject *temp = a; a = b; b = temp; }
2424 { Py_ssize_t size_temp = size_a;
2425 size_a = size_b;
2426 size_b = size_temp; }
2427 }
2428 z = _PyLong_New(size_a+1);
2429 if (z == NULL)
2430 return NULL;
2431 for (i = 0; i < size_b; ++i) {
2432 carry += a->ob_digit[i] + b->ob_digit[i];
2433 z->ob_digit[i] = carry & PyLong_MASK;
2434 carry >>= PyLong_SHIFT;
2435 }
2436 for (; i < size_a; ++i) {
2437 carry += a->ob_digit[i];
2438 z->ob_digit[i] = carry & PyLong_MASK;
2439 carry >>= PyLong_SHIFT;
2440 }
2441 z->ob_digit[i] = carry;
2442 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002443}
2444
2445/* Subtract the absolute values of two integers. */
2446
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002447static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002448x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002449{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002450 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2451 PyLongObject *z;
2452 Py_ssize_t i;
2453 int sign = 1;
2454 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002455
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002456 /* Ensure a is the larger of the two: */
2457 if (size_a < size_b) {
2458 sign = -1;
2459 { PyLongObject *temp = a; a = b; b = temp; }
2460 { Py_ssize_t size_temp = size_a;
2461 size_a = size_b;
2462 size_b = size_temp; }
2463 }
2464 else if (size_a == size_b) {
2465 /* Find highest digit where a and b differ: */
2466 i = size_a;
2467 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2468 ;
2469 if (i < 0)
2470 return _PyLong_New(0);
2471 if (a->ob_digit[i] < b->ob_digit[i]) {
2472 sign = -1;
2473 { PyLongObject *temp = a; a = b; b = temp; }
2474 }
2475 size_a = size_b = i+1;
2476 }
2477 z = _PyLong_New(size_a);
2478 if (z == NULL)
2479 return NULL;
2480 for (i = 0; i < size_b; ++i) {
2481 /* The following assumes unsigned arithmetic
2482 works module 2**N for some N>PyLong_SHIFT. */
2483 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2484 z->ob_digit[i] = borrow & PyLong_MASK;
2485 borrow >>= PyLong_SHIFT;
2486 borrow &= 1; /* Keep only one sign bit */
2487 }
2488 for (; i < size_a; ++i) {
2489 borrow = a->ob_digit[i] - borrow;
2490 z->ob_digit[i] = borrow & PyLong_MASK;
2491 borrow >>= PyLong_SHIFT;
2492 borrow &= 1; /* Keep only one sign bit */
2493 }
2494 assert(borrow == 0);
2495 if (sign < 0)
2496 z->ob_size = -(z->ob_size);
2497 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002498}
2499
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002500static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002501long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002502{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002503 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002504
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002505 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002506
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002507 if (a->ob_size < 0) {
2508 if (b->ob_size < 0) {
2509 z = x_add(a, b);
2510 if (z != NULL && z->ob_size != 0)
2511 z->ob_size = -(z->ob_size);
2512 }
2513 else
2514 z = x_sub(b, a);
2515 }
2516 else {
2517 if (b->ob_size < 0)
2518 z = x_sub(a, b);
2519 else
2520 z = x_add(a, b);
2521 }
2522 Py_DECREF(a);
2523 Py_DECREF(b);
2524 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002525}
2526
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002527static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002528long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002529{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002530 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002532 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002533
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002534 if (a->ob_size < 0) {
2535 if (b->ob_size < 0)
2536 z = x_sub(a, b);
2537 else
2538 z = x_add(a, b);
2539 if (z != NULL && z->ob_size != 0)
2540 z->ob_size = -(z->ob_size);
2541 }
2542 else {
2543 if (b->ob_size < 0)
2544 z = x_add(a, b);
2545 else
2546 z = x_sub(a, b);
2547 }
2548 Py_DECREF(a);
2549 Py_DECREF(b);
2550 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002551}
2552
Tim Peters5af4e6c2002-08-12 02:31:19 +00002553/* Grade school multiplication, ignoring the signs.
2554 * Returns the absolute value of the product, or NULL if error.
2555 */
2556static PyLongObject *
2557x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002558{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002559 PyLongObject *z;
2560 Py_ssize_t size_a = ABS(Py_SIZE(a));
2561 Py_ssize_t size_b = ABS(Py_SIZE(b));
2562 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002563
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002564 z = _PyLong_New(size_a + size_b);
2565 if (z == NULL)
2566 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002567
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002568 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2569 if (a == b) {
2570 /* Efficient squaring per HAC, Algorithm 14.16:
2571 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2572 * Gives slightly less than a 2x speedup when a == b,
2573 * via exploiting that each entry in the multiplication
2574 * pyramid appears twice (except for the size_a squares).
2575 */
2576 for (i = 0; i < size_a; ++i) {
2577 twodigits carry;
2578 twodigits f = a->ob_digit[i];
2579 digit *pz = z->ob_digit + (i << 1);
2580 digit *pa = a->ob_digit + i + 1;
2581 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002582
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002583 SIGCHECK({
2584 Py_DECREF(z);
2585 return NULL;
2586 })
Tim Peters0973b992004-08-29 22:16:50 +00002587
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002588 carry = *pz + f * f;
2589 *pz++ = (digit)(carry & PyLong_MASK);
2590 carry >>= PyLong_SHIFT;
2591 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002592
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002593 /* Now f is added in twice in each column of the
2594 * pyramid it appears. Same as adding f<<1 once.
2595 */
2596 f <<= 1;
2597 while (pa < paend) {
2598 carry += *pz + *pa++ * f;
2599 *pz++ = (digit)(carry & PyLong_MASK);
2600 carry >>= PyLong_SHIFT;
2601 assert(carry <= (PyLong_MASK << 1));
2602 }
2603 if (carry) {
2604 carry += *pz;
2605 *pz++ = (digit)(carry & PyLong_MASK);
2606 carry >>= PyLong_SHIFT;
2607 }
2608 if (carry)
2609 *pz += (digit)(carry & PyLong_MASK);
2610 assert((carry >> PyLong_SHIFT) == 0);
2611 }
2612 }
2613 else { /* a is not the same as b -- gradeschool long mult */
2614 for (i = 0; i < size_a; ++i) {
2615 twodigits carry = 0;
2616 twodigits f = a->ob_digit[i];
2617 digit *pz = z->ob_digit + i;
2618 digit *pb = b->ob_digit;
2619 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002620
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002621 SIGCHECK({
2622 Py_DECREF(z);
2623 return NULL;
2624 })
Tim Peters0973b992004-08-29 22:16:50 +00002625
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002626 while (pb < pbend) {
2627 carry += *pz + *pb++ * f;
2628 *pz++ = (digit)(carry & PyLong_MASK);
2629 carry >>= PyLong_SHIFT;
2630 assert(carry <= PyLong_MASK);
2631 }
2632 if (carry)
2633 *pz += (digit)(carry & PyLong_MASK);
2634 assert((carry >> PyLong_SHIFT) == 0);
2635 }
2636 }
2637 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002638}
2639
2640/* A helper for Karatsuba multiplication (k_mul).
2641 Takes a long "n" and an integer "size" representing the place to
2642 split, and sets low and high such that abs(n) == (high << size) + low,
2643 viewing the shift as being by digits. The sign bit is ignored, and
2644 the return values are >= 0.
2645 Returns 0 on success, -1 on failure.
2646*/
2647static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002648kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002649{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002650 PyLongObject *hi, *lo;
2651 Py_ssize_t size_lo, size_hi;
2652 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002653
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002654 size_lo = MIN(size_n, size);
2655 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002656
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002657 if ((hi = _PyLong_New(size_hi)) == NULL)
2658 return -1;
2659 if ((lo = _PyLong_New(size_lo)) == NULL) {
2660 Py_DECREF(hi);
2661 return -1;
2662 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002663
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002664 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2665 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002666
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002667 *high = long_normalize(hi);
2668 *low = long_normalize(lo);
2669 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002670}
2671
Tim Peters60004642002-08-12 22:01:34 +00002672static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2673
Tim Peters5af4e6c2002-08-12 02:31:19 +00002674/* Karatsuba multiplication. Ignores the input signs, and returns the
2675 * absolute value of the product (or NULL if error).
2676 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2677 */
2678static PyLongObject *
2679k_mul(PyLongObject *a, PyLongObject *b)
2680{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002681 Py_ssize_t asize = ABS(Py_SIZE(a));
2682 Py_ssize_t bsize = ABS(Py_SIZE(b));
2683 PyLongObject *ah = NULL;
2684 PyLongObject *al = NULL;
2685 PyLongObject *bh = NULL;
2686 PyLongObject *bl = NULL;
2687 PyLongObject *ret = NULL;
2688 PyLongObject *t1, *t2, *t3;
2689 Py_ssize_t shift; /* the number of digits we split off */
2690 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002691
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002692 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2693 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2694 * Then the original product is
2695 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2696 * By picking X to be a power of 2, "*X" is just shifting, and it's
2697 * been reduced to 3 multiplies on numbers half the size.
2698 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002699
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002700 /* We want to split based on the larger number; fiddle so that b
2701 * is largest.
2702 */
2703 if (asize > bsize) {
2704 t1 = a;
2705 a = b;
2706 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002707
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002708 i = asize;
2709 asize = bsize;
2710 bsize = i;
2711 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002712
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002713 /* Use gradeschool math when either number is too small. */
2714 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2715 if (asize <= i) {
2716 if (asize == 0)
2717 return _PyLong_New(0);
2718 else
2719 return x_mul(a, b);
2720 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002721
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002722 /* If a is small compared to b, splitting on b gives a degenerate
2723 * case with ah==0, and Karatsuba may be (even much) less efficient
2724 * than "grade school" then. However, we can still win, by viewing
2725 * b as a string of "big digits", each of width a->ob_size. That
2726 * leads to a sequence of balanced calls to k_mul.
2727 */
2728 if (2 * asize <= bsize)
2729 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002730
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002731 /* Split a & b into hi & lo pieces. */
2732 shift = bsize >> 1;
2733 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2734 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002735
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002736 if (a == b) {
2737 bh = ah;
2738 bl = al;
2739 Py_INCREF(bh);
2740 Py_INCREF(bl);
2741 }
2742 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002743
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002744 /* The plan:
2745 * 1. Allocate result space (asize + bsize digits: that's always
2746 * enough).
2747 * 2. Compute ah*bh, and copy into result at 2*shift.
2748 * 3. Compute al*bl, and copy into result at 0. Note that this
2749 * can't overlap with #2.
2750 * 4. Subtract al*bl from the result, starting at shift. This may
2751 * underflow (borrow out of the high digit), but we don't care:
2752 * we're effectively doing unsigned arithmetic mod
2753 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
2754 * borrows and carries out of the high digit can be ignored.
2755 * 5. Subtract ah*bh from the result, starting at shift.
2756 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2757 * at shift.
2758 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002759
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002760 /* 1. Allocate result space. */
2761 ret = _PyLong_New(asize + bsize);
2762 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002763#ifdef Py_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002764 /* Fill with trash, to catch reference to uninitialized digits. */
2765 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002766#endif
Tim Peters44121a62002-08-12 06:17:58 +00002767
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002768 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2769 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2770 assert(Py_SIZE(t1) >= 0);
2771 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
2772 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2773 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002774
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002775 /* Zero-out the digits higher than the ah*bh copy. */
2776 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
2777 if (i)
2778 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
2779 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002780
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002781 /* 3. t2 <- al*bl, and copy into the low digits. */
2782 if ((t2 = k_mul(al, bl)) == NULL) {
2783 Py_DECREF(t1);
2784 goto fail;
2785 }
2786 assert(Py_SIZE(t2) >= 0);
2787 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2788 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002789
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002790 /* Zero out remaining digits. */
2791 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
2792 if (i)
2793 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002794
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002795 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2796 * because it's fresher in cache.
2797 */
2798 i = Py_SIZE(ret) - shift; /* # digits after shift */
2799 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
2800 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002801
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002802 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
2803 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00002804
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002805 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
2806 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2807 Py_DECREF(ah);
2808 Py_DECREF(al);
2809 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002810
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002811 if (a == b) {
2812 t2 = t1;
2813 Py_INCREF(t2);
2814 }
2815 else if ((t2 = x_add(bh, bl)) == NULL) {
2816 Py_DECREF(t1);
2817 goto fail;
2818 }
2819 Py_DECREF(bh);
2820 Py_DECREF(bl);
2821 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002822
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002823 t3 = k_mul(t1, t2);
2824 Py_DECREF(t1);
2825 Py_DECREF(t2);
2826 if (t3 == NULL) goto fail;
2827 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002828
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002829 /* Add t3. It's not obvious why we can't run out of room here.
2830 * See the (*) comment after this function.
2831 */
2832 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
2833 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002834
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002835 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002836
2837 fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002838 Py_XDECREF(ret);
2839 Py_XDECREF(ah);
2840 Py_XDECREF(al);
2841 Py_XDECREF(bh);
2842 Py_XDECREF(bl);
2843 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002844}
2845
Tim Petersd6974a52002-08-13 20:37:51 +00002846/* (*) Why adding t3 can't "run out of room" above.
2847
Tim Petersab86c2b2002-08-15 20:06:00 +00002848Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2849to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002850
Tim Petersab86c2b2002-08-15 20:06:00 +000028511. For any integer i, i = c(i/2) + f(i/2). In particular,
2852 bsize = c(bsize/2) + f(bsize/2).
28532. shift = f(bsize/2)
28543. asize <= bsize
28554. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2856 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002857
Tim Petersab86c2b2002-08-15 20:06:00 +00002858We allocated asize + bsize result digits, and add t3 into them at an offset
2859of shift. This leaves asize+bsize-shift allocated digit positions for t3
2860to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2861asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002862
Tim Petersab86c2b2002-08-15 20:06:00 +00002863bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2864at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002865
Tim Petersab86c2b2002-08-15 20:06:00 +00002866If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2867digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2868most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002869
Tim Petersab86c2b2002-08-15 20:06:00 +00002870The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002871
Tim Petersab86c2b2002-08-15 20:06:00 +00002872 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002873
Tim Petersab86c2b2002-08-15 20:06:00 +00002874and we have asize + c(bsize/2) available digit positions. We need to show
2875this is always enough. An instance of c(bsize/2) cancels out in both, so
2876the question reduces to whether asize digits is enough to hold
2877(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2878then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2879asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002880digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002881asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002882c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2883is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2884bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002885
Tim Peters48d52c02002-08-14 17:07:32 +00002886Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2887clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2888ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002889*/
2890
Tim Peters60004642002-08-12 22:01:34 +00002891/* b has at least twice the digits of a, and a is big enough that Karatsuba
2892 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2893 * of slices, each with a->ob_size digits, and multiply the slices by a,
2894 * one at a time. This gives k_mul balanced inputs to work with, and is
2895 * also cache-friendly (we compute one double-width slice of the result
2896 * at a time, then move on, never bactracking except for the helpful
2897 * single-width slice overlap between successive partial sums).
2898 */
2899static PyLongObject *
2900k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2901{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002902 const Py_ssize_t asize = ABS(Py_SIZE(a));
2903 Py_ssize_t bsize = ABS(Py_SIZE(b));
2904 Py_ssize_t nbdone; /* # of b digits already multiplied */
2905 PyLongObject *ret;
2906 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00002907
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002908 assert(asize > KARATSUBA_CUTOFF);
2909 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00002910
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002911 /* Allocate result space, and zero it out. */
2912 ret = _PyLong_New(asize + bsize);
2913 if (ret == NULL)
2914 return NULL;
2915 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002916
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002917 /* Successive slices of b are copied into bslice. */
2918 bslice = _PyLong_New(asize);
2919 if (bslice == NULL)
2920 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00002921
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002922 nbdone = 0;
2923 while (bsize > 0) {
2924 PyLongObject *product;
2925 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002926
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002927 /* Multiply the next slice of b by a. */
2928 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2929 nbtouse * sizeof(digit));
2930 Py_SIZE(bslice) = nbtouse;
2931 product = k_mul(a, bslice);
2932 if (product == NULL)
2933 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00002934
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002935 /* Add into result. */
2936 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2937 product->ob_digit, Py_SIZE(product));
2938 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00002939
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002940 bsize -= nbtouse;
2941 nbdone += nbtouse;
2942 }
Tim Peters60004642002-08-12 22:01:34 +00002943
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002944 Py_DECREF(bslice);
2945 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00002946
2947 fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002948 Py_DECREF(ret);
2949 Py_XDECREF(bslice);
2950 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00002951}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002952
2953static PyObject *
2954long_mul(PyLongObject *v, PyLongObject *w)
2955{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002956 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002957
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002958 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
2959 Py_INCREF(Py_NotImplemented);
2960 return Py_NotImplemented;
2961 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002962
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002963 z = k_mul(a, b);
2964 /* Negate if exactly one of the inputs is negative. */
2965 if (((a->ob_size ^ b->ob_size) < 0) && z)
2966 z->ob_size = -(z->ob_size);
2967 Py_DECREF(a);
2968 Py_DECREF(b);
2969 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002970}
2971
Guido van Rossume32e0141992-01-19 16:31:05 +00002972/* The / and % operators are now defined in terms of divmod().
2973 The expression a mod b has the value a - b*floor(a/b).
2974 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002975 |a| by |b|, with the sign of a. This is also expressed
2976 as a - b*trunc(a/b), if trunc truncates towards zero.
2977 Some examples:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002978 a b a rem b a mod b
2979 13 10 3 3
2980 -13 10 -3 7
2981 13 -10 3 -7
2982 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002983 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002984 have different signs. We then subtract one from the 'div'
2985 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002986
Tim Peters47e52ee2004-08-30 02:44:38 +00002987/* Compute
2988 * *pdiv, *pmod = divmod(v, w)
2989 * NULL can be passed for pdiv or pmod, in which case that part of
2990 * the result is simply thrown away. The caller owns a reference to
2991 * each of these it requests (does not pass NULL for).
2992 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002993static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002994l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002995 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002996{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002997 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002998
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002999 if (long_divrem(v, w, &div, &mod) < 0)
3000 return -1;
3001 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3002 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3003 PyLongObject *temp;
3004 PyLongObject *one;
3005 temp = (PyLongObject *) long_add(mod, w);
3006 Py_DECREF(mod);
3007 mod = temp;
3008 if (mod == NULL) {
3009 Py_DECREF(div);
3010 return -1;
3011 }
3012 one = (PyLongObject *) PyLong_FromLong(1L);
3013 if (one == NULL ||
3014 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3015 Py_DECREF(mod);
3016 Py_DECREF(div);
3017 Py_XDECREF(one);
3018 return -1;
3019 }
3020 Py_DECREF(one);
3021 Py_DECREF(div);
3022 div = temp;
3023 }
3024 if (pdiv != NULL)
3025 *pdiv = div;
3026 else
3027 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003028
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003029 if (pmod != NULL)
3030 *pmod = mod;
3031 else
3032 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003033
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003034 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003035}
3036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003037static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003038long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00003039{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003040 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003041
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003042 CONVERT_BINOP(v, w, &a, &b);
3043 if (l_divmod(a, b, &div, NULL) < 0)
3044 div = NULL;
3045 Py_DECREF(a);
3046 Py_DECREF(b);
3047 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003048}
3049
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003050static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00003051long_classic_div(PyObject *v, PyObject *w)
3052{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003053 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00003054
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003055 CONVERT_BINOP(v, w, &a, &b);
3056 if (Py_DivisionWarningFlag &&
3057 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
3058 div = NULL;
3059 else if (l_divmod(a, b, &div, NULL) < 0)
3060 div = NULL;
3061 Py_DECREF(a);
3062 Py_DECREF(b);
3063 return (PyObject *)div;
Guido van Rossum393661d2001-08-31 17:40:15 +00003064}
3065
Mark Dickinson46572832009-12-27 14:55:57 +00003066/* PyLong/PyLong -> float, with correctly rounded result. */
3067
3068#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3069#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3070
Guido van Rossum393661d2001-08-31 17:40:15 +00003071static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00003072long_true_divide(PyObject *v, PyObject *w)
3073{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003074 PyLongObject *a, *b, *x;
3075 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3076 digit mask, low;
3077 int inexact, negate, a_is_small, b_is_small;
3078 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003079
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003080 CONVERT_BINOP(v, w, &a, &b);
Tim Peterse2a60002001-09-04 06:17:36 +00003081
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003082 /*
3083 Method in a nutshell:
Mark Dickinson46572832009-12-27 14:55:57 +00003084
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003085 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3086 1. choose a suitable integer 'shift'
3087 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3088 3. adjust x for correct rounding
3089 4. convert x to a double dx with the same value
3090 5. return ldexp(dx, shift).
Mark Dickinson46572832009-12-27 14:55:57 +00003091
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003092 In more detail:
Mark Dickinson46572832009-12-27 14:55:57 +00003093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003094 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3095 returns either 0.0 or -0.0, depending on the sign of b. For a and
3096 b both nonzero, ignore signs of a and b, and add the sign back in
3097 at the end. Now write a_bits and b_bits for the bit lengths of a
3098 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3099 for b). Then
Mark Dickinson46572832009-12-27 14:55:57 +00003100
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003101 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinson46572832009-12-27 14:55:57 +00003102
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003103 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3104 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3105 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3106 the way, we can assume that
Mark Dickinson46572832009-12-27 14:55:57 +00003107
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003108 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinson46572832009-12-27 14:55:57 +00003109
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003110 1. The integer 'shift' is chosen so that x has the right number of
3111 bits for a double, plus two or three extra bits that will be used
3112 in the rounding decisions. Writing a_bits and b_bits for the
3113 number of significant bits in a and b respectively, a
3114 straightforward formula for shift is:
Mark Dickinson46572832009-12-27 14:55:57 +00003115
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003116 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinson46572832009-12-27 14:55:57 +00003117
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003118 This is fine in the usual case, but if a/b is smaller than the
3119 smallest normal float then it can lead to double rounding on an
3120 IEEE 754 platform, giving incorrectly rounded results. So we
3121 adjust the formula slightly. The actual formula used is:
Mark Dickinson46572832009-12-27 14:55:57 +00003122
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003123 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinson46572832009-12-27 14:55:57 +00003124
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003125 2. The quantity x is computed by first shifting a (left -shift bits
3126 if shift <= 0, right shift bits if shift > 0) and then dividing by
3127 b. For both the shift and the division, we keep track of whether
3128 the result is inexact, in a flag 'inexact'; this information is
3129 needed at the rounding stage.
Mark Dickinson46572832009-12-27 14:55:57 +00003130
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003131 With the choice of shift above, together with our assumption that
3132 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3133 that x >= 1.
Mark Dickinson46572832009-12-27 14:55:57 +00003134
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003135 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3136 this with an exactly representable float of the form
Mark Dickinson46572832009-12-27 14:55:57 +00003137
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003138 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinson46572832009-12-27 14:55:57 +00003139
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003140 For float representability, we need x/2**extra_bits <
3141 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3142 DBL_MANT_DIG. This translates to the condition:
Mark Dickinson46572832009-12-27 14:55:57 +00003143
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003144 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinson46572832009-12-27 14:55:57 +00003145
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003146 To round, we just modify the bottom digit of x in-place; this can
3147 end up giving a digit with value > PyLONG_MASK, but that's not a
3148 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinson46572832009-12-27 14:55:57 +00003149
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003150 With the original choices for shift above, extra_bits will always
3151 be 2 or 3. Then rounding under the round-half-to-even rule, we
3152 round up iff the most significant of the extra bits is 1, and
3153 either: (a) the computation of x in step 2 had an inexact result,
3154 or (b) at least one other of the extra bits is 1, or (c) the least
3155 significant bit of x (above those to be rounded) is 1.
Mark Dickinson46572832009-12-27 14:55:57 +00003156
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003157 4. Conversion to a double is straightforward; all floating-point
3158 operations involved in the conversion are exact, so there's no
3159 danger of rounding errors.
Mark Dickinson46572832009-12-27 14:55:57 +00003160
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003161 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3162 The result will always be exactly representable as a double, except
3163 in the case that it overflows. To avoid dependence on the exact
3164 behaviour of ldexp on overflow, we check for overflow before
3165 applying ldexp. The result of ldexp is adjusted for sign before
3166 returning.
3167 */
Mark Dickinson46572832009-12-27 14:55:57 +00003168
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003169 /* Reduce to case where a and b are both positive. */
3170 a_size = ABS(Py_SIZE(a));
3171 b_size = ABS(Py_SIZE(b));
3172 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3173 if (b_size == 0) {
3174 PyErr_SetString(PyExc_ZeroDivisionError,
3175 "division by zero");
3176 goto error;
3177 }
3178 if (a_size == 0)
3179 goto underflow_or_zero;
Mark Dickinson46572832009-12-27 14:55:57 +00003180
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003181 /* Fast path for a and b small (exactly representable in a double).
3182 Relies on floating-point division being correctly rounded; results
3183 may be subject to double rounding on x86 machines that operate with
3184 the x87 FPU set to 64-bit precision. */
3185 a_is_small = a_size <= MANT_DIG_DIGITS ||
3186 (a_size == MANT_DIG_DIGITS+1 &&
3187 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3188 b_is_small = b_size <= MANT_DIG_DIGITS ||
3189 (b_size == MANT_DIG_DIGITS+1 &&
3190 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3191 if (a_is_small && b_is_small) {
3192 double da, db;
3193 da = a->ob_digit[--a_size];
3194 while (a_size > 0)
3195 da = da * PyLong_BASE + a->ob_digit[--a_size];
3196 db = b->ob_digit[--b_size];
3197 while (b_size > 0)
3198 db = db * PyLong_BASE + b->ob_digit[--b_size];
3199 result = da / db;
3200 goto success;
3201 }
Tim Peterse2a60002001-09-04 06:17:36 +00003202
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003203 /* Catch obvious cases of underflow and overflow */
3204 diff = a_size - b_size;
3205 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3206 /* Extreme overflow */
3207 goto overflow;
3208 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3209 /* Extreme underflow */
3210 goto underflow_or_zero;
3211 /* Next line is now safe from overflowing a Py_ssize_t */
3212 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3213 bits_in_digit(b->ob_digit[b_size - 1]);
3214 /* Now diff = a_bits - b_bits. */
3215 if (diff > DBL_MAX_EXP)
3216 goto overflow;
3217 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3218 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003219
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003220 /* Choose value for shift; see comments for step 1 above. */
3221 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinson46572832009-12-27 14:55:57 +00003222
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003223 inexact = 0;
Mark Dickinson46572832009-12-27 14:55:57 +00003224
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003225 /* x = abs(a * 2**-shift) */
3226 if (shift <= 0) {
3227 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3228 digit rem;
3229 /* x = a << -shift */
3230 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3231 /* In practice, it's probably impossible to end up
3232 here. Both a and b would have to be enormous,
3233 using close to SIZE_T_MAX bytes of memory each. */
3234 PyErr_SetString(PyExc_OverflowError,
3235 "intermediate overflow during division");
3236 goto error;
3237 }
3238 x = _PyLong_New(a_size + shift_digits + 1);
3239 if (x == NULL)
3240 goto error;
3241 for (i = 0; i < shift_digits; i++)
3242 x->ob_digit[i] = 0;
3243 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3244 a_size, -shift % PyLong_SHIFT);
3245 x->ob_digit[a_size + shift_digits] = rem;
3246 }
3247 else {
3248 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3249 digit rem;
3250 /* x = a >> shift */
3251 assert(a_size >= shift_digits);
3252 x = _PyLong_New(a_size - shift_digits);
3253 if (x == NULL)
3254 goto error;
3255 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3256 a_size - shift_digits, shift % PyLong_SHIFT);
3257 /* set inexact if any of the bits shifted out is nonzero */
3258 if (rem)
3259 inexact = 1;
3260 while (!inexact && shift_digits > 0)
3261 if (a->ob_digit[--shift_digits])
3262 inexact = 1;
3263 }
3264 long_normalize(x);
3265 x_size = Py_SIZE(x);
Mark Dickinson46572832009-12-27 14:55:57 +00003266
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003267 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3268 reference to x, so it's safe to modify it in-place. */
3269 if (b_size == 1) {
3270 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3271 b->ob_digit[0]);
3272 long_normalize(x);
3273 if (rem)
3274 inexact = 1;
3275 }
3276 else {
3277 PyLongObject *div, *rem;
3278 div = x_divrem(x, b, &rem);
3279 Py_DECREF(x);
3280 x = div;
3281 if (x == NULL)
3282 goto error;
3283 if (Py_SIZE(rem))
3284 inexact = 1;
3285 Py_DECREF(rem);
3286 }
3287 x_size = ABS(Py_SIZE(x));
3288 assert(x_size > 0); /* result of division is never zero */
3289 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinson46572832009-12-27 14:55:57 +00003290
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003291 /* The number of extra bits that have to be rounded away. */
3292 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3293 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinson46572832009-12-27 14:55:57 +00003294
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003295 /* Round by directly modifying the low digit of x. */
3296 mask = (digit)1 << (extra_bits - 1);
3297 low = x->ob_digit[0] | inexact;
3298 if (low & mask && low & (3*mask-1))
3299 low += mask;
3300 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinson46572832009-12-27 14:55:57 +00003301
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003302 /* Convert x to a double dx; the conversion is exact. */
3303 dx = x->ob_digit[--x_size];
3304 while (x_size > 0)
3305 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3306 Py_DECREF(x);
Mark Dickinson46572832009-12-27 14:55:57 +00003307
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003308 /* Check whether ldexp result will overflow a double. */
3309 if (shift + x_bits >= DBL_MAX_EXP &&
3310 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3311 goto overflow;
3312 result = ldexp(dx, (int)shift);
Mark Dickinson46572832009-12-27 14:55:57 +00003313
3314 success:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003315 Py_DECREF(a);
3316 Py_DECREF(b);
3317 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinson46572832009-12-27 14:55:57 +00003318
3319 underflow_or_zero:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003320 Py_DECREF(a);
3321 Py_DECREF(b);
3322 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinson46572832009-12-27 14:55:57 +00003323
3324 overflow:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003325 PyErr_SetString(PyExc_OverflowError,
3326 "integer division result too large for a float");
Mark Dickinson46572832009-12-27 14:55:57 +00003327 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003328 Py_DECREF(a);
3329 Py_DECREF(b);
3330 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003331}
3332
3333static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003334long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00003335{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003336 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003337
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003338 CONVERT_BINOP(v, w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003339
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003340 if (l_divmod(a, b, NULL, &mod) < 0)
3341 mod = NULL;
3342 Py_DECREF(a);
3343 Py_DECREF(b);
3344 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003345}
3346
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003347static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003348long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003349{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003350 PyLongObject *a, *b, *div, *mod;
3351 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003352
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003353 CONVERT_BINOP(v, w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003354
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003355 if (l_divmod(a, b, &div, &mod) < 0) {
3356 Py_DECREF(a);
3357 Py_DECREF(b);
3358 return NULL;
3359 }
3360 z = PyTuple_New(2);
3361 if (z != NULL) {
3362 PyTuple_SetItem(z, 0, (PyObject *) div);
3363 PyTuple_SetItem(z, 1, (PyObject *) mod);
3364 }
3365 else {
3366 Py_DECREF(div);
3367 Py_DECREF(mod);
3368 }
3369 Py_DECREF(a);
3370 Py_DECREF(b);
3371 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003372}
3373
Tim Peters47e52ee2004-08-30 02:44:38 +00003374/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003375static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003376long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003377{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003378 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3379 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003380
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003381 PyLongObject *z = NULL; /* accumulated result */
3382 Py_ssize_t i, j, k; /* counters */
3383 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003384
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003385 /* 5-ary values. If the exponent is large enough, table is
3386 * precomputed so that table[i] == a**i % c for i in range(32).
3387 */
3388 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3389 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003390
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003391 /* a, b, c = v, w, x */
3392 CONVERT_BINOP(v, w, &a, &b);
3393 if (PyLong_Check(x)) {
3394 c = (PyLongObject *)x;
3395 Py_INCREF(x);
3396 }
3397 else if (PyInt_Check(x)) {
3398 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
3399 if (c == NULL)
3400 goto Error;
3401 }
3402 else if (x == Py_None)
3403 c = NULL;
3404 else {
3405 Py_DECREF(a);
3406 Py_DECREF(b);
3407 Py_INCREF(Py_NotImplemented);
3408 return Py_NotImplemented;
3409 }
Tim Peters4c483c42001-09-05 06:24:58 +00003410
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003411 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3412 if (c) {
3413 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
3414 "cannot be negative when 3rd argument specified");
3415 goto Error;
3416 }
3417 else {
3418 /* else return a float. This works because we know
3419 that this calls float_pow() which converts its
3420 arguments to double. */
3421 Py_DECREF(a);
3422 Py_DECREF(b);
3423 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3424 }
3425 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003426
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003427 if (c) {
3428 /* if modulus == 0:
3429 raise ValueError() */
3430 if (Py_SIZE(c) == 0) {
3431 PyErr_SetString(PyExc_ValueError,
3432 "pow() 3rd argument cannot be 0");
3433 goto Error;
3434 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003435
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003436 /* if modulus < 0:
3437 negativeOutput = True
3438 modulus = -modulus */
3439 if (Py_SIZE(c) < 0) {
3440 negativeOutput = 1;
3441 temp = (PyLongObject *)_PyLong_Copy(c);
3442 if (temp == NULL)
3443 goto Error;
3444 Py_DECREF(c);
3445 c = temp;
3446 temp = NULL;
3447 c->ob_size = - c->ob_size;
3448 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003449
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003450 /* if modulus == 1:
3451 return 0 */
3452 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3453 z = (PyLongObject *)PyLong_FromLong(0L);
3454 goto Done;
3455 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003456
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003457 /* if base < 0:
3458 base = base % modulus
3459 Having the base positive just makes things easier. */
3460 if (Py_SIZE(a) < 0) {
3461 if (l_divmod(a, c, NULL, &temp) < 0)
3462 goto Error;
3463 Py_DECREF(a);
3464 a = temp;
3465 temp = NULL;
3466 }
3467 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003468
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003469 /* At this point a, b, and c are guaranteed non-negative UNLESS
3470 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003471
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003472 z = (PyLongObject *)PyLong_FromLong(1L);
3473 if (z == NULL)
3474 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003475
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003476 /* Perform a modular reduction, X = X % c, but leave X alone if c
3477 * is NULL.
3478 */
3479#define REDUCE(X) \
3480 if (c != NULL) { \
3481 if (l_divmod(X, c, NULL, &temp) < 0) \
3482 goto Error; \
3483 Py_XDECREF(X); \
3484 X = temp; \
3485 temp = NULL; \
3486 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003487
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003488 /* Multiply two values, then reduce the result:
3489 result = X*Y % c. If c is NULL, skip the mod. */
3490#define MULT(X, Y, result) \
3491{ \
3492 temp = (PyLongObject *)long_mul(X, Y); \
3493 if (temp == NULL) \
3494 goto Error; \
3495 Py_XDECREF(result); \
3496 result = temp; \
3497 temp = NULL; \
3498 REDUCE(result) \
Tim Peters47e52ee2004-08-30 02:44:38 +00003499}
3500
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003501 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3502 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3503 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3504 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3505 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003506
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003507 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
3508 MULT(z, z, z)
3509 if (bi & j)
3510 MULT(z, a, z)
3511 }
3512 }
3513 }
3514 else {
3515 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3516 Py_INCREF(z); /* still holds 1L */
3517 table[0] = z;
3518 for (i = 1; i < 32; ++i)
3519 MULT(table[i-1], a, table[i])
Tim Peters47e52ee2004-08-30 02:44:38 +00003520
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003521 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3522 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003523
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003524 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3525 const int index = (bi >> j) & 0x1f;
3526 for (k = 0; k < 5; ++k)
3527 MULT(z, z, z)
3528 if (index)
3529 MULT(z, table[index], z)
3530 }
3531 }
3532 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003533
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003534 if (negativeOutput && (Py_SIZE(z) != 0)) {
3535 temp = (PyLongObject *)long_sub(z, c);
3536 if (temp == NULL)
3537 goto Error;
3538 Py_DECREF(z);
3539 z = temp;
3540 temp = NULL;
3541 }
3542 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003543
3544 Error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003545 if (z != NULL) {
3546 Py_DECREF(z);
3547 z = NULL;
3548 }
3549 /* fall through */
Tim Peters47e52ee2004-08-30 02:44:38 +00003550 Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003551 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3552 for (i = 0; i < 32; ++i)
3553 Py_XDECREF(table[i]);
3554 }
3555 Py_DECREF(a);
3556 Py_DECREF(b);
3557 Py_XDECREF(c);
3558 Py_XDECREF(temp);
3559 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003560}
3561
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003562static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003563long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003564{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003565 /* Implement ~x as -(x+1) */
3566 PyLongObject *x;
3567 PyLongObject *w;
3568 w = (PyLongObject *)PyLong_FromLong(1L);
3569 if (w == NULL)
3570 return NULL;
3571 x = (PyLongObject *) long_add(v, w);
3572 Py_DECREF(w);
3573 if (x == NULL)
3574 return NULL;
3575 Py_SIZE(x) = -(Py_SIZE(x));
3576 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003577}
3578
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003579static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003580long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003581{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003582 PyLongObject *z;
3583 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
3584 /* -0 == 0 */
3585 Py_INCREF(v);
3586 return (PyObject *) v;
3587 }
3588 z = (PyLongObject *)_PyLong_Copy(v);
3589 if (z != NULL)
3590 z->ob_size = -(v->ob_size);
3591 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003592}
3593
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003594static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003595long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003596{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003597 if (v->ob_size < 0)
3598 return long_neg(v);
3599 else
3600 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003601}
3602
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003603static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003604long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003605{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003606 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003607}
3608
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003609static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003610long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003611{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003612 PyLongObject *a, *b;
3613 PyLongObject *z = NULL;
3614 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3615 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003616
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003617 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003618
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003619 if (Py_SIZE(a) < 0) {
3620 /* Right shifting negative numbers is harder */
3621 PyLongObject *a1, *a2;
3622 a1 = (PyLongObject *) long_invert(a);
3623 if (a1 == NULL)
3624 goto rshift_error;
3625 a2 = (PyLongObject *) long_rshift(a1, b);
3626 Py_DECREF(a1);
3627 if (a2 == NULL)
3628 goto rshift_error;
3629 z = (PyLongObject *) long_invert(a2);
3630 Py_DECREF(a2);
3631 }
3632 else {
3633 shiftby = PyLong_AsSsize_t((PyObject *)b);
3634 if (shiftby == -1L && PyErr_Occurred())
3635 goto rshift_error;
3636 if (shiftby < 0) {
3637 PyErr_SetString(PyExc_ValueError,
3638 "negative shift count");
3639 goto rshift_error;
3640 }
3641 wordshift = shiftby / PyLong_SHIFT;
3642 newsize = ABS(Py_SIZE(a)) - wordshift;
3643 if (newsize <= 0) {
3644 z = _PyLong_New(0);
3645 Py_DECREF(a);
3646 Py_DECREF(b);
3647 return (PyObject *)z;
3648 }
3649 loshift = shiftby % PyLong_SHIFT;
3650 hishift = PyLong_SHIFT - loshift;
3651 lomask = ((digit)1 << hishift) - 1;
3652 himask = PyLong_MASK ^ lomask;
3653 z = _PyLong_New(newsize);
3654 if (z == NULL)
3655 goto rshift_error;
3656 if (Py_SIZE(a) < 0)
3657 Py_SIZE(z) = -(Py_SIZE(z));
3658 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3659 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3660 if (i+1 < newsize)
3661 z->ob_digit[i] |=
3662 (a->ob_digit[j+1] << hishift) & himask;
3663 }
3664 z = long_normalize(z);
3665 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003666rshift_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003667 Py_DECREF(a);
3668 Py_DECREF(b);
3669 return (PyObject *) z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003670
Guido van Rossumc6913e71991-11-19 20:26:46 +00003671}
3672
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003673static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003674long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003675{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003676 /* This version due to Tim Peters */
3677 PyLongObject *a, *b;
3678 PyLongObject *z = NULL;
3679 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3680 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003681
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003682 CONVERT_BINOP(v, w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003683
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003684 shiftby = PyLong_AsSsize_t((PyObject *)b);
3685 if (shiftby == -1L && PyErr_Occurred())
3686 goto lshift_error;
3687 if (shiftby < 0) {
3688 PyErr_SetString(PyExc_ValueError, "negative shift count");
3689 goto lshift_error;
3690 }
3691 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3692 wordshift = shiftby / PyLong_SHIFT;
3693 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003694
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003695 oldsize = ABS(a->ob_size);
3696 newsize = oldsize + wordshift;
3697 if (remshift)
3698 ++newsize;
3699 z = _PyLong_New(newsize);
3700 if (z == NULL)
3701 goto lshift_error;
3702 if (a->ob_size < 0)
3703 z->ob_size = -(z->ob_size);
3704 for (i = 0; i < wordshift; i++)
3705 z->ob_digit[i] = 0;
3706 accum = 0;
3707 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3708 accum |= (twodigits)a->ob_digit[j] << remshift;
3709 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3710 accum >>= PyLong_SHIFT;
3711 }
3712 if (remshift)
3713 z->ob_digit[newsize-1] = (digit)accum;
3714 else
3715 assert(!accum);
3716 z = long_normalize(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003717lshift_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003718 Py_DECREF(a);
3719 Py_DECREF(b);
3720 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003721}
3722
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003723/* Compute two's complement of digit vector a[0:m], writing result to
3724 z[0:m]. The digit vector a need not be normalized, but should not
3725 be entirely zero. a and z may point to the same digit vector. */
3726
3727static void
3728v_complement(digit *z, digit *a, Py_ssize_t m)
3729{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003730 Py_ssize_t i;
3731 digit carry = 1;
3732 for (i = 0; i < m; ++i) {
3733 carry += a[i] ^ PyLong_MASK;
3734 z[i] = carry & PyLong_MASK;
3735 carry >>= PyLong_SHIFT;
3736 }
3737 assert(carry == 0);
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003738}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003739
3740/* Bitwise and/xor/or operations */
3741
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003742static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003743long_bitwise(PyLongObject *a,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003744 int op, /* '&', '|', '^' */
3745 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003746{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003747 int nega, negb, negz;
3748 Py_ssize_t size_a, size_b, size_z, i;
3749 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003750
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003751 /* Bitwise operations for negative numbers operate as though
3752 on a two's complement representation. So convert arguments
3753 from sign-magnitude to two's complement, and convert the
3754 result back to sign-magnitude at the end. */
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003755
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003756 /* If a is negative, replace it by its two's complement. */
3757 size_a = ABS(Py_SIZE(a));
3758 nega = Py_SIZE(a) < 0;
3759 if (nega) {
3760 z = _PyLong_New(size_a);
3761 if (z == NULL)
3762 return NULL;
3763 v_complement(z->ob_digit, a->ob_digit, size_a);
3764 a = z;
3765 }
3766 else
3767 /* Keep reference count consistent. */
3768 Py_INCREF(a);
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003769
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003770 /* Same for b. */
3771 size_b = ABS(Py_SIZE(b));
3772 negb = Py_SIZE(b) < 0;
3773 if (negb) {
3774 z = _PyLong_New(size_b);
3775 if (z == NULL) {
3776 Py_DECREF(a);
3777 return NULL;
3778 }
3779 v_complement(z->ob_digit, b->ob_digit, size_b);
3780 b = z;
3781 }
3782 else
3783 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003784
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003785 /* Swap a and b if necessary to ensure size_a >= size_b. */
3786 if (size_a < size_b) {
3787 z = a; a = b; b = z;
3788 size_z = size_a; size_a = size_b; size_b = size_z;
3789 negz = nega; nega = negb; negb = negz;
3790 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003791
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003792 /* JRH: The original logic here was to allocate the result value (z)
3793 as the longer of the two operands. However, there are some cases
3794 where the result is guaranteed to be shorter than that: AND of two
3795 positives, OR of two negatives: use the shorter number. AND with
3796 mixed signs: use the positive number. OR with mixed signs: use the
3797 negative number.
3798 */
3799 switch (op) {
3800 case '^':
3801 negz = nega ^ negb;
3802 size_z = size_a;
3803 break;
3804 case '&':
3805 negz = nega & negb;
3806 size_z = negb ? size_a : size_b;
3807 break;
3808 case '|':
3809 negz = nega | negb;
3810 size_z = negb ? size_b : size_a;
3811 break;
3812 default:
3813 PyErr_BadArgument();
3814 return NULL;
3815 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003816
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003817 /* We allow an extra digit if z is negative, to make sure that
3818 the final two's complement of z doesn't overflow. */
3819 z = _PyLong_New(size_z + negz);
3820 if (z == NULL) {
3821 Py_DECREF(a);
3822 Py_DECREF(b);
3823 return NULL;
3824 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003825
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003826 /* Compute digits for overlap of a and b. */
3827 switch(op) {
3828 case '&':
3829 for (i = 0; i < size_b; ++i)
3830 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
3831 break;
3832 case '|':
3833 for (i = 0; i < size_b; ++i)
3834 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
3835 break;
3836 case '^':
3837 for (i = 0; i < size_b; ++i)
3838 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
3839 break;
3840 default:
3841 PyErr_BadArgument();
3842 return NULL;
3843 }
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003844
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003845 /* Copy any remaining digits of a, inverting if necessary. */
3846 if (op == '^' && negb)
3847 for (; i < size_z; ++i)
3848 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
3849 else if (i < size_z)
3850 memcpy(&z->ob_digit[i], &a->ob_digit[i],
3851 (size_z-i)*sizeof(digit));
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003852
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003853 /* Complement result if negative. */
3854 if (negz) {
3855 Py_SIZE(z) = -(Py_SIZE(z));
3856 z->ob_digit[size_z] = PyLong_MASK;
3857 v_complement(z->ob_digit, z->ob_digit, size_z+1);
3858 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003859
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003860 Py_DECREF(a);
3861 Py_DECREF(b);
3862 return (PyObject *)long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003863}
3864
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003865static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003866long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003867{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003868 PyLongObject *a, *b;
3869 PyObject *c;
3870 CONVERT_BINOP(v, w, &a, &b);
3871 c = long_bitwise(a, '&', b);
3872 Py_DECREF(a);
3873 Py_DECREF(b);
3874 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003875}
3876
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003877static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003878long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003879{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003880 PyLongObject *a, *b;
3881 PyObject *c;
3882 CONVERT_BINOP(v, w, &a, &b);
3883 c = long_bitwise(a, '^', b);
3884 Py_DECREF(a);
3885 Py_DECREF(b);
3886 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003887}
3888
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003889static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003890long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003891{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003892 PyLongObject *a, *b;
3893 PyObject *c;
3894 CONVERT_BINOP(v, w, &a, &b);
3895 c = long_bitwise(a, '|', b);
3896 Py_DECREF(a);
3897 Py_DECREF(b);
3898 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003899}
3900
Guido van Rossum234f9421993-06-17 12:35:49 +00003901static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003902long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003903{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003904 if (PyInt_Check(*pw)) {
3905 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
3906 if (*pw == NULL)
3907 return -1;
3908 Py_INCREF(*pv);
3909 return 0;
3910 }
3911 else if (PyLong_Check(*pw)) {
3912 Py_INCREF(*pv);
3913 Py_INCREF(*pw);
3914 return 0;
3915 }
3916 return 1; /* Can't do it */
Guido van Rossume6eefc21992-08-14 12:06:52 +00003917}
3918
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003919static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003920long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003921{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003922 if (PyLong_CheckExact(v))
3923 Py_INCREF(v);
3924 else
3925 v = _PyLong_Copy((PyLongObject *)v);
3926 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003927}
3928
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003929static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003930long_int(PyObject *v)
3931{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003932 long x;
3933 x = PyLong_AsLong(v);
3934 if (PyErr_Occurred()) {
3935 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3936 PyErr_Clear();
3937 if (PyLong_CheckExact(v)) {
3938 Py_INCREF(v);
3939 return v;
3940 }
3941 else
3942 return _PyLong_Copy((PyLongObject *)v);
3943 }
3944 else
3945 return NULL;
3946 }
3947 return PyInt_FromLong(x);
Walter Dörwaldf1715402002-11-19 20:49:15 +00003948}
3949
3950static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003951long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003952{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003953 double result;
3954 result = PyLong_AsDouble(v);
3955 if (result == -1.0 && PyErr_Occurred())
3956 return NULL;
3957 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003958}
3959
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003960static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003961long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003962{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003963 return _PyLong_Format(v, 8, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003964}
3965
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003966static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003967long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003968{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003969 return _PyLong_Format(v, 16, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003970}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003971
3972static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003973long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003974
Tim Peters6d6c1a32001-08-02 04:15:00 +00003975static PyObject *
3976long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3977{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003978 PyObject *x = NULL;
3979 int base = -909; /* unlikely! */
3980 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003982 if (type != &PyLong_Type)
3983 return long_subtype_new(type, args, kwds); /* Wimp out */
3984 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3985 &x, &base))
3986 return NULL;
3987 if (x == NULL)
3988 return PyLong_FromLong(0L);
3989 if (base == -909)
3990 return PyNumber_Long(x);
3991 else if (PyString_Check(x)) {
3992 /* Since PyLong_FromString doesn't have a length parameter,
3993 * check here for possible NULs in the string. */
3994 char *string = PyString_AS_STRING(x);
3995 if (strlen(string) != (size_t)PyString_Size(x)) {
3996 /* create a repr() of the input string,
3997 * just like PyLong_FromString does. */
3998 PyObject *srepr;
3999 srepr = PyObject_Repr(x);
4000 if (srepr == NULL)
4001 return NULL;
4002 PyErr_Format(PyExc_ValueError,
4003 "invalid literal for long() with base %d: %s",
4004 base, PyString_AS_STRING(srepr));
4005 Py_DECREF(srepr);
4006 return NULL;
4007 }
4008 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
4009 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004010#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004011 else if (PyUnicode_Check(x))
4012 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4013 PyUnicode_GET_SIZE(x),
4014 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004015#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004016 else {
4017 PyErr_SetString(PyExc_TypeError,
4018 "long() can't convert non-string with explicit base");
4019 return NULL;
4020 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004021}
4022
Guido van Rossumbef14172001-08-29 15:47:46 +00004023/* Wimpy, slow approach to tp_new calls for subtypes of long:
4024 first create a regular long from whatever arguments we got,
4025 then allocate a subtype instance and initialize it from
4026 the regular long. The regular long is then thrown away.
4027*/
4028static PyObject *
4029long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4030{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004031 PyLongObject *tmp, *newobj;
4032 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004033
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004034 assert(PyType_IsSubtype(type, &PyLong_Type));
4035 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4036 if (tmp == NULL)
4037 return NULL;
4038 assert(PyLong_CheckExact(tmp));
4039 n = Py_SIZE(tmp);
4040 if (n < 0)
4041 n = -n;
4042 newobj = (PyLongObject *)type->tp_alloc(type, n);
4043 if (newobj == NULL) {
4044 Py_DECREF(tmp);
4045 return NULL;
4046 }
4047 assert(PyLong_Check(newobj));
4048 Py_SIZE(newobj) = Py_SIZE(tmp);
4049 for (i = 0; i < n; i++)
4050 newobj->ob_digit[i] = tmp->ob_digit[i];
4051 Py_DECREF(tmp);
4052 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004053}
4054
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004055static PyObject *
4056long_getnewargs(PyLongObject *v)
4057{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004058 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004059}
4060
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004061static PyObject *
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004062long_get0(PyLongObject *v, void *context) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004063 return PyLong_FromLong(0L);
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004064}
4065
4066static PyObject *
4067long_get1(PyLongObject *v, void *context) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004068 return PyLong_FromLong(1L);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004069}
4070
Eric Smitha9f7d622008-02-17 19:46:49 +00004071static PyObject *
4072long__format__(PyObject *self, PyObject *args)
4073{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004074 PyObject *format_spec;
Eric Smitha9f7d622008-02-17 19:46:49 +00004075
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004076 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
4077 return NULL;
4078 if (PyBytes_Check(format_spec))
4079 return _PyLong_FormatAdvanced(self,
4080 PyBytes_AS_STRING(format_spec),
4081 PyBytes_GET_SIZE(format_spec));
4082 if (PyUnicode_Check(format_spec)) {
4083 /* Convert format_spec to a str */
4084 PyObject *result;
4085 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00004086
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004087 if (str_spec == NULL)
4088 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00004089
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004090 result = _PyLong_FormatAdvanced(self,
4091 PyBytes_AS_STRING(str_spec),
4092 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00004093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004094 Py_DECREF(str_spec);
4095 return result;
4096 }
4097 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
4098 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00004099}
4100
Robert Schuppenies51df0642008-06-01 16:16:17 +00004101static PyObject *
4102long_sizeof(PyLongObject *v)
4103{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004104 Py_ssize_t res;
Robert Schuppenies51df0642008-06-01 16:16:17 +00004105
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004106 res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);
4107 return PyInt_FromSsize_t(res);
Robert Schuppenies51df0642008-06-01 16:16:17 +00004108}
4109
Mark Dickinson1a707982008-12-17 16:14:37 +00004110static PyObject *
4111long_bit_length(PyLongObject *v)
4112{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004113 PyLongObject *result, *x, *y;
4114 Py_ssize_t ndigits, msd_bits = 0;
4115 digit msd;
Mark Dickinson1a707982008-12-17 16:14:37 +00004116
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004117 assert(v != NULL);
4118 assert(PyLong_Check(v));
Mark Dickinson1a707982008-12-17 16:14:37 +00004119
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004120 ndigits = ABS(Py_SIZE(v));
4121 if (ndigits == 0)
4122 return PyInt_FromLong(0);
Mark Dickinson1a707982008-12-17 16:14:37 +00004123
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004124 msd = v->ob_digit[ndigits-1];
4125 while (msd >= 32) {
4126 msd_bits += 6;
4127 msd >>= 6;
4128 }
4129 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson1a707982008-12-17 16:14:37 +00004130
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004131 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4132 return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson1a707982008-12-17 16:14:37 +00004133
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004134 /* expression above may overflow; use Python integers instead */
4135 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4136 if (result == NULL)
4137 return NULL;
4138 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4139 if (x == NULL)
4140 goto error;
4141 y = (PyLongObject *)long_mul(result, x);
4142 Py_DECREF(x);
4143 if (y == NULL)
4144 goto error;
4145 Py_DECREF(result);
4146 result = y;
Mark Dickinson1a707982008-12-17 16:14:37 +00004147
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004148 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4149 if (x == NULL)
4150 goto error;
4151 y = (PyLongObject *)long_add(result, x);
4152 Py_DECREF(x);
4153 if (y == NULL)
4154 goto error;
4155 Py_DECREF(result);
4156 result = y;
Mark Dickinson1a707982008-12-17 16:14:37 +00004157
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004158 return (PyObject *)result;
Mark Dickinson1a707982008-12-17 16:14:37 +00004159
4160error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004161 Py_DECREF(result);
4162 return NULL;
Mark Dickinson1a707982008-12-17 16:14:37 +00004163}
4164
4165PyDoc_STRVAR(long_bit_length_doc,
4166"long.bit_length() -> int or long\n\
4167\n\
4168Number of bits necessary to represent self in binary.\n\
4169>>> bin(37L)\n\
4170'0b100101'\n\
4171>>> (37L).bit_length()\n\
41726");
4173
Christian Heimes6f341092008-04-18 23:13:07 +00004174#if 0
4175static PyObject *
4176long_is_finite(PyObject *v)
4177{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004178 Py_RETURN_TRUE;
Christian Heimes6f341092008-04-18 23:13:07 +00004179}
4180#endif
4181
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004182static PyMethodDef long_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004183 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4184 "Returns self, the complex conjugate of any long."},
4185 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4186 long_bit_length_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00004187#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004188 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4189 "Returns always True."},
Christian Heimes6f341092008-04-18 23:13:07 +00004190#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004191 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4192 "Truncating an Integral returns itself."},
4193 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4194 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4195 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4196 "Returns size in memory, in bytes"},
4197 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004198};
4199
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004200static PyGetSetDef long_getset[] = {
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004201 {"real",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004202 (getter)long_long, (setter)NULL,
4203 "the real part of a complex number",
4204 NULL},
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004205 {"imag",
4206 (getter)long_get0, (setter)NULL,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004207 "the imaginary part of a complex number",
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004208 NULL},
4209 {"numerator",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004210 (getter)long_long, (setter)NULL,
4211 "the numerator of a rational number in lowest terms",
4212 NULL},
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004213 {"denominator",
4214 (getter)long_get1, (setter)NULL,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004215 "the denominator of a rational number in lowest terms",
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004216 NULL},
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004217 {NULL} /* Sentinel */
4218};
4219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004220PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00004221"long(x[, base]) -> integer\n\
4222\n\
4223Convert a string or number to a long integer, if possible. A floating\n\
4224point argument will be truncated towards zero (this does not include a\n\
4225string representation of a floating point number!) When converting a\n\
4226string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004227converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004228
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004229static PyNumberMethods long_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004230 (binaryfunc) long_add, /*nb_add*/
4231 (binaryfunc) long_sub, /*nb_subtract*/
4232 (binaryfunc) long_mul, /*nb_multiply*/
4233 long_classic_div, /*nb_divide*/
4234 long_mod, /*nb_remainder*/
4235 long_divmod, /*nb_divmod*/
4236 long_pow, /*nb_power*/
4237 (unaryfunc) long_neg, /*nb_negative*/
4238 (unaryfunc) long_long, /*tp_positive*/
4239 (unaryfunc) long_abs, /*tp_absolute*/
4240 (inquiry) long_nonzero, /*tp_nonzero*/
4241 (unaryfunc) long_invert, /*nb_invert*/
4242 long_lshift, /*nb_lshift*/
4243 (binaryfunc) long_rshift, /*nb_rshift*/
4244 long_and, /*nb_and*/
4245 long_xor, /*nb_xor*/
4246 long_or, /*nb_or*/
4247 long_coerce, /*nb_coerce*/
4248 long_int, /*nb_int*/
4249 long_long, /*nb_long*/
4250 long_float, /*nb_float*/
4251 long_oct, /*nb_oct*/
4252 long_hex, /*nb_hex*/
4253 0, /* nb_inplace_add */
4254 0, /* nb_inplace_subtract */
4255 0, /* nb_inplace_multiply */
4256 0, /* nb_inplace_divide */
4257 0, /* nb_inplace_remainder */
4258 0, /* nb_inplace_power */
4259 0, /* nb_inplace_lshift */
4260 0, /* nb_inplace_rshift */
4261 0, /* nb_inplace_and */
4262 0, /* nb_inplace_xor */
4263 0, /* nb_inplace_or */
4264 long_div, /* nb_floor_divide */
4265 long_true_divide, /* nb_true_divide */
4266 0, /* nb_inplace_floor_divide */
4267 0, /* nb_inplace_true_divide */
4268 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004269};
4270
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004271PyTypeObject PyLong_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004272 PyObject_HEAD_INIT(&PyType_Type)
4273 0, /* ob_size */
4274 "long", /* tp_name */
4275 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4276 sizeof(digit), /* tp_itemsize */
4277 long_dealloc, /* tp_dealloc */
4278 0, /* tp_print */
4279 0, /* tp_getattr */
4280 0, /* tp_setattr */
4281 (cmpfunc)long_compare, /* tp_compare */
4282 long_repr, /* tp_repr */
4283 &long_as_number, /* tp_as_number */
4284 0, /* tp_as_sequence */
4285 0, /* tp_as_mapping */
4286 (hashfunc)long_hash, /* tp_hash */
4287 0, /* tp_call */
4288 long_str, /* tp_str */
4289 PyObject_GenericGetAttr, /* tp_getattro */
4290 0, /* tp_setattro */
4291 0, /* tp_as_buffer */
4292 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4293 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4294 long_doc, /* tp_doc */
4295 0, /* tp_traverse */
4296 0, /* tp_clear */
4297 0, /* tp_richcompare */
4298 0, /* tp_weaklistoffset */
4299 0, /* tp_iter */
4300 0, /* tp_iternext */
4301 long_methods, /* tp_methods */
4302 0, /* tp_members */
4303 long_getset, /* tp_getset */
4304 0, /* tp_base */
4305 0, /* tp_dict */
4306 0, /* tp_descr_get */
4307 0, /* tp_descr_set */
4308 0, /* tp_dictoffset */
4309 0, /* tp_init */
4310 0, /* tp_alloc */
4311 long_new, /* tp_new */
4312 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004313};
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004314
4315static PyTypeObject Long_InfoType;
4316
4317PyDoc_STRVAR(long_info__doc__,
4318"sys.long_info\n\
4319\n\
4320A struct sequence that holds information about Python's\n\
4321internal representation of integers. The attributes are read only.");
4322
4323static PyStructSequence_Field long_info_fields[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004324 {"bits_per_digit", "size of a digit in bits"},
4325 {"sizeof_digit", "size in bytes of the C type used to "
4326 "represent a digit"},
4327 {NULL, NULL}
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004328};
4329
4330static PyStructSequence_Desc long_info_desc = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004331 "sys.long_info", /* name */
4332 long_info__doc__, /* doc */
4333 long_info_fields, /* fields */
4334 2 /* number of fields */
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004335};
4336
4337PyObject *
4338PyLong_GetInfo(void)
4339{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004340 PyObject* long_info;
4341 int field = 0;
4342 long_info = PyStructSequence_New(&Long_InfoType);
4343 if (long_info == NULL)
4344 return NULL;
4345 PyStructSequence_SET_ITEM(long_info, field++,
4346 PyInt_FromLong(PyLong_SHIFT));
4347 PyStructSequence_SET_ITEM(long_info, field++,
4348 PyInt_FromLong(sizeof(digit)));
4349 if (PyErr_Occurred()) {
4350 Py_CLEAR(long_info);
4351 return NULL;
4352 }
4353 return long_info;
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004354}
4355
4356int
4357_PyLong_Init(void)
4358{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004359 /* initialize long_info */
4360 if (Long_InfoType.tp_name == 0)
4361 PyStructSequence_InitType(&Long_InfoType, &long_info_desc);
4362 return 1;
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004363}