blob: e6edb4f5868c5c82de3616fd6868afefc2584e82 [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"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00009
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Tim Peters5af4e6c2002-08-12 02:31:19 +000012/* For long multiplication, use the O(N**2) school algorithm unless
13 * both operands contain more than KARATSUBA_CUTOFF digits (this
Christian Heimes7f39c9f2008-01-25 12:18:43 +000014 * being an internal Python long digit, in base PyLong_BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000015 */
Tim Peters0973b992004-08-29 22:16:50 +000016#define KARATSUBA_CUTOFF 70
17#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000018
Tim Peters47e52ee2004-08-30 02:44:38 +000019/* For exponentiation, use the binary left-to-right algorithm
20 * unless the exponent contains more than FIVEARY_CUTOFF digits.
21 * In that case, do 5 bits at a time. The potential drawback is that
22 * a table of 2**5 intermediate results is computed.
23 */
24#define FIVEARY_CUTOFF 8
25
Guido van Rossume32e0141992-01-19 16:31:05 +000026#define ABS(x) ((x) < 0 ? -(x) : (x))
27
Tim Peters5af4e6c2002-08-12 02:31:19 +000028#undef MIN
29#undef MAX
30#define MAX(x, y) ((x) < (y) ? (y) : (x))
31#define MIN(x, y) ((x) > (y) ? (y) : (x))
32
Guido van Rossume32e0141992-01-19 16:31:05 +000033/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000034static PyLongObject *long_normalize(PyLongObject *);
35static PyLongObject *mul1(PyLongObject *, wdigit);
36static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000037static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Guido van Rossume32e0141992-01-19 16:31:05 +000038
Guido van Rossumc0b618a1997-05-02 03:12:38 +000039#define SIGCHECK(PyTryBlock) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000040 if (--_Py_Ticker < 0) { \
41 _Py_Ticker = _Py_CheckInterval; \
42 if (PyErr_CheckSignals()) PyTryBlock \
43 }
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000044
Guido van Rossumedcc38a1991-05-05 20:09:44 +000045/* Normalize (remove leading zeros from) a long int object.
46 Doesn't attempt to free the storage--in most cases, due to the nature
47 of the algorithms used, this could save at most be one word anyway. */
48
Guido van Rossumc0b618a1997-05-02 03:12:38 +000049static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000050long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000051{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000052 Py_ssize_t j = ABS(Py_SIZE(v));
53 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +000054
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000055 while (i > 0 && v->ob_digit[i-1] == 0)
56 --i;
57 if (i != j)
58 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
59 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +000060}
61
62/* Allocate a new long int object with size digits.
63 Return NULL and set exception if we run out of memory. */
64
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 Pitrouc7c96a92010-05-09 15:15:40 +000068 if (size > PY_SSIZE_T_MAX) {
69 PyErr_NoMemory();
70 return NULL;
71 }
72 /* coverity[ampersand_in_size] */
73 /* XXX(nnorwitz): This can overflow --
74 PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect overflow */
75 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000076}
77
Tim Peters64b5ce32001-09-10 20:52:51 +000078PyObject *
79_PyLong_Copy(PyLongObject *src)
80{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000081 PyLongObject *result;
82 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000083
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000084 assert(src != NULL);
85 i = src->ob_size;
86 if (i < 0)
87 i = -(i);
88 result = _PyLong_New(i);
89 if (result != NULL) {
90 result->ob_size = src->ob_size;
91 while (--i >= 0)
92 result->ob_digit[i] = src->ob_digit[i];
93 }
94 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +000095}
96
Guido van Rossumedcc38a1991-05-05 20:09:44 +000097/* Create a new long int object from a C long int */
98
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000100PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000101{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000102 PyLongObject *v;
103 unsigned long abs_ival;
104 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
105 int ndigits = 0;
106 int negative = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000107
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000108 if (ival < 0) {
109 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
110 ANSI C says that the result of -ival is undefined when ival
111 == LONG_MIN. Hence the following workaround. */
112 abs_ival = (unsigned long)(-1-ival) + 1;
113 negative = 1;
114 }
115 else {
116 abs_ival = (unsigned long)ival;
117 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000118
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000119 /* Count the number of Python digits.
120 We used to pick 5 ("big enough for anything"), but that's a
121 waste of time and space given that 5*15 = 75 bits are rarely
122 needed. */
123 t = abs_ival;
124 while (t) {
125 ++ndigits;
126 t >>= PyLong_SHIFT;
127 }
128 v = _PyLong_New(ndigits);
129 if (v != NULL) {
130 digit *p = v->ob_digit;
131 v->ob_size = negative ? -ndigits : ndigits;
132 t = abs_ival;
133 while (t) {
134 *p++ = (digit)(t & PyLong_MASK);
135 t >>= PyLong_SHIFT;
136 }
137 }
138 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000139}
140
Guido van Rossum53756b11997-01-03 17:14:46 +0000141/* Create a new long int object from a C unsigned long int */
142
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000144PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000145{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000146 PyLongObject *v;
147 unsigned long t;
148 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000149
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000150 /* Count the number of Python digits. */
151 t = (unsigned long)ival;
152 while (t) {
153 ++ndigits;
154 t >>= PyLong_SHIFT;
155 }
156 v = _PyLong_New(ndigits);
157 if (v != NULL) {
158 digit *p = v->ob_digit;
159 Py_SIZE(v) = ndigits;
160 while (ival) {
161 *p++ = (digit)(ival & PyLong_MASK);
162 ival >>= PyLong_SHIFT;
163 }
164 }
165 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000166}
167
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000168/* Create a new long int object from a C double */
169
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000172{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000173 PyLongObject *v;
174 double frac;
175 int i, ndig, expo, neg;
176 neg = 0;
177 if (Py_IS_INFINITY(dval)) {
178 PyErr_SetString(PyExc_OverflowError,
179 "cannot convert float infinity to integer");
180 return NULL;
181 }
182 if (Py_IS_NAN(dval)) {
183 PyErr_SetString(PyExc_ValueError,
184 "cannot convert float NaN to integer");
185 return NULL;
186 }
187 if (dval < 0.0) {
188 neg = 1;
189 dval = -dval;
190 }
191 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
192 if (expo <= 0)
193 return PyLong_FromLong(0L);
194 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
195 v = _PyLong_New(ndig);
196 if (v == NULL)
197 return NULL;
198 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
199 for (i = ndig; --i >= 0; ) {
200 long bits = (long)frac;
201 v->ob_digit[i] = (digit) bits;
202 frac = frac - (double)bits;
203 frac = ldexp(frac, PyLong_SHIFT);
204 }
205 if (neg)
206 Py_SIZE(v) = -(Py_SIZE(v));
207 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000208}
209
Armin Rigo7ccbca92006-10-04 12:17:45 +0000210/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
211 * anything about what happens when a signed integer operation overflows,
212 * and some compilers think they're doing you a favor by being "clever"
213 * then. The bit pattern for the largest postive signed long is
214 * (unsigned long)LONG_MAX, and for the smallest negative signed long
215 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
216 * However, some other compilers warn about applying unary minus to an
217 * unsigned operand. Hence the weird "0-".
218 */
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000219#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
220#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Armin Rigo7ccbca92006-10-04 12:17:45 +0000221
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000222/* Get a C long int from a long int object.
223 Returns -1 and sets an error condition if overflow occurs. */
224
225long
Tim Peters9f688bf2000-07-07 15:53:28 +0000226PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000227{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000228 /* This version by Tim Peters */
229 register PyLongObject *v;
230 unsigned long x, prev;
231 Py_ssize_t i;
232 int sign;
Guido van Rossumf7531811998-05-26 14:33:37 +0000233
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000234 if (vv == NULL || !PyLong_Check(vv)) {
235 if (vv != NULL && PyInt_Check(vv))
236 return PyInt_AsLong(vv);
237 PyErr_BadInternalCall();
238 return -1;
239 }
240 v = (PyLongObject *)vv;
241 i = v->ob_size;
242 sign = 1;
243 x = 0;
244 if (i < 0) {
245 sign = -1;
246 i = -(i);
247 }
248 while (--i >= 0) {
249 prev = x;
250 x = (x << PyLong_SHIFT) + v->ob_digit[i];
251 if ((x >> PyLong_SHIFT) != prev)
252 goto overflow;
253 }
254 /* Haven't lost any bits, but casting to long requires extra care
255 * (see comment above).
256 */
257 if (x <= (unsigned long)LONG_MAX) {
258 return (long)x * sign;
259 }
260 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
261 return LONG_MIN;
262 }
263 /* else overflow */
Guido van Rossumf7531811998-05-26 14:33:37 +0000264
265 overflow:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000266 PyErr_SetString(PyExc_OverflowError,
267 "long int too large to convert to int");
268 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000269}
270
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000271/* Get a Py_ssize_t from a long int object.
272 Returns -1 and sets an error condition if overflow occurs. */
273
274Py_ssize_t
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000275PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000276 register PyLongObject *v;
277 size_t x, prev;
278 Py_ssize_t i;
279 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000280
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000281 if (vv == NULL || !PyLong_Check(vv)) {
282 PyErr_BadInternalCall();
283 return -1;
284 }
285 v = (PyLongObject *)vv;
286 i = v->ob_size;
287 sign = 1;
288 x = 0;
289 if (i < 0) {
290 sign = -1;
291 i = -(i);
292 }
293 while (--i >= 0) {
294 prev = x;
295 x = (x << PyLong_SHIFT) + v->ob_digit[i];
296 if ((x >> PyLong_SHIFT) != prev)
297 goto overflow;
298 }
299 /* Haven't lost any bits, but casting to a signed type requires
300 * extra care (see comment above).
301 */
302 if (x <= (size_t)PY_SSIZE_T_MAX) {
303 return (Py_ssize_t)x * sign;
304 }
305 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
306 return PY_SSIZE_T_MIN;
307 }
308 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000309
310 overflow:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000311 PyErr_SetString(PyExc_OverflowError,
312 "long int too large to convert to int");
313 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000314}
315
Guido van Rossumd8c80482002-08-13 00:24:58 +0000316/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000317 Returns -1 and sets an error condition if overflow occurs. */
318
319unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000320PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000321{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000322 register PyLongObject *v;
323 unsigned long x, prev;
324 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000325
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000326 if (vv == NULL || !PyLong_Check(vv)) {
327 if (vv != NULL && PyInt_Check(vv)) {
328 long val = PyInt_AsLong(vv);
329 if (val < 0) {
330 PyErr_SetString(PyExc_OverflowError,
331 "can't convert negative value to unsigned long");
332 return (unsigned long) -1;
333 }
334 return val;
335 }
336 PyErr_BadInternalCall();
337 return (unsigned long) -1;
338 }
339 v = (PyLongObject *)vv;
340 i = Py_SIZE(v);
341 x = 0;
342 if (i < 0) {
343 PyErr_SetString(PyExc_OverflowError,
344 "can't convert negative value to unsigned long");
345 return (unsigned long) -1;
346 }
347 while (--i >= 0) {
348 prev = x;
349 x = (x << PyLong_SHIFT) + v->ob_digit[i];
350 if ((x >> PyLong_SHIFT) != prev) {
351 PyErr_SetString(PyExc_OverflowError,
352 "long int too large to convert");
353 return (unsigned long) -1;
354 }
355 }
356 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000357}
358
Thomas Hellera4ea6032003-04-17 18:55:45 +0000359/* Get a C unsigned long int from a long int object, ignoring the high bits.
360 Returns -1 and sets an error condition if an error occurs. */
361
362unsigned long
363PyLong_AsUnsignedLongMask(PyObject *vv)
364{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000365 register PyLongObject *v;
366 unsigned long x;
367 Py_ssize_t i;
368 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000369
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000370 if (vv == NULL || !PyLong_Check(vv)) {
371 if (vv != NULL && PyInt_Check(vv))
372 return PyInt_AsUnsignedLongMask(vv);
373 PyErr_BadInternalCall();
374 return (unsigned long) -1;
375 }
376 v = (PyLongObject *)vv;
377 i = v->ob_size;
378 sign = 1;
379 x = 0;
380 if (i < 0) {
381 sign = -1;
382 i = -i;
383 }
384 while (--i >= 0) {
385 x = (x << PyLong_SHIFT) + v->ob_digit[i];
386 }
387 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000388}
389
Tim Peters5b8132f2003-01-31 15:52:05 +0000390int
391_PyLong_Sign(PyObject *vv)
392{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000393 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000394
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000395 assert(v != NULL);
396 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000397
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000398 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000399}
400
Tim Petersbaefd9e2003-01-28 20:37:45 +0000401size_t
402_PyLong_NumBits(PyObject *vv)
403{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000404 PyLongObject *v = (PyLongObject *)vv;
405 size_t result = 0;
406 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000407
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000408 assert(v != NULL);
409 assert(PyLong_Check(v));
410 ndigits = ABS(Py_SIZE(v));
411 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
412 if (ndigits > 0) {
413 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000414
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000415 result = (ndigits - 1) * PyLong_SHIFT;
416 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
417 goto Overflow;
418 do {
419 ++result;
420 if (result == 0)
421 goto Overflow;
422 msd >>= 1;
423 } while (msd);
424 }
425 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000426
427Overflow:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000428 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
429 "to express in a platform size_t");
430 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000431}
432
Tim Peters2a9b3672001-06-11 21:23:58 +0000433PyObject *
434_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000435 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000436{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000437 const unsigned char* pstartbyte;/* LSB of bytes */
438 int incr; /* direction to move pstartbyte */
439 const unsigned char* pendbyte; /* MSB of bytes */
440 size_t numsignificantbytes; /* number of bytes that matter */
441 size_t ndigits; /* number of Python long digits */
442 PyLongObject* v; /* result */
443 int idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000444
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000445 if (n == 0)
446 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000447
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000448 if (little_endian) {
449 pstartbyte = bytes;
450 pendbyte = bytes + n - 1;
451 incr = 1;
452 }
453 else {
454 pstartbyte = bytes + n - 1;
455 pendbyte = bytes;
456 incr = -1;
457 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000458
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000459 if (is_signed)
460 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000461
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000462 /* Compute numsignificantbytes. This consists of finding the most
463 significant byte. Leading 0 bytes are insignficant if the number
464 is positive, and leading 0xff bytes if negative. */
465 {
466 size_t i;
467 const unsigned char* p = pendbyte;
468 const int pincr = -incr; /* search MSB to LSB */
469 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000470
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000471 for (i = 0; i < n; ++i, p += pincr) {
472 if (*p != insignficant)
473 break;
474 }
475 numsignificantbytes = n - i;
476 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
477 actually has 2 significant bytes. OTOH, 0xff0001 ==
478 -0x00ffff, so we wouldn't *need* to bump it there; but we
479 do for 0xffff = -0x0001. To be safe without bothering to
480 check every case, bump it regardless. */
481 if (is_signed && numsignificantbytes < n)
482 ++numsignificantbytes;
483 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000484
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000485 /* How many Python long digits do we need? We have
486 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
487 bits, so it's the ceiling of the quotient. */
488 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
489 if (ndigits > (size_t)INT_MAX)
490 return PyErr_NoMemory();
491 v = _PyLong_New((int)ndigits);
492 if (v == NULL)
493 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000494
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000495 /* Copy the bits over. The tricky parts are computing 2's-comp on
496 the fly for signed numbers, and dealing with the mismatch between
497 8-bit bytes and (probably) 15-bit Python digits.*/
498 {
499 size_t i;
500 twodigits carry = 1; /* for 2's-comp calculation */
501 twodigits accum = 0; /* sliding register */
502 unsigned int accumbits = 0; /* number of bits in accum */
503 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000504
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000505 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
506 twodigits thisbyte = *p;
507 /* Compute correction for 2's comp, if needed. */
508 if (is_signed) {
509 thisbyte = (0xff ^ thisbyte) + carry;
510 carry = thisbyte >> 8;
511 thisbyte &= 0xff;
512 }
513 /* Because we're going LSB to MSB, thisbyte is
514 more significant than what's already in accum,
515 so needs to be prepended to accum. */
516 accum |= (twodigits)thisbyte << accumbits;
517 accumbits += 8;
518 if (accumbits >= PyLong_SHIFT) {
519 /* There's enough to fill a Python digit. */
520 assert(idigit < (int)ndigits);
521 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
522 ++idigit;
523 accum >>= PyLong_SHIFT;
524 accumbits -= PyLong_SHIFT;
525 assert(accumbits < PyLong_SHIFT);
526 }
527 }
528 assert(accumbits < PyLong_SHIFT);
529 if (accumbits) {
530 assert(idigit < (int)ndigits);
531 v->ob_digit[idigit] = (digit)accum;
532 ++idigit;
533 }
534 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000535
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000536 Py_SIZE(v) = is_signed ? -idigit : idigit;
537 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000538}
539
540int
541_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000542 unsigned char* bytes, size_t n,
543 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000544{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000545 Py_ssize_t i; /* index into v->ob_digit */
546 Py_ssize_t ndigits; /* |v->ob_size| */
547 twodigits accum; /* sliding register */
548 unsigned int accumbits; /* # bits in accum */
549 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
550 digit carry; /* for computing 2's-comp */
551 size_t j; /* # bytes filled */
552 unsigned char* p; /* pointer to next byte in bytes */
553 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000554
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000555 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000556
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000557 if (Py_SIZE(v) < 0) {
558 ndigits = -(Py_SIZE(v));
559 if (!is_signed) {
560 PyErr_SetString(PyExc_TypeError,
561 "can't convert negative long to unsigned");
562 return -1;
563 }
564 do_twos_comp = 1;
565 }
566 else {
567 ndigits = Py_SIZE(v);
568 do_twos_comp = 0;
569 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000570
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000571 if (little_endian) {
572 p = bytes;
573 pincr = 1;
574 }
575 else {
576 p = bytes + n - 1;
577 pincr = -1;
578 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000579
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000580 /* Copy over all the Python digits.
581 It's crucial that every Python digit except for the MSD contribute
582 exactly PyLong_SHIFT bits to the total, so first assert that the long is
583 normalized. */
584 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
585 j = 0;
586 accum = 0;
587 accumbits = 0;
588 carry = do_twos_comp ? 1 : 0;
589 for (i = 0; i < ndigits; ++i) {
590 digit thisdigit = v->ob_digit[i];
591 if (do_twos_comp) {
592 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
593 carry = thisdigit >> PyLong_SHIFT;
594 thisdigit &= PyLong_MASK;
595 }
596 /* Because we're going LSB to MSB, thisdigit is more
597 significant than what's already in accum, so needs to be
598 prepended to accum. */
599 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000600
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000601 /* The most-significant digit may be (probably is) at least
602 partly empty. */
603 if (i == ndigits - 1) {
604 /* Count # of sign bits -- they needn't be stored,
605 * although for signed conversion we need later to
606 * make sure at least one sign bit gets stored. */
607 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
608 thisdigit;
609 while (s != 0) {
610 s >>= 1;
611 accumbits++;
612 }
613 }
614 else
615 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000616
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000617 /* Store as many bytes as possible. */
618 while (accumbits >= 8) {
619 if (j >= n)
620 goto Overflow;
621 ++j;
622 *p = (unsigned char)(accum & 0xff);
623 p += pincr;
624 accumbits -= 8;
625 accum >>= 8;
626 }
627 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000628
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000629 /* Store the straggler (if any). */
630 assert(accumbits < 8);
631 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
632 if (accumbits > 0) {
633 if (j >= n)
634 goto Overflow;
635 ++j;
636 if (do_twos_comp) {
637 /* Fill leading bits of the byte with sign bits
638 (appropriately pretending that the long had an
639 infinite supply of sign bits). */
640 accum |= (~(twodigits)0) << accumbits;
641 }
642 *p = (unsigned char)(accum & 0xff);
643 p += pincr;
644 }
645 else if (j == n && n > 0 && is_signed) {
646 /* The main loop filled the byte array exactly, so the code
647 just above didn't get to ensure there's a sign bit, and the
648 loop below wouldn't add one either. Make sure a sign bit
649 exists. */
650 unsigned char msb = *(p - pincr);
651 int sign_bit_set = msb >= 0x80;
652 assert(accumbits == 0);
653 if (sign_bit_set == do_twos_comp)
654 return 0;
655 else
656 goto Overflow;
657 }
Tim Peters05607ad2001-06-13 21:01:27 +0000658
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000659 /* Fill remaining bytes with copies of the sign bit. */
660 {
661 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
662 for ( ; j < n; ++j, p += pincr)
663 *p = signbyte;
664 }
Tim Peters05607ad2001-06-13 21:01:27 +0000665
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000666 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000667
668Overflow:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000669 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
670 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000671
Tim Peters2a9b3672001-06-11 21:23:58 +0000672}
673
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000674double
675_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
676{
677/* NBITS_WANTED should be > the number of bits in a double's precision,
678 but small enough so that 2**NBITS_WANTED is within the normal double
679 range. nbitsneeded is set to 1 less than that because the most-significant
680 Python digit contains at least 1 significant bit, but we don't want to
681 bother counting them (catering to the worst case cheaply).
682
683 57 is one more than VAX-D double precision; I (Tim) don't know of a double
684 format with more precision than that; it's 1 larger so that we add in at
685 least one round bit to stand in for the ignored least-significant bits.
686*/
687#define NBITS_WANTED 57
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000688 PyLongObject *v;
689 double x;
690 const double multiplier = (double)(1L << PyLong_SHIFT);
691 Py_ssize_t i;
692 int sign;
693 int nbitsneeded;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000694
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000695 if (vv == NULL || !PyLong_Check(vv)) {
696 PyErr_BadInternalCall();
697 return -1;
698 }
699 v = (PyLongObject *)vv;
700 i = Py_SIZE(v);
701 sign = 1;
702 if (i < 0) {
703 sign = -1;
704 i = -(i);
705 }
706 else if (i == 0) {
707 *exponent = 0;
708 return 0.0;
709 }
710 --i;
711 x = (double)v->ob_digit[i];
712 nbitsneeded = NBITS_WANTED - 1;
713 /* Invariant: i Python digits remain unaccounted for. */
714 while (i > 0 && nbitsneeded > 0) {
715 --i;
716 x = x * multiplier + (double)v->ob_digit[i];
717 nbitsneeded -= PyLong_SHIFT;
718 }
719 /* There are i digits we didn't shift in. Pretending they're all
720 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
721 *exponent = i;
722 assert(x > 0.0);
723 return x * sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000724#undef NBITS_WANTED
725}
726
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000727/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000728
729double
Tim Peters9f688bf2000-07-07 15:53:28 +0000730PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000731{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000732 int e = -1;
733 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000734
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000735 if (vv == NULL || !PyLong_Check(vv)) {
736 PyErr_BadInternalCall();
737 return -1;
738 }
739 x = _PyLong_AsScaledDouble(vv, &e);
740 if (x == -1.0 && PyErr_Occurred())
741 return -1.0;
742 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
743 set correctly after a successful _PyLong_AsScaledDouble() call */
744 assert(e >= 0);
745 if (e > INT_MAX / PyLong_SHIFT)
746 goto overflow;
747 errno = 0;
748 x = ldexp(x, e * PyLong_SHIFT);
749 if (Py_OVERFLOWED(x))
750 goto overflow;
751 return x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000752
753overflow:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000754 PyErr_SetString(PyExc_OverflowError,
755 "long int too large to convert to float");
756 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000757}
758
Guido van Rossum78694d91998-09-18 14:14:13 +0000759/* Create a new long (or int) object from a C pointer */
760
761PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000762PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000763{
Tim Peters70128a12001-06-16 08:48:40 +0000764#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000765 if ((long)p < 0)
766 return PyLong_FromUnsignedLong((unsigned long)p);
767 return PyInt_FromLong((long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000768#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000769
Tim Peters70128a12001-06-16 08:48:40 +0000770#ifndef HAVE_LONG_LONG
771# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
772#endif
773#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000774# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000775#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000776 /* optimize null pointers */
777 if (p == NULL)
778 return PyInt_FromLong(0);
779 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000780
781#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000782}
783
784/* Get a C pointer from a long object (or an int object in some cases) */
785
786void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000787PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000788{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000789 /* This function will allow int or long objects. If vv is neither,
790 then the PyLong_AsLong*() functions will raise the exception:
791 PyExc_SystemError, "bad argument to internal function"
792 */
Tim Peters70128a12001-06-16 08:48:40 +0000793#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000794 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000795
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000796 if (PyInt_Check(vv))
797 x = PyInt_AS_LONG(vv);
798 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
799 x = PyLong_AsLong(vv);
800 else
801 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000802#else
Tim Peters70128a12001-06-16 08:48:40 +0000803
804#ifndef HAVE_LONG_LONG
805# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
806#endif
807#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000808# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000809#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000810 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000811
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000812 if (PyInt_Check(vv))
813 x = PyInt_AS_LONG(vv);
814 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
815 x = PyLong_AsLongLong(vv);
816 else
817 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000818
819#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000820
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000821 if (x == -1 && PyErr_Occurred())
822 return NULL;
823 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000824}
825
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000826#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000827
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000828/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000829 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000830 */
831
Tim Peterscf37dfc2001-06-14 18:42:50 +0000832#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000833
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000834/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000835
836PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000837PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000838{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000839 PyLongObject *v;
840 unsigned PY_LONG_LONG abs_ival;
841 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
842 int ndigits = 0;
843 int negative = 0;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000844
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000845 if (ival < 0) {
846 /* avoid signed overflow on negation; see comments
847 in PyLong_FromLong above. */
848 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
849 negative = 1;
850 }
851 else {
852 abs_ival = (unsigned PY_LONG_LONG)ival;
853 }
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000854
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000855 /* Count the number of Python digits.
856 We used to pick 5 ("big enough for anything"), but that's a
857 waste of time and space given that 5*15 = 75 bits are rarely
858 needed. */
859 t = abs_ival;
860 while (t) {
861 ++ndigits;
862 t >>= PyLong_SHIFT;
863 }
864 v = _PyLong_New(ndigits);
865 if (v != NULL) {
866 digit *p = v->ob_digit;
867 Py_SIZE(v) = negative ? -ndigits : ndigits;
868 t = abs_ival;
869 while (t) {
870 *p++ = (digit)(t & PyLong_MASK);
871 t >>= PyLong_SHIFT;
872 }
873 }
874 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000875}
876
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000877/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000878
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000879PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000880PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000881{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000882 PyLongObject *v;
883 unsigned PY_LONG_LONG t;
884 int ndigits = 0;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000885
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000886 /* Count the number of Python digits. */
887 t = (unsigned PY_LONG_LONG)ival;
888 while (t) {
889 ++ndigits;
890 t >>= PyLong_SHIFT;
891 }
892 v = _PyLong_New(ndigits);
893 if (v != NULL) {
894 digit *p = v->ob_digit;
895 Py_SIZE(v) = ndigits;
896 while (ival) {
897 *p++ = (digit)(ival & PyLong_MASK);
898 ival >>= PyLong_SHIFT;
899 }
900 }
901 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000902}
903
Martin v. Löwis18e16552006-02-15 17:27:45 +0000904/* Create a new long int object from a C Py_ssize_t. */
905
906PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000907PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000908{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000909 Py_ssize_t bytes = ival;
910 int one = 1;
911 return _PyLong_FromByteArray(
912 (unsigned char *)&bytes,
913 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000914}
915
916/* Create a new long int object from a C size_t. */
917
918PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000919PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000920{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000921 size_t bytes = ival;
922 int one = 1;
923 return _PyLong_FromByteArray(
924 (unsigned char *)&bytes,
925 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000926}
927
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000928/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000929 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000930
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000931PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000932PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000933{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000934 PY_LONG_LONG bytes;
935 int one = 1;
936 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +0000937
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000938 if (vv == NULL) {
939 PyErr_BadInternalCall();
940 return -1;
941 }
942 if (!PyLong_Check(vv)) {
943 PyNumberMethods *nb;
944 PyObject *io;
945 if (PyInt_Check(vv))
946 return (PY_LONG_LONG)PyInt_AsLong(vv);
947 if ((nb = vv->ob_type->tp_as_number) == NULL ||
948 nb->nb_int == NULL) {
949 PyErr_SetString(PyExc_TypeError, "an integer is required");
950 return -1;
951 }
952 io = (*nb->nb_int) (vv);
953 if (io == NULL)
954 return -1;
955 if (PyInt_Check(io)) {
956 bytes = PyInt_AsLong(io);
957 Py_DECREF(io);
958 return bytes;
959 }
960 if (PyLong_Check(io)) {
961 bytes = PyLong_AsLongLong(io);
962 Py_DECREF(io);
963 return bytes;
964 }
965 Py_DECREF(io);
966 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
967 return -1;
968 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000969
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000970 res = _PyLong_AsByteArray(
971 (PyLongObject *)vv, (unsigned char *)&bytes,
972 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000973
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000974 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
975 if (res < 0)
976 return (PY_LONG_LONG)-1;
977 else
978 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000979}
980
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000981/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000982 Return -1 and set an error if overflow occurs. */
983
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000984unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000985PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000986{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000987 unsigned PY_LONG_LONG bytes;
988 int one = 1;
989 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +0000990
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000991 if (vv == NULL || !PyLong_Check(vv)) {
992 PyErr_BadInternalCall();
993 return (unsigned PY_LONG_LONG)-1;
994 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000995
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000996 res = _PyLong_AsByteArray(
997 (PyLongObject *)vv, (unsigned char *)&bytes,
998 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000999
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001000 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1001 if (res < 0)
1002 return (unsigned PY_LONG_LONG)res;
1003 else
1004 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001005}
Tim Petersd1a7da62001-06-13 00:35:57 +00001006
Thomas Hellera4ea6032003-04-17 18:55:45 +00001007/* Get a C unsigned long int from a long int object, ignoring the high bits.
1008 Returns -1 and sets an error condition if an error occurs. */
1009
1010unsigned PY_LONG_LONG
1011PyLong_AsUnsignedLongLongMask(PyObject *vv)
1012{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001013 register PyLongObject *v;
1014 unsigned PY_LONG_LONG x;
1015 Py_ssize_t i;
1016 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001017
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001018 if (vv == NULL || !PyLong_Check(vv)) {
1019 PyErr_BadInternalCall();
1020 return (unsigned long) -1;
1021 }
1022 v = (PyLongObject *)vv;
1023 i = v->ob_size;
1024 sign = 1;
1025 x = 0;
1026 if (i < 0) {
1027 sign = -1;
1028 i = -i;
1029 }
1030 while (--i >= 0) {
1031 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1032 }
1033 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001034}
Tim Petersd1a7da62001-06-13 00:35:57 +00001035#undef IS_LITTLE_ENDIAN
1036
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001037#endif /* HAVE_LONG_LONG */
1038
Neil Schemenauerba872e22001-01-04 01:46:03 +00001039
1040static int
1041convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001042 if (PyLong_Check(v)) {
1043 *a = (PyLongObject *) v;
1044 Py_INCREF(v);
1045 }
1046 else if (PyInt_Check(v)) {
1047 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1048 }
1049 else {
1050 return 0;
1051 }
1052 if (PyLong_Check(w)) {
1053 *b = (PyLongObject *) w;
1054 Py_INCREF(w);
1055 }
1056 else if (PyInt_Check(w)) {
1057 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1058 }
1059 else {
1060 Py_DECREF(*a);
1061 return 0;
1062 }
1063 return 1;
Neil Schemenauerba872e22001-01-04 01:46:03 +00001064}
1065
1066#define CONVERT_BINOP(v, w, a, b) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001067 if (!convert_binop(v, w, a, b)) { \
1068 Py_INCREF(Py_NotImplemented); \
1069 return Py_NotImplemented; \
1070 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001071
Tim Peters877a2122002-08-12 05:09:36 +00001072/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1073 * is modified in place, by adding y to it. Carries are propagated as far as
1074 * x[m-1], and the remaining carry (0 or 1) is returned.
1075 */
1076static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001077v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001078{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001079 Py_ssize_t i;
1080 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001081
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001082 assert(m >= n);
1083 for (i = 0; i < n; ++i) {
1084 carry += x[i] + y[i];
1085 x[i] = carry & PyLong_MASK;
1086 carry >>= PyLong_SHIFT;
1087 assert((carry & 1) == carry);
1088 }
1089 for (; carry && i < m; ++i) {
1090 carry += x[i];
1091 x[i] = carry & PyLong_MASK;
1092 carry >>= PyLong_SHIFT;
1093 assert((carry & 1) == carry);
1094 }
1095 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001096}
1097
1098/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1099 * is modified in place, by subtracting y from it. Borrows are propagated as
1100 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1101 */
1102static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001103v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001104{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001105 Py_ssize_t i;
1106 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001107
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001108 assert(m >= n);
1109 for (i = 0; i < n; ++i) {
1110 borrow = x[i] - y[i] - borrow;
1111 x[i] = borrow & PyLong_MASK;
1112 borrow >>= PyLong_SHIFT;
1113 borrow &= 1; /* keep only 1 sign bit */
1114 }
1115 for (; borrow && i < m; ++i) {
1116 borrow = x[i] - borrow;
1117 x[i] = borrow & PyLong_MASK;
1118 borrow >>= PyLong_SHIFT;
1119 borrow &= 1;
1120 }
1121 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001122}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001123
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001124/* Multiply by a single digit, ignoring the sign. */
1125
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001126static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001127mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001128{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001129 return muladd1(a, n, (digit)0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001130}
1131
1132/* Multiply by a single digit and add a single digit, ignoring the sign. */
1133
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001134static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001135muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001136{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001137 Py_ssize_t size_a = ABS(Py_SIZE(a));
1138 PyLongObject *z = _PyLong_New(size_a+1);
1139 twodigits carry = extra;
1140 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001141
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001142 if (z == NULL)
1143 return NULL;
1144 for (i = 0; i < size_a; ++i) {
1145 carry += (twodigits)a->ob_digit[i] * n;
1146 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1147 carry >>= PyLong_SHIFT;
1148 }
1149 z->ob_digit[i] = (digit) carry;
1150 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001151}
1152
Tim Peters212e6142001-07-14 12:23:19 +00001153/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1154 in pout, and returning the remainder. pin and pout point at the LSD.
1155 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Eric Smith5e527eb2008-02-10 01:36:53 +00001156 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001157 immutable. */
1158
1159static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001160inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001161{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001162 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001163
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001164 assert(n > 0 && n <= PyLong_MASK);
1165 pin += size;
1166 pout += size;
1167 while (--size >= 0) {
1168 digit hi;
1169 rem = (rem << PyLong_SHIFT) + *--pin;
1170 *--pout = hi = (digit)(rem / n);
1171 rem -= (twodigits)hi * n;
1172 }
1173 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001174}
1175
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001176/* Divide a long integer by a digit, returning both the quotient
1177 (as function result) and the remainder (through *prem).
1178 The sign of a is ignored; n should not be zero. */
1179
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001180static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001181divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001182{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001183 const Py_ssize_t size = ABS(Py_SIZE(a));
1184 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001185
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001186 assert(n > 0 && n <= PyLong_MASK);
1187 z = _PyLong_New(size);
1188 if (z == NULL)
1189 return NULL;
1190 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1191 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001192}
1193
Eric Smith5e527eb2008-02-10 01:36:53 +00001194/* Convert the long to a string object with given base,
1195 appending a base prefix of 0[box] if base is 2, 8 or 16.
1196 Add a trailing "L" if addL is non-zero.
1197 If newstyle is zero, then use the pre-2.6 behavior of octal having
1198 a leading "0", instead of the prefix "0o" */
1199PyAPI_FUNC(PyObject *)
1200_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001201{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001202 register PyLongObject *a = (PyLongObject *)aa;
1203 PyStringObject *str;
1204 Py_ssize_t i, sz;
1205 Py_ssize_t size_a;
1206 char *p;
1207 int bits;
1208 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001209
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001210 if (a == NULL || !PyLong_Check(a)) {
1211 PyErr_BadInternalCall();
1212 return NULL;
1213 }
1214 assert(base >= 2 && base <= 36);
1215 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001216
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001217 /* Compute a rough upper bound for the length of the string */
1218 i = base;
1219 bits = 0;
1220 while (i > 1) {
1221 ++bits;
1222 i >>= 1;
1223 }
1224 i = 5 + (addL ? 1 : 0);
1225 /* ensure we don't get signed overflow in sz calculation */
1226 if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {
1227 PyErr_SetString(PyExc_OverflowError,
1228 "long is too large to format");
1229 return NULL;
1230 }
1231 sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;
1232 assert(sz >= 0);
1233 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
1234 if (str == NULL)
1235 return NULL;
1236 p = PyString_AS_STRING(str) + sz;
1237 *p = '\0';
1238 if (addL)
1239 *--p = 'L';
1240 if (a->ob_size < 0)
1241 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001242
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001243 if (a->ob_size == 0) {
1244 *--p = '0';
1245 }
1246 else if ((base & (base - 1)) == 0) {
1247 /* JRH: special case for power-of-2 bases */
1248 twodigits accum = 0;
1249 int accumbits = 0; /* # of bits in accum */
1250 int basebits = 1; /* # of bits in base-1 */
1251 i = base;
1252 while ((i >>= 1) > 1)
1253 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001254
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001255 for (i = 0; i < size_a; ++i) {
1256 accum |= (twodigits)a->ob_digit[i] << accumbits;
1257 accumbits += PyLong_SHIFT;
1258 assert(accumbits >= basebits);
1259 do {
1260 char cdigit = (char)(accum & (base - 1));
1261 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1262 assert(p > PyString_AS_STRING(str));
1263 *--p = cdigit;
1264 accumbits -= basebits;
1265 accum >>= basebits;
1266 } while (i < size_a-1 ? accumbits >= basebits :
1267 accum > 0);
1268 }
1269 }
1270 else {
1271 /* Not 0, and base not a power of 2. Divide repeatedly by
1272 base, but for speed use the highest power of base that
1273 fits in a digit. */
1274 Py_ssize_t size = size_a;
1275 digit *pin = a->ob_digit;
1276 PyLongObject *scratch;
1277 /* powbasw <- largest power of base that fits in a digit. */
1278 digit powbase = base; /* powbase == base ** power */
1279 int power = 1;
1280 for (;;) {
1281 unsigned long newpow = powbase * (unsigned long)base;
1282 if (newpow >> PyLong_SHIFT)
1283 /* doesn't fit in a digit */
1284 break;
1285 powbase = (digit)newpow;
1286 ++power;
1287 }
Tim Peters212e6142001-07-14 12:23:19 +00001288
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001289 /* Get a scratch area for repeated division. */
1290 scratch = _PyLong_New(size);
1291 if (scratch == NULL) {
1292 Py_DECREF(str);
1293 return NULL;
1294 }
Tim Peters212e6142001-07-14 12:23:19 +00001295
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001296 /* Repeatedly divide by powbase. */
1297 do {
1298 int ntostore = power;
1299 digit rem = inplace_divrem1(scratch->ob_digit,
1300 pin, size, powbase);
1301 pin = scratch->ob_digit; /* no need to use a again */
1302 if (pin[size - 1] == 0)
1303 --size;
1304 SIGCHECK({
1305 Py_DECREF(scratch);
1306 Py_DECREF(str);
1307 return NULL;
1308 })
Tim Peters212e6142001-07-14 12:23:19 +00001309
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001310 /* Break rem into digits. */
1311 assert(ntostore > 0);
1312 do {
1313 digit nextrem = (digit)(rem / base);
1314 char c = (char)(rem - nextrem * base);
1315 assert(p > PyString_AS_STRING(str));
1316 c += (c < 10) ? '0' : 'a'-10;
1317 *--p = c;
1318 rem = nextrem;
1319 --ntostore;
1320 /* Termination is a bit delicate: must not
1321 store leading zeroes, so must get out if
1322 remaining quotient and rem are both 0. */
1323 } while (ntostore && (size || rem));
1324 } while (size != 0);
1325 Py_DECREF(scratch);
1326 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001327
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001328 if (base == 2) {
1329 *--p = 'b';
1330 *--p = '0';
1331 }
1332 else if (base == 8) {
1333 if (newstyle) {
1334 *--p = 'o';
1335 *--p = '0';
1336 }
1337 else
1338 if (size_a != 0)
1339 *--p = '0';
1340 }
1341 else if (base == 16) {
1342 *--p = 'x';
1343 *--p = '0';
1344 }
1345 else if (base != 10) {
1346 *--p = '#';
1347 *--p = '0' + base%10;
1348 if (base > 10)
1349 *--p = '0' + base/10;
1350 }
1351 if (sign)
1352 *--p = sign;
1353 if (p != PyString_AS_STRING(str)) {
1354 char *q = PyString_AS_STRING(str);
1355 assert(p > q);
1356 do {
1357 } while ((*q++ = *p++) != '\0');
1358 q--;
1359 _PyString_Resize((PyObject **)&str,
1360 (Py_ssize_t) (q - PyString_AS_STRING(str)));
1361 }
1362 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001363}
1364
Tim Petersda53afa2006-05-25 17:34:03 +00001365/* Table of digit values for 8-bit string -> integer conversion.
1366 * '0' maps to 0, ..., '9' maps to 9.
1367 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1368 * All other indices map to 37.
1369 * Note that when converting a base B string, a char c is a legitimate
1370 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1371 */
1372int _PyLong_DigitValue[256] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001373 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1374 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1375 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1376 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1377 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1378 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1379 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1380 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1381 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1382 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1383 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1384 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1385 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1386 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1387 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1388 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Tim Peters696cf432006-05-24 21:10:40 +00001389};
1390
1391/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001392 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1393 * non-digit (which may be *str!). A normalized long is returned.
1394 * The point to this routine is that it takes time linear in the number of
1395 * string characters.
1396 */
1397static PyLongObject *
1398long_from_binary_base(char **str, int base)
1399{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001400 char *p = *str;
1401 char *start = p;
1402 int bits_per_char;
1403 Py_ssize_t n;
1404 PyLongObject *z;
1405 twodigits accum;
1406 int bits_in_accum;
1407 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001408
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001409 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1410 n = base;
1411 for (bits_per_char = -1; n; ++bits_per_char)
1412 n >>= 1;
1413 /* n <- total # of bits needed, while setting p to end-of-string */
1414 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1415 ++p;
1416 *str = p;
1417 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1418 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1419 if (n / bits_per_char < p - start) {
1420 PyErr_SetString(PyExc_ValueError,
1421 "long string too large to convert");
1422 return NULL;
1423 }
1424 n = n / PyLong_SHIFT;
1425 z = _PyLong_New(n);
1426 if (z == NULL)
1427 return NULL;
1428 /* Read string from right, and fill in long from left; i.e.,
1429 * from least to most significant in both.
1430 */
1431 accum = 0;
1432 bits_in_accum = 0;
1433 pdigit = z->ob_digit;
1434 while (--p >= start) {
1435 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
1436 assert(k >= 0 && k < base);
1437 accum |= (twodigits)k << bits_in_accum;
1438 bits_in_accum += bits_per_char;
1439 if (bits_in_accum >= PyLong_SHIFT) {
1440 *pdigit++ = (digit)(accum & PyLong_MASK);
1441 assert(pdigit - z->ob_digit <= n);
1442 accum >>= PyLong_SHIFT;
1443 bits_in_accum -= PyLong_SHIFT;
1444 assert(bits_in_accum < PyLong_SHIFT);
1445 }
1446 }
1447 if (bits_in_accum) {
1448 assert(bits_in_accum <= PyLong_SHIFT);
1449 *pdigit++ = (digit)accum;
1450 assert(pdigit - z->ob_digit <= n);
1451 }
1452 while (pdigit - z->ob_digit < n)
1453 *pdigit++ = 0;
1454 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001455}
1456
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001457PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001458PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001459{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001460 int sign = 1;
1461 char *start, *orig_str = str;
1462 PyLongObject *z;
1463 PyObject *strobj, *strrepr;
1464 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001465
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001466 if ((base != 0 && base < 2) || base > 36) {
1467 PyErr_SetString(PyExc_ValueError,
1468 "long() arg 2 must be >= 2 and <= 36");
1469 return NULL;
1470 }
1471 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1472 str++;
1473 if (*str == '+')
1474 ++str;
1475 else if (*str == '-') {
1476 ++str;
1477 sign = -1;
1478 }
1479 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1480 str++;
1481 if (base == 0) {
1482 /* No base given. Deduce the base from the contents
1483 of the string */
1484 if (str[0] != '0')
1485 base = 10;
1486 else if (str[1] == 'x' || str[1] == 'X')
1487 base = 16;
1488 else if (str[1] == 'o' || str[1] == 'O')
1489 base = 8;
1490 else if (str[1] == 'b' || str[1] == 'B')
1491 base = 2;
1492 else
1493 /* "old" (C-style) octal literal, still valid in
1494 2.x, although illegal in 3.x */
1495 base = 8;
1496 }
1497 /* Whether or not we were deducing the base, skip leading chars
1498 as needed */
1499 if (str[0] == '0' &&
1500 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1501 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1502 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1503 str += 2;
Tim Peters696cf432006-05-24 21:10:40 +00001504
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001505 start = str;
1506 if ((base & (base - 1)) == 0)
1507 z = long_from_binary_base(&str, base);
1508 else {
Tim Peters696cf432006-05-24 21:10:40 +00001509/***
1510Binary bases can be converted in time linear in the number of digits, because
1511Python's representation base is binary. Other bases (including decimal!) use
1512the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001513
Tim Peters696cf432006-05-24 21:10:40 +00001514First some math: the largest integer that can be expressed in N base-B digits
1515is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1516case number of Python digits needed to hold it is the smallest integer n s.t.
1517
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001518 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1519 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1520 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001521
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001522The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute
Tim Peters696cf432006-05-24 21:10:40 +00001523this quickly. A Python long with that much space is reserved near the start,
1524and the result is computed into it.
1525
1526The input string is actually treated as being in base base**i (i.e., i digits
1527are processed at a time), where two more static arrays hold:
1528
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001529 convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE
Tim Peters696cf432006-05-24 21:10:40 +00001530 convmultmax_base[base] = base ** convwidth_base[base]
1531
1532The first of these is the largest i such that i consecutive input digits
1533must fit in a single Python digit. The second is effectively the input
1534base we're really using.
1535
1536Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1537convmultmax_base[base], the result is "simply"
1538
1539 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1540
1541where B = convmultmax_base[base].
Tim Peters9faa3ed2006-05-30 15:53:34 +00001542
1543Error analysis: as above, the number of Python digits `n` needed is worst-
1544case
1545
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001546 n >= N * log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001547
1548where `N` is the number of input digits in base `B`. This is computed via
1549
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001550 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001551
1552below. Two numeric concerns are how much space this can waste, and whether
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001553the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15,
Tim Peters9faa3ed2006-05-30 15:53:34 +00001554which is the default (and it's unlikely anyone changes that).
1555
1556Waste isn't a problem: provided the first input digit isn't 0, the difference
1557between the worst-case input with N digits and the smallest input with N
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001558digits is about a factor of B, but B is small compared to PyLong_BASE so at most
Tim Peters9faa3ed2006-05-30 15:53:34 +00001559one allocated Python digit can remain unused on that count. If
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001560N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001561and adding 1 returns a result 1 larger than necessary. However, that can't
1562happen: whenever B is a power of 2, long_from_binary_base() is called
1563instead, and it's impossible for B**i to be an integer power of 2**15 when
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001564B 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 +00001565an exact integer when B is not a power of 2, since B**i has a prime factor
1566other than 2 in that case, but (2**15)**j's only prime factor is 2).
1567
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001568The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001569is a little bit larger than an exact integer, but due to roundoff errors (in
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001570computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001571yields a numeric result a little less than that integer. Unfortunately, "how
1572close can a transcendental function get to an integer over some range?"
1573questions are generally theoretically intractable. Computer analysis via
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001574continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued
Tim Peters9faa3ed2006-05-30 15:53:34 +00001575fractions, giving a sequence i/j of "the best" rational approximations. Then
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001576j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001577we can get very close to being in trouble, but very rarely. For example,
157876573 is a denominator in one of the continued-fraction approximations to
1579log(10)/log(2**15), and indeed:
1580
1581 >>> log(10)/log(2**15)*76573
1582 16958.000000654003
1583
1584is very close to an integer. If we were working with IEEE single-precision,
1585rounding errors could kill us. Finding worst cases in IEEE double-precision
1586requires better-than-double-precision log() functions, and Tim didn't bother.
1587Instead the code checks to see whether the allocated space is enough as each
1588new Python digit is added, and copies the whole thing to a larger long if not.
1589This should happen extremely rarely, and in fact I don't have a test case
1590that triggers it(!). Instead the code was tested by artificially allocating
1591just 1 digit at the start, so that the copying code was exercised for every
1592digit beyond the first.
Tim Peters696cf432006-05-24 21:10:40 +00001593***/
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001594 register twodigits c; /* current input character */
1595 Py_ssize_t size_z;
1596 int i;
1597 int convwidth;
1598 twodigits convmultmax, convmult;
1599 digit *pz, *pzstop;
1600 char* scan;
Tim Peters696cf432006-05-24 21:10:40 +00001601
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001602 static double log_base_PyLong_BASE[37] = {0.0e0,};
1603 static int convwidth_base[37] = {0,};
1604 static twodigits convmultmax_base[37] = {0,};
Tim Peters696cf432006-05-24 21:10:40 +00001605
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001606 if (log_base_PyLong_BASE[base] == 0.0) {
1607 twodigits convmax = base;
1608 int i = 1;
Tim Peters696cf432006-05-24 21:10:40 +00001609
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001610 log_base_PyLong_BASE[base] = log((double)base) /
1611 log((double)PyLong_BASE);
1612 for (;;) {
1613 twodigits next = convmax * base;
1614 if (next > PyLong_BASE)
1615 break;
1616 convmax = next;
1617 ++i;
1618 }
1619 convmultmax_base[base] = convmax;
1620 assert(i > 0);
1621 convwidth_base[base] = i;
1622 }
Tim Peters696cf432006-05-24 21:10:40 +00001623
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001624 /* Find length of the string of numeric characters. */
1625 scan = str;
1626 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1627 ++scan;
Tim Peters696cf432006-05-24 21:10:40 +00001628
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001629 /* Create a long object that can contain the largest possible
1630 * integer with this base and length. Note that there's no
1631 * need to initialize z->ob_digit -- no slot is read up before
1632 * being stored into.
1633 */
1634 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
1635 /* Uncomment next line to test exceedingly rare copy code */
1636 /* size_z = 1; */
1637 assert(size_z > 0);
1638 z = _PyLong_New(size_z);
1639 if (z == NULL)
1640 return NULL;
1641 Py_SIZE(z) = 0;
Tim Peters696cf432006-05-24 21:10:40 +00001642
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001643 /* `convwidth` consecutive input digits are treated as a single
1644 * digit in base `convmultmax`.
1645 */
1646 convwidth = convwidth_base[base];
1647 convmultmax = convmultmax_base[base];
Tim Peters696cf432006-05-24 21:10:40 +00001648
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001649 /* Work ;-) */
1650 while (str < scan) {
1651 /* grab up to convwidth digits from the input string */
1652 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1653 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1654 c = (twodigits)(c * base +
1655 _PyLong_DigitValue[Py_CHARMASK(*str)]);
1656 assert(c < PyLong_BASE);
1657 }
Tim Peters696cf432006-05-24 21:10:40 +00001658
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001659 convmult = convmultmax;
1660 /* Calculate the shift only if we couldn't get
1661 * convwidth digits.
1662 */
1663 if (i != convwidth) {
1664 convmult = base;
1665 for ( ; i > 1; --i)
1666 convmult *= base;
1667 }
Tim Peters696cf432006-05-24 21:10:40 +00001668
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001669 /* Multiply z by convmult, and add c. */
1670 pz = z->ob_digit;
1671 pzstop = pz + Py_SIZE(z);
1672 for (; pz < pzstop; ++pz) {
1673 c += (twodigits)*pz * convmult;
1674 *pz = (digit)(c & PyLong_MASK);
1675 c >>= PyLong_SHIFT;
1676 }
1677 /* carry off the current end? */
1678 if (c) {
1679 assert(c < PyLong_BASE);
1680 if (Py_SIZE(z) < size_z) {
1681 *pz = (digit)c;
1682 ++Py_SIZE(z);
1683 }
1684 else {
1685 PyLongObject *tmp;
1686 /* Extremely rare. Get more space. */
1687 assert(Py_SIZE(z) == size_z);
1688 tmp = _PyLong_New(size_z + 1);
1689 if (tmp == NULL) {
1690 Py_DECREF(z);
1691 return NULL;
1692 }
1693 memcpy(tmp->ob_digit,
1694 z->ob_digit,
1695 sizeof(digit) * size_z);
1696 Py_DECREF(z);
1697 z = tmp;
1698 z->ob_digit[size_z] = (digit)c;
1699 ++size_z;
1700 }
1701 }
1702 }
1703 }
1704 if (z == NULL)
1705 return NULL;
1706 if (str == start)
1707 goto onError;
1708 if (sign < 0)
1709 Py_SIZE(z) = -(Py_SIZE(z));
1710 if (*str == 'L' || *str == 'l')
1711 str++;
1712 while (*str && isspace(Py_CHARMASK(*str)))
1713 str++;
1714 if (*str != '\0')
1715 goto onError;
1716 if (pend)
1717 *pend = str;
1718 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001719
1720 onError:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001721 Py_XDECREF(z);
1722 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1723 strobj = PyString_FromStringAndSize(orig_str, slen);
1724 if (strobj == NULL)
1725 return NULL;
1726 strrepr = PyObject_Repr(strobj);
1727 Py_DECREF(strobj);
1728 if (strrepr == NULL)
1729 return NULL;
1730 PyErr_Format(PyExc_ValueError,
1731 "invalid literal for long() with base %d: %s",
1732 base, PyString_AS_STRING(strrepr));
1733 Py_DECREF(strrepr);
1734 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001735}
1736
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001737#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001738PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001739PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001740{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001741 PyObject *result;
1742 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001743
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001744 if (buffer == NULL)
1745 return NULL;
Walter Dörwald07e14762002-11-06 16:15:14 +00001746
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001747 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1748 PyMem_FREE(buffer);
1749 return NULL;
1750 }
1751 result = PyLong_FromString(buffer, NULL, base);
1752 PyMem_FREE(buffer);
1753 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001754}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001755#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001756
Tim Peters9f688bf2000-07-07 15:53:28 +00001757/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001758static PyLongObject *x_divrem
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001759 (PyLongObject *, PyLongObject *, PyLongObject **);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001760static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00001761static int long_divrem(PyLongObject *, PyLongObject *,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001762 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001763
1764/* Long division with remainder, top-level routine */
1765
Guido van Rossume32e0141992-01-19 16:31:05 +00001766static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001767long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001768 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001769{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001770 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
1771 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001772
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001773 if (size_b == 0) {
1774 PyErr_SetString(PyExc_ZeroDivisionError,
1775 "long division or modulo by zero");
1776 return -1;
1777 }
1778 if (size_a < size_b ||
1779 (size_a == size_b &&
1780 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
1781 /* |a| < |b|. */
1782 *pdiv = _PyLong_New(0);
1783 if (*pdiv == NULL)
1784 return -1;
1785 Py_INCREF(a);
1786 *prem = (PyLongObject *) a;
1787 return 0;
1788 }
1789 if (size_b == 1) {
1790 digit rem = 0;
1791 z = divrem1(a, b->ob_digit[0], &rem);
1792 if (z == NULL)
1793 return -1;
1794 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
1795 if (*prem == NULL) {
1796 Py_DECREF(z);
1797 return -1;
1798 }
1799 }
1800 else {
1801 z = x_divrem(a, b, prem);
1802 if (z == NULL)
1803 return -1;
1804 }
1805 /* Set the signs.
1806 The quotient z has the sign of a*b;
1807 the remainder r has the sign of a,
1808 so a = b*z + r. */
1809 if ((a->ob_size < 0) != (b->ob_size < 0))
1810 z->ob_size = -(z->ob_size);
1811 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1812 (*prem)->ob_size = -((*prem)->ob_size);
1813 *pdiv = z;
1814 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001815}
1816
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001817/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001818
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001819static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001820x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001821{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001822 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
1823 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
1824 PyLongObject *v = mul1(v1, d);
1825 PyLongObject *w = mul1(w1, d);
1826 PyLongObject *a;
1827 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001828
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001829 if (v == NULL || w == NULL) {
1830 Py_XDECREF(v);
1831 Py_XDECREF(w);
1832 return NULL;
1833 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001834
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001835 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
1836 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
1837 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001838
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001839 size_v = ABS(Py_SIZE(v));
1840 k = size_v - size_w;
1841 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001842
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001843 for (j = size_v; a != NULL && k >= 0; --j, --k) {
1844 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
1845 twodigits q;
1846 stwodigits carry = 0;
1847 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001848
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001849 SIGCHECK({
1850 Py_DECREF(a);
1851 a = NULL;
1852 break;
1853 })
1854 if (vj == w->ob_digit[size_w-1])
1855 q = PyLong_MASK;
1856 else
1857 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
1858 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00001859
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001860 while (w->ob_digit[size_w-2]*q >
1861 ((
1862 ((twodigits)vj << PyLong_SHIFT)
1863 + v->ob_digit[j-1]
1864 - q*w->ob_digit[size_w-1]
1865 ) << PyLong_SHIFT)
1866 + v->ob_digit[j-2])
1867 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001868
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001869 for (i = 0; i < size_w && i+k < size_v; ++i) {
1870 twodigits z = w->ob_digit[i] * q;
1871 digit zz = (digit) (z >> PyLong_SHIFT);
1872 carry += v->ob_digit[i+k] - z
1873 + ((twodigits)zz << PyLong_SHIFT);
1874 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
1875 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
1876 carry, PyLong_SHIFT);
1877 carry -= zz;
1878 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001879
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001880 if (i+k < size_v) {
1881 carry += v->ob_digit[i+k];
1882 v->ob_digit[i+k] = 0;
1883 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001884
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001885 if (carry == 0)
1886 a->ob_digit[k] = (digit) q;
1887 else {
1888 assert(carry == -1);
1889 a->ob_digit[k] = (digit) q-1;
1890 carry = 0;
1891 for (i = 0; i < size_w && i+k < size_v; ++i) {
1892 carry += v->ob_digit[i+k] + w->ob_digit[i];
1893 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
1894 carry = Py_ARITHMETIC_RIGHT_SHIFT(
1895 BASE_TWODIGITS_TYPE,
1896 carry, PyLong_SHIFT);
1897 }
1898 }
1899 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001900
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001901 if (a == NULL)
1902 *prem = NULL;
1903 else {
1904 a = long_normalize(a);
1905 *prem = divrem1(v, d, &d);
1906 /* d receives the (unused) remainder */
1907 if (*prem == NULL) {
1908 Py_DECREF(a);
1909 a = NULL;
1910 }
1911 }
1912 Py_DECREF(v);
1913 Py_DECREF(w);
1914 return a;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001915}
1916
1917/* Methods */
1918
1919static void
Tim Peters9f688bf2000-07-07 15:53:28 +00001920long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001921{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001922 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001923}
1924
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001925static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001926long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001927{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001928 return _PyLong_Format(v, 10, 1, 0);
Fred Drake121ee271999-12-23 15:41:28 +00001929}
1930
1931static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001932long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00001933{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001934 return _PyLong_Format(v, 10, 0, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001935}
1936
1937static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001938long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001939{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001940 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001941
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001942 if (Py_SIZE(a) != Py_SIZE(b)) {
1943 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
1944 sign = 0;
1945 else
1946 sign = Py_SIZE(a) - Py_SIZE(b);
1947 }
1948 else {
1949 Py_ssize_t i = ABS(Py_SIZE(a));
1950 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1951 ;
1952 if (i < 0)
1953 sign = 0;
1954 else {
1955 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
1956 if (Py_SIZE(a) < 0)
1957 sign = -sign;
1958 }
1959 }
1960 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001961}
1962
Guido van Rossum9bfef441993-03-29 10:43:31 +00001963static long
Tim Peters9f688bf2000-07-07 15:53:28 +00001964long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001965{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001966 unsigned long x;
1967 Py_ssize_t i;
1968 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001969
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001970 /* This is designed so that Python ints and longs with the
1971 same value hash to the same value, otherwise comparisons
1972 of mapping keys will turn out weird */
1973 i = v->ob_size;
1974 sign = 1;
1975 x = 0;
1976 if (i < 0) {
1977 sign = -1;
1978 i = -(i);
1979 }
1980#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
1981 /* The following loop produces a C unsigned long x such that x is
1982 congruent to the absolute value of v modulo ULONG_MAX. The
1983 resulting x is nonzero if and only if v is. */
1984 while (--i >= 0) {
1985 /* Force a native long #-bits (32 or 64) circular shift */
1986 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) |
1987 ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
1988 x += v->ob_digit[i];
1989 /* If the addition above overflowed we compensate by
1990 incrementing. This preserves the value modulo
1991 ULONG_MAX. */
1992 if (x < v->ob_digit[i])
1993 x++;
1994 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001995#undef LONG_BIT_PyLong_SHIFT
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001996 x = x * sign;
1997 if (x == -1)
1998 x = -2;
1999 return x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002000}
2001
2002
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002003/* Add the absolute values of two long integers. */
2004
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002005static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002006x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002007{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002008 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2009 PyLongObject *z;
2010 Py_ssize_t i;
2011 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002012
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002013 /* Ensure a is the larger of the two: */
2014 if (size_a < size_b) {
2015 { PyLongObject *temp = a; a = b; b = temp; }
2016 { Py_ssize_t size_temp = size_a;
2017 size_a = size_b;
2018 size_b = size_temp; }
2019 }
2020 z = _PyLong_New(size_a+1);
2021 if (z == NULL)
2022 return NULL;
2023 for (i = 0; i < size_b; ++i) {
2024 carry += a->ob_digit[i] + b->ob_digit[i];
2025 z->ob_digit[i] = carry & PyLong_MASK;
2026 carry >>= PyLong_SHIFT;
2027 }
2028 for (; i < size_a; ++i) {
2029 carry += a->ob_digit[i];
2030 z->ob_digit[i] = carry & PyLong_MASK;
2031 carry >>= PyLong_SHIFT;
2032 }
2033 z->ob_digit[i] = carry;
2034 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002035}
2036
2037/* Subtract the absolute values of two integers. */
2038
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002039static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002040x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002041{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002042 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2043 PyLongObject *z;
2044 Py_ssize_t i;
2045 int sign = 1;
2046 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002047
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002048 /* Ensure a is the larger of the two: */
2049 if (size_a < size_b) {
2050 sign = -1;
2051 { PyLongObject *temp = a; a = b; b = temp; }
2052 { Py_ssize_t size_temp = size_a;
2053 size_a = size_b;
2054 size_b = size_temp; }
2055 }
2056 else if (size_a == size_b) {
2057 /* Find highest digit where a and b differ: */
2058 i = size_a;
2059 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2060 ;
2061 if (i < 0)
2062 return _PyLong_New(0);
2063 if (a->ob_digit[i] < b->ob_digit[i]) {
2064 sign = -1;
2065 { PyLongObject *temp = a; a = b; b = temp; }
2066 }
2067 size_a = size_b = i+1;
2068 }
2069 z = _PyLong_New(size_a);
2070 if (z == NULL)
2071 return NULL;
2072 for (i = 0; i < size_b; ++i) {
2073 /* The following assumes unsigned arithmetic
2074 works module 2**N for some N>PyLong_SHIFT. */
2075 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2076 z->ob_digit[i] = borrow & PyLong_MASK;
2077 borrow >>= PyLong_SHIFT;
2078 borrow &= 1; /* Keep only one sign bit */
2079 }
2080 for (; i < size_a; ++i) {
2081 borrow = a->ob_digit[i] - borrow;
2082 z->ob_digit[i] = borrow & PyLong_MASK;
2083 borrow >>= PyLong_SHIFT;
2084 borrow &= 1; /* Keep only one sign bit */
2085 }
2086 assert(borrow == 0);
2087 if (sign < 0)
2088 z->ob_size = -(z->ob_size);
2089 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090}
2091
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002092static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002093long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002094{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002095 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002096
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002097 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002098
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002099 if (a->ob_size < 0) {
2100 if (b->ob_size < 0) {
2101 z = x_add(a, b);
2102 if (z != NULL && z->ob_size != 0)
2103 z->ob_size = -(z->ob_size);
2104 }
2105 else
2106 z = x_sub(b, a);
2107 }
2108 else {
2109 if (b->ob_size < 0)
2110 z = x_sub(a, b);
2111 else
2112 z = x_add(a, b);
2113 }
2114 Py_DECREF(a);
2115 Py_DECREF(b);
2116 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002117}
2118
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002119static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002120long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002121{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002122 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002123
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002124 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002125
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002126 if (a->ob_size < 0) {
2127 if (b->ob_size < 0)
2128 z = x_sub(a, b);
2129 else
2130 z = x_add(a, b);
2131 if (z != NULL && z->ob_size != 0)
2132 z->ob_size = -(z->ob_size);
2133 }
2134 else {
2135 if (b->ob_size < 0)
2136 z = x_add(a, b);
2137 else
2138 z = x_sub(a, b);
2139 }
2140 Py_DECREF(a);
2141 Py_DECREF(b);
2142 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002143}
2144
Tim Peters5af4e6c2002-08-12 02:31:19 +00002145/* Grade school multiplication, ignoring the signs.
2146 * Returns the absolute value of the product, or NULL if error.
2147 */
2148static PyLongObject *
2149x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002150{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002151 PyLongObject *z;
2152 Py_ssize_t size_a = ABS(Py_SIZE(a));
2153 Py_ssize_t size_b = ABS(Py_SIZE(b));
2154 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002155
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002156 z = _PyLong_New(size_a + size_b);
2157 if (z == NULL)
2158 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002159
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002160 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2161 if (a == b) {
2162 /* Efficient squaring per HAC, Algorithm 14.16:
2163 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2164 * Gives slightly less than a 2x speedup when a == b,
2165 * via exploiting that each entry in the multiplication
2166 * pyramid appears twice (except for the size_a squares).
2167 */
2168 for (i = 0; i < size_a; ++i) {
2169 twodigits carry;
2170 twodigits f = a->ob_digit[i];
2171 digit *pz = z->ob_digit + (i << 1);
2172 digit *pa = a->ob_digit + i + 1;
2173 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002174
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002175 SIGCHECK({
2176 Py_DECREF(z);
2177 return NULL;
2178 })
Tim Peters0973b992004-08-29 22:16:50 +00002179
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002180 carry = *pz + f * f;
2181 *pz++ = (digit)(carry & PyLong_MASK);
2182 carry >>= PyLong_SHIFT;
2183 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002184
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002185 /* Now f is added in twice in each column of the
2186 * pyramid it appears. Same as adding f<<1 once.
2187 */
2188 f <<= 1;
2189 while (pa < paend) {
2190 carry += *pz + *pa++ * f;
2191 *pz++ = (digit)(carry & PyLong_MASK);
2192 carry >>= PyLong_SHIFT;
2193 assert(carry <= (PyLong_MASK << 1));
2194 }
2195 if (carry) {
2196 carry += *pz;
2197 *pz++ = (digit)(carry & PyLong_MASK);
2198 carry >>= PyLong_SHIFT;
2199 }
2200 if (carry)
2201 *pz += (digit)(carry & PyLong_MASK);
2202 assert((carry >> PyLong_SHIFT) == 0);
2203 }
2204 }
2205 else { /* a is not the same as b -- gradeschool long mult */
2206 for (i = 0; i < size_a; ++i) {
2207 twodigits carry = 0;
2208 twodigits f = a->ob_digit[i];
2209 digit *pz = z->ob_digit + i;
2210 digit *pb = b->ob_digit;
2211 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002212
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002213 SIGCHECK({
2214 Py_DECREF(z);
2215 return NULL;
2216 })
Tim Peters0973b992004-08-29 22:16:50 +00002217
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002218 while (pb < pbend) {
2219 carry += *pz + *pb++ * f;
2220 *pz++ = (digit)(carry & PyLong_MASK);
2221 carry >>= PyLong_SHIFT;
2222 assert(carry <= PyLong_MASK);
2223 }
2224 if (carry)
2225 *pz += (digit)(carry & PyLong_MASK);
2226 assert((carry >> PyLong_SHIFT) == 0);
2227 }
2228 }
2229 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002230}
2231
2232/* A helper for Karatsuba multiplication (k_mul).
2233 Takes a long "n" and an integer "size" representing the place to
2234 split, and sets low and high such that abs(n) == (high << size) + low,
2235 viewing the shift as being by digits. The sign bit is ignored, and
2236 the return values are >= 0.
2237 Returns 0 on success, -1 on failure.
2238*/
2239static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002240kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002241{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002242 PyLongObject *hi, *lo;
2243 Py_ssize_t size_lo, size_hi;
2244 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002245
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002246 size_lo = MIN(size_n, size);
2247 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002248
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002249 if ((hi = _PyLong_New(size_hi)) == NULL)
2250 return -1;
2251 if ((lo = _PyLong_New(size_lo)) == NULL) {
2252 Py_DECREF(hi);
2253 return -1;
2254 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002255
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002256 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2257 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002258
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002259 *high = long_normalize(hi);
2260 *low = long_normalize(lo);
2261 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002262}
2263
Tim Peters60004642002-08-12 22:01:34 +00002264static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2265
Tim Peters5af4e6c2002-08-12 02:31:19 +00002266/* Karatsuba multiplication. Ignores the input signs, and returns the
2267 * absolute value of the product (or NULL if error).
2268 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2269 */
2270static PyLongObject *
2271k_mul(PyLongObject *a, PyLongObject *b)
2272{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002273 Py_ssize_t asize = ABS(Py_SIZE(a));
2274 Py_ssize_t bsize = ABS(Py_SIZE(b));
2275 PyLongObject *ah = NULL;
2276 PyLongObject *al = NULL;
2277 PyLongObject *bh = NULL;
2278 PyLongObject *bl = NULL;
2279 PyLongObject *ret = NULL;
2280 PyLongObject *t1, *t2, *t3;
2281 Py_ssize_t shift; /* the number of digits we split off */
2282 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002283
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002284 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2285 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2286 * Then the original product is
2287 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2288 * By picking X to be a power of 2, "*X" is just shifting, and it's
2289 * been reduced to 3 multiplies on numbers half the size.
2290 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002291
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002292 /* We want to split based on the larger number; fiddle so that b
2293 * is largest.
2294 */
2295 if (asize > bsize) {
2296 t1 = a;
2297 a = b;
2298 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002299
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002300 i = asize;
2301 asize = bsize;
2302 bsize = i;
2303 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002304
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002305 /* Use gradeschool math when either number is too small. */
2306 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2307 if (asize <= i) {
2308 if (asize == 0)
2309 return _PyLong_New(0);
2310 else
2311 return x_mul(a, b);
2312 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002313
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002314 /* If a is small compared to b, splitting on b gives a degenerate
2315 * case with ah==0, and Karatsuba may be (even much) less efficient
2316 * than "grade school" then. However, we can still win, by viewing
2317 * b as a string of "big digits", each of width a->ob_size. That
2318 * leads to a sequence of balanced calls to k_mul.
2319 */
2320 if (2 * asize <= bsize)
2321 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002322
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002323 /* Split a & b into hi & lo pieces. */
2324 shift = bsize >> 1;
2325 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2326 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002327
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002328 if (a == b) {
2329 bh = ah;
2330 bl = al;
2331 Py_INCREF(bh);
2332 Py_INCREF(bl);
2333 }
2334 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002335
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002336 /* The plan:
2337 * 1. Allocate result space (asize + bsize digits: that's always
2338 * enough).
2339 * 2. Compute ah*bh, and copy into result at 2*shift.
2340 * 3. Compute al*bl, and copy into result at 0. Note that this
2341 * can't overlap with #2.
2342 * 4. Subtract al*bl from the result, starting at shift. This may
2343 * underflow (borrow out of the high digit), but we don't care:
2344 * we're effectively doing unsigned arithmetic mod
2345 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
2346 * borrows and carries out of the high digit can be ignored.
2347 * 5. Subtract ah*bh from the result, starting at shift.
2348 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2349 * at shift.
2350 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002351
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002352 /* 1. Allocate result space. */
2353 ret = _PyLong_New(asize + bsize);
2354 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002355#ifdef Py_DEBUG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002356 /* Fill with trash, to catch reference to uninitialized digits. */
2357 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002358#endif
Tim Peters44121a62002-08-12 06:17:58 +00002359
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002360 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2361 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2362 assert(Py_SIZE(t1) >= 0);
2363 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
2364 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2365 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002366
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002367 /* Zero-out the digits higher than the ah*bh copy. */
2368 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
2369 if (i)
2370 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
2371 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002372
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002373 /* 3. t2 <- al*bl, and copy into the low digits. */
2374 if ((t2 = k_mul(al, bl)) == NULL) {
2375 Py_DECREF(t1);
2376 goto fail;
2377 }
2378 assert(Py_SIZE(t2) >= 0);
2379 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2380 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002381
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002382 /* Zero out remaining digits. */
2383 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
2384 if (i)
2385 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002386
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002387 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2388 * because it's fresher in cache.
2389 */
2390 i = Py_SIZE(ret) - shift; /* # digits after shift */
2391 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
2392 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002393
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002394 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
2395 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00002396
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002397 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
2398 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2399 Py_DECREF(ah);
2400 Py_DECREF(al);
2401 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002402
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002403 if (a == b) {
2404 t2 = t1;
2405 Py_INCREF(t2);
2406 }
2407 else if ((t2 = x_add(bh, bl)) == NULL) {
2408 Py_DECREF(t1);
2409 goto fail;
2410 }
2411 Py_DECREF(bh);
2412 Py_DECREF(bl);
2413 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002414
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002415 t3 = k_mul(t1, t2);
2416 Py_DECREF(t1);
2417 Py_DECREF(t2);
2418 if (t3 == NULL) goto fail;
2419 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002420
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002421 /* Add t3. It's not obvious why we can't run out of room here.
2422 * See the (*) comment after this function.
2423 */
2424 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
2425 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002426
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002427 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002428
2429 fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002430 Py_XDECREF(ret);
2431 Py_XDECREF(ah);
2432 Py_XDECREF(al);
2433 Py_XDECREF(bh);
2434 Py_XDECREF(bl);
2435 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002436}
2437
Tim Petersd6974a52002-08-13 20:37:51 +00002438/* (*) Why adding t3 can't "run out of room" above.
2439
Tim Petersab86c2b2002-08-15 20:06:00 +00002440Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2441to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002442
Tim Petersab86c2b2002-08-15 20:06:00 +000024431. For any integer i, i = c(i/2) + f(i/2). In particular,
2444 bsize = c(bsize/2) + f(bsize/2).
24452. shift = f(bsize/2)
24463. asize <= bsize
24474. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2448 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002449
Tim Petersab86c2b2002-08-15 20:06:00 +00002450We allocated asize + bsize result digits, and add t3 into them at an offset
2451of shift. This leaves asize+bsize-shift allocated digit positions for t3
2452to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2453asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002454
Tim Petersab86c2b2002-08-15 20:06:00 +00002455bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2456at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002457
Tim Petersab86c2b2002-08-15 20:06:00 +00002458If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2459digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2460most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002461
Tim Petersab86c2b2002-08-15 20:06:00 +00002462The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002463
Tim Petersab86c2b2002-08-15 20:06:00 +00002464 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002465
Tim Petersab86c2b2002-08-15 20:06:00 +00002466and we have asize + c(bsize/2) available digit positions. We need to show
2467this is always enough. An instance of c(bsize/2) cancels out in both, so
2468the question reduces to whether asize digits is enough to hold
2469(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2470then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2471asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002472digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002473asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002474c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2475is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2476bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002477
Tim Peters48d52c02002-08-14 17:07:32 +00002478Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2479clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2480ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002481*/
2482
Tim Peters60004642002-08-12 22:01:34 +00002483/* b has at least twice the digits of a, and a is big enough that Karatsuba
2484 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2485 * of slices, each with a->ob_size digits, and multiply the slices by a,
2486 * one at a time. This gives k_mul balanced inputs to work with, and is
2487 * also cache-friendly (we compute one double-width slice of the result
2488 * at a time, then move on, never bactracking except for the helpful
2489 * single-width slice overlap between successive partial sums).
2490 */
2491static PyLongObject *
2492k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2493{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002494 const Py_ssize_t asize = ABS(Py_SIZE(a));
2495 Py_ssize_t bsize = ABS(Py_SIZE(b));
2496 Py_ssize_t nbdone; /* # of b digits already multiplied */
2497 PyLongObject *ret;
2498 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00002499
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002500 assert(asize > KARATSUBA_CUTOFF);
2501 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00002502
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002503 /* Allocate result space, and zero it out. */
2504 ret = _PyLong_New(asize + bsize);
2505 if (ret == NULL)
2506 return NULL;
2507 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002508
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002509 /* Successive slices of b are copied into bslice. */
2510 bslice = _PyLong_New(asize);
2511 if (bslice == NULL)
2512 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00002513
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002514 nbdone = 0;
2515 while (bsize > 0) {
2516 PyLongObject *product;
2517 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002518
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002519 /* Multiply the next slice of b by a. */
2520 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2521 nbtouse * sizeof(digit));
2522 Py_SIZE(bslice) = nbtouse;
2523 product = k_mul(a, bslice);
2524 if (product == NULL)
2525 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00002526
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002527 /* Add into result. */
2528 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2529 product->ob_digit, Py_SIZE(product));
2530 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00002531
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002532 bsize -= nbtouse;
2533 nbdone += nbtouse;
2534 }
Tim Peters60004642002-08-12 22:01:34 +00002535
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002536 Py_DECREF(bslice);
2537 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00002538
2539 fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002540 Py_DECREF(ret);
2541 Py_XDECREF(bslice);
2542 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00002543}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002544
2545static PyObject *
2546long_mul(PyLongObject *v, PyLongObject *w)
2547{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002548 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002549
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002550 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
2551 Py_INCREF(Py_NotImplemented);
2552 return Py_NotImplemented;
2553 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002554
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002555 z = k_mul(a, b);
2556 /* Negate if exactly one of the inputs is negative. */
2557 if (((a->ob_size ^ b->ob_size) < 0) && z)
2558 z->ob_size = -(z->ob_size);
2559 Py_DECREF(a);
2560 Py_DECREF(b);
2561 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002562}
2563
Guido van Rossume32e0141992-01-19 16:31:05 +00002564/* The / and % operators are now defined in terms of divmod().
2565 The expression a mod b has the value a - b*floor(a/b).
2566 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002567 |a| by |b|, with the sign of a. This is also expressed
2568 as a - b*trunc(a/b), if trunc truncates towards zero.
2569 Some examples:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002570 a b a rem b a mod b
2571 13 10 3 3
2572 -13 10 -3 7
2573 13 -10 3 -7
2574 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002575 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002576 have different signs. We then subtract one from the 'div'
2577 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002578
Tim Peters47e52ee2004-08-30 02:44:38 +00002579/* Compute
2580 * *pdiv, *pmod = divmod(v, w)
2581 * NULL can be passed for pdiv or pmod, in which case that part of
2582 * the result is simply thrown away. The caller owns a reference to
2583 * each of these it requests (does not pass NULL for).
2584 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002585static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002586l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002587 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002588{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002589 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002590
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002591 if (long_divrem(v, w, &div, &mod) < 0)
2592 return -1;
2593 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2594 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
2595 PyLongObject *temp;
2596 PyLongObject *one;
2597 temp = (PyLongObject *) long_add(mod, w);
2598 Py_DECREF(mod);
2599 mod = temp;
2600 if (mod == NULL) {
2601 Py_DECREF(div);
2602 return -1;
2603 }
2604 one = (PyLongObject *) PyLong_FromLong(1L);
2605 if (one == NULL ||
2606 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2607 Py_DECREF(mod);
2608 Py_DECREF(div);
2609 Py_XDECREF(one);
2610 return -1;
2611 }
2612 Py_DECREF(one);
2613 Py_DECREF(div);
2614 div = temp;
2615 }
2616 if (pdiv != NULL)
2617 *pdiv = div;
2618 else
2619 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00002620
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002621 if (pmod != NULL)
2622 *pmod = mod;
2623 else
2624 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00002625
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002626 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00002627}
2628
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002629static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002630long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002631{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002632 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002633
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002634 CONVERT_BINOP(v, w, &a, &b);
2635 if (l_divmod(a, b, &div, NULL) < 0)
2636 div = NULL;
2637 Py_DECREF(a);
2638 Py_DECREF(b);
2639 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002640}
2641
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002642static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00002643long_classic_div(PyObject *v, PyObject *w)
2644{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002645 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002646
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002647 CONVERT_BINOP(v, w, &a, &b);
2648 if (Py_DivisionWarningFlag &&
2649 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
2650 div = NULL;
2651 else if (l_divmod(a, b, &div, NULL) < 0)
2652 div = NULL;
2653 Py_DECREF(a);
2654 Py_DECREF(b);
2655 return (PyObject *)div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002656}
2657
2658static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002659long_true_divide(PyObject *v, PyObject *w)
2660{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002661 PyLongObject *a, *b;
2662 double ad, bd;
2663 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002664
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002665 CONVERT_BINOP(v, w, &a, &b);
2666 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2667 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
2668 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2669 Py_DECREF(a);
2670 Py_DECREF(b);
2671 if (failed)
2672 return NULL;
2673 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2674 but should really be set correctly after sucessful calls to
2675 _PyLong_AsScaledDouble() */
2676 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002677
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002678 if (bd == 0.0) {
2679 PyErr_SetString(PyExc_ZeroDivisionError,
2680 "long division or modulo by zero");
2681 return NULL;
2682 }
Tim Peterse2a60002001-09-04 06:17:36 +00002683
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002684 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
2685 ad /= bd; /* overflow/underflow impossible here */
2686 aexp -= bexp;
2687 if (aexp > INT_MAX / PyLong_SHIFT)
2688 goto overflow;
2689 else if (aexp < -(INT_MAX / PyLong_SHIFT))
2690 return PyFloat_FromDouble(0.0); /* underflow to 0 */
2691 errno = 0;
2692 ad = ldexp(ad, aexp * PyLong_SHIFT);
2693 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
2694 goto overflow;
2695 return PyFloat_FromDouble(ad);
Tim Peterse2a60002001-09-04 06:17:36 +00002696
2697overflow:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002698 PyErr_SetString(PyExc_OverflowError,
2699 "long/long too large for a float");
2700 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002701
Tim Peters20dab9f2001-09-04 05:31:47 +00002702}
2703
2704static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002705long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002706{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002707 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002708
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002709 CONVERT_BINOP(v, w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002710
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002711 if (l_divmod(a, b, NULL, &mod) < 0)
2712 mod = NULL;
2713 Py_DECREF(a);
2714 Py_DECREF(b);
2715 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002716}
2717
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002718static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002719long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002720{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002721 PyLongObject *a, *b, *div, *mod;
2722 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002723
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002724 CONVERT_BINOP(v, w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002725
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002726 if (l_divmod(a, b, &div, &mod) < 0) {
2727 Py_DECREF(a);
2728 Py_DECREF(b);
2729 return NULL;
2730 }
2731 z = PyTuple_New(2);
2732 if (z != NULL) {
2733 PyTuple_SetItem(z, 0, (PyObject *) div);
2734 PyTuple_SetItem(z, 1, (PyObject *) mod);
2735 }
2736 else {
2737 Py_DECREF(div);
2738 Py_DECREF(mod);
2739 }
2740 Py_DECREF(a);
2741 Py_DECREF(b);
2742 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002743}
2744
Tim Peters47e52ee2004-08-30 02:44:38 +00002745/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002746static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002747long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002748{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002749 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2750 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002751
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002752 PyLongObject *z = NULL; /* accumulated result */
2753 Py_ssize_t i, j, k; /* counters */
2754 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00002755
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002756 /* 5-ary values. If the exponent is large enough, table is
2757 * precomputed so that table[i] == a**i % c for i in range(32).
2758 */
2759 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2760 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00002761
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002762 /* a, b, c = v, w, x */
2763 CONVERT_BINOP(v, w, &a, &b);
2764 if (PyLong_Check(x)) {
2765 c = (PyLongObject *)x;
2766 Py_INCREF(x);
2767 }
2768 else if (PyInt_Check(x)) {
2769 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
2770 if (c == NULL)
2771 goto Error;
2772 }
2773 else if (x == Py_None)
2774 c = NULL;
2775 else {
2776 Py_DECREF(a);
2777 Py_DECREF(b);
2778 Py_INCREF(Py_NotImplemented);
2779 return Py_NotImplemented;
2780 }
Tim Peters4c483c42001-09-05 06:24:58 +00002781
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002782 if (Py_SIZE(b) < 0) { /* if exponent is negative */
2783 if (c) {
2784 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
2785 "cannot be negative when 3rd argument specified");
2786 goto Error;
2787 }
2788 else {
2789 /* else return a float. This works because we know
2790 that this calls float_pow() which converts its
2791 arguments to double. */
2792 Py_DECREF(a);
2793 Py_DECREF(b);
2794 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
2795 }
2796 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002797
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002798 if (c) {
2799 /* if modulus == 0:
2800 raise ValueError() */
2801 if (Py_SIZE(c) == 0) {
2802 PyErr_SetString(PyExc_ValueError,
2803 "pow() 3rd argument cannot be 0");
2804 goto Error;
2805 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002806
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002807 /* if modulus < 0:
2808 negativeOutput = True
2809 modulus = -modulus */
2810 if (Py_SIZE(c) < 0) {
2811 negativeOutput = 1;
2812 temp = (PyLongObject *)_PyLong_Copy(c);
2813 if (temp == NULL)
2814 goto Error;
2815 Py_DECREF(c);
2816 c = temp;
2817 temp = NULL;
2818 c->ob_size = - c->ob_size;
2819 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002820
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002821 /* if modulus == 1:
2822 return 0 */
2823 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
2824 z = (PyLongObject *)PyLong_FromLong(0L);
2825 goto Done;
2826 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002827
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002828 /* if base < 0:
2829 base = base % modulus
2830 Having the base positive just makes things easier. */
2831 if (Py_SIZE(a) < 0) {
2832 if (l_divmod(a, c, NULL, &temp) < 0)
2833 goto Error;
2834 Py_DECREF(a);
2835 a = temp;
2836 temp = NULL;
2837 }
2838 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002839
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002840 /* At this point a, b, and c are guaranteed non-negative UNLESS
2841 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00002842
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002843 z = (PyLongObject *)PyLong_FromLong(1L);
2844 if (z == NULL)
2845 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002846
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002847 /* Perform a modular reduction, X = X % c, but leave X alone if c
2848 * is NULL.
2849 */
2850#define REDUCE(X) \
2851 if (c != NULL) { \
2852 if (l_divmod(X, c, NULL, &temp) < 0) \
2853 goto Error; \
2854 Py_XDECREF(X); \
2855 X = temp; \
2856 temp = NULL; \
2857 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002858
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002859 /* Multiply two values, then reduce the result:
2860 result = X*Y % c. If c is NULL, skip the mod. */
2861#define MULT(X, Y, result) \
2862{ \
2863 temp = (PyLongObject *)long_mul(X, Y); \
2864 if (temp == NULL) \
2865 goto Error; \
2866 Py_XDECREF(result); \
2867 result = temp; \
2868 temp = NULL; \
2869 REDUCE(result) \
Tim Peters47e52ee2004-08-30 02:44:38 +00002870}
2871
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002872 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
2873 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2874 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
2875 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
2876 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00002877
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002878 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
2879 MULT(z, z, z)
2880 if (bi & j)
2881 MULT(z, a, z)
2882 }
2883 }
2884 }
2885 else {
2886 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2887 Py_INCREF(z); /* still holds 1L */
2888 table[0] = z;
2889 for (i = 1; i < 32; ++i)
2890 MULT(table[i-1], a, table[i])
Tim Peters47e52ee2004-08-30 02:44:38 +00002891
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002892 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
2893 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00002894
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002895 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
2896 const int index = (bi >> j) & 0x1f;
2897 for (k = 0; k < 5; ++k)
2898 MULT(z, z, z)
2899 if (index)
2900 MULT(z, table[index], z)
2901 }
2902 }
2903 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002904
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002905 if (negativeOutput && (Py_SIZE(z) != 0)) {
2906 temp = (PyLongObject *)long_sub(z, c);
2907 if (temp == NULL)
2908 goto Error;
2909 Py_DECREF(z);
2910 z = temp;
2911 temp = NULL;
2912 }
2913 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00002914
2915 Error:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002916 if (z != NULL) {
2917 Py_DECREF(z);
2918 z = NULL;
2919 }
2920 /* fall through */
Tim Peters47e52ee2004-08-30 02:44:38 +00002921 Done:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002922 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
2923 for (i = 0; i < 32; ++i)
2924 Py_XDECREF(table[i]);
2925 }
2926 Py_DECREF(a);
2927 Py_DECREF(b);
2928 Py_XDECREF(c);
2929 Py_XDECREF(temp);
2930 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002931}
2932
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002933static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002934long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002935{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002936 /* Implement ~x as -(x+1) */
2937 PyLongObject *x;
2938 PyLongObject *w;
2939 w = (PyLongObject *)PyLong_FromLong(1L);
2940 if (w == NULL)
2941 return NULL;
2942 x = (PyLongObject *) long_add(v, w);
2943 Py_DECREF(w);
2944 if (x == NULL)
2945 return NULL;
2946 Py_SIZE(x) = -(Py_SIZE(x));
2947 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002948}
2949
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002950static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002951long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002952{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002953 PyLongObject *z;
2954 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
2955 /* -0 == 0 */
2956 Py_INCREF(v);
2957 return (PyObject *) v;
2958 }
2959 z = (PyLongObject *)_PyLong_Copy(v);
2960 if (z != NULL)
2961 z->ob_size = -(v->ob_size);
2962 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002963}
2964
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002965static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002966long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002967{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002968 if (v->ob_size < 0)
2969 return long_neg(v);
2970 else
2971 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002972}
2973
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002974static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002975long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002976{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002977 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002978}
2979
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002980static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002981long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002982{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002983 PyLongObject *a, *b;
2984 PyLongObject *z = NULL;
2985 long shiftby;
2986 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
2987 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002988
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002989 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002990
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002991 if (Py_SIZE(a) < 0) {
2992 /* Right shifting negative numbers is harder */
2993 PyLongObject *a1, *a2;
2994 a1 = (PyLongObject *) long_invert(a);
2995 if (a1 == NULL)
2996 goto rshift_error;
2997 a2 = (PyLongObject *) long_rshift(a1, b);
2998 Py_DECREF(a1);
2999 if (a2 == NULL)
3000 goto rshift_error;
3001 z = (PyLongObject *) long_invert(a2);
3002 Py_DECREF(a2);
3003 }
3004 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003005
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003006 shiftby = PyLong_AsLong((PyObject *)b);
3007 if (shiftby == -1L && PyErr_Occurred())
3008 goto rshift_error;
3009 if (shiftby < 0) {
3010 PyErr_SetString(PyExc_ValueError,
3011 "negative shift count");
3012 goto rshift_error;
3013 }
3014 wordshift = shiftby / PyLong_SHIFT;
3015 newsize = ABS(Py_SIZE(a)) - wordshift;
3016 if (newsize <= 0) {
3017 z = _PyLong_New(0);
3018 Py_DECREF(a);
3019 Py_DECREF(b);
3020 return (PyObject *)z;
3021 }
3022 loshift = shiftby % PyLong_SHIFT;
3023 hishift = PyLong_SHIFT - loshift;
3024 lomask = ((digit)1 << hishift) - 1;
3025 himask = PyLong_MASK ^ lomask;
3026 z = _PyLong_New(newsize);
3027 if (z == NULL)
3028 goto rshift_error;
3029 if (Py_SIZE(a) < 0)
3030 Py_SIZE(z) = -(Py_SIZE(z));
3031 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3032 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3033 if (i+1 < newsize)
3034 z->ob_digit[i] |=
3035 (a->ob_digit[j+1] << hishift) & himask;
3036 }
3037 z = long_normalize(z);
3038 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003039rshift_error:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003040 Py_DECREF(a);
3041 Py_DECREF(b);
3042 return (PyObject *) z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003043
Guido van Rossumc6913e71991-11-19 20:26:46 +00003044}
3045
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003046static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003047long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003048{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003049 /* This version due to Tim Peters */
3050 PyLongObject *a, *b;
3051 PyLongObject *z = NULL;
3052 long shiftby;
3053 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
3054 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003055
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003056 CONVERT_BINOP(v, w, &a, &b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003057
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003058 shiftby = PyLong_AsLong((PyObject *)b);
3059 if (shiftby == -1L && PyErr_Occurred())
3060 goto lshift_error;
3061 if (shiftby < 0) {
3062 PyErr_SetString(PyExc_ValueError, "negative shift count");
3063 goto lshift_error;
3064 }
3065 if ((long)(int)shiftby != shiftby) {
3066 PyErr_SetString(PyExc_ValueError,
3067 "outrageous left shift count");
3068 goto lshift_error;
3069 }
3070 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3071 wordshift = (int)shiftby / PyLong_SHIFT;
3072 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003073
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003074 oldsize = ABS(a->ob_size);
3075 newsize = oldsize + wordshift;
3076 if (remshift)
3077 ++newsize;
3078 z = _PyLong_New(newsize);
3079 if (z == NULL)
3080 goto lshift_error;
3081 if (a->ob_size < 0)
3082 z->ob_size = -(z->ob_size);
3083 for (i = 0; i < wordshift; i++)
3084 z->ob_digit[i] = 0;
3085 accum = 0;
3086 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3087 accum |= (twodigits)a->ob_digit[j] << remshift;
3088 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3089 accum >>= PyLong_SHIFT;
3090 }
3091 if (remshift)
3092 z->ob_digit[newsize-1] = (digit)accum;
3093 else
3094 assert(!accum);
3095 z = long_normalize(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003096lshift_error:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003097 Py_DECREF(a);
3098 Py_DECREF(b);
3099 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003100}
3101
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003102
3103/* Bitwise and/xor/or operations */
3104
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003105static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003106long_bitwise(PyLongObject *a,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003107 int op, /* '&', '|', '^' */
3108 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003109{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003110 digit maska, maskb; /* 0 or PyLong_MASK */
3111 int negz;
3112 Py_ssize_t size_a, size_b, size_z;
3113 PyLongObject *z;
3114 int i;
3115 digit diga, digb;
3116 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003117
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003118 if (Py_SIZE(a) < 0) {
3119 a = (PyLongObject *) long_invert(a);
3120 if (a == NULL)
3121 return NULL;
3122 maska = PyLong_MASK;
3123 }
3124 else {
3125 Py_INCREF(a);
3126 maska = 0;
3127 }
3128 if (Py_SIZE(b) < 0) {
3129 b = (PyLongObject *) long_invert(b);
3130 if (b == NULL) {
3131 Py_DECREF(a);
3132 return NULL;
3133 }
3134 maskb = PyLong_MASK;
3135 }
3136 else {
3137 Py_INCREF(b);
3138 maskb = 0;
3139 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003140
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003141 negz = 0;
3142 switch (op) {
3143 case '^':
3144 if (maska != maskb) {
3145 maska ^= PyLong_MASK;
3146 negz = -1;
3147 }
3148 break;
3149 case '&':
3150 if (maska && maskb) {
3151 op = '|';
3152 maska ^= PyLong_MASK;
3153 maskb ^= PyLong_MASK;
3154 negz = -1;
3155 }
3156 break;
3157 case '|':
3158 if (maska || maskb) {
3159 op = '&';
3160 maska ^= PyLong_MASK;
3161 maskb ^= PyLong_MASK;
3162 negz = -1;
3163 }
3164 break;
3165 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003166
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003167 /* JRH: The original logic here was to allocate the result value (z)
3168 as the longer of the two operands. However, there are some cases
3169 where the result is guaranteed to be shorter than that: AND of two
3170 positives, OR of two negatives: use the shorter number. AND with
3171 mixed signs: use the positive number. OR with mixed signs: use the
3172 negative number. After the transformations above, op will be '&'
3173 iff one of these cases applies, and mask will be non-0 for operands
3174 whose length should be ignored.
3175 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003176
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003177 size_a = Py_SIZE(a);
3178 size_b = Py_SIZE(b);
3179 size_z = op == '&'
3180 ? (maska
3181 ? size_b
3182 : (maskb ? size_a : MIN(size_a, size_b)))
3183 : MAX(size_a, size_b);
3184 z = _PyLong_New(size_z);
3185 if (z == NULL) {
3186 Py_DECREF(a);
3187 Py_DECREF(b);
3188 return NULL;
3189 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003190
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003191 for (i = 0; i < size_z; ++i) {
3192 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3193 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3194 switch (op) {
3195 case '&': z->ob_digit[i] = diga & digb; break;
3196 case '|': z->ob_digit[i] = diga | digb; break;
3197 case '^': z->ob_digit[i] = diga ^ digb; break;
3198 }
3199 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003200
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003201 Py_DECREF(a);
3202 Py_DECREF(b);
3203 z = long_normalize(z);
3204 if (negz == 0)
3205 return (PyObject *) z;
3206 v = long_invert(z);
3207 Py_DECREF(z);
3208 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003209}
3210
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003211static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003212long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003213{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003214 PyLongObject *a, *b;
3215 PyObject *c;
3216 CONVERT_BINOP(v, w, &a, &b);
3217 c = long_bitwise(a, '&', b);
3218 Py_DECREF(a);
3219 Py_DECREF(b);
3220 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003221}
3222
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003223static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003224long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003225{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003226 PyLongObject *a, *b;
3227 PyObject *c;
3228 CONVERT_BINOP(v, w, &a, &b);
3229 c = long_bitwise(a, '^', b);
3230 Py_DECREF(a);
3231 Py_DECREF(b);
3232 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003233}
3234
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003235static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003236long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003237{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003238 PyLongObject *a, *b;
3239 PyObject *c;
3240 CONVERT_BINOP(v, w, &a, &b);
3241 c = long_bitwise(a, '|', b);
3242 Py_DECREF(a);
3243 Py_DECREF(b);
3244 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003245}
3246
Guido van Rossum234f9421993-06-17 12:35:49 +00003247static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003248long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003249{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003250 if (PyInt_Check(*pw)) {
3251 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
3252 if (*pw == NULL)
3253 return -1;
3254 Py_INCREF(*pv);
3255 return 0;
3256 }
3257 else if (PyLong_Check(*pw)) {
3258 Py_INCREF(*pv);
3259 Py_INCREF(*pw);
3260 return 0;
3261 }
3262 return 1; /* Can't do it */
Guido van Rossume6eefc21992-08-14 12:06:52 +00003263}
3264
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003265static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003266long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003267{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003268 if (PyLong_CheckExact(v))
3269 Py_INCREF(v);
3270 else
3271 v = _PyLong_Copy((PyLongObject *)v);
3272 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003273}
3274
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003275static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003276long_int(PyObject *v)
3277{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003278 long x;
3279 x = PyLong_AsLong(v);
3280 if (PyErr_Occurred()) {
3281 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3282 PyErr_Clear();
3283 if (PyLong_CheckExact(v)) {
3284 Py_INCREF(v);
3285 return v;
3286 }
3287 else
3288 return _PyLong_Copy((PyLongObject *)v);
3289 }
3290 else
3291 return NULL;
3292 }
3293 return PyInt_FromLong(x);
Walter Dörwaldf1715402002-11-19 20:49:15 +00003294}
3295
3296static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003297long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003298{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003299 double result;
3300 result = PyLong_AsDouble(v);
3301 if (result == -1.0 && PyErr_Occurred())
3302 return NULL;
3303 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003304}
3305
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003306static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003307long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003308{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003309 return _PyLong_Format(v, 8, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003310}
3311
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003312static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003313long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003314{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003315 return _PyLong_Format(v, 16, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003316}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003317
3318static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003319long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003320
Tim Peters6d6c1a32001-08-02 04:15:00 +00003321static PyObject *
3322long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3323{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003324 PyObject *x = NULL;
3325 int base = -909; /* unlikely! */
3326 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003327
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003328 if (type != &PyLong_Type)
3329 return long_subtype_new(type, args, kwds); /* Wimp out */
3330 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3331 &x, &base))
3332 return NULL;
3333 if (x == NULL)
3334 return PyLong_FromLong(0L);
3335 if (base == -909)
3336 return PyNumber_Long(x);
3337 else if (PyString_Check(x)) {
3338 /* Since PyLong_FromString doesn't have a length parameter,
3339 * check here for possible NULs in the string. */
3340 char *string = PyString_AS_STRING(x);
3341 if (strlen(string) != PyString_Size(x)) {
3342 /* create a repr() of the input string,
3343 * just like PyLong_FromString does. */
3344 PyObject *srepr;
3345 srepr = PyObject_Repr(x);
3346 if (srepr == NULL)
3347 return NULL;
3348 PyErr_Format(PyExc_ValueError,
3349 "invalid literal for long() with base %d: %s",
3350 base, PyString_AS_STRING(srepr));
3351 Py_DECREF(srepr);
3352 return NULL;
3353 }
3354 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
3355 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003356#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003357 else if (PyUnicode_Check(x))
3358 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3359 PyUnicode_GET_SIZE(x),
3360 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003361#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003362 else {
3363 PyErr_SetString(PyExc_TypeError,
3364 "long() can't convert non-string with explicit base");
3365 return NULL;
3366 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367}
3368
Guido van Rossumbef14172001-08-29 15:47:46 +00003369/* Wimpy, slow approach to tp_new calls for subtypes of long:
3370 first create a regular long from whatever arguments we got,
3371 then allocate a subtype instance and initialize it from
3372 the regular long. The regular long is then thrown away.
3373*/
3374static PyObject *
3375long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3376{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003377 PyLongObject *tmp, *newobj;
3378 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003379
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003380 assert(PyType_IsSubtype(type, &PyLong_Type));
3381 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3382 if (tmp == NULL)
3383 return NULL;
3384 assert(PyLong_CheckExact(tmp));
3385 n = Py_SIZE(tmp);
3386 if (n < 0)
3387 n = -n;
3388 newobj = (PyLongObject *)type->tp_alloc(type, n);
3389 if (newobj == NULL) {
3390 Py_DECREF(tmp);
3391 return NULL;
3392 }
3393 assert(PyLong_Check(newobj));
3394 Py_SIZE(newobj) = Py_SIZE(tmp);
3395 for (i = 0; i < n; i++)
3396 newobj->ob_digit[i] = tmp->ob_digit[i];
3397 Py_DECREF(tmp);
3398 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003399}
3400
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003401static PyObject *
3402long_getnewargs(PyLongObject *v)
3403{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003404 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003405}
3406
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003407static PyObject *
3408long_getN(PyLongObject *v, void *context) {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003409 return PyLong_FromLong((Py_intptr_t)context);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003410}
3411
Eric Smitha9f7d622008-02-17 19:46:49 +00003412static PyObject *
3413long__format__(PyObject *self, PyObject *args)
3414{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003415 PyObject *format_spec;
Eric Smitha9f7d622008-02-17 19:46:49 +00003416
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003417 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3418 return NULL;
3419 if (PyBytes_Check(format_spec))
3420 return _PyLong_FormatAdvanced(self,
3421 PyBytes_AS_STRING(format_spec),
3422 PyBytes_GET_SIZE(format_spec));
3423 if (PyUnicode_Check(format_spec)) {
3424 /* Convert format_spec to a str */
3425 PyObject *result;
3426 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00003427
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003428 if (str_spec == NULL)
3429 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00003430
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003431 result = _PyLong_FormatAdvanced(self,
3432 PyBytes_AS_STRING(str_spec),
3433 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00003434
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003435 Py_DECREF(str_spec);
3436 return result;
3437 }
3438 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
3439 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00003440}
3441
Robert Schuppenies51df0642008-06-01 16:16:17 +00003442static PyObject *
3443long_sizeof(PyLongObject *v)
3444{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003445 Py_ssize_t res;
Robert Schuppenies51df0642008-06-01 16:16:17 +00003446
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003447 res = v->ob_type->tp_basicsize;
3448 if (v->ob_size != 0)
3449 res += abs(v->ob_size) * sizeof(digit);
3450 return PyInt_FromSsize_t(res);
Robert Schuppenies51df0642008-06-01 16:16:17 +00003451}
3452
Christian Heimes6f341092008-04-18 23:13:07 +00003453#if 0
3454static PyObject *
3455long_is_finite(PyObject *v)
3456{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003457 Py_RETURN_TRUE;
Christian Heimes6f341092008-04-18 23:13:07 +00003458}
3459#endif
3460
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003461static PyMethodDef long_methods[] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003462 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3463 "Returns self, the complex conjugate of any long."},
Christian Heimes6f341092008-04-18 23:13:07 +00003464#if 0
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003465 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3466 "Returns always True."},
Christian Heimes6f341092008-04-18 23:13:07 +00003467#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003468 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3469 "Truncating an Integral returns itself."},
3470 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3471 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
3472 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
3473 "Returns size in memory, in bytes"},
3474 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003475};
3476
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003477static PyGetSetDef long_getset[] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003478 {"real",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003479 (getter)long_long, (setter)NULL,
3480 "the real part of a complex number",
3481 NULL},
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003482 {"imag",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003483 (getter)long_getN, (setter)NULL,
3484 "the imaginary part of a complex number",
3485 (void*)0},
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003486 {"numerator",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003487 (getter)long_long, (setter)NULL,
3488 "the numerator of a rational number in lowest terms",
3489 NULL},
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003490 {"denominator",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003491 (getter)long_getN, (setter)NULL,
3492 "the denominator of a rational number in lowest terms",
3493 (void*)1},
3494 {NULL} /* Sentinel */
3495};
3496
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003497PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003498"long(x[, base]) -> integer\n\
3499\n\
3500Convert a string or number to a long integer, if possible. A floating\n\
3501point argument will be truncated towards zero (this does not include a\n\
3502string representation of a floating point number!) When converting a\n\
3503string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003504converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003505
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003506static PyNumberMethods long_as_number = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003507 (binaryfunc) long_add, /*nb_add*/
3508 (binaryfunc) long_sub, /*nb_subtract*/
3509 (binaryfunc) long_mul, /*nb_multiply*/
3510 long_classic_div, /*nb_divide*/
3511 long_mod, /*nb_remainder*/
3512 long_divmod, /*nb_divmod*/
3513 long_pow, /*nb_power*/
3514 (unaryfunc) long_neg, /*nb_negative*/
3515 (unaryfunc) long_long, /*tp_positive*/
3516 (unaryfunc) long_abs, /*tp_absolute*/
3517 (inquiry) long_nonzero, /*tp_nonzero*/
3518 (unaryfunc) long_invert, /*nb_invert*/
3519 long_lshift, /*nb_lshift*/
3520 (binaryfunc) long_rshift, /*nb_rshift*/
3521 long_and, /*nb_and*/
3522 long_xor, /*nb_xor*/
3523 long_or, /*nb_or*/
3524 long_coerce, /*nb_coerce*/
3525 long_int, /*nb_int*/
3526 long_long, /*nb_long*/
3527 long_float, /*nb_float*/
3528 long_oct, /*nb_oct*/
3529 long_hex, /*nb_hex*/
3530 0, /* nb_inplace_add */
3531 0, /* nb_inplace_subtract */
3532 0, /* nb_inplace_multiply */
3533 0, /* nb_inplace_divide */
3534 0, /* nb_inplace_remainder */
3535 0, /* nb_inplace_power */
3536 0, /* nb_inplace_lshift */
3537 0, /* nb_inplace_rshift */
3538 0, /* nb_inplace_and */
3539 0, /* nb_inplace_xor */
3540 0, /* nb_inplace_or */
3541 long_div, /* nb_floor_divide */
3542 long_true_divide, /* nb_true_divide */
3543 0, /* nb_inplace_floor_divide */
3544 0, /* nb_inplace_true_divide */
3545 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003546};
3547
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003548PyTypeObject PyLong_Type = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003549 PyObject_HEAD_INIT(&PyType_Type)
3550 0, /* ob_size */
3551 "long", /* tp_name */
3552 sizeof(PyLongObject) - sizeof(digit), /* tp_basicsize */
3553 sizeof(digit), /* tp_itemsize */
3554 long_dealloc, /* tp_dealloc */
3555 0, /* tp_print */
3556 0, /* tp_getattr */
3557 0, /* tp_setattr */
3558 (cmpfunc)long_compare, /* tp_compare */
3559 long_repr, /* tp_repr */
3560 &long_as_number, /* tp_as_number */
3561 0, /* tp_as_sequence */
3562 0, /* tp_as_mapping */
3563 (hashfunc)long_hash, /* tp_hash */
3564 0, /* tp_call */
3565 long_str, /* tp_str */
3566 PyObject_GenericGetAttr, /* tp_getattro */
3567 0, /* tp_setattro */
3568 0, /* tp_as_buffer */
3569 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3570 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
3571 long_doc, /* tp_doc */
3572 0, /* tp_traverse */
3573 0, /* tp_clear */
3574 0, /* tp_richcompare */
3575 0, /* tp_weaklistoffset */
3576 0, /* tp_iter */
3577 0, /* tp_iternext */
3578 long_methods, /* tp_methods */
3579 0, /* tp_members */
3580 long_getset, /* tp_getset */
3581 0, /* tp_base */
3582 0, /* tp_dict */
3583 0, /* tp_descr_get */
3584 0, /* tp_descr_set */
3585 0, /* tp_dictoffset */
3586 0, /* tp_init */
3587 0, /* tp_alloc */
3588 long_new, /* tp_new */
3589 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003590};