blob: 51442d33f57bc312fed308ae906b4856860197b1 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003/* Long (arbitrary precision) integer object implementation */
4
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00005/* XXX The functional organization of this file is terrible */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00008#include "longintrepr.h"
Mark Dickinsonefc82f72009-03-20 15:51:55 +00009#include "structseq.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +000010
Mark Dickinson6736cf82009-04-20 21:13:33 +000011#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000012#include <ctype.h>
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000013#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000014
Tim Peters5af4e6c2002-08-12 02:31:19 +000015/* For long multiplication, use the O(N**2) school algorithm unless
16 * both operands contain more than KARATSUBA_CUTOFF digits (this
Christian Heimes7f39c9f2008-01-25 12:18:43 +000017 * being an internal Python long digit, in base PyLong_BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000018 */
Tim Peters0973b992004-08-29 22:16:50 +000019#define KARATSUBA_CUTOFF 70
20#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000021
Tim Peters47e52ee2004-08-30 02:44:38 +000022/* For exponentiation, use the binary left-to-right algorithm
23 * unless the exponent contains more than FIVEARY_CUTOFF digits.
24 * In that case, do 5 bits at a time. The potential drawback is that
25 * a table of 2**5 intermediate results is computed.
26 */
27#define FIVEARY_CUTOFF 8
28
Guido van Rossume32e0141992-01-19 16:31:05 +000029#define ABS(x) ((x) < 0 ? -(x) : (x))
30
Tim Peters5af4e6c2002-08-12 02:31:19 +000031#undef MIN
32#undef MAX
33#define MAX(x, y) ((x) < (y) ? (y) : (x))
34#define MIN(x, y) ((x) > (y) ? (y) : (x))
35
Guido van Rossumc0b618a1997-05-02 03:12:38 +000036#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000037 if (--_Py_Ticker < 0) { \
38 _Py_Ticker = _Py_CheckInterval; \
Tim Petersd89fc222006-05-25 22:28:46 +000039 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000040 }
41
Guido van Rossumedcc38a1991-05-05 20:09:44 +000042/* Normalize (remove leading zeros from) a long int object.
43 Doesn't attempt to free the storage--in most cases, due to the nature
44 of the algorithms used, this could save at most be one word anyway. */
45
Guido van Rossumc0b618a1997-05-02 03:12:38 +000046static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000047long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000048{
Christian Heimese93237d2007-12-19 02:37:44 +000049 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +000050 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +000051
Guido van Rossumedcc38a1991-05-05 20:09:44 +000052 while (i > 0 && v->ob_digit[i-1] == 0)
53 --i;
54 if (i != j)
Christian Heimese93237d2007-12-19 02:37:44 +000055 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +000056 return v;
57}
58
59/* Allocate a new long int object with size digits.
60 Return NULL and set exception if we run out of memory. */
61
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000062#define MAX_LONG_DIGITS \
63 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
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{
Mark Dickinsonbcf6b182009-02-15 15:48:39 +000068 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000069 PyErr_SetString(PyExc_OverflowError,
70 "too many digits in integer");
Martin v. Löwis18e16552006-02-15 17:27:45 +000071 return NULL;
72 }
Christian Heimes4956d2b2008-01-18 19:12:56 +000073 /* coverity[ampersand_in_size] */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000074 /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect
75 overflow */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000076 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000077}
78
Tim Peters64b5ce32001-09-10 20:52:51 +000079PyObject *
80_PyLong_Copy(PyLongObject *src)
81{
82 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +000083 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000084
85 assert(src != NULL);
86 i = src->ob_size;
87 if (i < 0)
88 i = -(i);
89 result = _PyLong_New(i);
90 if (result != NULL) {
Tim Peters5329cdb2002-03-02 04:18:04 +000091 result->ob_size = src->ob_size;
Tim Peters64b5ce32001-09-10 20:52:51 +000092 while (--i >= 0)
93 result->ob_digit[i] = src->ob_digit[i];
94 }
95 return (PyObject *)result;
96}
97
Guido van Rossumedcc38a1991-05-05 20:09:44 +000098/* Create a new long int object from a C long int */
99
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000100PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000101PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102{
Tim Petersce9de2f2001-06-14 04:56:19 +0000103 PyLongObject *v;
Mark Dickinson27a63252008-04-15 20:51:18 +0000104 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000105 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
106 int ndigits = 0;
107 int negative = 0;
108
109 if (ival < 0) {
Mark Dickinson27a63252008-04-15 20:51:18 +0000110 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
111 ANSI C says that the result of -ival is undefined when ival
112 == LONG_MIN. Hence the following workaround. */
113 abs_ival = (unsigned long)(-1-ival) + 1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000114 negative = 1;
115 }
Mark Dickinson27a63252008-04-15 20:51:18 +0000116 else {
117 abs_ival = (unsigned long)ival;
118 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000119
120 /* Count the number of Python digits.
121 We used to pick 5 ("big enough for anything"), but that's a
122 waste of time and space given that 5*15 = 75 bits are rarely
123 needed. */
Mark Dickinson27a63252008-04-15 20:51:18 +0000124 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000125 while (t) {
126 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000127 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000128 }
129 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000130 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000131 digit *p = v->ob_digit;
132 v->ob_size = negative ? -ndigits : ndigits;
Mark Dickinson27a63252008-04-15 20:51:18 +0000133 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000134 while (t) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000135 *p++ = (digit)(t & PyLong_MASK);
136 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000137 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000138 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000140}
141
Guido van Rossum53756b11997-01-03 17:14:46 +0000142/* Create a new long int object from a C unsigned long int */
143
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000144PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000145PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000146{
Tim Petersce9de2f2001-06-14 04:56:19 +0000147 PyLongObject *v;
148 unsigned long t;
149 int ndigits = 0;
150
151 /* Count the number of Python digits. */
152 t = (unsigned long)ival;
153 while (t) {
154 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000155 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000156 }
157 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000158 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000159 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000160 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000161 while (ival) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000162 *p++ = (digit)(ival & PyLong_MASK);
163 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000164 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000165 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000166 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000167}
168
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000169/* Create a new long int object from a C double */
170
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000172PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000173{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000174 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000175 double frac;
176 int i, ndig, expo, neg;
177 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000178 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000179 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonb6467572008-08-04 21:30:09 +0000180 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000181 return NULL;
182 }
Christian Heimes8267d1d2008-01-04 00:37:34 +0000183 if (Py_IS_NAN(dval)) {
Mark Dickinsonb6467572008-08-04 21:30:09 +0000184 PyErr_SetString(PyExc_ValueError,
185 "cannot convert float NaN to integer");
186 return NULL;
Christian Heimes8267d1d2008-01-04 00:37:34 +0000187 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000188 if (dval < 0.0) {
189 neg = 1;
190 dval = -dval;
191 }
192 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
193 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000194 return PyLong_FromLong(0L);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000195 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000196 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000197 if (v == NULL)
198 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000199 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000200 for (i = ndig; --i >= 0; ) {
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000201 digit bits = (digit)frac;
202 v->ob_digit[i] = bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000203 frac = frac - (double)bits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000204 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000205 }
206 if (neg)
Christian Heimese93237d2007-12-19 02:37:44 +0000207 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000208 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000209}
210
Armin Rigo7ccbca92006-10-04 12:17:45 +0000211/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
212 * anything about what happens when a signed integer operation overflows,
213 * and some compilers think they're doing you a favor by being "clever"
214 * then. The bit pattern for the largest postive signed long is
215 * (unsigned long)LONG_MAX, and for the smallest negative signed long
216 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
217 * However, some other compilers warn about applying unary minus to an
218 * unsigned operand. Hence the weird "0-".
219 */
220#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
221#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
222
Mark Dickinsone31d3002009-12-21 11:21:25 +0000223/* Get a C long int from a Python long or Python int object.
224 On overflow, returns -1 and sets *overflow to 1 or -1 depending
225 on the sign of the result. Otherwise *overflow is 0.
226
227 For other errors (e.g., type error), returns -1 and sets an error
228 condition.
229*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000230
231long
Mark Dickinsone31d3002009-12-21 11:21:25 +0000232PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000233{
Guido van Rossumf7531811998-05-26 14:33:37 +0000234 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000235 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000236 unsigned long x, prev;
Mark Dickinsone31d3002009-12-21 11:21:25 +0000237 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000238 Py_ssize_t i;
239 int sign;
Mark Dickinsone31d3002009-12-21 11:21:25 +0000240 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000241
Mark Dickinsone31d3002009-12-21 11:21:25 +0000242 *overflow = 0;
243 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000245 return -1;
246 }
Guido van Rossumf7531811998-05-26 14:33:37 +0000247
Mark Dickinsone31d3002009-12-21 11:21:25 +0000248 if(PyInt_Check(vv))
249 return PyInt_AsLong(vv);
250
251 if (!PyLong_Check(vv)) {
252 PyNumberMethods *nb;
253 nb = vv->ob_type->tp_as_number;
254 if (nb == NULL || nb->nb_int == NULL) {
255 PyErr_SetString(PyExc_TypeError,
256 "an integer is required");
257 return -1;
258 }
259 vv = (*nb->nb_int) (vv);
260 if (vv == NULL)
261 return -1;
262 do_decref = 1;
263 if(PyInt_Check(vv)) {
264 res = PyInt_AsLong(vv);
265 goto exit;
266 }
267 if (!PyLong_Check(vv)) {
268 Py_DECREF(vv);
269 PyErr_SetString(PyExc_TypeError,
270 "nb_int should return int object");
271 return -1;
272 }
273 }
274
275 res = -1;
276 v = (PyLongObject *)vv;
277 i = Py_SIZE(v);
278
279 switch (i) {
280 case -1:
281 res = -(sdigit)v->ob_digit[0];
282 break;
283 case 0:
284 res = 0;
285 break;
286 case 1:
287 res = v->ob_digit[0];
288 break;
289 default:
290 sign = 1;
291 x = 0;
292 if (i < 0) {
293 sign = -1;
294 i = -(i);
295 }
296 while (--i >= 0) {
297 prev = x;
298 x = (x << PyLong_SHIFT) + v->ob_digit[i];
299 if ((x >> PyLong_SHIFT) != prev) {
300 *overflow = sign;
301 goto exit;
302 }
303 }
304 /* Haven't lost any bits, but casting to long requires extra
305 * care (see comment above).
306 */
307 if (x <= (unsigned long)LONG_MAX) {
308 res = (long)x * sign;
309 }
310 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
311 res = LONG_MIN;
312 }
313 else {
314 *overflow = sign;
315 /* res is already set to -1 */
316 }
317 }
318 exit:
319 if (do_decref) {
320 Py_DECREF(vv);
321 }
322 return res;
323}
324
325/* Get a C long int from a long int object.
326 Returns -1 and sets an error condition if overflow occurs. */
327
328long
329PyLong_AsLong(PyObject *obj)
330{
331 int overflow;
332 long result = PyLong_AsLongAndOverflow(obj, &overflow);
333 if (overflow) {
334 /* XXX: could be cute and give a different
335 message for overflow == -1 */
336 PyErr_SetString(PyExc_OverflowError,
337 "Python int too large to convert to C long");
338 }
339 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000340}
341
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000342/* Get a Py_ssize_t from a long int object.
343 Returns -1 and sets an error condition if overflow occurs. */
344
345Py_ssize_t
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000346PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000347 register PyLongObject *v;
348 size_t x, prev;
349 Py_ssize_t i;
350 int sign;
351
352 if (vv == NULL || !PyLong_Check(vv)) {
353 PyErr_BadInternalCall();
354 return -1;
355 }
356 v = (PyLongObject *)vv;
357 i = v->ob_size;
358 sign = 1;
359 x = 0;
360 if (i < 0) {
361 sign = -1;
362 i = -(i);
363 }
364 while (--i >= 0) {
365 prev = x;
Mark Dickinson71adc932009-09-28 16:52:40 +0000366 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000367 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000368 goto overflow;
369 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000370 /* Haven't lost any bits, but casting to a signed type requires
371 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000372 */
Armin Rigo7ccbca92006-10-04 12:17:45 +0000373 if (x <= (size_t)PY_SSIZE_T_MAX) {
374 return (Py_ssize_t)x * sign;
375 }
376 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
377 return PY_SSIZE_T_MIN;
378 }
379 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000380
381 overflow:
382 PyErr_SetString(PyExc_OverflowError,
383 "long int too large to convert to int");
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000384 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000385}
386
Guido van Rossumd8c80482002-08-13 00:24:58 +0000387/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000388 Returns -1 and sets an error condition if overflow occurs. */
389
390unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000391PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000392{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000394 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000395 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000396
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000398 if (vv != NULL && PyInt_Check(vv)) {
399 long val = PyInt_AsLong(vv);
400 if (val < 0) {
401 PyErr_SetString(PyExc_OverflowError,
402 "can't convert negative value to unsigned long");
403 return (unsigned long) -1;
404 }
405 return val;
406 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000407 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000408 return (unsigned long) -1;
409 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000410 v = (PyLongObject *)vv;
Christian Heimese93237d2007-12-19 02:37:44 +0000411 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000412 x = 0;
413 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000414 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum53756b11997-01-03 17:14:46 +0000415 "can't convert negative value to unsigned long");
416 return (unsigned long) -1;
417 }
418 while (--i >= 0) {
419 prev = x;
Mark Dickinson71adc932009-09-28 16:52:40 +0000420 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000421 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000422 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +0000423 "long int too large to convert");
Guido van Rossum53756b11997-01-03 17:14:46 +0000424 return (unsigned long) -1;
425 }
426 }
427 return x;
428}
429
Thomas Hellera4ea6032003-04-17 18:55:45 +0000430/* Get a C unsigned long int from a long int object, ignoring the high bits.
431 Returns -1 and sets an error condition if an error occurs. */
432
433unsigned long
434PyLong_AsUnsignedLongMask(PyObject *vv)
435{
436 register PyLongObject *v;
437 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000438 Py_ssize_t i;
439 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000440
441 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000442 if (vv != NULL && PyInt_Check(vv))
443 return PyInt_AsUnsignedLongMask(vv);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000444 PyErr_BadInternalCall();
445 return (unsigned long) -1;
446 }
447 v = (PyLongObject *)vv;
448 i = v->ob_size;
449 sign = 1;
450 x = 0;
451 if (i < 0) {
452 sign = -1;
453 i = -i;
454 }
455 while (--i >= 0) {
Mark Dickinson71adc932009-09-28 16:52:40 +0000456 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000457 }
458 return x * sign;
459}
460
Tim Peters5b8132f2003-01-31 15:52:05 +0000461int
462_PyLong_Sign(PyObject *vv)
463{
464 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000465
466 assert(v != NULL);
467 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000468
Christian Heimese93237d2007-12-19 02:37:44 +0000469 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000470}
471
Tim Petersbaefd9e2003-01-28 20:37:45 +0000472size_t
473_PyLong_NumBits(PyObject *vv)
474{
475 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000476 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000477 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000478
479 assert(v != NULL);
480 assert(PyLong_Check(v));
Christian Heimese93237d2007-12-19 02:37:44 +0000481 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000482 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
483 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000484 digit msd = v->ob_digit[ndigits - 1];
485
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000486 result = (ndigits - 1) * PyLong_SHIFT;
487 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000488 goto Overflow;
489 do {
490 ++result;
491 if (result == 0)
492 goto Overflow;
493 msd >>= 1;
494 } while (msd);
495 }
496 return result;
497
498Overflow:
499 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
500 "to express in a platform size_t");
501 return (size_t)-1;
502}
503
Tim Peters2a9b3672001-06-11 21:23:58 +0000504PyObject *
505_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
506 int little_endian, int is_signed)
507{
508 const unsigned char* pstartbyte;/* LSB of bytes */
509 int incr; /* direction to move pstartbyte */
510 const unsigned char* pendbyte; /* MSB of bytes */
511 size_t numsignificantbytes; /* number of bytes that matter */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000512 Py_ssize_t ndigits; /* number of Python long digits */
Tim Peters2a9b3672001-06-11 21:23:58 +0000513 PyLongObject* v; /* result */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000514 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000515
516 if (n == 0)
517 return PyLong_FromLong(0L);
518
519 if (little_endian) {
520 pstartbyte = bytes;
521 pendbyte = bytes + n - 1;
522 incr = 1;
523 }
524 else {
525 pstartbyte = bytes + n - 1;
526 pendbyte = bytes;
527 incr = -1;
528 }
529
530 if (is_signed)
531 is_signed = *pendbyte >= 0x80;
532
533 /* Compute numsignificantbytes. This consists of finding the most
534 significant byte. Leading 0 bytes are insignficant if the number
535 is positive, and leading 0xff bytes if negative. */
536 {
537 size_t i;
538 const unsigned char* p = pendbyte;
539 const int pincr = -incr; /* search MSB to LSB */
540 const unsigned char insignficant = is_signed ? 0xff : 0x00;
541
542 for (i = 0; i < n; ++i, p += pincr) {
543 if (*p != insignficant)
544 break;
545 }
546 numsignificantbytes = n - i;
547 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
548 actually has 2 significant bytes. OTOH, 0xff0001 ==
549 -0x00ffff, so we wouldn't *need* to bump it there; but we
550 do for 0xffff = -0x0001. To be safe without bothering to
551 check every case, bump it regardless. */
552 if (is_signed && numsignificantbytes < n)
553 ++numsignificantbytes;
554 }
555
556 /* How many Python long digits do we need? We have
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000557 8*numsignificantbytes bits, and each Python long digit has
558 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
559 /* catch overflow before it happens */
560 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
561 PyErr_SetString(PyExc_OverflowError,
562 "byte array too long to convert to int");
563 return NULL;
564 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000565 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000566 v = _PyLong_New(ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000567 if (v == NULL)
568 return NULL;
569
570 /* Copy the bits over. The tricky parts are computing 2's-comp on
571 the fly for signed numbers, and dealing with the mismatch between
572 8-bit bytes and (probably) 15-bit Python digits.*/
573 {
574 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000575 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000576 twodigits accum = 0; /* sliding register */
577 unsigned int accumbits = 0; /* number of bits in accum */
578 const unsigned char* p = pstartbyte;
579
580 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000581 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000582 /* Compute correction for 2's comp, if needed. */
583 if (is_signed) {
584 thisbyte = (0xff ^ thisbyte) + carry;
585 carry = thisbyte >> 8;
586 thisbyte &= 0xff;
587 }
588 /* Because we're going LSB to MSB, thisbyte is
589 more significant than what's already in accum,
590 so needs to be prepended to accum. */
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000591 accum |= (twodigits)thisbyte << accumbits;
Tim Peters2a9b3672001-06-11 21:23:58 +0000592 accumbits += 8;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000593 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000594 /* There's enough to fill a Python digit. */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000595 assert(idigit < ndigits);
596 v->ob_digit[idigit] = (digit)(accum &
597 PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000598 ++idigit;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000599 accum >>= PyLong_SHIFT;
600 accumbits -= PyLong_SHIFT;
601 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000602 }
603 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000604 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000605 if (accumbits) {
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000606 assert(idigit < ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000607 v->ob_digit[idigit] = (digit)accum;
608 ++idigit;
609 }
610 }
611
Christian Heimese93237d2007-12-19 02:37:44 +0000612 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000613 return (PyObject *)long_normalize(v);
614}
615
616int
617_PyLong_AsByteArray(PyLongObject* v,
618 unsigned char* bytes, size_t n,
619 int little_endian, int is_signed)
620{
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000621 Py_ssize_t i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000622 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000623 twodigits accum; /* sliding register */
624 unsigned int accumbits; /* # bits in accum */
625 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
Mark Dickinson1afe6dd2009-01-25 22:12:31 +0000626 digit carry; /* for computing 2's-comp */
Tim Peters2a9b3672001-06-11 21:23:58 +0000627 size_t j; /* # bytes filled */
628 unsigned char* p; /* pointer to next byte in bytes */
629 int pincr; /* direction to move p */
630
631 assert(v != NULL && PyLong_Check(v));
632
Christian Heimese93237d2007-12-19 02:37:44 +0000633 if (Py_SIZE(v) < 0) {
634 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000635 if (!is_signed) {
Mark Dickinson4015f622009-02-10 15:46:50 +0000636 PyErr_SetString(PyExc_OverflowError,
Tim Peters2a9b3672001-06-11 21:23:58 +0000637 "can't convert negative long to unsigned");
638 return -1;
639 }
640 do_twos_comp = 1;
641 }
642 else {
Christian Heimese93237d2007-12-19 02:37:44 +0000643 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000644 do_twos_comp = 0;
645 }
646
647 if (little_endian) {
648 p = bytes;
649 pincr = 1;
650 }
651 else {
652 p = bytes + n - 1;
653 pincr = -1;
654 }
655
Tim Peters898cf852001-06-13 20:50:08 +0000656 /* Copy over all the Python digits.
657 It's crucial that every Python digit except for the MSD contribute
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000658 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000659 normalized. */
660 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000661 j = 0;
662 accum = 0;
663 accumbits = 0;
664 carry = do_twos_comp ? 1 : 0;
665 for (i = 0; i < ndigits; ++i) {
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000666 digit thisdigit = v->ob_digit[i];
Tim Peters2a9b3672001-06-11 21:23:58 +0000667 if (do_twos_comp) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000668 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
669 carry = thisdigit >> PyLong_SHIFT;
670 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000671 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000672 /* Because we're going LSB to MSB, thisdigit is more
673 significant than what's already in accum, so needs to be
674 prepended to accum. */
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000675 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000676
Tim Petersede05092001-06-14 08:53:38 +0000677 /* The most-significant digit may be (probably is) at least
678 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000679 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000680 /* Count # of sign bits -- they needn't be stored,
681 * although for signed conversion we need later to
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000682 * make sure at least one sign bit gets stored. */
683 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
684 thisdigit;
685 while (s != 0) {
686 s >>= 1;
687 accumbits++;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000688 }
Tim Peters7a3bfc32001-06-12 01:22:22 +0000689 }
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000690 else
691 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000692
Tim Peters2a9b3672001-06-11 21:23:58 +0000693 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000694 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000695 if (j >= n)
696 goto Overflow;
697 ++j;
698 *p = (unsigned char)(accum & 0xff);
699 p += pincr;
700 accumbits -= 8;
701 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000702 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000703 }
704
705 /* Store the straggler (if any). */
706 assert(accumbits < 8);
707 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000708 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000709 if (j >= n)
710 goto Overflow;
711 ++j;
712 if (do_twos_comp) {
713 /* Fill leading bits of the byte with sign bits
714 (appropriately pretending that the long had an
715 infinite supply of sign bits). */
716 accum |= (~(twodigits)0) << accumbits;
717 }
718 *p = (unsigned char)(accum & 0xff);
719 p += pincr;
720 }
Tim Peters05607ad2001-06-13 21:01:27 +0000721 else if (j == n && n > 0 && is_signed) {
722 /* The main loop filled the byte array exactly, so the code
723 just above didn't get to ensure there's a sign bit, and the
724 loop below wouldn't add one either. Make sure a sign bit
725 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000726 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000727 int sign_bit_set = msb >= 0x80;
728 assert(accumbits == 0);
729 if (sign_bit_set == do_twos_comp)
730 return 0;
731 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000732 goto Overflow;
733 }
Tim Peters05607ad2001-06-13 21:01:27 +0000734
735 /* Fill remaining bytes with copies of the sign bit. */
736 {
737 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
738 for ( ; j < n; ++j, p += pincr)
739 *p = signbyte;
740 }
741
Tim Peters2a9b3672001-06-11 21:23:58 +0000742 return 0;
743
744Overflow:
745 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
746 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000747
Tim Peters2a9b3672001-06-11 21:23:58 +0000748}
749
Guido van Rossum78694d91998-09-18 14:14:13 +0000750/* Create a new long (or int) object from a C pointer */
751
752PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000753PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000754{
Tim Peters70128a12001-06-16 08:48:40 +0000755#if SIZEOF_VOID_P <= SIZEOF_LONG
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000756 if ((long)p < 0)
757 return PyLong_FromUnsignedLong((unsigned long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000758 return PyInt_FromLong((long)p);
759#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000760
Tim Peters70128a12001-06-16 08:48:40 +0000761#ifndef HAVE_LONG_LONG
762# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
763#endif
764#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000765# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000766#endif
767 /* optimize null pointers */
768 if (p == NULL)
769 return PyInt_FromLong(0);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000770 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000771
772#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000773}
774
775/* Get a C pointer from a long object (or an int object in some cases) */
776
777void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000778PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000779{
780 /* This function will allow int or long objects. If vv is neither,
781 then the PyLong_AsLong*() functions will raise the exception:
782 PyExc_SystemError, "bad argument to internal function"
783 */
Tim Peters70128a12001-06-16 08:48:40 +0000784#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000785 long x;
786
Tim Peters70128a12001-06-16 08:48:40 +0000787 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000788 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000789 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000790 x = PyLong_AsLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000791 else
792 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000793#else
Tim Peters70128a12001-06-16 08:48:40 +0000794
795#ifndef HAVE_LONG_LONG
796# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
797#endif
798#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000799# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000800#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000801 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000802
Tim Peters70128a12001-06-16 08:48:40 +0000803 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000804 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000805 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000806 x = PyLong_AsLongLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000807 else
808 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000809
810#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000811
812 if (x == -1 && PyErr_Occurred())
813 return NULL;
814 return (void *)x;
815}
816
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000817#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000818
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000819/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000820 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000821 */
822
Tim Peterscf37dfc2001-06-14 18:42:50 +0000823#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000824
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000825/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000826
827PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000828PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000829{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000830 PyLongObject *v;
Mark Dickinson27a63252008-04-15 20:51:18 +0000831 unsigned PY_LONG_LONG abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000832 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
833 int ndigits = 0;
834 int negative = 0;
835
836 if (ival < 0) {
Mark Dickinson27a63252008-04-15 20:51:18 +0000837 /* avoid signed overflow on negation; see comments
838 in PyLong_FromLong above. */
839 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000840 negative = 1;
841 }
Mark Dickinson27a63252008-04-15 20:51:18 +0000842 else {
843 abs_ival = (unsigned PY_LONG_LONG)ival;
844 }
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000845
846 /* Count the number of Python digits.
847 We used to pick 5 ("big enough for anything"), but that's a
848 waste of time and space given that 5*15 = 75 bits are rarely
849 needed. */
Mark Dickinson27a63252008-04-15 20:51:18 +0000850 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000851 while (t) {
852 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000853 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000854 }
855 v = _PyLong_New(ndigits);
856 if (v != NULL) {
857 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000858 Py_SIZE(v) = negative ? -ndigits : ndigits;
Mark Dickinson27a63252008-04-15 20:51:18 +0000859 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000860 while (t) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000861 *p++ = (digit)(t & PyLong_MASK);
862 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000863 }
864 }
865 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000866}
867
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000868/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000869
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000870PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000871PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000872{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000873 PyLongObject *v;
874 unsigned PY_LONG_LONG t;
875 int ndigits = 0;
876
877 /* Count the number of Python digits. */
878 t = (unsigned PY_LONG_LONG)ival;
879 while (t) {
880 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000881 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000882 }
883 v = _PyLong_New(ndigits);
884 if (v != NULL) {
885 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000886 Py_SIZE(v) = ndigits;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000887 while (ival) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000888 *p++ = (digit)(ival & PyLong_MASK);
889 ival >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000890 }
891 }
892 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000893}
894
Martin v. Löwis18e16552006-02-15 17:27:45 +0000895/* Create a new long int object from a C Py_ssize_t. */
896
897PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000898PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000899{
900 Py_ssize_t bytes = ival;
901 int one = 1;
902 return _PyLong_FromByteArray(
903 (unsigned char *)&bytes,
Kristján Valur Jónssonf0303942007-05-03 20:27:03 +0000904 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000905}
906
907/* Create a new long int object from a C size_t. */
908
909PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000910PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000911{
912 size_t bytes = ival;
913 int one = 1;
914 return _PyLong_FromByteArray(
915 (unsigned char *)&bytes,
916 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
917}
918
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000919/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000920 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000921
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000922PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000923PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000924{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000925 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000926 int one = 1;
927 int res;
928
Tim Petersd38b1c72001-09-30 05:09:37 +0000929 if (vv == NULL) {
930 PyErr_BadInternalCall();
931 return -1;
932 }
933 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000934 PyNumberMethods *nb;
935 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +0000936 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000937 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000938 if ((nb = vv->ob_type->tp_as_number) == NULL ||
939 nb->nb_int == NULL) {
940 PyErr_SetString(PyExc_TypeError, "an integer is required");
941 return -1;
942 }
943 io = (*nb->nb_int) (vv);
944 if (io == NULL)
945 return -1;
946 if (PyInt_Check(io)) {
947 bytes = PyInt_AsLong(io);
948 Py_DECREF(io);
949 return bytes;
950 }
951 if (PyLong_Check(io)) {
952 bytes = PyLong_AsLongLong(io);
953 Py_DECREF(io);
954 return bytes;
955 }
956 Py_DECREF(io);
957 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000958 return -1;
959 }
960
Tim Petersd1a7da62001-06-13 00:35:57 +0000961 res = _PyLong_AsByteArray(
962 (PyLongObject *)vv, (unsigned char *)&bytes,
963 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000964
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000965 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000966 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000967 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000968 else
969 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000970}
971
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000972/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000973 Return -1 and set an error if overflow occurs. */
974
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000975unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000976PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000977{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000978 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000979 int one = 1;
980 int res;
981
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000982 if (vv == NULL || !PyLong_Check(vv)) {
983 PyErr_BadInternalCall();
Skip Montanaro429433b2006-04-18 00:35:43 +0000984 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000985 }
986
Tim Petersd1a7da62001-06-13 00:35:57 +0000987 res = _PyLong_AsByteArray(
988 (PyLongObject *)vv, (unsigned char *)&bytes,
989 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000990
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000991 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000992 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000993 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000994 else
995 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000996}
Tim Petersd1a7da62001-06-13 00:35:57 +0000997
Thomas Hellera4ea6032003-04-17 18:55:45 +0000998/* Get a C unsigned long int from a long int object, ignoring the high bits.
999 Returns -1 and sets an error condition if an error occurs. */
1000
1001unsigned PY_LONG_LONG
1002PyLong_AsUnsignedLongLongMask(PyObject *vv)
1003{
1004 register PyLongObject *v;
1005 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001006 Py_ssize_t i;
1007 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001008
1009 if (vv == NULL || !PyLong_Check(vv)) {
1010 PyErr_BadInternalCall();
1011 return (unsigned long) -1;
1012 }
1013 v = (PyLongObject *)vv;
1014 i = v->ob_size;
1015 sign = 1;
1016 x = 0;
1017 if (i < 0) {
1018 sign = -1;
1019 i = -i;
1020 }
1021 while (--i >= 0) {
Mark Dickinson71adc932009-09-28 16:52:40 +00001022 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001023 }
1024 return x * sign;
1025}
Tim Petersd1a7da62001-06-13 00:35:57 +00001026#undef IS_LITTLE_ENDIAN
1027
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001028#endif /* HAVE_LONG_LONG */
1029
Neil Schemenauerba872e22001-01-04 01:46:03 +00001030
1031static int
1032convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001033 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001034 *a = (PyLongObject *) v;
1035 Py_INCREF(v);
1036 }
1037 else if (PyInt_Check(v)) {
1038 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1039 }
1040 else {
1041 return 0;
1042 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001043 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001044 *b = (PyLongObject *) w;
1045 Py_INCREF(w);
1046 }
1047 else if (PyInt_Check(w)) {
1048 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1049 }
1050 else {
1051 Py_DECREF(*a);
1052 return 0;
1053 }
1054 return 1;
1055}
1056
1057#define CONVERT_BINOP(v, w, a, b) \
1058 if (!convert_binop(v, w, a, b)) { \
1059 Py_INCREF(Py_NotImplemented); \
1060 return Py_NotImplemented; \
1061 }
1062
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001063/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1064 2**k if d is nonzero, else 0. */
1065
1066static const unsigned char BitLengthTable[32] = {
1067 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1068 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
1069};
1070
1071static int
1072bits_in_digit(digit d)
1073{
1074 int d_bits = 0;
1075 while (d >= 32) {
1076 d_bits += 6;
1077 d >>= 6;
1078 }
1079 d_bits += (int)BitLengthTable[d];
1080 return d_bits;
1081}
1082
Tim Peters877a2122002-08-12 05:09:36 +00001083/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1084 * is modified in place, by adding y to it. Carries are propagated as far as
1085 * x[m-1], and the remaining carry (0 or 1) is returned.
1086 */
1087static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001088v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001089{
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001090 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001091 digit carry = 0;
1092
1093 assert(m >= n);
1094 for (i = 0; i < n; ++i) {
1095 carry += x[i] + y[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001096 x[i] = carry & PyLong_MASK;
1097 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001098 assert((carry & 1) == carry);
1099 }
1100 for (; carry && i < m; ++i) {
1101 carry += x[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001102 x[i] = carry & PyLong_MASK;
1103 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001104 assert((carry & 1) == carry);
1105 }
1106 return carry;
1107}
1108
1109/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1110 * is modified in place, by subtracting y from it. Borrows are propagated as
1111 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1112 */
1113static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001115{
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001116 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001117 digit borrow = 0;
1118
1119 assert(m >= n);
1120 for (i = 0; i < n; ++i) {
1121 borrow = x[i] - y[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001122 x[i] = borrow & PyLong_MASK;
1123 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001124 borrow &= 1; /* keep only 1 sign bit */
1125 }
1126 for (; borrow && i < m; ++i) {
1127 borrow = x[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001128 x[i] = borrow & PyLong_MASK;
1129 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001130 borrow &= 1;
1131 }
1132 return borrow;
1133}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001134
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001135/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1136 * result in z[0:m], and return the d bits shifted out of the top.
1137 */
1138static digit
1139v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001140{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001141 Py_ssize_t i;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001142 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001143
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001144 assert(0 <= d && d < PyLong_SHIFT);
1145 for (i=0; i < m; i++) {
1146 twodigits acc = (twodigits)a[i] << d | carry;
1147 z[i] = (digit)acc & PyLong_MASK;
1148 carry = (digit)(acc >> PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001149 }
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001150 return carry;
1151}
1152
1153/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1154 * result in z[0:m], and return the d bits shifted out of the bottom.
1155 */
1156static digit
1157v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1158{
1159 Py_ssize_t i;
1160 digit carry = 0;
1161 digit mask = ((digit)1 << d) - 1U;
1162
1163 assert(0 <= d && d < PyLong_SHIFT);
1164 for (i=m; i-- > 0;) {
1165 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1166 carry = (digit)acc & mask;
1167 z[i] = (digit)(acc >> d);
1168 }
1169 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001170}
1171
Tim Peters212e6142001-07-14 12:23:19 +00001172/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1173 in pout, and returning the remainder. pin and pout point at the LSD.
1174 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Eric Smith5e527eb2008-02-10 01:36:53 +00001175 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001176 immutable. */
1177
1178static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001179inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001180{
1181 twodigits rem = 0;
1182
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001183 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001184 pin += size;
1185 pout += size;
1186 while (--size >= 0) {
1187 digit hi;
Mark Dickinson71adc932009-09-28 16:52:40 +00001188 rem = (rem << PyLong_SHIFT) | *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001189 *--pout = hi = (digit)(rem / n);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001190 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001191 }
1192 return (digit)rem;
1193}
1194
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001195/* Divide a long integer by a digit, returning both the quotient
1196 (as function result) and the remainder (through *prem).
1197 The sign of a is ignored; n should not be zero. */
1198
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001199static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001200divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001201{
Christian Heimese93237d2007-12-19 02:37:44 +00001202 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001203 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001204
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001205 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001206 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001207 if (z == NULL)
1208 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001209 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001210 return long_normalize(z);
1211}
1212
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001213/* Convert a long integer to a base 10 string. Returns a new non-shared
1214 string. (Return value is non-shared so that callers can modify the
1215 returned value if necessary.) */
1216
1217static PyObject *
1218long_to_decimal_string(PyObject *aa, int addL)
1219{
1220 PyLongObject *scratch, *a;
1221 PyObject *str;
1222 Py_ssize_t size, strlen, size_a, i, j;
1223 digit *pout, *pin, rem, tenpow;
1224 char *p;
1225 int negative;
1226
1227 a = (PyLongObject *)aa;
1228 if (a == NULL || !PyLong_Check(a)) {
1229 PyErr_BadInternalCall();
1230 return NULL;
1231 }
1232 size_a = ABS(Py_SIZE(a));
1233 negative = Py_SIZE(a) < 0;
1234
1235 /* quick and dirty upper bound for the number of digits
1236 required to express a in base _PyLong_DECIMAL_BASE:
1237
1238 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
1239
1240 But log2(a) < size_a * PyLong_SHIFT, and
1241 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1242 > 3 * _PyLong_DECIMAL_SHIFT
1243 */
1244 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1245 PyErr_SetString(PyExc_OverflowError,
1246 "long is too large to format");
1247 return NULL;
1248 }
1249 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1250 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1251 scratch = _PyLong_New(size);
1252 if (scratch == NULL)
1253 return NULL;
1254
1255 /* convert array of base _PyLong_BASE digits in pin to an array of
1256 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1257 Volume 2 (3rd edn), section 4.4, Method 1b). */
1258 pin = a->ob_digit;
1259 pout = scratch->ob_digit;
1260 size = 0;
1261 for (i = size_a; --i >= 0; ) {
1262 digit hi = pin[i];
1263 for (j = 0; j < size; j++) {
1264 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
Mark Dickinson40ee8612009-09-21 16:16:44 +00001265 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1266 pout[j] = (digit)(z - (twodigits)hi *
1267 _PyLong_DECIMAL_BASE);
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001268 }
1269 while (hi) {
1270 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1271 hi /= _PyLong_DECIMAL_BASE;
1272 }
1273 /* check for keyboard interrupt */
1274 SIGCHECK({
1275 Py_DECREF(scratch);
1276 return NULL;
1277 })
1278 }
1279 /* pout should have at least one digit, so that the case when a = 0
1280 works correctly */
1281 if (size == 0)
1282 pout[size++] = 0;
1283
1284 /* calculate exact length of output string, and allocate */
1285 strlen = (addL != 0) + negative +
1286 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1287 tenpow = 10;
1288 rem = pout[size-1];
1289 while (rem >= tenpow) {
1290 tenpow *= 10;
1291 strlen++;
1292 }
1293 str = PyString_FromStringAndSize(NULL, strlen);
1294 if (str == NULL) {
1295 Py_DECREF(scratch);
1296 return NULL;
1297 }
1298
1299 /* fill the string right-to-left */
1300 p = PyString_AS_STRING(str) + strlen;
1301 *p = '\0';
1302 if (addL)
1303 *--p = 'L';
1304 /* pout[0] through pout[size-2] contribute exactly
1305 _PyLong_DECIMAL_SHIFT digits each */
1306 for (i=0; i < size - 1; i++) {
1307 rem = pout[i];
1308 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1309 *--p = '0' + rem % 10;
1310 rem /= 10;
1311 }
1312 }
1313 /* pout[size-1]: always produce at least one decimal digit */
1314 rem = pout[i];
1315 do {
1316 *--p = '0' + rem % 10;
1317 rem /= 10;
1318 } while (rem != 0);
1319
1320 /* and sign */
1321 if (negative)
1322 *--p = '-';
1323
1324 /* check we've counted correctly */
1325 assert(p == PyString_AS_STRING(str));
1326 Py_DECREF(scratch);
1327 return (PyObject *)str;
1328}
1329
Eric Smith5e527eb2008-02-10 01:36:53 +00001330/* Convert the long to a string object with given base,
1331 appending a base prefix of 0[box] if base is 2, 8 or 16.
1332 Add a trailing "L" if addL is non-zero.
1333 If newstyle is zero, then use the pre-2.6 behavior of octal having
1334 a leading "0", instead of the prefix "0o" */
1335PyAPI_FUNC(PyObject *)
1336_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001337{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001338 register PyLongObject *a = (PyLongObject *)aa;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001339 PyStringObject *str;
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001340 Py_ssize_t i, sz;
Neal Norwitzc09efa82006-07-23 07:53:14 +00001341 Py_ssize_t size_a;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001342 char *p;
1343 int bits;
1344 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001345
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001346 if (base == 10)
1347 return long_to_decimal_string((PyObject *)a, addL);
1348
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001349 if (a == NULL || !PyLong_Check(a)) {
1350 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001351 return NULL;
1352 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001353 assert(base >= 2 && base <= 36);
Christian Heimese93237d2007-12-19 02:37:44 +00001354 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001355
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001356 /* Compute a rough upper bound for the length of the string */
1357 i = base;
1358 bits = 0;
1359 while (i > 1) {
1360 ++bits;
1361 i >>= 1;
1362 }
Armin Rigo7ccbca92006-10-04 12:17:45 +00001363 i = 5 + (addL ? 1 : 0);
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001364 /* ensure we don't get signed overflow in sz calculation */
1365 if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00001366 PyErr_SetString(PyExc_OverflowError,
1367 "long is too large to format");
1368 return NULL;
1369 }
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001370 sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;
1371 assert(sz >= 0);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001372 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001373 if (str == NULL)
1374 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001375 p = PyString_AS_STRING(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001376 *p = '\0';
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001377 if (addL)
1378 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001379 if (a->ob_size < 0)
1380 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001381
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001382 if (a->ob_size == 0) {
1383 *--p = '0';
1384 }
1385 else if ((base & (base - 1)) == 0) {
1386 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001387 twodigits accum = 0;
1388 int accumbits = 0; /* # of bits in accum */
1389 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001390 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001391 while ((i >>= 1) > 1)
1392 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001393
1394 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001395 accum |= (twodigits)a->ob_digit[i] << accumbits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001396 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001397 assert(accumbits >= basebits);
1398 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001399 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001400 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001401 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001402 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001403 accumbits -= basebits;
1404 accum >>= basebits;
1405 } while (i < size_a-1 ? accumbits >= basebits :
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001406 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001407 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001408 }
1409 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001410 /* Not 0, and base not a power of 2. Divide repeatedly by
1411 base, but for speed use the highest power of base that
1412 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001413 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001414 digit *pin = a->ob_digit;
1415 PyLongObject *scratch;
1416 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001417 digit powbase = base; /* powbase == base ** power */
1418 int power = 1;
1419 for (;;) {
Mark Dickinsonb6464872009-02-25 20:29:50 +00001420 twodigits newpow = powbase * (twodigits)base;
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001421 if (newpow >> PyLong_SHIFT)
1422 /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001423 break;
1424 powbase = (digit)newpow;
1425 ++power;
1426 }
Tim Peters212e6142001-07-14 12:23:19 +00001427
1428 /* Get a scratch area for repeated division. */
1429 scratch = _PyLong_New(size);
1430 if (scratch == NULL) {
1431 Py_DECREF(str);
1432 return NULL;
1433 }
1434
1435 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001436 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001437 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001438 digit rem = inplace_divrem1(scratch->ob_digit,
1439 pin, size, powbase);
1440 pin = scratch->ob_digit; /* no need to use a again */
1441 if (pin[size - 1] == 0)
1442 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001443 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001444 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001445 Py_DECREF(str);
1446 return NULL;
1447 })
Tim Peters212e6142001-07-14 12:23:19 +00001448
1449 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001450 assert(ntostore > 0);
1451 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001452 digit nextrem = (digit)(rem / base);
1453 char c = (char)(rem - nextrem * base);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001454 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001455 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001456 *--p = c;
1457 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001458 --ntostore;
1459 /* Termination is a bit delicate: must not
1460 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001461 remaining quotient and rem are both 0. */
1462 } while (ntostore && (size || rem));
1463 } while (size != 0);
1464 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001465 }
1466
Eric Smith5e527eb2008-02-10 01:36:53 +00001467 if (base == 2) {
1468 *--p = 'b';
1469 *--p = '0';
1470 }
1471 else if (base == 8) {
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001472 if (newstyle) {
Eric Smith5e527eb2008-02-10 01:36:53 +00001473 *--p = 'o';
Guido van Rossum2c475421992-08-14 15:13:07 +00001474 *--p = '0';
Eric Smith5e527eb2008-02-10 01:36:53 +00001475 }
1476 else
1477 if (size_a != 0)
1478 *--p = '0';
Guido van Rossum2c475421992-08-14 15:13:07 +00001479 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001480 else if (base == 16) {
1481 *--p = 'x';
1482 *--p = '0';
1483 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001484 else if (base != 10) {
1485 *--p = '#';
1486 *--p = '0' + base%10;
1487 if (base > 10)
1488 *--p = '0' + base/10;
1489 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001490 if (sign)
1491 *--p = sign;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001492 if (p != PyString_AS_STRING(str)) {
1493 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001494 assert(p > q);
1495 do {
1496 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001497 q--;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001498 _PyString_Resize((PyObject **)&str,
1499 (Py_ssize_t) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001500 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001501 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001502}
1503
Tim Petersda53afa2006-05-25 17:34:03 +00001504/* Table of digit values for 8-bit string -> integer conversion.
1505 * '0' maps to 0, ..., '9' maps to 9.
1506 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1507 * All other indices map to 37.
1508 * Note that when converting a base B string, a char c is a legitimate
1509 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1510 */
1511int _PyLong_DigitValue[256] = {
Tim Peters696cf432006-05-24 21:10:40 +00001512 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1513 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1514 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1515 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1516 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1517 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1518 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1519 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1520 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1521 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1522 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1523 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1524 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1525 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1526 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1527 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Tim Peters696cf432006-05-24 21:10:40 +00001528};
1529
1530/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001531 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1532 * non-digit (which may be *str!). A normalized long is returned.
1533 * The point to this routine is that it takes time linear in the number of
1534 * string characters.
1535 */
1536static PyLongObject *
1537long_from_binary_base(char **str, int base)
1538{
1539 char *p = *str;
1540 char *start = p;
1541 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001542 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001543 PyLongObject *z;
1544 twodigits accum;
1545 int bits_in_accum;
1546 digit *pdigit;
1547
1548 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1549 n = base;
1550 for (bits_per_char = -1; n; ++bits_per_char)
1551 n >>= 1;
1552 /* n <- total # of bits needed, while setting p to end-of-string */
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001553 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001554 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001555 *str = p;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001556 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1557 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001558 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001559 PyErr_SetString(PyExc_ValueError,
1560 "long string too large to convert");
1561 return NULL;
1562 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001563 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001564 z = _PyLong_New(n);
1565 if (z == NULL)
1566 return NULL;
1567 /* Read string from right, and fill in long from left; i.e.,
1568 * from least to most significant in both.
1569 */
1570 accum = 0;
1571 bits_in_accum = 0;
1572 pdigit = z->ob_digit;
1573 while (--p >= start) {
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001574 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001575 assert(k >= 0 && k < base);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001576 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00001577 bits_in_accum += bits_per_char;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001578 if (bits_in_accum >= PyLong_SHIFT) {
1579 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001580 assert(pdigit - z->ob_digit <= n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001581 accum >>= PyLong_SHIFT;
1582 bits_in_accum -= PyLong_SHIFT;
1583 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001584 }
1585 }
1586 if (bits_in_accum) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001587 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001588 *pdigit++ = (digit)accum;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001589 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001590 }
1591 while (pdigit - z->ob_digit < n)
1592 *pdigit++ = 0;
1593 return long_normalize(z);
1594}
1595
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001596PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001597PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001598{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001599 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001600 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001601 PyLongObject *z;
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001602 PyObject *strobj, *strrepr;
1603 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001604
Guido van Rossum472c04f1996-12-05 21:57:21 +00001605 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001606 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001607 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001608 return NULL;
1609 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001610 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001611 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001612 if (*str == '+')
1613 ++str;
1614 else if (*str == '-') {
1615 ++str;
1616 sign = -1;
1617 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001618 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001619 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001620 if (base == 0) {
Eric Smith9ff19b52008-03-17 17:32:20 +00001621 /* No base given. Deduce the base from the contents
1622 of the string */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001623 if (str[0] != '0')
1624 base = 10;
1625 else if (str[1] == 'x' || str[1] == 'X')
1626 base = 16;
Eric Smith9ff19b52008-03-17 17:32:20 +00001627 else if (str[1] == 'o' || str[1] == 'O')
1628 base = 8;
1629 else if (str[1] == 'b' || str[1] == 'B')
1630 base = 2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001631 else
Eric Smith9ff19b52008-03-17 17:32:20 +00001632 /* "old" (C-style) octal literal, still valid in
1633 2.x, although illegal in 3.x */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001634 base = 8;
1635 }
Eric Smith9ff19b52008-03-17 17:32:20 +00001636 /* Whether or not we were deducing the base, skip leading chars
1637 as needed */
1638 if (str[0] == '0' &&
1639 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1640 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1641 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001642 str += 2;
Tim Peters696cf432006-05-24 21:10:40 +00001643
Guido van Rossume6762971998-06-22 03:54:46 +00001644 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001645 if ((base & (base - 1)) == 0)
1646 z = long_from_binary_base(&str, base);
1647 else {
Tim Peters696cf432006-05-24 21:10:40 +00001648/***
1649Binary bases can be converted in time linear in the number of digits, because
1650Python's representation base is binary. Other bases (including decimal!) use
1651the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001652
Tim Peters696cf432006-05-24 21:10:40 +00001653First some math: the largest integer that can be expressed in N base-B digits
1654is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1655case number of Python digits needed to hold it is the smallest integer n s.t.
1656
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001657 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1658 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1659 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001660
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001661The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute
Tim Peters696cf432006-05-24 21:10:40 +00001662this quickly. A Python long with that much space is reserved near the start,
1663and the result is computed into it.
1664
1665The input string is actually treated as being in base base**i (i.e., i digits
1666are processed at a time), where two more static arrays hold:
1667
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001668 convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE
Tim Peters696cf432006-05-24 21:10:40 +00001669 convmultmax_base[base] = base ** convwidth_base[base]
1670
1671The first of these is the largest i such that i consecutive input digits
1672must fit in a single Python digit. The second is effectively the input
1673base we're really using.
1674
1675Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1676convmultmax_base[base], the result is "simply"
1677
1678 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1679
1680where B = convmultmax_base[base].
Tim Peters9faa3ed2006-05-30 15:53:34 +00001681
1682Error analysis: as above, the number of Python digits `n` needed is worst-
1683case
1684
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001685 n >= N * log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001686
1687where `N` is the number of input digits in base `B`. This is computed via
1688
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001689 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001690
1691below. Two numeric concerns are how much space this can waste, and whether
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001692the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15,
Tim Peters9faa3ed2006-05-30 15:53:34 +00001693which is the default (and it's unlikely anyone changes that).
1694
1695Waste isn't a problem: provided the first input digit isn't 0, the difference
1696between the worst-case input with N digits and the smallest input with N
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001697digits is about a factor of B, but B is small compared to PyLong_BASE so at most
Tim Peters9faa3ed2006-05-30 15:53:34 +00001698one allocated Python digit can remain unused on that count. If
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001699N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001700and adding 1 returns a result 1 larger than necessary. However, that can't
1701happen: whenever B is a power of 2, long_from_binary_base() is called
1702instead, and it's impossible for B**i to be an integer power of 2**15 when
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001703B 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 +00001704an exact integer when B is not a power of 2, since B**i has a prime factor
1705other than 2 in that case, but (2**15)**j's only prime factor is 2).
1706
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001707The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001708is a little bit larger than an exact integer, but due to roundoff errors (in
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001709computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001710yields a numeric result a little less than that integer. Unfortunately, "how
1711close can a transcendental function get to an integer over some range?"
1712questions are generally theoretically intractable. Computer analysis via
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001713continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued
Tim Peters9faa3ed2006-05-30 15:53:34 +00001714fractions, giving a sequence i/j of "the best" rational approximations. Then
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001715j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001716we can get very close to being in trouble, but very rarely. For example,
171776573 is a denominator in one of the continued-fraction approximations to
1718log(10)/log(2**15), and indeed:
1719
1720 >>> log(10)/log(2**15)*76573
1721 16958.000000654003
1722
1723is very close to an integer. If we were working with IEEE single-precision,
1724rounding errors could kill us. Finding worst cases in IEEE double-precision
1725requires better-than-double-precision log() functions, and Tim didn't bother.
1726Instead the code checks to see whether the allocated space is enough as each
1727new Python digit is added, and copies the whole thing to a larger long if not.
1728This should happen extremely rarely, and in fact I don't have a test case
1729that triggers it(!). Instead the code was tested by artificially allocating
1730just 1 digit at the start, so that the copying code was exercised for every
1731digit beyond the first.
Tim Peters696cf432006-05-24 21:10:40 +00001732***/
1733 register twodigits c; /* current input character */
1734 Py_ssize_t size_z;
1735 int i;
1736 int convwidth;
1737 twodigits convmultmax, convmult;
1738 digit *pz, *pzstop;
1739 char* scan;
1740
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001741 static double log_base_PyLong_BASE[37] = {0.0e0,};
Tim Peters696cf432006-05-24 21:10:40 +00001742 static int convwidth_base[37] = {0,};
1743 static twodigits convmultmax_base[37] = {0,};
1744
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001745 if (log_base_PyLong_BASE[base] == 0.0) {
Tim Peters696cf432006-05-24 21:10:40 +00001746 twodigits convmax = base;
1747 int i = 1;
1748
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001749 log_base_PyLong_BASE[base] = log((double)base) /
1750 log((double)PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001751 for (;;) {
1752 twodigits next = convmax * base;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001753 if (next > PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001754 break;
1755 convmax = next;
1756 ++i;
1757 }
1758 convmultmax_base[base] = convmax;
1759 assert(i > 0);
1760 convwidth_base[base] = i;
1761 }
1762
1763 /* Find length of the string of numeric characters. */
1764 scan = str;
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001765 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Tim Peters696cf432006-05-24 21:10:40 +00001766 ++scan;
1767
1768 /* Create a long object that can contain the largest possible
1769 * integer with this base and length. Note that there's no
1770 * need to initialize z->ob_digit -- no slot is read up before
1771 * being stored into.
1772 */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001773 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001774 /* Uncomment next line to test exceedingly rare copy code */
1775 /* size_z = 1; */
Tim Peters696cf432006-05-24 21:10:40 +00001776 assert(size_z > 0);
1777 z = _PyLong_New(size_z);
1778 if (z == NULL)
1779 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00001780 Py_SIZE(z) = 0;
Tim Peters696cf432006-05-24 21:10:40 +00001781
1782 /* `convwidth` consecutive input digits are treated as a single
1783 * digit in base `convmultmax`.
1784 */
1785 convwidth = convwidth_base[base];
1786 convmultmax = convmultmax_base[base];
1787
1788 /* Work ;-) */
1789 while (str < scan) {
1790 /* grab up to convwidth digits from the input string */
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001791 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Tim Peters696cf432006-05-24 21:10:40 +00001792 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1793 c = (twodigits)(c * base +
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001794 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001795 assert(c < PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001796 }
1797
1798 convmult = convmultmax;
1799 /* Calculate the shift only if we couldn't get
1800 * convwidth digits.
1801 */
1802 if (i != convwidth) {
1803 convmult = base;
1804 for ( ; i > 1; --i)
1805 convmult *= base;
1806 }
1807
1808 /* Multiply z by convmult, and add c. */
1809 pz = z->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +00001810 pzstop = pz + Py_SIZE(z);
Tim Peters696cf432006-05-24 21:10:40 +00001811 for (; pz < pzstop; ++pz) {
1812 c += (twodigits)*pz * convmult;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001813 *pz = (digit)(c & PyLong_MASK);
1814 c >>= PyLong_SHIFT;
Tim Peters696cf432006-05-24 21:10:40 +00001815 }
1816 /* carry off the current end? */
1817 if (c) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001818 assert(c < PyLong_BASE);
Christian Heimese93237d2007-12-19 02:37:44 +00001819 if (Py_SIZE(z) < size_z) {
Tim Peters9faa3ed2006-05-30 15:53:34 +00001820 *pz = (digit)c;
Christian Heimese93237d2007-12-19 02:37:44 +00001821 ++Py_SIZE(z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001822 }
1823 else {
1824 PyLongObject *tmp;
1825 /* Extremely rare. Get more space. */
Christian Heimese93237d2007-12-19 02:37:44 +00001826 assert(Py_SIZE(z) == size_z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001827 tmp = _PyLong_New(size_z + 1);
1828 if (tmp == NULL) {
1829 Py_DECREF(z);
1830 return NULL;
1831 }
1832 memcpy(tmp->ob_digit,
1833 z->ob_digit,
1834 sizeof(digit) * size_z);
1835 Py_DECREF(z);
1836 z = tmp;
1837 z->ob_digit[size_z] = (digit)c;
1838 ++size_z;
1839 }
Tim Peters696cf432006-05-24 21:10:40 +00001840 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001841 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001842 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001843 if (z == NULL)
1844 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001845 if (str == start)
1846 goto onError;
Tim Peters696cf432006-05-24 21:10:40 +00001847 if (sign < 0)
Christian Heimese93237d2007-12-19 02:37:44 +00001848 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001849 if (*str == 'L' || *str == 'l')
1850 str++;
1851 while (*str && isspace(Py_CHARMASK(*str)))
1852 str++;
1853 if (*str != '\0')
1854 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001855 if (pend)
1856 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001857 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001858
1859 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001860 Py_XDECREF(z);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001861 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001862 strobj = PyString_FromStringAndSize(orig_str, slen);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001863 if (strobj == NULL)
1864 return NULL;
1865 strrepr = PyObject_Repr(strobj);
1866 Py_DECREF(strobj);
1867 if (strrepr == NULL)
1868 return NULL;
1869 PyErr_Format(PyExc_ValueError,
1870 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001871 base, PyString_AS_STRING(strrepr));
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001872 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001873 return NULL;
1874}
1875
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001876#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001877PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001878PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001879{
Walter Dörwald07e14762002-11-06 16:15:14 +00001880 PyObject *result;
Anthony Baxter377be112006-04-11 06:54:30 +00001881 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001882
Walter Dörwald07e14762002-11-06 16:15:14 +00001883 if (buffer == NULL)
1884 return NULL;
1885
1886 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1887 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001888 return NULL;
1889 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001890 result = PyLong_FromString(buffer, NULL, base);
1891 PyMem_FREE(buffer);
1892 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001893}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001894#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001895
Tim Peters9f688bf2000-07-07 15:53:28 +00001896/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001897static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001898 (PyLongObject *, PyLongObject *, PyLongObject **);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001899static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001900
1901/* Long division with remainder, top-level routine */
1902
Guido van Rossume32e0141992-01-19 16:31:05 +00001903static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001904long_divrem(PyLongObject *a, PyLongObject *b,
1905 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001906{
Christian Heimese93237d2007-12-19 02:37:44 +00001907 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001908 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001909
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001910 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001911 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001912 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001913 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001914 }
1915 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001916 (size_a == size_b &&
1917 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001918 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001919 *pdiv = _PyLong_New(0);
Georg Brandlc02e1312007-04-11 17:16:24 +00001920 if (*pdiv == NULL)
1921 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001922 Py_INCREF(a);
1923 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001924 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001925 }
1926 if (size_b == 1) {
1927 digit rem = 0;
1928 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001929 if (z == NULL)
1930 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001931 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Georg Brandlc02e1312007-04-11 17:16:24 +00001932 if (*prem == NULL) {
1933 Py_DECREF(z);
1934 return -1;
1935 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001936 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001937 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001938 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001939 if (z == NULL)
1940 return -1;
1941 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001942 /* Set the signs.
1943 The quotient z has the sign of a*b;
1944 the remainder r has the sign of a,
1945 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001946 if ((a->ob_size < 0) != (b->ob_size < 0))
1947 z->ob_size = -(z->ob_size);
1948 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1949 (*prem)->ob_size = -((*prem)->ob_size);
1950 *pdiv = z;
1951 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001952}
1953
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001954/* Unsigned long division with remainder -- the algorithm. The arguments v1
1955 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001956
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001957static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001958x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001959{
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001960 PyLongObject *v, *w, *a;
1961 Py_ssize_t i, k, size_v, size_w;
1962 int d;
1963 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
1964 twodigits vv;
1965 sdigit zhi;
1966 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001967
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001968 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
1969 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
1970 handle the special case when the initial estimate q for a quotient
1971 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
1972 that won't overflow a digit. */
1973
1974 /* allocate space; w will also be used to hold the final remainder */
1975 size_v = ABS(Py_SIZE(v1));
1976 size_w = ABS(Py_SIZE(w1));
1977 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
1978 v = _PyLong_New(size_v+1);
1979 if (v == NULL) {
1980 *prem = NULL;
1981 return NULL;
1982 }
1983 w = _PyLong_New(size_w);
1984 if (w == NULL) {
1985 Py_DECREF(v);
1986 *prem = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001987 return NULL;
1988 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001989
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001990 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
1991 shift v1 left by the same amount. Results go into w and v. */
1992 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
1993 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
1994 assert(carry == 0);
1995 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
1996 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
1997 v->ob_digit[size_v] = carry;
1998 size_v++;
1999 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002000
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002001 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2002 at most (and usually exactly) k = size_v - size_w digits. */
Neal Norwitzc6a989a2006-05-10 06:57:58 +00002003 k = size_v - size_w;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002004 assert(k >= 0);
2005 a = _PyLong_New(k);
2006 if (a == NULL) {
2007 Py_DECREF(w);
2008 Py_DECREF(v);
2009 *prem = NULL;
2010 return NULL;
2011 }
2012 v0 = v->ob_digit;
2013 w0 = w->ob_digit;
2014 wm1 = w0[size_w-1];
2015 wm2 = w0[size_w-2];
2016 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2017 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2018 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002019
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002020 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002021 Py_DECREF(a);
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002022 Py_DECREF(w);
2023 Py_DECREF(v);
2024 *prem = NULL;
2025 return NULL;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002026 })
Tim Peters5af4e6c2002-08-12 02:31:19 +00002027
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002028 /* estimate quotient digit q; may overestimate by 1 (rare) */
2029 vtop = vk[size_w];
2030 assert(vtop <= wm1);
2031 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2032 q = (digit)(vv / wm1);
2033 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2034 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2035 | vk[size_w-2])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002036 --q;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002037 r += wm1;
2038 if (r >= PyLong_BASE)
2039 break;
2040 }
2041 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002042
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002043 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2044 zhi = 0;
2045 for (i = 0; i < size_w; ++i) {
2046 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2047 -PyLong_BASE * q <= z < PyLong_BASE */
2048 z = (sdigit)vk[i] + zhi -
2049 (stwodigits)q * (stwodigits)w0[i];
2050 vk[i] = (digit)z & PyLong_MASK;
2051 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
2052 z, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002053 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002054
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002055 /* add w back if q was too large (this branch taken rarely) */
2056 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2057 if ((sdigit)vtop + zhi < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002058 carry = 0;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002059 for (i = 0; i < size_w; ++i) {
2060 carry += vk[i] + w0[i];
2061 vk[i] = carry & PyLong_MASK;
2062 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002063 }
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002064 --q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002065 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002066
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002067 /* store quotient digit */
2068 assert(q < PyLong_BASE);
2069 *--ak = q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002070 }
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002071
2072 /* unshift remainder; we reuse w to store the result */
2073 carry = v_rshift(w0, v0, size_w, d);
2074 assert(carry==0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002075 Py_DECREF(v);
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002076
2077 *prem = long_normalize(w);
2078 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079}
2080
Mark Dickinsond3e32322010-01-02 14:45:40 +00002081/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2082 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2083 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2084 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2085 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2086 -1.0. */
2087
2088/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2089#if DBL_MANT_DIG == 53
2090#define EXP2_DBL_MANT_DIG 9007199254740992.0
2091#else
2092#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2093#endif
2094
2095double
2096_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2097{
2098 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2099 /* See below for why x_digits is always large enough. */
2100 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2101 double dx;
2102 /* Correction term for round-half-to-even rounding. For a digit x,
2103 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2104 multiple of 4, rounding ties to a multiple of 8. */
2105 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
2106
2107 a_size = ABS(Py_SIZE(a));
2108 if (a_size == 0) {
2109 /* Special case for 0: significand 0.0, exponent 0. */
2110 *e = 0;
2111 return 0.0;
2112 }
2113 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2114 /* The following is an overflow-free version of the check
2115 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2116 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2117 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2118 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
2119 goto overflow;
2120 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
2121
2122 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2123 (shifting left if a_bits <= DBL_MANT_DIG + 2).
2124
2125 Number of digits needed for result: write // for floor division.
2126 Then if shifting left, we end up using
2127
2128 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
2129
2130 digits. If shifting right, we use
2131
2132 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
2133
2134 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2135 the inequalities
2136
2137 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2138 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2139 1 + (m - n - 1) // PyLong_SHIFT,
2140
2141 valid for any integers m and n, we find that x_size satisfies
2142
2143 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
2144
2145 in both cases.
2146 */
2147 if (a_bits <= DBL_MANT_DIG + 2) {
2148 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2149 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2150 x_size = 0;
2151 while (x_size < shift_digits)
2152 x_digits[x_size++] = 0;
2153 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2154 shift_bits);
2155 x_size += a_size;
2156 x_digits[x_size++] = rem;
2157 }
2158 else {
2159 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2160 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2161 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2162 a_size - shift_digits, shift_bits);
2163 x_size = a_size - shift_digits;
2164 /* For correct rounding below, we need the least significant
2165 bit of x to be 'sticky' for this shift: if any of the bits
2166 shifted out was nonzero, we set the least significant bit
2167 of x. */
2168 if (rem)
2169 x_digits[0] |= 1;
2170 else
2171 while (shift_digits > 0)
2172 if (a->ob_digit[--shift_digits]) {
2173 x_digits[0] |= 1;
2174 break;
2175 }
2176 }
2177 assert(1 <= x_size && x_size <= sizeof(x_digits)/sizeof(digit));
2178
2179 /* Round, and convert to double. */
2180 x_digits[0] += half_even_correction[x_digits[0] & 7];
2181 dx = x_digits[--x_size];
2182 while (x_size > 0)
2183 dx = dx * PyLong_BASE + x_digits[--x_size];
2184
2185 /* Rescale; make correction if result is 1.0. */
2186 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2187 if (dx == 1.0) {
2188 if (a_bits == PY_SSIZE_T_MAX)
2189 goto overflow;
2190 dx = 0.5;
2191 a_bits += 1;
2192 }
2193
2194 *e = a_bits;
2195 return Py_SIZE(a) < 0 ? -dx : dx;
2196
2197 overflow:
2198 /* exponent > PY_SSIZE_T_MAX */
2199 PyErr_SetString(PyExc_OverflowError,
2200 "huge integer: number of bits overflows a Py_ssize_t");
2201 *e = 0;
2202 return -1.0;
2203}
2204
2205/* Get a C double from a long int object. Rounds to the nearest double,
2206 using the round-half-to-even rule in the case of a tie. */
2207
2208double
2209PyLong_AsDouble(PyObject *v)
2210{
2211 Py_ssize_t exponent;
2212 double x;
2213
2214 if (v == NULL || !PyLong_Check(v)) {
2215 PyErr_BadInternalCall();
2216 return -1.0;
2217 }
2218 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2219 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2220 PyErr_SetString(PyExc_OverflowError,
2221 "long int too large to convert to float");
2222 return -1.0;
2223 }
2224 return ldexp(x, exponent);
2225}
2226
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002227/* Methods */
2228
2229static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002230long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002231{
Christian Heimese93237d2007-12-19 02:37:44 +00002232 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002233}
2234
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002235static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002236long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002237{
Eric Smith5e527eb2008-02-10 01:36:53 +00002238 return _PyLong_Format(v, 10, 1, 0);
Fred Drake121ee271999-12-23 15:41:28 +00002239}
2240
2241static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002242long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00002243{
Eric Smith5e527eb2008-02-10 01:36:53 +00002244 return _PyLong_Format(v, 10, 0, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002245}
2246
2247static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002248long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002249{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002250 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002251
Christian Heimese93237d2007-12-19 02:37:44 +00002252 if (Py_SIZE(a) != Py_SIZE(b)) {
2253 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002254 sign = 0;
2255 else
Christian Heimese93237d2007-12-19 02:37:44 +00002256 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002257 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002258 else {
Christian Heimese93237d2007-12-19 02:37:44 +00002259 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002260 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2261 ;
2262 if (i < 0)
2263 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002264 else {
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00002265 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimese93237d2007-12-19 02:37:44 +00002266 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002267 sign = -sign;
2268 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002269 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002270 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002271}
2272
Guido van Rossum9bfef441993-03-29 10:43:31 +00002273static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002274long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002275{
Mark Dickinson6ffa4a22009-01-26 21:36:30 +00002276 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002277 Py_ssize_t i;
2278 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002279
2280 /* This is designed so that Python ints and longs with the
2281 same value hash to the same value, otherwise comparisons
2282 of mapping keys will turn out weird */
2283 i = v->ob_size;
2284 sign = 1;
2285 x = 0;
2286 if (i < 0) {
2287 sign = -1;
2288 i = -(i);
2289 }
Mark Dickinsona0eae032009-01-26 21:40:08 +00002290 /* The following loop produces a C unsigned long x such that x is
2291 congruent to the absolute value of v modulo ULONG_MAX. The
2292 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002293 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002294 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00002295 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002296 x += v->ob_digit[i];
Mark Dickinson6ffa4a22009-01-26 21:36:30 +00002297 /* If the addition above overflowed we compensate by
2298 incrementing. This preserves the value modulo
2299 ULONG_MAX. */
2300 if (x < v->ob_digit[i])
Facundo Batistad544df72007-09-19 15:10:06 +00002301 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002302 }
2303 x = x * sign;
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00002304 if (x == (unsigned long)-1)
2305 x = (unsigned long)-2;
2306 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002307}
2308
2309
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002310/* Add the absolute values of two long integers. */
2311
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002312static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002313x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002314{
Christian Heimese93237d2007-12-19 02:37:44 +00002315 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002316 PyLongObject *z;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00002317 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002318 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002319
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002320 /* Ensure a is the larger of the two: */
2321 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002322 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002323 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002324 size_a = size_b;
2325 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002326 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002327 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002328 if (z == NULL)
2329 return NULL;
2330 for (i = 0; i < size_b; ++i) {
2331 carry += a->ob_digit[i] + b->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002332 z->ob_digit[i] = carry & PyLong_MASK;
2333 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002334 }
2335 for (; i < size_a; ++i) {
2336 carry += a->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002337 z->ob_digit[i] = carry & PyLong_MASK;
2338 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002339 }
2340 z->ob_digit[i] = carry;
2341 return long_normalize(z);
2342}
2343
2344/* Subtract the absolute values of two integers. */
2345
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002346static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002347x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002348{
Christian Heimese93237d2007-12-19 02:37:44 +00002349 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002350 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002351 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002352 int sign = 1;
2353 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002354
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002355 /* Ensure a is the larger of the two: */
2356 if (size_a < size_b) {
2357 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002358 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002359 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002360 size_a = size_b;
2361 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002362 }
2363 else if (size_a == size_b) {
2364 /* Find highest digit where a and b differ: */
2365 i = size_a;
2366 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2367 ;
2368 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002369 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002370 if (a->ob_digit[i] < b->ob_digit[i]) {
2371 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002372 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002373 }
2374 size_a = size_b = i+1;
2375 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002376 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002377 if (z == NULL)
2378 return NULL;
2379 for (i = 0; i < size_b; ++i) {
2380 /* The following assumes unsigned arithmetic
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002381 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002382 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002383 z->ob_digit[i] = borrow & PyLong_MASK;
2384 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002385 borrow &= 1; /* Keep only one sign bit */
2386 }
2387 for (; i < size_a; ++i) {
2388 borrow = a->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002389 z->ob_digit[i] = borrow & PyLong_MASK;
2390 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002391 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002392 }
2393 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002394 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002395 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002396 return long_normalize(z);
2397}
2398
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002399static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002400long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002401{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002402 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002403
Neil Schemenauerba872e22001-01-04 01:46:03 +00002404 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2405
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002406 if (a->ob_size < 0) {
2407 if (b->ob_size < 0) {
2408 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002409 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002410 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002411 }
2412 else
2413 z = x_sub(b, a);
2414 }
2415 else {
2416 if (b->ob_size < 0)
2417 z = x_sub(a, b);
2418 else
2419 z = x_add(a, b);
2420 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002421 Py_DECREF(a);
2422 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002423 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002424}
2425
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002426static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002427long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002428{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002429 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002430
Neil Schemenauerba872e22001-01-04 01:46:03 +00002431 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2432
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002433 if (a->ob_size < 0) {
2434 if (b->ob_size < 0)
2435 z = x_sub(a, b);
2436 else
2437 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002438 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002439 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002440 }
2441 else {
2442 if (b->ob_size < 0)
2443 z = x_add(a, b);
2444 else
2445 z = x_sub(a, b);
2446 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002447 Py_DECREF(a);
2448 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002449 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002450}
2451
Tim Peters5af4e6c2002-08-12 02:31:19 +00002452/* Grade school multiplication, ignoring the signs.
2453 * Returns the absolute value of the product, or NULL if error.
2454 */
2455static PyLongObject *
2456x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002457{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002458 PyLongObject *z;
Christian Heimese93237d2007-12-19 02:37:44 +00002459 Py_ssize_t size_a = ABS(Py_SIZE(a));
2460 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002461 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002462
Tim Peters5af4e6c2002-08-12 02:31:19 +00002463 z = _PyLong_New(size_a + size_b);
2464 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002465 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002466
Christian Heimese93237d2007-12-19 02:37:44 +00002467 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002468 if (a == b) {
2469 /* Efficient squaring per HAC, Algorithm 14.16:
2470 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2471 * Gives slightly less than a 2x speedup when a == b,
2472 * via exploiting that each entry in the multiplication
2473 * pyramid appears twice (except for the size_a squares).
2474 */
2475 for (i = 0; i < size_a; ++i) {
2476 twodigits carry;
2477 twodigits f = a->ob_digit[i];
2478 digit *pz = z->ob_digit + (i << 1);
2479 digit *pa = a->ob_digit + i + 1;
2480 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002481
Tim Peters0973b992004-08-29 22:16:50 +00002482 SIGCHECK({
2483 Py_DECREF(z);
2484 return NULL;
2485 })
2486
2487 carry = *pz + f * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002488 *pz++ = (digit)(carry & PyLong_MASK);
2489 carry >>= PyLong_SHIFT;
2490 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002491
2492 /* Now f is added in twice in each column of the
2493 * pyramid it appears. Same as adding f<<1 once.
2494 */
2495 f <<= 1;
2496 while (pa < paend) {
2497 carry += *pz + *pa++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002498 *pz++ = (digit)(carry & PyLong_MASK);
2499 carry >>= PyLong_SHIFT;
2500 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002501 }
2502 if (carry) {
2503 carry += *pz;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002504 *pz++ = (digit)(carry & PyLong_MASK);
2505 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002506 }
2507 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002508 *pz += (digit)(carry & PyLong_MASK);
2509 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002510 }
Tim Peters0973b992004-08-29 22:16:50 +00002511 }
2512 else { /* a is not the same as b -- gradeschool long mult */
2513 for (i = 0; i < size_a; ++i) {
2514 twodigits carry = 0;
2515 twodigits f = a->ob_digit[i];
2516 digit *pz = z->ob_digit + i;
2517 digit *pb = b->ob_digit;
2518 digit *pbend = b->ob_digit + size_b;
2519
2520 SIGCHECK({
2521 Py_DECREF(z);
2522 return NULL;
2523 })
2524
2525 while (pb < pbend) {
2526 carry += *pz + *pb++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002527 *pz++ = (digit)(carry & PyLong_MASK);
2528 carry >>= PyLong_SHIFT;
2529 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002530 }
2531 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002532 *pz += (digit)(carry & PyLong_MASK);
2533 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002534 }
2535 }
Tim Peters44121a62002-08-12 06:17:58 +00002536 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002537}
2538
2539/* A helper for Karatsuba multiplication (k_mul).
2540 Takes a long "n" and an integer "size" representing the place to
2541 split, and sets low and high such that abs(n) == (high << size) + low,
2542 viewing the shift as being by digits. The sign bit is ignored, and
2543 the return values are >= 0.
2544 Returns 0 on success, -1 on failure.
2545*/
2546static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002547kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002548{
2549 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002550 Py_ssize_t size_lo, size_hi;
Christian Heimese93237d2007-12-19 02:37:44 +00002551 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002552
2553 size_lo = MIN(size_n, size);
2554 size_hi = size_n - size_lo;
2555
2556 if ((hi = _PyLong_New(size_hi)) == NULL)
2557 return -1;
2558 if ((lo = _PyLong_New(size_lo)) == NULL) {
2559 Py_DECREF(hi);
2560 return -1;
2561 }
2562
2563 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2564 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2565
2566 *high = long_normalize(hi);
2567 *low = long_normalize(lo);
2568 return 0;
2569}
2570
Tim Peters60004642002-08-12 22:01:34 +00002571static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2572
Tim Peters5af4e6c2002-08-12 02:31:19 +00002573/* Karatsuba multiplication. Ignores the input signs, and returns the
2574 * absolute value of the product (or NULL if error).
2575 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2576 */
2577static PyLongObject *
2578k_mul(PyLongObject *a, PyLongObject *b)
2579{
Christian Heimese93237d2007-12-19 02:37:44 +00002580 Py_ssize_t asize = ABS(Py_SIZE(a));
2581 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002582 PyLongObject *ah = NULL;
2583 PyLongObject *al = NULL;
2584 PyLongObject *bh = NULL;
2585 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002586 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002587 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002588 Py_ssize_t shift; /* the number of digits we split off */
2589 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002590
Tim Peters5af4e6c2002-08-12 02:31:19 +00002591 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2592 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2593 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002594 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002595 * By picking X to be a power of 2, "*X" is just shifting, and it's
2596 * been reduced to 3 multiplies on numbers half the size.
2597 */
2598
Tim Petersfc07e562002-08-12 02:54:10 +00002599 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002600 * is largest.
2601 */
Tim Peters738eda72002-08-12 15:08:20 +00002602 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002603 t1 = a;
2604 a = b;
2605 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002606
2607 i = asize;
2608 asize = bsize;
2609 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002610 }
2611
2612 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002613 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2614 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002615 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002616 return _PyLong_New(0);
2617 else
2618 return x_mul(a, b);
2619 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002620
Tim Peters60004642002-08-12 22:01:34 +00002621 /* If a is small compared to b, splitting on b gives a degenerate
2622 * case with ah==0, and Karatsuba may be (even much) less efficient
2623 * than "grade school" then. However, we can still win, by viewing
2624 * b as a string of "big digits", each of width a->ob_size. That
2625 * leads to a sequence of balanced calls to k_mul.
2626 */
2627 if (2 * asize <= bsize)
2628 return k_lopsided_mul(a, b);
2629
Tim Petersd6974a52002-08-13 20:37:51 +00002630 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002631 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002632 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002633 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002634
Tim Peters0973b992004-08-29 22:16:50 +00002635 if (a == b) {
2636 bh = ah;
2637 bl = al;
2638 Py_INCREF(bh);
2639 Py_INCREF(bl);
2640 }
2641 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002642
Tim Petersd64c1de2002-08-12 17:36:03 +00002643 /* The plan:
2644 * 1. Allocate result space (asize + bsize digits: that's always
2645 * enough).
2646 * 2. Compute ah*bh, and copy into result at 2*shift.
2647 * 3. Compute al*bl, and copy into result at 0. Note that this
2648 * can't overlap with #2.
2649 * 4. Subtract al*bl from the result, starting at shift. This may
2650 * underflow (borrow out of the high digit), but we don't care:
2651 * we're effectively doing unsigned arithmetic mod
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002652 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
Tim Petersd64c1de2002-08-12 17:36:03 +00002653 * borrows and carries out of the high digit can be ignored.
2654 * 5. Subtract ah*bh from the result, starting at shift.
2655 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2656 * at shift.
2657 */
2658
2659 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002660 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002661 if (ret == NULL) goto fail;
2662#ifdef Py_DEBUG
2663 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002664 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002665#endif
Tim Peters44121a62002-08-12 06:17:58 +00002666
Tim Petersd64c1de2002-08-12 17:36:03 +00002667 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002668 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002669 assert(Py_SIZE(t1) >= 0);
2670 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002671 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimese93237d2007-12-19 02:37:44 +00002672 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002673
2674 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimese93237d2007-12-19 02:37:44 +00002675 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002676 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002677 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002678 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002679
Tim Petersd64c1de2002-08-12 17:36:03 +00002680 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002681 if ((t2 = k_mul(al, bl)) == NULL) {
2682 Py_DECREF(t1);
2683 goto fail;
2684 }
Christian Heimese93237d2007-12-19 02:37:44 +00002685 assert(Py_SIZE(t2) >= 0);
2686 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2687 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002688
2689 /* Zero out remaining digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002690 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002691 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002692 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002693
Tim Petersd64c1de2002-08-12 17:36:03 +00002694 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2695 * because it's fresher in cache.
2696 */
Christian Heimese93237d2007-12-19 02:37:44 +00002697 i = Py_SIZE(ret) - shift; /* # digits after shift */
2698 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002699 Py_DECREF(t2);
2700
Christian Heimese93237d2007-12-19 02:37:44 +00002701 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002702 Py_DECREF(t1);
2703
Tim Petersd64c1de2002-08-12 17:36:03 +00002704 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002705 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2706 Py_DECREF(ah);
2707 Py_DECREF(al);
2708 ah = al = NULL;
2709
Tim Peters0973b992004-08-29 22:16:50 +00002710 if (a == b) {
2711 t2 = t1;
2712 Py_INCREF(t2);
2713 }
2714 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002715 Py_DECREF(t1);
2716 goto fail;
2717 }
2718 Py_DECREF(bh);
2719 Py_DECREF(bl);
2720 bh = bl = NULL;
2721
Tim Peters738eda72002-08-12 15:08:20 +00002722 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002723 Py_DECREF(t1);
2724 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002725 if (t3 == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002726 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002727
Tim Petersd6974a52002-08-13 20:37:51 +00002728 /* Add t3. It's not obvious why we can't run out of room here.
2729 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002730 */
Christian Heimese93237d2007-12-19 02:37:44 +00002731 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002732 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002733
Tim Peters5af4e6c2002-08-12 02:31:19 +00002734 return long_normalize(ret);
2735
2736 fail:
2737 Py_XDECREF(ret);
2738 Py_XDECREF(ah);
2739 Py_XDECREF(al);
2740 Py_XDECREF(bh);
2741 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002742 return NULL;
2743}
2744
Tim Petersd6974a52002-08-13 20:37:51 +00002745/* (*) Why adding t3 can't "run out of room" above.
2746
Tim Petersab86c2b2002-08-15 20:06:00 +00002747Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2748to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002749
Tim Petersab86c2b2002-08-15 20:06:00 +000027501. For any integer i, i = c(i/2) + f(i/2). In particular,
2751 bsize = c(bsize/2) + f(bsize/2).
27522. shift = f(bsize/2)
27533. asize <= bsize
27544. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2755 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002756
Tim Petersab86c2b2002-08-15 20:06:00 +00002757We allocated asize + bsize result digits, and add t3 into them at an offset
2758of shift. This leaves asize+bsize-shift allocated digit positions for t3
2759to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2760asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002761
Tim Petersab86c2b2002-08-15 20:06:00 +00002762bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2763at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002764
Tim Petersab86c2b2002-08-15 20:06:00 +00002765If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2766digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2767most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002768
Tim Petersab86c2b2002-08-15 20:06:00 +00002769The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002770
Tim Petersab86c2b2002-08-15 20:06:00 +00002771 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002772
Tim Petersab86c2b2002-08-15 20:06:00 +00002773and we have asize + c(bsize/2) available digit positions. We need to show
2774this is always enough. An instance of c(bsize/2) cancels out in both, so
2775the question reduces to whether asize digits is enough to hold
2776(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2777then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2778asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002779digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002780asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002781c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2782is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2783bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002784
Tim Peters48d52c02002-08-14 17:07:32 +00002785Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2786clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2787ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002788*/
2789
Tim Peters60004642002-08-12 22:01:34 +00002790/* b has at least twice the digits of a, and a is big enough that Karatsuba
2791 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2792 * of slices, each with a->ob_size digits, and multiply the slices by a,
2793 * one at a time. This gives k_mul balanced inputs to work with, and is
2794 * also cache-friendly (we compute one double-width slice of the result
2795 * at a time, then move on, never bactracking except for the helpful
2796 * single-width slice overlap between successive partial sums).
2797 */
2798static PyLongObject *
2799k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2800{
Christian Heimese93237d2007-12-19 02:37:44 +00002801 const Py_ssize_t asize = ABS(Py_SIZE(a));
2802 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002803 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002804 PyLongObject *ret;
2805 PyLongObject *bslice = NULL;
2806
2807 assert(asize > KARATSUBA_CUTOFF);
2808 assert(2 * asize <= bsize);
2809
2810 /* Allocate result space, and zero it out. */
2811 ret = _PyLong_New(asize + bsize);
2812 if (ret == NULL)
2813 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002814 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002815
2816 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002817 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002818 if (bslice == NULL)
2819 goto fail;
2820
2821 nbdone = 0;
2822 while (bsize > 0) {
2823 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002824 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002825
2826 /* Multiply the next slice of b by a. */
2827 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2828 nbtouse * sizeof(digit));
Christian Heimese93237d2007-12-19 02:37:44 +00002829 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002830 product = k_mul(a, bslice);
2831 if (product == NULL)
2832 goto fail;
2833
2834 /* Add into result. */
Christian Heimese93237d2007-12-19 02:37:44 +00002835 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2836 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002837 Py_DECREF(product);
2838
2839 bsize -= nbtouse;
2840 nbdone += nbtouse;
2841 }
2842
2843 Py_DECREF(bslice);
2844 return long_normalize(ret);
2845
2846 fail:
2847 Py_DECREF(ret);
2848 Py_XDECREF(bslice);
2849 return NULL;
2850}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002851
2852static PyObject *
2853long_mul(PyLongObject *v, PyLongObject *w)
2854{
2855 PyLongObject *a, *b, *z;
2856
2857 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002858 Py_INCREF(Py_NotImplemented);
2859 return Py_NotImplemented;
2860 }
2861
Tim Petersd64c1de2002-08-12 17:36:03 +00002862 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002863 /* Negate if exactly one of the inputs is negative. */
2864 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002865 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002866 Py_DECREF(a);
2867 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002868 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002869}
2870
Guido van Rossume32e0141992-01-19 16:31:05 +00002871/* The / and % operators are now defined in terms of divmod().
2872 The expression a mod b has the value a - b*floor(a/b).
2873 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002874 |a| by |b|, with the sign of a. This is also expressed
2875 as a - b*trunc(a/b), if trunc truncates towards zero.
2876 Some examples:
2877 a b a rem b a mod b
2878 13 10 3 3
2879 -13 10 -3 7
2880 13 -10 3 -7
2881 -13 -10 -3 -3
2882 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002883 have different signs. We then subtract one from the 'div'
2884 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002885
Tim Peters47e52ee2004-08-30 02:44:38 +00002886/* Compute
2887 * *pdiv, *pmod = divmod(v, w)
2888 * NULL can be passed for pdiv or pmod, in which case that part of
2889 * the result is simply thrown away. The caller owns a reference to
2890 * each of these it requests (does not pass NULL for).
2891 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002892static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002893l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002894 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002895{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002896 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002897
Guido van Rossume32e0141992-01-19 16:31:05 +00002898 if (long_divrem(v, w, &div, &mod) < 0)
2899 return -1;
Christian Heimese93237d2007-12-19 02:37:44 +00002900 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2901 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002902 PyLongObject *temp;
2903 PyLongObject *one;
2904 temp = (PyLongObject *) long_add(mod, w);
2905 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002906 mod = temp;
2907 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002908 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002909 return -1;
2910 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002911 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002912 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002913 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2914 Py_DECREF(mod);
2915 Py_DECREF(div);
2916 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002917 return -1;
2918 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002919 Py_DECREF(one);
2920 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002921 div = temp;
2922 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002923 if (pdiv != NULL)
2924 *pdiv = div;
2925 else
2926 Py_DECREF(div);
2927
2928 if (pmod != NULL)
2929 *pmod = mod;
2930 else
2931 Py_DECREF(mod);
2932
Guido van Rossume32e0141992-01-19 16:31:05 +00002933 return 0;
2934}
2935
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002936static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002937long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002938{
Tim Peters47e52ee2004-08-30 02:44:38 +00002939 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002940
2941 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002942 if (l_divmod(a, b, &div, NULL) < 0)
2943 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002944 Py_DECREF(a);
2945 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002946 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002947}
2948
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002949static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00002950long_classic_div(PyObject *v, PyObject *w)
2951{
Tim Peters47e52ee2004-08-30 02:44:38 +00002952 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002953
2954 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00002955 if (Py_DivisionWarningFlag &&
2956 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
2957 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00002958 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00002959 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00002960 Py_DECREF(a);
2961 Py_DECREF(b);
2962 return (PyObject *)div;
2963}
2964
Mark Dickinson46572832009-12-27 14:55:57 +00002965/* PyLong/PyLong -> float, with correctly rounded result. */
2966
2967#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
2968#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
2969
Guido van Rossum393661d2001-08-31 17:40:15 +00002970static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002971long_true_divide(PyObject *v, PyObject *w)
2972{
Mark Dickinson46572832009-12-27 14:55:57 +00002973 PyLongObject *a, *b, *x;
2974 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
2975 digit mask, low;
2976 int inexact, negate, a_is_small, b_is_small;
2977 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00002978
2979 CONVERT_BINOP(v, w, &a, &b);
Tim Peterse2a60002001-09-04 06:17:36 +00002980
Mark Dickinson46572832009-12-27 14:55:57 +00002981 /*
2982 Method in a nutshell:
2983
2984 0. reduce to case a, b > 0; filter out obvious underflow/overflow
2985 1. choose a suitable integer 'shift'
2986 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
2987 3. adjust x for correct rounding
2988 4. convert x to a double dx with the same value
2989 5. return ldexp(dx, shift).
2990
2991 In more detail:
2992
2993 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
2994 returns either 0.0 or -0.0, depending on the sign of b. For a and
2995 b both nonzero, ignore signs of a and b, and add the sign back in
2996 at the end. Now write a_bits and b_bits for the bit lengths of a
2997 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
2998 for b). Then
2999
3000 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
3001
3002 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3003 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3004 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3005 the way, we can assume that
3006
3007 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
3008
3009 1. The integer 'shift' is chosen so that x has the right number of
3010 bits for a double, plus two or three extra bits that will be used
3011 in the rounding decisions. Writing a_bits and b_bits for the
3012 number of significant bits in a and b respectively, a
3013 straightforward formula for shift is:
3014
3015 shift = a_bits - b_bits - DBL_MANT_DIG - 2
3016
3017 This is fine in the usual case, but if a/b is smaller than the
3018 smallest normal float then it can lead to double rounding on an
3019 IEEE 754 platform, giving incorrectly rounded results. So we
3020 adjust the formula slightly. The actual formula used is:
3021
3022 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
3023
3024 2. The quantity x is computed by first shifting a (left -shift bits
3025 if shift <= 0, right shift bits if shift > 0) and then dividing by
3026 b. For both the shift and the division, we keep track of whether
3027 the result is inexact, in a flag 'inexact'; this information is
3028 needed at the rounding stage.
3029
3030 With the choice of shift above, together with our assumption that
3031 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3032 that x >= 1.
3033
3034 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3035 this with an exactly representable float of the form
3036
3037 round(x/2**extra_bits) * 2**(extra_bits+shift).
3038
3039 For float representability, we need x/2**extra_bits <
3040 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3041 DBL_MANT_DIG. This translates to the condition:
3042
3043 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
3044
3045 To round, we just modify the bottom digit of x in-place; this can
3046 end up giving a digit with value > PyLONG_MASK, but that's not a
3047 problem since digits can hold values up to 2*PyLONG_MASK+1.
3048
3049 With the original choices for shift above, extra_bits will always
3050 be 2 or 3. Then rounding under the round-half-to-even rule, we
3051 round up iff the most significant of the extra bits is 1, and
3052 either: (a) the computation of x in step 2 had an inexact result,
3053 or (b) at least one other of the extra bits is 1, or (c) the least
3054 significant bit of x (above those to be rounded) is 1.
3055
3056 4. Conversion to a double is straightforward; all floating-point
3057 operations involved in the conversion are exact, so there's no
3058 danger of rounding errors.
3059
3060 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3061 The result will always be exactly representable as a double, except
3062 in the case that it overflows. To avoid dependence on the exact
3063 behaviour of ldexp on overflow, we check for overflow before
3064 applying ldexp. The result of ldexp is adjusted for sign before
3065 returning.
3066 */
3067
3068 /* Reduce to case where a and b are both positive. */
3069 a_size = ABS(Py_SIZE(a));
3070 b_size = ABS(Py_SIZE(b));
3071 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3072 if (b_size == 0) {
Tim Peterse2a60002001-09-04 06:17:36 +00003073 PyErr_SetString(PyExc_ZeroDivisionError,
Mark Dickinson46572832009-12-27 14:55:57 +00003074 "division by zero");
3075 goto error;
3076 }
3077 if (a_size == 0)
3078 goto underflow_or_zero;
3079
3080 /* Fast path for a and b small (exactly representable in a double).
3081 Relies on floating-point division being correctly rounded; results
3082 may be subject to double rounding on x86 machines that operate with
3083 the x87 FPU set to 64-bit precision. */
3084 a_is_small = a_size <= MANT_DIG_DIGITS ||
3085 (a_size == MANT_DIG_DIGITS+1 &&
3086 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3087 b_is_small = b_size <= MANT_DIG_DIGITS ||
3088 (b_size == MANT_DIG_DIGITS+1 &&
3089 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3090 if (a_is_small && b_is_small) {
3091 double da, db;
3092 da = a->ob_digit[--a_size];
3093 while (a_size > 0)
3094 da = da * PyLong_BASE + a->ob_digit[--a_size];
3095 db = b->ob_digit[--b_size];
3096 while (b_size > 0)
3097 db = db * PyLong_BASE + b->ob_digit[--b_size];
3098 result = da / db;
3099 goto success;
Tim Peterse2a60002001-09-04 06:17:36 +00003100 }
3101
Mark Dickinson46572832009-12-27 14:55:57 +00003102 /* Catch obvious cases of underflow and overflow */
3103 diff = a_size - b_size;
3104 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3105 /* Extreme overflow */
Tim Peterse2a60002001-09-04 06:17:36 +00003106 goto overflow;
Mark Dickinson46572832009-12-27 14:55:57 +00003107 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3108 /* Extreme underflow */
3109 goto underflow_or_zero;
3110 /* Next line is now safe from overflowing a Py_ssize_t */
3111 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3112 bits_in_digit(b->ob_digit[b_size - 1]);
3113 /* Now diff = a_bits - b_bits. */
3114 if (diff > DBL_MAX_EXP)
Tim Peterse2a60002001-09-04 06:17:36 +00003115 goto overflow;
Mark Dickinson46572832009-12-27 14:55:57 +00003116 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3117 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003118
Mark Dickinson46572832009-12-27 14:55:57 +00003119 /* Choose value for shift; see comments for step 1 above. */
3120 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
3121
3122 inexact = 0;
3123
3124 /* x = abs(a * 2**-shift) */
3125 if (shift <= 0) {
3126 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3127 digit rem;
3128 /* x = a << -shift */
3129 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3130 /* In practice, it's probably impossible to end up
3131 here. Both a and b would have to be enormous,
3132 using close to SIZE_T_MAX bytes of memory each. */
3133 PyErr_SetString(PyExc_OverflowError,
3134 "intermediate overflow during division");
3135 goto error;
3136 }
3137 x = _PyLong_New(a_size + shift_digits + 1);
3138 if (x == NULL)
3139 goto error;
3140 for (i = 0; i < shift_digits; i++)
3141 x->ob_digit[i] = 0;
3142 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3143 a_size, -shift % PyLong_SHIFT);
3144 x->ob_digit[a_size + shift_digits] = rem;
3145 }
3146 else {
3147 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3148 digit rem;
3149 /* x = a >> shift */
3150 assert(a_size >= shift_digits);
3151 x = _PyLong_New(a_size - shift_digits);
3152 if (x == NULL)
3153 goto error;
3154 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3155 a_size - shift_digits, shift % PyLong_SHIFT);
3156 /* set inexact if any of the bits shifted out is nonzero */
3157 if (rem)
3158 inexact = 1;
3159 while (!inexact && shift_digits > 0)
3160 if (a->ob_digit[--shift_digits])
3161 inexact = 1;
3162 }
3163 long_normalize(x);
3164 x_size = Py_SIZE(x);
3165
3166 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3167 reference to x, so it's safe to modify it in-place. */
3168 if (b_size == 1) {
3169 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3170 b->ob_digit[0]);
3171 long_normalize(x);
3172 if (rem)
3173 inexact = 1;
3174 }
3175 else {
3176 PyLongObject *div, *rem;
3177 div = x_divrem(x, b, &rem);
3178 Py_DECREF(x);
3179 x = div;
3180 if (x == NULL)
3181 goto error;
3182 if (Py_SIZE(rem))
3183 inexact = 1;
3184 Py_DECREF(rem);
3185 }
3186 x_size = ABS(Py_SIZE(x));
3187 assert(x_size > 0); /* result of division is never zero */
3188 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
3189
3190 /* The number of extra bits that have to be rounded away. */
3191 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3192 assert(extra_bits == 2 || extra_bits == 3);
3193
3194 /* Round by directly modifying the low digit of x. */
3195 mask = (digit)1 << (extra_bits - 1);
3196 low = x->ob_digit[0] | inexact;
3197 if (low & mask && low & (3*mask-1))
3198 low += mask;
3199 x->ob_digit[0] = low & ~(mask-1U);
3200
3201 /* Convert x to a double dx; the conversion is exact. */
3202 dx = x->ob_digit[--x_size];
3203 while (x_size > 0)
3204 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3205 Py_DECREF(x);
3206
3207 /* Check whether ldexp result will overflow a double. */
3208 if (shift + x_bits >= DBL_MAX_EXP &&
3209 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, x_bits)))
3210 goto overflow;
3211 result = ldexp(dx, shift);
3212
3213 success:
3214 Py_DECREF(a);
3215 Py_DECREF(b);
3216 return PyFloat_FromDouble(negate ? -result : result);
3217
3218 underflow_or_zero:
3219 Py_DECREF(a);
3220 Py_DECREF(b);
3221 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
3222
3223 overflow:
Tim Peterse2a60002001-09-04 06:17:36 +00003224 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson46572832009-12-27 14:55:57 +00003225 "integer division result too large for a float");
3226 error:
3227 Py_DECREF(a);
3228 Py_DECREF(b);
Tim Peterse2a60002001-09-04 06:17:36 +00003229 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003230}
3231
3232static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003233long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00003234{
Tim Peters47e52ee2004-08-30 02:44:38 +00003235 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003236
3237 CONVERT_BINOP(v, w, &a, &b);
3238
Tim Peters47e52ee2004-08-30 02:44:38 +00003239 if (l_divmod(a, b, NULL, &mod) < 0)
3240 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003241 Py_DECREF(a);
3242 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003243 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003244}
3245
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003246static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003247long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003248{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003249 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003250 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003251
3252 CONVERT_BINOP(v, w, &a, &b);
3253
3254 if (l_divmod(a, b, &div, &mod) < 0) {
3255 Py_DECREF(a);
3256 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003257 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003258 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003259 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003260 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003261 PyTuple_SetItem(z, 0, (PyObject *) div);
3262 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003263 }
3264 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003265 Py_DECREF(div);
3266 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003267 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003268 Py_DECREF(a);
3269 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003270 return z;
3271}
3272
Tim Peters47e52ee2004-08-30 02:44:38 +00003273/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003274static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003275long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003276{
Tim Peters47e52ee2004-08-30 02:44:38 +00003277 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3278 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003279
Tim Peters47e52ee2004-08-30 02:44:38 +00003280 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003281 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003282 PyLongObject *temp = NULL;
3283
3284 /* 5-ary values. If the exponent is large enough, table is
3285 * precomputed so that table[i] == a**i % c for i in range(32).
3286 */
3287 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3288 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3289
3290 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003291 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003292 if (PyLong_Check(x)) {
3293 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003294 Py_INCREF(x);
3295 }
Tim Petersde7990b2005-07-17 23:45:23 +00003296 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003297 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00003298 if (c == NULL)
3299 goto Error;
3300 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003301 else if (x == Py_None)
3302 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003303 else {
3304 Py_DECREF(a);
3305 Py_DECREF(b);
3306 Py_INCREF(Py_NotImplemented);
3307 return Py_NotImplemented;
3308 }
Tim Peters4c483c42001-09-05 06:24:58 +00003309
Christian Heimese93237d2007-12-19 02:37:44 +00003310 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003311 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003312 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003313 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003314 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003315 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003316 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003317 /* else return a float. This works because we know
3318 that this calls float_pow() which converts its
3319 arguments to double. */
3320 Py_DECREF(a);
3321 Py_DECREF(b);
3322 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003323 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003324 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003325
3326 if (c) {
3327 /* if modulus == 0:
3328 raise ValueError() */
Christian Heimese93237d2007-12-19 02:37:44 +00003329 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003330 PyErr_SetString(PyExc_ValueError,
3331 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003332 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003333 }
3334
3335 /* if modulus < 0:
3336 negativeOutput = True
3337 modulus = -modulus */
Christian Heimese93237d2007-12-19 02:37:44 +00003338 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003339 negativeOutput = 1;
3340 temp = (PyLongObject *)_PyLong_Copy(c);
3341 if (temp == NULL)
3342 goto Error;
3343 Py_DECREF(c);
3344 c = temp;
3345 temp = NULL;
3346 c->ob_size = - c->ob_size;
3347 }
3348
3349 /* if modulus == 1:
3350 return 0 */
Christian Heimese93237d2007-12-19 02:37:44 +00003351 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003352 z = (PyLongObject *)PyLong_FromLong(0L);
3353 goto Done;
3354 }
3355
3356 /* if base < 0:
3357 base = base % modulus
3358 Having the base positive just makes things easier. */
Christian Heimese93237d2007-12-19 02:37:44 +00003359 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003360 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003361 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003362 Py_DECREF(a);
3363 a = temp;
3364 temp = NULL;
3365 }
3366 }
3367
3368 /* At this point a, b, and c are guaranteed non-negative UNLESS
3369 c is NULL, in which case a may be negative. */
3370
3371 z = (PyLongObject *)PyLong_FromLong(1L);
3372 if (z == NULL)
3373 goto Error;
3374
3375 /* Perform a modular reduction, X = X % c, but leave X alone if c
3376 * is NULL.
3377 */
3378#define REDUCE(X) \
3379 if (c != NULL) { \
3380 if (l_divmod(X, c, NULL, &temp) < 0) \
3381 goto Error; \
3382 Py_XDECREF(X); \
3383 X = temp; \
3384 temp = NULL; \
3385 }
3386
3387 /* Multiply two values, then reduce the result:
3388 result = X*Y % c. If c is NULL, skip the mod. */
3389#define MULT(X, Y, result) \
3390{ \
3391 temp = (PyLongObject *)long_mul(X, Y); \
3392 if (temp == NULL) \
3393 goto Error; \
3394 Py_XDECREF(result); \
3395 result = temp; \
3396 temp = NULL; \
3397 REDUCE(result) \
3398}
3399
Christian Heimese93237d2007-12-19 02:37:44 +00003400 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003401 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3402 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimese93237d2007-12-19 02:37:44 +00003403 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003404 digit bi = b->ob_digit[i];
3405
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00003406 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003407 MULT(z, z, z)
3408 if (bi & j)
3409 MULT(z, a, z)
3410 }
3411 }
3412 }
3413 else {
3414 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3415 Py_INCREF(z); /* still holds 1L */
3416 table[0] = z;
3417 for (i = 1; i < 32; ++i)
3418 MULT(table[i-1], a, table[i])
3419
Christian Heimese93237d2007-12-19 02:37:44 +00003420 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003421 const digit bi = b->ob_digit[i];
3422
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003423 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003424 const int index = (bi >> j) & 0x1f;
3425 for (k = 0; k < 5; ++k)
3426 MULT(z, z, z)
3427 if (index)
3428 MULT(z, table[index], z)
3429 }
3430 }
3431 }
3432
Christian Heimese93237d2007-12-19 02:37:44 +00003433 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003434 temp = (PyLongObject *)long_sub(z, c);
3435 if (temp == NULL)
3436 goto Error;
3437 Py_DECREF(z);
3438 z = temp;
3439 temp = NULL;
3440 }
3441 goto Done;
3442
3443 Error:
3444 if (z != NULL) {
3445 Py_DECREF(z);
3446 z = NULL;
3447 }
3448 /* fall through */
3449 Done:
Christian Heimese93237d2007-12-19 02:37:44 +00003450 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003451 for (i = 0; i < 32; ++i)
3452 Py_XDECREF(table[i]);
3453 }
Tim Petersde7990b2005-07-17 23:45:23 +00003454 Py_DECREF(a);
3455 Py_DECREF(b);
3456 Py_XDECREF(c);
3457 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003458 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003459}
3460
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003461static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003462long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003463{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003464 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003465 PyLongObject *x;
3466 PyLongObject *w;
3467 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003468 if (w == NULL)
3469 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003470 x = (PyLongObject *) long_add(v, w);
3471 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003472 if (x == NULL)
3473 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00003474 Py_SIZE(x) = -(Py_SIZE(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003475 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003476}
3477
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003478static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003479long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003480{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003481 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003482 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003483 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003484 Py_INCREF(v);
3485 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003486 }
Tim Peters69c2de32001-09-11 22:31:33 +00003487 z = (PyLongObject *)_PyLong_Copy(v);
3488 if (z != NULL)
3489 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003490 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003491}
3492
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003493static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003494long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003495{
3496 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003497 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003498 else
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003499 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003500}
3501
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003502static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003503long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003504{
Christian Heimese93237d2007-12-19 02:37:44 +00003505 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003506}
3507
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003508static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003509long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003510{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003511 PyLongObject *a, *b;
3512 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003513 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003514 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003515 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003516
Neil Schemenauerba872e22001-01-04 01:46:03 +00003517 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3518
Christian Heimese93237d2007-12-19 02:37:44 +00003519 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003520 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003521 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003522 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003523 if (a1 == NULL)
3524 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003525 a2 = (PyLongObject *) long_rshift(a1, b);
3526 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003527 if (a2 == NULL)
3528 goto rshift_error;
3529 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003530 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003531 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003532 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003533
Neil Schemenauerba872e22001-01-04 01:46:03 +00003534 shiftby = PyLong_AsLong((PyObject *)b);
3535 if (shiftby == -1L && PyErr_Occurred())
3536 goto rshift_error;
3537 if (shiftby < 0) {
3538 PyErr_SetString(PyExc_ValueError,
3539 "negative shift count");
3540 goto rshift_error;
3541 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003542 wordshift = shiftby / PyLong_SHIFT;
Christian Heimese93237d2007-12-19 02:37:44 +00003543 newsize = ABS(Py_SIZE(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003544 if (newsize <= 0) {
3545 z = _PyLong_New(0);
3546 Py_DECREF(a);
3547 Py_DECREF(b);
3548 return (PyObject *)z;
3549 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003550 loshift = shiftby % PyLong_SHIFT;
3551 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003552 lomask = ((digit)1 << hishift) - 1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003553 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003554 z = _PyLong_New(newsize);
3555 if (z == NULL)
3556 goto rshift_error;
Christian Heimese93237d2007-12-19 02:37:44 +00003557 if (Py_SIZE(a) < 0)
3558 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003559 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3560 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3561 if (i+1 < newsize)
3562 z->ob_digit[i] |=
3563 (a->ob_digit[j+1] << hishift) & himask;
3564 }
3565 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003566 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003567rshift_error:
3568 Py_DECREF(a);
3569 Py_DECREF(b);
3570 return (PyObject *) z;
3571
Guido van Rossumc6913e71991-11-19 20:26:46 +00003572}
3573
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003574static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003575long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003576{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003577 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003578 PyLongObject *a, *b;
3579 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003580 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003581 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003582 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003583
Neil Schemenauerba872e22001-01-04 01:46:03 +00003584 CONVERT_BINOP(v, w, &a, &b);
3585
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003586 shiftby = PyLong_AsLong((PyObject *)b);
3587 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003588 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003589 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003590 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003591 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003592 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003593 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003594 PyErr_SetString(PyExc_ValueError,
3595 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003596 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003597 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003598 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3599 wordshift = (int)shiftby / PyLong_SHIFT;
3600 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003601
3602 oldsize = ABS(a->ob_size);
3603 newsize = oldsize + wordshift;
3604 if (remshift)
3605 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003606 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003607 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003608 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003609 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003610 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003611 for (i = 0; i < wordshift; i++)
3612 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003613 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003614 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003615 accum |= (twodigits)a->ob_digit[j] << remshift;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003616 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3617 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003618 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003619 if (remshift)
3620 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003621 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003622 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003623 z = long_normalize(z);
3624lshift_error:
3625 Py_DECREF(a);
3626 Py_DECREF(b);
3627 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003628}
3629
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003630/* Compute two's complement of digit vector a[0:m], writing result to
3631 z[0:m]. The digit vector a need not be normalized, but should not
3632 be entirely zero. a and z may point to the same digit vector. */
3633
3634static void
3635v_complement(digit *z, digit *a, Py_ssize_t m)
3636{
3637 Py_ssize_t i;
3638 digit carry = 1;
3639 for (i = 0; i < m; ++i) {
3640 carry += a[i] ^ PyLong_MASK;
3641 z[i] = carry & PyLong_MASK;
3642 carry >>= PyLong_SHIFT;
3643 }
3644 assert(carry == 0);
3645}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003646
3647/* Bitwise and/xor/or operations */
3648
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003649static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003650long_bitwise(PyLongObject *a,
3651 int op, /* '&', '|', '^' */
3652 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003653{
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003654 int nega, negb, negz;
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00003655 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003656 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003657
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003658 /* Bitwise operations for negative numbers operate as though
3659 on a two's complement representation. So convert arguments
3660 from sign-magnitude to two's complement, and convert the
3661 result back to sign-magnitude at the end. */
3662
3663 /* If a is negative, replace it by its two's complement. */
3664 size_a = ABS(Py_SIZE(a));
3665 nega = Py_SIZE(a) < 0;
3666 if (nega) {
3667 z = _PyLong_New(size_a);
3668 if (z == NULL)
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003669 return NULL;
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003670 v_complement(z->ob_digit, a->ob_digit, size_a);
3671 a = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003672 }
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003673 else
3674 /* Keep reference count consistent. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003675 Py_INCREF(a);
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003676
3677 /* Same for b. */
3678 size_b = ABS(Py_SIZE(b));
3679 negb = Py_SIZE(b) < 0;
3680 if (negb) {
3681 z = _PyLong_New(size_b);
3682 if (z == NULL) {
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003683 Py_DECREF(a);
3684 return NULL;
3685 }
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003686 v_complement(z->ob_digit, b->ob_digit, size_b);
3687 b = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003688 }
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003689 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003690 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003691
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003692 /* Swap a and b if necessary to ensure size_a >= size_b. */
3693 if (size_a < size_b) {
3694 z = a; a = b; b = z;
3695 size_z = size_a; size_a = size_b; size_b = size_z;
3696 negz = nega; nega = negb; negb = negz;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003697 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003698
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003699 /* JRH: The original logic here was to allocate the result value (z)
3700 as the longer of the two operands. However, there are some cases
3701 where the result is guaranteed to be shorter than that: AND of two
3702 positives, OR of two negatives: use the shorter number. AND with
3703 mixed signs: use the positive number. OR with mixed signs: use the
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003704 negative number.
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003705 */
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003706 switch (op) {
3707 case '^':
3708 negz = nega ^ negb;
3709 size_z = size_a;
3710 break;
3711 case '&':
3712 negz = nega & negb;
3713 size_z = negb ? size_a : size_b;
3714 break;
3715 case '|':
3716 negz = nega | negb;
3717 size_z = negb ? size_b : size_a;
3718 break;
3719 default:
3720 PyErr_BadArgument();
3721 return NULL;
3722 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003723
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003724 /* We allow an extra digit if z is negative, to make sure that
3725 the final two's complement of z doesn't overflow. */
3726 z = _PyLong_New(size_z + negz);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003727 if (z == NULL) {
Neal Norwitzef02b9e2006-07-16 02:00:32 +00003728 Py_DECREF(a);
3729 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003730 return NULL;
3731 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003732
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003733 /* Compute digits for overlap of a and b. */
3734 switch(op) {
3735 case '&':
3736 for (i = 0; i < size_b; ++i)
3737 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
3738 break;
3739 case '|':
3740 for (i = 0; i < size_b; ++i)
3741 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
3742 break;
3743 case '^':
3744 for (i = 0; i < size_b; ++i)
3745 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
3746 break;
3747 default:
3748 PyErr_BadArgument();
3749 return NULL;
3750 }
3751
3752 /* Copy any remaining digits of a, inverting if necessary. */
3753 if (op == '^' && negb)
3754 for (; i < size_z; ++i)
3755 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
3756 else if (i < size_z)
3757 memcpy(&z->ob_digit[i], &a->ob_digit[i],
3758 (size_z-i)*sizeof(digit));
3759
3760 /* Complement result if negative. */
3761 if (negz) {
3762 Py_SIZE(z) = -(Py_SIZE(z));
3763 z->ob_digit[size_z] = PyLong_MASK;
3764 v_complement(z->ob_digit, z->ob_digit, size_z+1);
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003765 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003766
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003767 Py_DECREF(a);
3768 Py_DECREF(b);
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003769 return (PyObject *)long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003770}
3771
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003772static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003773long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003774{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003775 PyLongObject *a, *b;
3776 PyObject *c;
3777 CONVERT_BINOP(v, w, &a, &b);
3778 c = long_bitwise(a, '&', b);
3779 Py_DECREF(a);
3780 Py_DECREF(b);
3781 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003782}
3783
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003784static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003785long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003786{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003787 PyLongObject *a, *b;
3788 PyObject *c;
3789 CONVERT_BINOP(v, w, &a, &b);
3790 c = long_bitwise(a, '^', b);
3791 Py_DECREF(a);
3792 Py_DECREF(b);
3793 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003794}
3795
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003796static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003797long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003798{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003799 PyLongObject *a, *b;
3800 PyObject *c;
3801 CONVERT_BINOP(v, w, &a, &b);
3802 c = long_bitwise(a, '|', b);
3803 Py_DECREF(a);
3804 Py_DECREF(b);
3805 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003806}
3807
Guido van Rossum234f9421993-06-17 12:35:49 +00003808static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003809long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003810{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003811 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00003812 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Georg Brandlc02e1312007-04-11 17:16:24 +00003813 if (*pw == NULL)
3814 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003815 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00003816 return 0;
3817 }
Guido van Rossum1952e382001-09-19 01:25:16 +00003818 else if (PyLong_Check(*pw)) {
3819 Py_INCREF(*pv);
3820 Py_INCREF(*pw);
3821 return 0;
3822 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00003823 return 1; /* Can't do it */
3824}
3825
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003826static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003827long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003828{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003829 if (PyLong_CheckExact(v))
3830 Py_INCREF(v);
3831 else
3832 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003833 return v;
3834}
3835
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003836static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003837long_int(PyObject *v)
3838{
3839 long x;
3840 x = PyLong_AsLong(v);
3841 if (PyErr_Occurred()) {
3842 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3843 PyErr_Clear();
3844 if (PyLong_CheckExact(v)) {
3845 Py_INCREF(v);
3846 return v;
3847 }
3848 else
3849 return _PyLong_Copy((PyLongObject *)v);
3850 }
3851 else
3852 return NULL;
3853 }
3854 return PyInt_FromLong(x);
3855}
3856
3857static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003858long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003859{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003860 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003861 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003862 if (result == -1.0 && PyErr_Occurred())
3863 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003864 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003865}
3866
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003867static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003868long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003869{
Eric Smith5e527eb2008-02-10 01:36:53 +00003870 return _PyLong_Format(v, 8, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003871}
3872
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003873static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003874long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003875{
Eric Smith5e527eb2008-02-10 01:36:53 +00003876 return _PyLong_Format(v, 16, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003877}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003878
3879static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003880long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003881
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882static PyObject *
3883long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3884{
3885 PyObject *x = NULL;
3886 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003887 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003888
Guido van Rossumbef14172001-08-29 15:47:46 +00003889 if (type != &PyLong_Type)
3890 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003891 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3892 &x, &base))
3893 return NULL;
3894 if (x == NULL)
3895 return PyLong_FromLong(0L);
3896 if (base == -909)
3897 return PyNumber_Long(x);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003898 else if (PyString_Check(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003899 /* Since PyLong_FromString doesn't have a length parameter,
3900 * check here for possible NULs in the string. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003901 char *string = PyString_AS_STRING(x);
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00003902 if (strlen(string) != (size_t)PyString_Size(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003903 /* create a repr() of the input string,
3904 * just like PyLong_FromString does. */
3905 PyObject *srepr;
3906 srepr = PyObject_Repr(x);
3907 if (srepr == NULL)
3908 return NULL;
3909 PyErr_Format(PyExc_ValueError,
3910 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003911 base, PyString_AS_STRING(srepr));
Georg Brandl00cd8182007-03-06 18:41:12 +00003912 Py_DECREF(srepr);
3913 return NULL;
3914 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003915 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Georg Brandl00cd8182007-03-06 18:41:12 +00003916 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003917#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003918 else if (PyUnicode_Check(x))
3919 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3920 PyUnicode_GET_SIZE(x),
3921 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003922#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003923 else {
3924 PyErr_SetString(PyExc_TypeError,
3925 "long() can't convert non-string with explicit base");
3926 return NULL;
3927 }
3928}
3929
Guido van Rossumbef14172001-08-29 15:47:46 +00003930/* Wimpy, slow approach to tp_new calls for subtypes of long:
3931 first create a regular long from whatever arguments we got,
3932 then allocate a subtype instance and initialize it from
3933 the regular long. The regular long is then thrown away.
3934*/
3935static PyObject *
3936long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3937{
Anthony Baxter377be112006-04-11 06:54:30 +00003938 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003939 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003940
3941 assert(PyType_IsSubtype(type, &PyLong_Type));
3942 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3943 if (tmp == NULL)
3944 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003945 assert(PyLong_CheckExact(tmp));
Christian Heimese93237d2007-12-19 02:37:44 +00003946 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003947 if (n < 0)
3948 n = -n;
Anthony Baxter377be112006-04-11 06:54:30 +00003949 newobj = (PyLongObject *)type->tp_alloc(type, n);
3950 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003951 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003952 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003953 }
Anthony Baxter377be112006-04-11 06:54:30 +00003954 assert(PyLong_Check(newobj));
Christian Heimese93237d2007-12-19 02:37:44 +00003955 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003956 for (i = 0; i < n; i++)
Anthony Baxter377be112006-04-11 06:54:30 +00003957 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003958 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00003959 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003960}
3961
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003962static PyObject *
3963long_getnewargs(PyLongObject *v)
3964{
3965 return Py_BuildValue("(N)", _PyLong_Copy(v));
3966}
3967
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003968static PyObject *
Mark Dickinsond4b5c982009-05-02 17:55:01 +00003969long_get0(PyLongObject *v, void *context) {
3970 return PyLong_FromLong(0L);
3971}
3972
3973static PyObject *
3974long_get1(PyLongObject *v, void *context) {
3975 return PyLong_FromLong(1L);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003976}
3977
Eric Smitha9f7d622008-02-17 19:46:49 +00003978static PyObject *
3979long__format__(PyObject *self, PyObject *args)
3980{
3981 PyObject *format_spec;
3982
3983 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3984 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00003985 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00003986 return _PyLong_FormatAdvanced(self,
3987 PyBytes_AS_STRING(format_spec),
3988 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00003989 if (PyUnicode_Check(format_spec)) {
3990 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00003991 PyObject *result;
3992 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00003993
Eric Smithdc13b792008-05-30 18:10:04 +00003994 if (str_spec == NULL)
3995 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00003996
Eric Smithdc13b792008-05-30 18:10:04 +00003997 result = _PyLong_FormatAdvanced(self,
3998 PyBytes_AS_STRING(str_spec),
3999 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00004000
Eric Smithdc13b792008-05-30 18:10:04 +00004001 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00004002 return result;
4003 }
4004 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
4005 return NULL;
4006}
4007
Robert Schuppenies51df0642008-06-01 16:16:17 +00004008static PyObject *
4009long_sizeof(PyLongObject *v)
4010{
4011 Py_ssize_t res;
4012
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00004013 res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);
Robert Schuppenies51df0642008-06-01 16:16:17 +00004014 return PyInt_FromSsize_t(res);
4015}
4016
Mark Dickinson1a707982008-12-17 16:14:37 +00004017static PyObject *
4018long_bit_length(PyLongObject *v)
4019{
4020 PyLongObject *result, *x, *y;
4021 Py_ssize_t ndigits, msd_bits = 0;
4022 digit msd;
4023
4024 assert(v != NULL);
4025 assert(PyLong_Check(v));
4026
4027 ndigits = ABS(Py_SIZE(v));
4028 if (ndigits == 0)
4029 return PyInt_FromLong(0);
4030
4031 msd = v->ob_digit[ndigits-1];
4032 while (msd >= 32) {
4033 msd_bits += 6;
4034 msd >>= 6;
4035 }
4036 msd_bits += (long)(BitLengthTable[msd]);
4037
4038 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4039 return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
4040
4041 /* expression above may overflow; use Python integers instead */
4042 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4043 if (result == NULL)
4044 return NULL;
4045 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4046 if (x == NULL)
4047 goto error;
4048 y = (PyLongObject *)long_mul(result, x);
4049 Py_DECREF(x);
4050 if (y == NULL)
4051 goto error;
4052 Py_DECREF(result);
4053 result = y;
4054
4055 x = (PyLongObject *)PyLong_FromLong(msd_bits);
4056 if (x == NULL)
4057 goto error;
4058 y = (PyLongObject *)long_add(result, x);
4059 Py_DECREF(x);
4060 if (y == NULL)
4061 goto error;
4062 Py_DECREF(result);
4063 result = y;
4064
4065 return (PyObject *)result;
4066
4067error:
4068 Py_DECREF(result);
4069 return NULL;
4070}
4071
4072PyDoc_STRVAR(long_bit_length_doc,
4073"long.bit_length() -> int or long\n\
4074\n\
4075Number of bits necessary to represent self in binary.\n\
4076>>> bin(37L)\n\
4077'0b100101'\n\
4078>>> (37L).bit_length()\n\
40796");
4080
Christian Heimes6f341092008-04-18 23:13:07 +00004081#if 0
4082static PyObject *
4083long_is_finite(PyObject *v)
4084{
4085 Py_RETURN_TRUE;
4086}
4087#endif
4088
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004089static PyMethodDef long_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004090 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4091 "Returns self, the complex conjugate of any long."},
Mark Dickinson1a707982008-12-17 16:14:37 +00004092 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4093 long_bit_length_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00004094#if 0
4095 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4096 "Returns always True."},
4097#endif
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004098 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4099 "Truncating an Integral returns itself."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004100 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smitha9f7d622008-02-17 19:46:49 +00004101 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Robert Schuppenies51df0642008-06-01 16:16:17 +00004102 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00004103 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004104 {NULL, NULL} /* sentinel */
4105};
4106
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004107static PyGetSetDef long_getset[] = {
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004108 {"real",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004109 (getter)long_long, (setter)NULL,
4110 "the real part of a complex number",
4111 NULL},
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004112 {"imag",
4113 (getter)long_get0, (setter)NULL,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004114 "the imaginary part of a complex number",
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004115 NULL},
4116 {"numerator",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004117 (getter)long_long, (setter)NULL,
4118 "the numerator of a rational number in lowest terms",
4119 NULL},
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004120 {"denominator",
4121 (getter)long_get1, (setter)NULL,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004122 "the denominator of a rational number in lowest terms",
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004123 NULL},
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004124 {NULL} /* Sentinel */
4125};
4126
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004127PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00004128"long(x[, base]) -> integer\n\
4129\n\
4130Convert a string or number to a long integer, if possible. A floating\n\
4131point argument will be truncated towards zero (this does not include a\n\
4132string representation of a floating point number!) When converting a\n\
4133string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004134converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004135
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004136static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00004137 (binaryfunc) long_add, /*nb_add*/
4138 (binaryfunc) long_sub, /*nb_subtract*/
4139 (binaryfunc) long_mul, /*nb_multiply*/
Georg Brandl347b3002006-03-30 11:57:00 +00004140 long_classic_div, /*nb_divide*/
4141 long_mod, /*nb_remainder*/
4142 long_divmod, /*nb_divmod*/
4143 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004144 (unaryfunc) long_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004145 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004146 (unaryfunc) long_abs, /*tp_absolute*/
4147 (inquiry) long_nonzero, /*tp_nonzero*/
4148 (unaryfunc) long_invert, /*nb_invert*/
Georg Brandl347b3002006-03-30 11:57:00 +00004149 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004150 (binaryfunc) long_rshift, /*nb_rshift*/
Georg Brandl347b3002006-03-30 11:57:00 +00004151 long_and, /*nb_and*/
4152 long_xor, /*nb_xor*/
4153 long_or, /*nb_or*/
4154 long_coerce, /*nb_coerce*/
4155 long_int, /*nb_int*/
4156 long_long, /*nb_long*/
4157 long_float, /*nb_float*/
4158 long_oct, /*nb_oct*/
4159 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00004160 0, /* nb_inplace_add */
4161 0, /* nb_inplace_subtract */
4162 0, /* nb_inplace_multiply */
4163 0, /* nb_inplace_divide */
4164 0, /* nb_inplace_remainder */
4165 0, /* nb_inplace_power */
4166 0, /* nb_inplace_lshift */
4167 0, /* nb_inplace_rshift */
4168 0, /* nb_inplace_and */
4169 0, /* nb_inplace_xor */
4170 0, /* nb_inplace_or */
Georg Brandl347b3002006-03-30 11:57:00 +00004171 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00004172 long_true_divide, /* nb_true_divide */
4173 0, /* nb_inplace_floor_divide */
4174 0, /* nb_inplace_true_divide */
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004175 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004176};
4177
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004178PyTypeObject PyLong_Type = {
4179 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004180 0, /* ob_size */
4181 "long", /* tp_name */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00004182 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004183 sizeof(digit), /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00004184 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004185 0, /* tp_print */
4186 0, /* tp_getattr */
4187 0, /* tp_setattr */
4188 (cmpfunc)long_compare, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00004189 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004190 &long_as_number, /* tp_as_number */
4191 0, /* tp_as_sequence */
4192 0, /* tp_as_mapping */
4193 (hashfunc)long_hash, /* tp_hash */
4194 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00004195 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004196 PyObject_GenericGetAttr, /* tp_getattro */
4197 0, /* tp_setattro */
4198 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00004199 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00004200 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201 long_doc, /* tp_doc */
4202 0, /* tp_traverse */
4203 0, /* tp_clear */
4204 0, /* tp_richcompare */
4205 0, /* tp_weaklistoffset */
4206 0, /* tp_iter */
4207 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004208 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004209 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004210 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004211 0, /* tp_base */
4212 0, /* tp_dict */
4213 0, /* tp_descr_get */
4214 0, /* tp_descr_set */
4215 0, /* tp_dictoffset */
4216 0, /* tp_init */
4217 0, /* tp_alloc */
4218 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00004219 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004220};
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004221
4222static PyTypeObject Long_InfoType;
4223
4224PyDoc_STRVAR(long_info__doc__,
4225"sys.long_info\n\
4226\n\
4227A struct sequence that holds information about Python's\n\
4228internal representation of integers. The attributes are read only.");
4229
4230static PyStructSequence_Field long_info_fields[] = {
4231 {"bits_per_digit", "size of a digit in bits"},
4232 {"sizeof_digit", "size in bytes of the C type used to "
4233 "represent a digit"},
4234 {NULL, NULL}
4235};
4236
4237static PyStructSequence_Desc long_info_desc = {
4238 "sys.long_info", /* name */
4239 long_info__doc__, /* doc */
4240 long_info_fields, /* fields */
4241 2 /* number of fields */
4242};
4243
4244PyObject *
4245PyLong_GetInfo(void)
4246{
4247 PyObject* long_info;
4248 int field = 0;
4249 long_info = PyStructSequence_New(&Long_InfoType);
4250 if (long_info == NULL)
4251 return NULL;
Mark Dickinson48e3fd22009-04-02 18:39:37 +00004252 PyStructSequence_SET_ITEM(long_info, field++,
4253 PyInt_FromLong(PyLong_SHIFT));
4254 PyStructSequence_SET_ITEM(long_info, field++,
4255 PyInt_FromLong(sizeof(digit)));
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004256 if (PyErr_Occurred()) {
4257 Py_CLEAR(long_info);
4258 return NULL;
4259 }
4260 return long_info;
4261}
4262
4263int
4264_PyLong_Init(void)
4265{
4266 /* initialize long_info */
4267 if (Long_InfoType.tp_name == 0)
4268 PyStructSequence_InitType(&Long_InfoType, &long_info_desc);
4269 return 1;
4270}