blob: 78a7792e8266904bf2a8c34e9d37a16c50710783 [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
Mark Dickinsona36507c2010-01-30 10:08:33 +0000824#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000825
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000826/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000827
828PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000829PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000830{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000831 PyLongObject *v;
Mark Dickinson27a63252008-04-15 20:51:18 +0000832 unsigned PY_LONG_LONG abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000833 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
834 int ndigits = 0;
835 int negative = 0;
836
837 if (ival < 0) {
Mark Dickinson27a63252008-04-15 20:51:18 +0000838 /* avoid signed overflow on negation; see comments
839 in PyLong_FromLong above. */
840 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000841 negative = 1;
842 }
Mark Dickinson27a63252008-04-15 20:51:18 +0000843 else {
844 abs_ival = (unsigned PY_LONG_LONG)ival;
845 }
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000846
847 /* Count the number of Python digits.
848 We used to pick 5 ("big enough for anything"), but that's a
849 waste of time and space given that 5*15 = 75 bits are rarely
850 needed. */
Mark Dickinson27a63252008-04-15 20:51:18 +0000851 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000852 while (t) {
853 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000854 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000855 }
856 v = _PyLong_New(ndigits);
857 if (v != NULL) {
858 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000859 Py_SIZE(v) = negative ? -ndigits : ndigits;
Mark Dickinson27a63252008-04-15 20:51:18 +0000860 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000861 while (t) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000862 *p++ = (digit)(t & PyLong_MASK);
863 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000864 }
865 }
866 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000867}
868
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000869/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000870
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000871PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000872PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000873{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000874 PyLongObject *v;
875 unsigned PY_LONG_LONG t;
876 int ndigits = 0;
877
878 /* Count the number of Python digits. */
879 t = (unsigned PY_LONG_LONG)ival;
880 while (t) {
881 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000882 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000883 }
884 v = _PyLong_New(ndigits);
885 if (v != NULL) {
886 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000887 Py_SIZE(v) = ndigits;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000888 while (ival) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000889 *p++ = (digit)(ival & PyLong_MASK);
890 ival >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000891 }
892 }
893 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000894}
895
Martin v. Löwis18e16552006-02-15 17:27:45 +0000896/* Create a new long int object from a C Py_ssize_t. */
897
898PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000899PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000900{
901 Py_ssize_t bytes = ival;
902 int one = 1;
903 return _PyLong_FromByteArray(
904 (unsigned char *)&bytes,
Kristján Valur Jónssonf0303942007-05-03 20:27:03 +0000905 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000906}
907
908/* Create a new long int object from a C size_t. */
909
910PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000911PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000912{
913 size_t bytes = ival;
914 int one = 1;
915 return _PyLong_FromByteArray(
916 (unsigned char *)&bytes,
917 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
918}
919
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000920/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000921 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000922
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000923PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000924PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000925{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000926 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000927 int one = 1;
928 int res;
929
Tim Petersd38b1c72001-09-30 05:09:37 +0000930 if (vv == NULL) {
931 PyErr_BadInternalCall();
932 return -1;
933 }
934 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000935 PyNumberMethods *nb;
936 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +0000937 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000938 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000939 if ((nb = vv->ob_type->tp_as_number) == NULL ||
940 nb->nb_int == NULL) {
941 PyErr_SetString(PyExc_TypeError, "an integer is required");
942 return -1;
943 }
944 io = (*nb->nb_int) (vv);
945 if (io == NULL)
946 return -1;
947 if (PyInt_Check(io)) {
948 bytes = PyInt_AsLong(io);
949 Py_DECREF(io);
950 return bytes;
951 }
952 if (PyLong_Check(io)) {
953 bytes = PyLong_AsLongLong(io);
954 Py_DECREF(io);
955 return bytes;
956 }
957 Py_DECREF(io);
958 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000959 return -1;
960 }
961
Tim Petersd1a7da62001-06-13 00:35:57 +0000962 res = _PyLong_AsByteArray(
963 (PyLongObject *)vv, (unsigned char *)&bytes,
964 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000965
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000966 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000967 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000968 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000969 else
970 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000971}
972
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000973/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000974 Return -1 and set an error if overflow occurs. */
975
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000976unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000977PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000978{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000979 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000980 int one = 1;
981 int res;
982
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000983 if (vv == NULL || !PyLong_Check(vv)) {
984 PyErr_BadInternalCall();
Skip Montanaro429433b2006-04-18 00:35:43 +0000985 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000986 }
987
Tim Petersd1a7da62001-06-13 00:35:57 +0000988 res = _PyLong_AsByteArray(
989 (PyLongObject *)vv, (unsigned char *)&bytes,
990 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000991
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000992 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000993 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000994 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000995 else
996 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000997}
Tim Petersd1a7da62001-06-13 00:35:57 +0000998
Thomas Hellera4ea6032003-04-17 18:55:45 +0000999/* Get a C unsigned long int from a long int object, ignoring the high bits.
1000 Returns -1 and sets an error condition if an error occurs. */
1001
1002unsigned PY_LONG_LONG
1003PyLong_AsUnsignedLongLongMask(PyObject *vv)
1004{
1005 register PyLongObject *v;
1006 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001007 Py_ssize_t i;
1008 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001009
1010 if (vv == NULL || !PyLong_Check(vv)) {
1011 PyErr_BadInternalCall();
1012 return (unsigned long) -1;
1013 }
1014 v = (PyLongObject *)vv;
1015 i = v->ob_size;
1016 sign = 1;
1017 x = 0;
1018 if (i < 0) {
1019 sign = -1;
1020 i = -i;
1021 }
1022 while (--i >= 0) {
Mark Dickinson71adc932009-09-28 16:52:40 +00001023 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001024 }
1025 return x * sign;
1026}
Mark Dickinsona36507c2010-01-30 10:08:33 +00001027
1028/* Get a C long long int from a Python long or Python int object.
1029 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1030 on the sign of the result. Otherwise *overflow is 0.
1031
1032 For other errors (e.g., type error), returns -1 and sets an error
1033 condition.
1034*/
1035
1036PY_LONG_LONG
1037PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1038{
1039 /* This version by Tim Peters */
1040 register PyLongObject *v;
1041 unsigned PY_LONG_LONG x, prev;
1042 PY_LONG_LONG res;
1043 Py_ssize_t i;
1044 int sign;
1045 int do_decref = 0; /* if nb_int was called */
1046
1047 *overflow = 0;
1048 if (vv == NULL) {
1049 PyErr_BadInternalCall();
1050 return -1;
1051 }
1052
1053 if (PyInt_Check(vv))
1054 return PyInt_AsLong(vv);
1055
1056 if (!PyLong_Check(vv)) {
1057 PyNumberMethods *nb;
1058 nb = vv->ob_type->tp_as_number;
1059 if (nb == NULL || nb->nb_int == NULL) {
1060 PyErr_SetString(PyExc_TypeError,
1061 "an integer is required");
1062 return -1;
1063 }
1064 vv = (*nb->nb_int) (vv);
1065 if (vv == NULL)
1066 return -1;
1067 do_decref = 1;
1068 if(PyInt_Check(vv)) {
1069 res = PyInt_AsLong(vv);
1070 goto exit;
1071 }
1072 if (!PyLong_Check(vv)) {
1073 Py_DECREF(vv);
1074 PyErr_SetString(PyExc_TypeError,
1075 "nb_int should return int object");
1076 return -1;
1077 }
1078 }
1079
1080 res = -1;
1081 v = (PyLongObject *)vv;
1082 i = Py_SIZE(v);
1083
1084 switch (i) {
1085 case -1:
1086 res = -(sdigit)v->ob_digit[0];
1087 break;
1088 case 0:
1089 res = 0;
1090 break;
1091 case 1:
1092 res = v->ob_digit[0];
1093 break;
1094 default:
1095 sign = 1;
1096 x = 0;
1097 if (i < 0) {
1098 sign = -1;
1099 i = -(i);
1100 }
1101 while (--i >= 0) {
1102 prev = x;
1103 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1104 if ((x >> PyLong_SHIFT) != prev) {
1105 *overflow = sign;
1106 goto exit;
1107 }
1108 }
1109 /* Haven't lost any bits, but casting to long requires extra
1110 * care (see comment above).
1111 */
1112 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1113 res = (PY_LONG_LONG)x * sign;
1114 }
1115 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1116 res = PY_LLONG_MIN;
1117 }
1118 else {
1119 *overflow = sign;
1120 /* res is already set to -1 */
1121 }
1122 }
1123 exit:
1124 if (do_decref) {
1125 Py_DECREF(vv);
1126 }
1127 return res;
1128}
1129
Tim Petersd1a7da62001-06-13 00:35:57 +00001130#undef IS_LITTLE_ENDIAN
1131
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001132#endif /* HAVE_LONG_LONG */
1133
Neil Schemenauerba872e22001-01-04 01:46:03 +00001134
1135static int
1136convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001137 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001138 *a = (PyLongObject *) v;
1139 Py_INCREF(v);
1140 }
1141 else if (PyInt_Check(v)) {
1142 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1143 }
1144 else {
1145 return 0;
1146 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001147 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001148 *b = (PyLongObject *) w;
1149 Py_INCREF(w);
1150 }
1151 else if (PyInt_Check(w)) {
1152 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1153 }
1154 else {
1155 Py_DECREF(*a);
1156 return 0;
1157 }
1158 return 1;
1159}
1160
1161#define CONVERT_BINOP(v, w, a, b) \
1162 if (!convert_binop(v, w, a, b)) { \
1163 Py_INCREF(Py_NotImplemented); \
1164 return Py_NotImplemented; \
1165 }
1166
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001167/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1168 2**k if d is nonzero, else 0. */
1169
1170static const unsigned char BitLengthTable[32] = {
1171 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1172 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
1173};
1174
1175static int
1176bits_in_digit(digit d)
1177{
1178 int d_bits = 0;
1179 while (d >= 32) {
1180 d_bits += 6;
1181 d >>= 6;
1182 }
1183 d_bits += (int)BitLengthTable[d];
1184 return d_bits;
1185}
1186
Tim Peters877a2122002-08-12 05:09:36 +00001187/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1188 * is modified in place, by adding y to it. Carries are propagated as far as
1189 * x[m-1], and the remaining carry (0 or 1) is returned.
1190 */
1191static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001192v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001193{
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001194 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001195 digit carry = 0;
1196
1197 assert(m >= n);
1198 for (i = 0; i < n; ++i) {
1199 carry += x[i] + y[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001200 x[i] = carry & PyLong_MASK;
1201 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001202 assert((carry & 1) == carry);
1203 }
1204 for (; carry && i < m; ++i) {
1205 carry += x[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001206 x[i] = carry & PyLong_MASK;
1207 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001208 assert((carry & 1) == carry);
1209 }
1210 return carry;
1211}
1212
1213/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1214 * is modified in place, by subtracting y from it. Borrows are propagated as
1215 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1216 */
1217static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001218v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001219{
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001220 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001221 digit borrow = 0;
1222
1223 assert(m >= n);
1224 for (i = 0; i < n; ++i) {
1225 borrow = x[i] - y[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001226 x[i] = borrow & PyLong_MASK;
1227 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001228 borrow &= 1; /* keep only 1 sign bit */
1229 }
1230 for (; borrow && i < m; ++i) {
1231 borrow = x[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001232 x[i] = borrow & PyLong_MASK;
1233 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001234 borrow &= 1;
1235 }
1236 return borrow;
1237}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001238
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001239/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1240 * result in z[0:m], and return the d bits shifted out of the top.
1241 */
1242static digit
1243v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001244{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001245 Py_ssize_t i;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001246 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001247
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001248 assert(0 <= d && d < PyLong_SHIFT);
1249 for (i=0; i < m; i++) {
1250 twodigits acc = (twodigits)a[i] << d | carry;
1251 z[i] = (digit)acc & PyLong_MASK;
1252 carry = (digit)(acc >> PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001253 }
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001254 return carry;
1255}
1256
1257/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1258 * result in z[0:m], and return the d bits shifted out of the bottom.
1259 */
1260static digit
1261v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1262{
1263 Py_ssize_t i;
1264 digit carry = 0;
1265 digit mask = ((digit)1 << d) - 1U;
1266
1267 assert(0 <= d && d < PyLong_SHIFT);
1268 for (i=m; i-- > 0;) {
1269 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1270 carry = (digit)acc & mask;
1271 z[i] = (digit)(acc >> d);
1272 }
1273 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001274}
1275
Tim Peters212e6142001-07-14 12:23:19 +00001276/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1277 in pout, and returning the remainder. pin and pout point at the LSD.
1278 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Eric Smith5e527eb2008-02-10 01:36:53 +00001279 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001280 immutable. */
1281
1282static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001283inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001284{
1285 twodigits rem = 0;
1286
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001287 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001288 pin += size;
1289 pout += size;
1290 while (--size >= 0) {
1291 digit hi;
Mark Dickinson71adc932009-09-28 16:52:40 +00001292 rem = (rem << PyLong_SHIFT) | *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001293 *--pout = hi = (digit)(rem / n);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001294 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001295 }
1296 return (digit)rem;
1297}
1298
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001299/* Divide a long integer by a digit, returning both the quotient
1300 (as function result) and the remainder (through *prem).
1301 The sign of a is ignored; n should not be zero. */
1302
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001303static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001304divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001305{
Christian Heimese93237d2007-12-19 02:37:44 +00001306 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001307 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001308
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001309 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001310 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001311 if (z == NULL)
1312 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001313 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001314 return long_normalize(z);
1315}
1316
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001317/* Convert a long integer to a base 10 string. Returns a new non-shared
1318 string. (Return value is non-shared so that callers can modify the
1319 returned value if necessary.) */
1320
1321static PyObject *
1322long_to_decimal_string(PyObject *aa, int addL)
1323{
1324 PyLongObject *scratch, *a;
1325 PyObject *str;
1326 Py_ssize_t size, strlen, size_a, i, j;
1327 digit *pout, *pin, rem, tenpow;
1328 char *p;
1329 int negative;
1330
1331 a = (PyLongObject *)aa;
1332 if (a == NULL || !PyLong_Check(a)) {
1333 PyErr_BadInternalCall();
1334 return NULL;
1335 }
1336 size_a = ABS(Py_SIZE(a));
1337 negative = Py_SIZE(a) < 0;
1338
1339 /* quick and dirty upper bound for the number of digits
1340 required to express a in base _PyLong_DECIMAL_BASE:
1341
1342 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
1343
1344 But log2(a) < size_a * PyLong_SHIFT, and
1345 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1346 > 3 * _PyLong_DECIMAL_SHIFT
1347 */
1348 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1349 PyErr_SetString(PyExc_OverflowError,
1350 "long is too large to format");
1351 return NULL;
1352 }
1353 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1354 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1355 scratch = _PyLong_New(size);
1356 if (scratch == NULL)
1357 return NULL;
1358
1359 /* convert array of base _PyLong_BASE digits in pin to an array of
1360 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1361 Volume 2 (3rd edn), section 4.4, Method 1b). */
1362 pin = a->ob_digit;
1363 pout = scratch->ob_digit;
1364 size = 0;
1365 for (i = size_a; --i >= 0; ) {
1366 digit hi = pin[i];
1367 for (j = 0; j < size; j++) {
1368 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
Mark Dickinson40ee8612009-09-21 16:16:44 +00001369 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1370 pout[j] = (digit)(z - (twodigits)hi *
1371 _PyLong_DECIMAL_BASE);
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001372 }
1373 while (hi) {
1374 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1375 hi /= _PyLong_DECIMAL_BASE;
1376 }
1377 /* check for keyboard interrupt */
1378 SIGCHECK({
1379 Py_DECREF(scratch);
1380 return NULL;
1381 })
1382 }
1383 /* pout should have at least one digit, so that the case when a = 0
1384 works correctly */
1385 if (size == 0)
1386 pout[size++] = 0;
1387
1388 /* calculate exact length of output string, and allocate */
1389 strlen = (addL != 0) + negative +
1390 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1391 tenpow = 10;
1392 rem = pout[size-1];
1393 while (rem >= tenpow) {
1394 tenpow *= 10;
1395 strlen++;
1396 }
1397 str = PyString_FromStringAndSize(NULL, strlen);
1398 if (str == NULL) {
1399 Py_DECREF(scratch);
1400 return NULL;
1401 }
1402
1403 /* fill the string right-to-left */
1404 p = PyString_AS_STRING(str) + strlen;
1405 *p = '\0';
1406 if (addL)
1407 *--p = 'L';
1408 /* pout[0] through pout[size-2] contribute exactly
1409 _PyLong_DECIMAL_SHIFT digits each */
1410 for (i=0; i < size - 1; i++) {
1411 rem = pout[i];
1412 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1413 *--p = '0' + rem % 10;
1414 rem /= 10;
1415 }
1416 }
1417 /* pout[size-1]: always produce at least one decimal digit */
1418 rem = pout[i];
1419 do {
1420 *--p = '0' + rem % 10;
1421 rem /= 10;
1422 } while (rem != 0);
1423
1424 /* and sign */
1425 if (negative)
1426 *--p = '-';
1427
1428 /* check we've counted correctly */
1429 assert(p == PyString_AS_STRING(str));
1430 Py_DECREF(scratch);
1431 return (PyObject *)str;
1432}
1433
Eric Smith5e527eb2008-02-10 01:36:53 +00001434/* Convert the long to a string object with given base,
1435 appending a base prefix of 0[box] if base is 2, 8 or 16.
1436 Add a trailing "L" if addL is non-zero.
1437 If newstyle is zero, then use the pre-2.6 behavior of octal having
1438 a leading "0", instead of the prefix "0o" */
1439PyAPI_FUNC(PyObject *)
1440_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001441{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001442 register PyLongObject *a = (PyLongObject *)aa;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001443 PyStringObject *str;
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001444 Py_ssize_t i, sz;
Neal Norwitzc09efa82006-07-23 07:53:14 +00001445 Py_ssize_t size_a;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001446 char *p;
1447 int bits;
1448 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001449
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001450 if (base == 10)
1451 return long_to_decimal_string((PyObject *)a, addL);
1452
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001453 if (a == NULL || !PyLong_Check(a)) {
1454 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001455 return NULL;
1456 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001457 assert(base >= 2 && base <= 36);
Christian Heimese93237d2007-12-19 02:37:44 +00001458 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001459
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001460 /* Compute a rough upper bound for the length of the string */
1461 i = base;
1462 bits = 0;
1463 while (i > 1) {
1464 ++bits;
1465 i >>= 1;
1466 }
Armin Rigo7ccbca92006-10-04 12:17:45 +00001467 i = 5 + (addL ? 1 : 0);
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001468 /* ensure we don't get signed overflow in sz calculation */
1469 if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00001470 PyErr_SetString(PyExc_OverflowError,
1471 "long is too large to format");
1472 return NULL;
1473 }
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001474 sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;
1475 assert(sz >= 0);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001476 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001477 if (str == NULL)
1478 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001479 p = PyString_AS_STRING(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001480 *p = '\0';
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001481 if (addL)
1482 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001483 if (a->ob_size < 0)
1484 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001485
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001486 if (a->ob_size == 0) {
1487 *--p = '0';
1488 }
1489 else if ((base & (base - 1)) == 0) {
1490 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001491 twodigits accum = 0;
1492 int accumbits = 0; /* # of bits in accum */
1493 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001494 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001495 while ((i >>= 1) > 1)
1496 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001497
1498 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001499 accum |= (twodigits)a->ob_digit[i] << accumbits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001500 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001501 assert(accumbits >= basebits);
1502 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001503 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001504 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001505 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001506 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001507 accumbits -= basebits;
1508 accum >>= basebits;
1509 } while (i < size_a-1 ? accumbits >= basebits :
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001510 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001511 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001512 }
1513 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001514 /* Not 0, and base not a power of 2. Divide repeatedly by
1515 base, but for speed use the highest power of base that
1516 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001517 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001518 digit *pin = a->ob_digit;
1519 PyLongObject *scratch;
1520 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001521 digit powbase = base; /* powbase == base ** power */
1522 int power = 1;
1523 for (;;) {
Mark Dickinsonb6464872009-02-25 20:29:50 +00001524 twodigits newpow = powbase * (twodigits)base;
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001525 if (newpow >> PyLong_SHIFT)
1526 /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001527 break;
1528 powbase = (digit)newpow;
1529 ++power;
1530 }
Tim Peters212e6142001-07-14 12:23:19 +00001531
1532 /* Get a scratch area for repeated division. */
1533 scratch = _PyLong_New(size);
1534 if (scratch == NULL) {
1535 Py_DECREF(str);
1536 return NULL;
1537 }
1538
1539 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001540 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001541 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001542 digit rem = inplace_divrem1(scratch->ob_digit,
1543 pin, size, powbase);
1544 pin = scratch->ob_digit; /* no need to use a again */
1545 if (pin[size - 1] == 0)
1546 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001547 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001548 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001549 Py_DECREF(str);
1550 return NULL;
1551 })
Tim Peters212e6142001-07-14 12:23:19 +00001552
1553 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001554 assert(ntostore > 0);
1555 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001556 digit nextrem = (digit)(rem / base);
1557 char c = (char)(rem - nextrem * base);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001558 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001559 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001560 *--p = c;
1561 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001562 --ntostore;
1563 /* Termination is a bit delicate: must not
1564 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001565 remaining quotient and rem are both 0. */
1566 } while (ntostore && (size || rem));
1567 } while (size != 0);
1568 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001569 }
1570
Eric Smith5e527eb2008-02-10 01:36:53 +00001571 if (base == 2) {
1572 *--p = 'b';
1573 *--p = '0';
1574 }
1575 else if (base == 8) {
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001576 if (newstyle) {
Eric Smith5e527eb2008-02-10 01:36:53 +00001577 *--p = 'o';
Guido van Rossum2c475421992-08-14 15:13:07 +00001578 *--p = '0';
Eric Smith5e527eb2008-02-10 01:36:53 +00001579 }
1580 else
1581 if (size_a != 0)
1582 *--p = '0';
Guido van Rossum2c475421992-08-14 15:13:07 +00001583 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001584 else if (base == 16) {
1585 *--p = 'x';
1586 *--p = '0';
1587 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001588 else if (base != 10) {
1589 *--p = '#';
1590 *--p = '0' + base%10;
1591 if (base > 10)
1592 *--p = '0' + base/10;
1593 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001594 if (sign)
1595 *--p = sign;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001596 if (p != PyString_AS_STRING(str)) {
1597 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001598 assert(p > q);
1599 do {
1600 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001601 q--;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001602 _PyString_Resize((PyObject **)&str,
1603 (Py_ssize_t) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001604 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001605 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001606}
1607
Tim Petersda53afa2006-05-25 17:34:03 +00001608/* Table of digit values for 8-bit string -> integer conversion.
1609 * '0' maps to 0, ..., '9' maps to 9.
1610 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1611 * All other indices map to 37.
1612 * Note that when converting a base B string, a char c is a legitimate
1613 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1614 */
1615int _PyLong_DigitValue[256] = {
Tim Peters696cf432006-05-24 21:10:40 +00001616 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1617 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1618 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1619 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1620 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1621 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1622 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1623 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1624 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1625 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1626 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1627 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1628 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1629 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1630 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1631 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Tim Peters696cf432006-05-24 21:10:40 +00001632};
1633
1634/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001635 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1636 * non-digit (which may be *str!). A normalized long is returned.
1637 * The point to this routine is that it takes time linear in the number of
1638 * string characters.
1639 */
1640static PyLongObject *
1641long_from_binary_base(char **str, int base)
1642{
1643 char *p = *str;
1644 char *start = p;
1645 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001646 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001647 PyLongObject *z;
1648 twodigits accum;
1649 int bits_in_accum;
1650 digit *pdigit;
1651
1652 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1653 n = base;
1654 for (bits_per_char = -1; n; ++bits_per_char)
1655 n >>= 1;
1656 /* n <- total # of bits needed, while setting p to end-of-string */
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001657 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001658 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001659 *str = p;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001660 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1661 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001662 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001663 PyErr_SetString(PyExc_ValueError,
1664 "long string too large to convert");
1665 return NULL;
1666 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001667 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001668 z = _PyLong_New(n);
1669 if (z == NULL)
1670 return NULL;
1671 /* Read string from right, and fill in long from left; i.e.,
1672 * from least to most significant in both.
1673 */
1674 accum = 0;
1675 bits_in_accum = 0;
1676 pdigit = z->ob_digit;
1677 while (--p >= start) {
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001678 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001679 assert(k >= 0 && k < base);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001680 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00001681 bits_in_accum += bits_per_char;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001682 if (bits_in_accum >= PyLong_SHIFT) {
1683 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001684 assert(pdigit - z->ob_digit <= n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001685 accum >>= PyLong_SHIFT;
1686 bits_in_accum -= PyLong_SHIFT;
1687 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001688 }
1689 }
1690 if (bits_in_accum) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001691 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001692 *pdigit++ = (digit)accum;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001693 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001694 }
1695 while (pdigit - z->ob_digit < n)
1696 *pdigit++ = 0;
1697 return long_normalize(z);
1698}
1699
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001700PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001701PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001702{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001703 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001704 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001705 PyLongObject *z;
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001706 PyObject *strobj, *strrepr;
1707 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001708
Guido van Rossum472c04f1996-12-05 21:57:21 +00001709 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001710 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001711 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001712 return NULL;
1713 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001714 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001715 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001716 if (*str == '+')
1717 ++str;
1718 else if (*str == '-') {
1719 ++str;
1720 sign = -1;
1721 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001722 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001723 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001724 if (base == 0) {
Eric Smith9ff19b52008-03-17 17:32:20 +00001725 /* No base given. Deduce the base from the contents
1726 of the string */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001727 if (str[0] != '0')
1728 base = 10;
1729 else if (str[1] == 'x' || str[1] == 'X')
1730 base = 16;
Eric Smith9ff19b52008-03-17 17:32:20 +00001731 else if (str[1] == 'o' || str[1] == 'O')
1732 base = 8;
1733 else if (str[1] == 'b' || str[1] == 'B')
1734 base = 2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001735 else
Eric Smith9ff19b52008-03-17 17:32:20 +00001736 /* "old" (C-style) octal literal, still valid in
1737 2.x, although illegal in 3.x */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001738 base = 8;
1739 }
Eric Smith9ff19b52008-03-17 17:32:20 +00001740 /* Whether or not we were deducing the base, skip leading chars
1741 as needed */
1742 if (str[0] == '0' &&
1743 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1744 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1745 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001746 str += 2;
Tim Peters696cf432006-05-24 21:10:40 +00001747
Guido van Rossume6762971998-06-22 03:54:46 +00001748 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001749 if ((base & (base - 1)) == 0)
1750 z = long_from_binary_base(&str, base);
1751 else {
Tim Peters696cf432006-05-24 21:10:40 +00001752/***
1753Binary bases can be converted in time linear in the number of digits, because
1754Python's representation base is binary. Other bases (including decimal!) use
1755the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001756
Tim Peters696cf432006-05-24 21:10:40 +00001757First some math: the largest integer that can be expressed in N base-B digits
1758is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1759case number of Python digits needed to hold it is the smallest integer n s.t.
1760
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001761 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1762 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1763 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001764
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001765The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute
Tim Peters696cf432006-05-24 21:10:40 +00001766this quickly. A Python long with that much space is reserved near the start,
1767and the result is computed into it.
1768
1769The input string is actually treated as being in base base**i (i.e., i digits
1770are processed at a time), where two more static arrays hold:
1771
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001772 convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE
Tim Peters696cf432006-05-24 21:10:40 +00001773 convmultmax_base[base] = base ** convwidth_base[base]
1774
1775The first of these is the largest i such that i consecutive input digits
1776must fit in a single Python digit. The second is effectively the input
1777base we're really using.
1778
1779Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1780convmultmax_base[base], the result is "simply"
1781
1782 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1783
1784where B = convmultmax_base[base].
Tim Peters9faa3ed2006-05-30 15:53:34 +00001785
1786Error analysis: as above, the number of Python digits `n` needed is worst-
1787case
1788
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001789 n >= N * log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001790
1791where `N` is the number of input digits in base `B`. This is computed via
1792
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001793 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001794
1795below. Two numeric concerns are how much space this can waste, and whether
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001796the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15,
Tim Peters9faa3ed2006-05-30 15:53:34 +00001797which is the default (and it's unlikely anyone changes that).
1798
1799Waste isn't a problem: provided the first input digit isn't 0, the difference
1800between the worst-case input with N digits and the smallest input with N
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001801digits is about a factor of B, but B is small compared to PyLong_BASE so at most
Tim Peters9faa3ed2006-05-30 15:53:34 +00001802one allocated Python digit can remain unused on that count. If
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001803N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001804and adding 1 returns a result 1 larger than necessary. However, that can't
1805happen: whenever B is a power of 2, long_from_binary_base() is called
1806instead, and it's impossible for B**i to be an integer power of 2**15 when
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001807B is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be
Tim Peters9faa3ed2006-05-30 15:53:34 +00001808an exact integer when B is not a power of 2, since B**i has a prime factor
1809other than 2 in that case, but (2**15)**j's only prime factor is 2).
1810
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001811The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001812is a little bit larger than an exact integer, but due to roundoff errors (in
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001813computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001814yields a numeric result a little less than that integer. Unfortunately, "how
1815close can a transcendental function get to an integer over some range?"
1816questions are generally theoretically intractable. Computer analysis via
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001817continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued
Tim Peters9faa3ed2006-05-30 15:53:34 +00001818fractions, giving a sequence i/j of "the best" rational approximations. Then
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001819j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001820we can get very close to being in trouble, but very rarely. For example,
182176573 is a denominator in one of the continued-fraction approximations to
1822log(10)/log(2**15), and indeed:
1823
1824 >>> log(10)/log(2**15)*76573
1825 16958.000000654003
1826
1827is very close to an integer. If we were working with IEEE single-precision,
1828rounding errors could kill us. Finding worst cases in IEEE double-precision
1829requires better-than-double-precision log() functions, and Tim didn't bother.
1830Instead the code checks to see whether the allocated space is enough as each
1831new Python digit is added, and copies the whole thing to a larger long if not.
1832This should happen extremely rarely, and in fact I don't have a test case
1833that triggers it(!). Instead the code was tested by artificially allocating
1834just 1 digit at the start, so that the copying code was exercised for every
1835digit beyond the first.
Tim Peters696cf432006-05-24 21:10:40 +00001836***/
1837 register twodigits c; /* current input character */
1838 Py_ssize_t size_z;
1839 int i;
1840 int convwidth;
1841 twodigits convmultmax, convmult;
1842 digit *pz, *pzstop;
1843 char* scan;
1844
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001845 static double log_base_PyLong_BASE[37] = {0.0e0,};
Tim Peters696cf432006-05-24 21:10:40 +00001846 static int convwidth_base[37] = {0,};
1847 static twodigits convmultmax_base[37] = {0,};
1848
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001849 if (log_base_PyLong_BASE[base] == 0.0) {
Tim Peters696cf432006-05-24 21:10:40 +00001850 twodigits convmax = base;
1851 int i = 1;
1852
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001853 log_base_PyLong_BASE[base] = log((double)base) /
1854 log((double)PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001855 for (;;) {
1856 twodigits next = convmax * base;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001857 if (next > PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001858 break;
1859 convmax = next;
1860 ++i;
1861 }
1862 convmultmax_base[base] = convmax;
1863 assert(i > 0);
1864 convwidth_base[base] = i;
1865 }
1866
1867 /* Find length of the string of numeric characters. */
1868 scan = str;
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001869 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Tim Peters696cf432006-05-24 21:10:40 +00001870 ++scan;
1871
1872 /* Create a long object that can contain the largest possible
1873 * integer with this base and length. Note that there's no
1874 * need to initialize z->ob_digit -- no slot is read up before
1875 * being stored into.
1876 */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001877 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001878 /* Uncomment next line to test exceedingly rare copy code */
1879 /* size_z = 1; */
Tim Peters696cf432006-05-24 21:10:40 +00001880 assert(size_z > 0);
1881 z = _PyLong_New(size_z);
1882 if (z == NULL)
1883 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00001884 Py_SIZE(z) = 0;
Tim Peters696cf432006-05-24 21:10:40 +00001885
1886 /* `convwidth` consecutive input digits are treated as a single
1887 * digit in base `convmultmax`.
1888 */
1889 convwidth = convwidth_base[base];
1890 convmultmax = convmultmax_base[base];
1891
1892 /* Work ;-) */
1893 while (str < scan) {
1894 /* grab up to convwidth digits from the input string */
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001895 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Tim Peters696cf432006-05-24 21:10:40 +00001896 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1897 c = (twodigits)(c * base +
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001898 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001899 assert(c < PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001900 }
1901
1902 convmult = convmultmax;
1903 /* Calculate the shift only if we couldn't get
1904 * convwidth digits.
1905 */
1906 if (i != convwidth) {
1907 convmult = base;
1908 for ( ; i > 1; --i)
1909 convmult *= base;
1910 }
1911
1912 /* Multiply z by convmult, and add c. */
1913 pz = z->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +00001914 pzstop = pz + Py_SIZE(z);
Tim Peters696cf432006-05-24 21:10:40 +00001915 for (; pz < pzstop; ++pz) {
1916 c += (twodigits)*pz * convmult;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001917 *pz = (digit)(c & PyLong_MASK);
1918 c >>= PyLong_SHIFT;
Tim Peters696cf432006-05-24 21:10:40 +00001919 }
1920 /* carry off the current end? */
1921 if (c) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001922 assert(c < PyLong_BASE);
Christian Heimese93237d2007-12-19 02:37:44 +00001923 if (Py_SIZE(z) < size_z) {
Tim Peters9faa3ed2006-05-30 15:53:34 +00001924 *pz = (digit)c;
Christian Heimese93237d2007-12-19 02:37:44 +00001925 ++Py_SIZE(z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001926 }
1927 else {
1928 PyLongObject *tmp;
1929 /* Extremely rare. Get more space. */
Christian Heimese93237d2007-12-19 02:37:44 +00001930 assert(Py_SIZE(z) == size_z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001931 tmp = _PyLong_New(size_z + 1);
1932 if (tmp == NULL) {
1933 Py_DECREF(z);
1934 return NULL;
1935 }
1936 memcpy(tmp->ob_digit,
1937 z->ob_digit,
1938 sizeof(digit) * size_z);
1939 Py_DECREF(z);
1940 z = tmp;
1941 z->ob_digit[size_z] = (digit)c;
1942 ++size_z;
1943 }
Tim Peters696cf432006-05-24 21:10:40 +00001944 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001945 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001946 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001947 if (z == NULL)
1948 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001949 if (str == start)
1950 goto onError;
Tim Peters696cf432006-05-24 21:10:40 +00001951 if (sign < 0)
Christian Heimese93237d2007-12-19 02:37:44 +00001952 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001953 if (*str == 'L' || *str == 'l')
1954 str++;
1955 while (*str && isspace(Py_CHARMASK(*str)))
1956 str++;
1957 if (*str != '\0')
1958 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001959 if (pend)
1960 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001961 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001962
1963 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001964 Py_XDECREF(z);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001965 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001966 strobj = PyString_FromStringAndSize(orig_str, slen);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001967 if (strobj == NULL)
1968 return NULL;
1969 strrepr = PyObject_Repr(strobj);
1970 Py_DECREF(strobj);
1971 if (strrepr == NULL)
1972 return NULL;
1973 PyErr_Format(PyExc_ValueError,
1974 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001975 base, PyString_AS_STRING(strrepr));
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001976 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001977 return NULL;
1978}
1979
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001980#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001981PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001982PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001983{
Walter Dörwald07e14762002-11-06 16:15:14 +00001984 PyObject *result;
Anthony Baxter377be112006-04-11 06:54:30 +00001985 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001986
Walter Dörwald07e14762002-11-06 16:15:14 +00001987 if (buffer == NULL)
1988 return NULL;
1989
1990 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1991 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001992 return NULL;
1993 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001994 result = PyLong_FromString(buffer, NULL, base);
1995 PyMem_FREE(buffer);
1996 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001997}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001998#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001999
Tim Peters9f688bf2000-07-07 15:53:28 +00002000/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002001static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002002 (PyLongObject *, PyLongObject *, PyLongObject **);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002003static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002004
2005/* Long division with remainder, top-level routine */
2006
Guido van Rossume32e0141992-01-19 16:31:05 +00002007static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002008long_divrem(PyLongObject *a, PyLongObject *b,
2009 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002010{
Christian Heimese93237d2007-12-19 02:37:44 +00002011 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002012 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002013
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002014 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002015 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00002016 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002017 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002018 }
2019 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002020 (size_a == size_b &&
2021 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002022 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002023 *pdiv = _PyLong_New(0);
Georg Brandlc02e1312007-04-11 17:16:24 +00002024 if (*pdiv == NULL)
2025 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002026 Py_INCREF(a);
2027 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002028 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002029 }
2030 if (size_b == 1) {
2031 digit rem = 0;
2032 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002033 if (z == NULL)
2034 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002035 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Georg Brandlc02e1312007-04-11 17:16:24 +00002036 if (*prem == NULL) {
2037 Py_DECREF(z);
2038 return -1;
2039 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002040 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002041 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002042 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002043 if (z == NULL)
2044 return -1;
2045 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002046 /* Set the signs.
2047 The quotient z has the sign of a*b;
2048 the remainder r has the sign of a,
2049 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00002050 if ((a->ob_size < 0) != (b->ob_size < 0))
2051 z->ob_size = -(z->ob_size);
2052 if (a->ob_size < 0 && (*prem)->ob_size != 0)
2053 (*prem)->ob_size = -((*prem)->ob_size);
2054 *pdiv = z;
2055 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002056}
2057
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002058/* Unsigned long division with remainder -- the algorithm. The arguments v1
2059 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002060
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002061static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002062x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002063{
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002064 PyLongObject *v, *w, *a;
2065 Py_ssize_t i, k, size_v, size_w;
2066 int d;
2067 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2068 twodigits vv;
2069 sdigit zhi;
2070 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002071
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002072 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2073 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2074 handle the special case when the initial estimate q for a quotient
2075 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2076 that won't overflow a digit. */
2077
2078 /* allocate space; w will also be used to hold the final remainder */
2079 size_v = ABS(Py_SIZE(v1));
2080 size_w = ABS(Py_SIZE(w1));
2081 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2082 v = _PyLong_New(size_v+1);
2083 if (v == NULL) {
2084 *prem = NULL;
2085 return NULL;
2086 }
2087 w = _PyLong_New(size_w);
2088 if (w == NULL) {
2089 Py_DECREF(v);
2090 *prem = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002091 return NULL;
2092 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002093
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002094 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2095 shift v1 left by the same amount. Results go into w and v. */
2096 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2097 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2098 assert(carry == 0);
2099 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2100 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2101 v->ob_digit[size_v] = carry;
2102 size_v++;
2103 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002104
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002105 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2106 at most (and usually exactly) k = size_v - size_w digits. */
Neal Norwitzc6a989a2006-05-10 06:57:58 +00002107 k = size_v - size_w;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002108 assert(k >= 0);
2109 a = _PyLong_New(k);
2110 if (a == NULL) {
2111 Py_DECREF(w);
2112 Py_DECREF(v);
2113 *prem = NULL;
2114 return NULL;
2115 }
2116 v0 = v->ob_digit;
2117 w0 = w->ob_digit;
2118 wm1 = w0[size_w-1];
2119 wm2 = w0[size_w-2];
2120 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2121 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2122 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002123
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002124 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002125 Py_DECREF(a);
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002126 Py_DECREF(w);
2127 Py_DECREF(v);
2128 *prem = NULL;
2129 return NULL;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002130 })
Tim Peters5af4e6c2002-08-12 02:31:19 +00002131
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002132 /* estimate quotient digit q; may overestimate by 1 (rare) */
2133 vtop = vk[size_w];
2134 assert(vtop <= wm1);
2135 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2136 q = (digit)(vv / wm1);
2137 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2138 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2139 | vk[size_w-2])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002140 --q;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002141 r += wm1;
2142 if (r >= PyLong_BASE)
2143 break;
2144 }
2145 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002146
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002147 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2148 zhi = 0;
2149 for (i = 0; i < size_w; ++i) {
2150 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2151 -PyLong_BASE * q <= z < PyLong_BASE */
2152 z = (sdigit)vk[i] + zhi -
2153 (stwodigits)q * (stwodigits)w0[i];
2154 vk[i] = (digit)z & PyLong_MASK;
2155 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
2156 z, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002157 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002158
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002159 /* add w back if q was too large (this branch taken rarely) */
2160 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2161 if ((sdigit)vtop + zhi < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002162 carry = 0;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002163 for (i = 0; i < size_w; ++i) {
2164 carry += vk[i] + w0[i];
2165 vk[i] = carry & PyLong_MASK;
2166 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002167 }
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002168 --q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002169 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002170
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002171 /* store quotient digit */
2172 assert(q < PyLong_BASE);
2173 *--ak = q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002174 }
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002175
2176 /* unshift remainder; we reuse w to store the result */
2177 carry = v_rshift(w0, v0, size_w, d);
2178 assert(carry==0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002179 Py_DECREF(v);
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002180
2181 *prem = long_normalize(w);
2182 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002183}
2184
Mark Dickinsond3e32322010-01-02 14:45:40 +00002185/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2186 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2187 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2188 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2189 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2190 -1.0. */
2191
2192/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2193#if DBL_MANT_DIG == 53
2194#define EXP2_DBL_MANT_DIG 9007199254740992.0
2195#else
2196#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2197#endif
2198
2199double
2200_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2201{
2202 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2203 /* See below for why x_digits is always large enough. */
2204 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2205 double dx;
2206 /* Correction term for round-half-to-even rounding. For a digit x,
2207 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2208 multiple of 4, rounding ties to a multiple of 8. */
2209 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
2210
2211 a_size = ABS(Py_SIZE(a));
2212 if (a_size == 0) {
2213 /* Special case for 0: significand 0.0, exponent 0. */
2214 *e = 0;
2215 return 0.0;
2216 }
2217 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2218 /* The following is an overflow-free version of the check
2219 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2220 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2221 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2222 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
2223 goto overflow;
2224 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
2225
2226 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2227 (shifting left if a_bits <= DBL_MANT_DIG + 2).
2228
2229 Number of digits needed for result: write // for floor division.
2230 Then if shifting left, we end up using
2231
2232 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
2233
2234 digits. If shifting right, we use
2235
2236 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
2237
2238 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2239 the inequalities
2240
2241 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2242 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2243 1 + (m - n - 1) // PyLong_SHIFT,
2244
2245 valid for any integers m and n, we find that x_size satisfies
2246
2247 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
2248
2249 in both cases.
2250 */
2251 if (a_bits <= DBL_MANT_DIG + 2) {
2252 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2253 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2254 x_size = 0;
2255 while (x_size < shift_digits)
2256 x_digits[x_size++] = 0;
2257 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2258 shift_bits);
2259 x_size += a_size;
2260 x_digits[x_size++] = rem;
2261 }
2262 else {
2263 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2264 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2265 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2266 a_size - shift_digits, shift_bits);
2267 x_size = a_size - shift_digits;
2268 /* For correct rounding below, we need the least significant
2269 bit of x to be 'sticky' for this shift: if any of the bits
2270 shifted out was nonzero, we set the least significant bit
2271 of x. */
2272 if (rem)
2273 x_digits[0] |= 1;
2274 else
2275 while (shift_digits > 0)
2276 if (a->ob_digit[--shift_digits]) {
2277 x_digits[0] |= 1;
2278 break;
2279 }
2280 }
Mark Dickinsonea7e5512010-04-06 18:58:54 +00002281 assert(1 <= x_size && x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
Mark Dickinsond3e32322010-01-02 14:45:40 +00002282
2283 /* Round, and convert to double. */
2284 x_digits[0] += half_even_correction[x_digits[0] & 7];
2285 dx = x_digits[--x_size];
2286 while (x_size > 0)
2287 dx = dx * PyLong_BASE + x_digits[--x_size];
2288
2289 /* Rescale; make correction if result is 1.0. */
2290 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2291 if (dx == 1.0) {
2292 if (a_bits == PY_SSIZE_T_MAX)
2293 goto overflow;
2294 dx = 0.5;
2295 a_bits += 1;
2296 }
2297
2298 *e = a_bits;
2299 return Py_SIZE(a) < 0 ? -dx : dx;
2300
2301 overflow:
2302 /* exponent > PY_SSIZE_T_MAX */
2303 PyErr_SetString(PyExc_OverflowError,
2304 "huge integer: number of bits overflows a Py_ssize_t");
2305 *e = 0;
2306 return -1.0;
2307}
2308
2309/* Get a C double from a long int object. Rounds to the nearest double,
2310 using the round-half-to-even rule in the case of a tie. */
2311
2312double
2313PyLong_AsDouble(PyObject *v)
2314{
2315 Py_ssize_t exponent;
2316 double x;
2317
2318 if (v == NULL || !PyLong_Check(v)) {
2319 PyErr_BadInternalCall();
2320 return -1.0;
2321 }
2322 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2323 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2324 PyErr_SetString(PyExc_OverflowError,
2325 "long int too large to convert to float");
2326 return -1.0;
2327 }
2328 return ldexp(x, exponent);
2329}
2330
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002331/* Methods */
2332
2333static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002334long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002335{
Christian Heimese93237d2007-12-19 02:37:44 +00002336 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002337}
2338
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002339static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002340long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002341{
Eric Smith5e527eb2008-02-10 01:36:53 +00002342 return _PyLong_Format(v, 10, 1, 0);
Fred Drake121ee271999-12-23 15:41:28 +00002343}
2344
2345static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002346long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00002347{
Eric Smith5e527eb2008-02-10 01:36:53 +00002348 return _PyLong_Format(v, 10, 0, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002349}
2350
2351static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002352long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002353{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002354 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002355
Christian Heimese93237d2007-12-19 02:37:44 +00002356 if (Py_SIZE(a) != Py_SIZE(b)) {
2357 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002358 sign = 0;
2359 else
Christian Heimese93237d2007-12-19 02:37:44 +00002360 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002361 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002362 else {
Christian Heimese93237d2007-12-19 02:37:44 +00002363 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002364 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2365 ;
2366 if (i < 0)
2367 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002368 else {
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00002369 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimese93237d2007-12-19 02:37:44 +00002370 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002371 sign = -sign;
2372 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002373 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002374 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002375}
2376
Guido van Rossum9bfef441993-03-29 10:43:31 +00002377static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002378long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002379{
Mark Dickinson6ffa4a22009-01-26 21:36:30 +00002380 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002381 Py_ssize_t i;
2382 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002383
2384 /* This is designed so that Python ints and longs with the
2385 same value hash to the same value, otherwise comparisons
2386 of mapping keys will turn out weird */
2387 i = v->ob_size;
2388 sign = 1;
2389 x = 0;
2390 if (i < 0) {
2391 sign = -1;
2392 i = -(i);
2393 }
Mark Dickinsona0eae032009-01-26 21:40:08 +00002394 /* The following loop produces a C unsigned long x such that x is
2395 congruent to the absolute value of v modulo ULONG_MAX. The
2396 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002397 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002398 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00002399 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002400 x += v->ob_digit[i];
Mark Dickinson6ffa4a22009-01-26 21:36:30 +00002401 /* If the addition above overflowed we compensate by
2402 incrementing. This preserves the value modulo
2403 ULONG_MAX. */
2404 if (x < v->ob_digit[i])
Facundo Batistad544df72007-09-19 15:10:06 +00002405 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002406 }
2407 x = x * sign;
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00002408 if (x == (unsigned long)-1)
2409 x = (unsigned long)-2;
2410 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002411}
2412
2413
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002414/* Add the absolute values of two long integers. */
2415
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002416static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002417x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002418{
Christian Heimese93237d2007-12-19 02:37:44 +00002419 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002420 PyLongObject *z;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00002421 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002422 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002423
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002424 /* Ensure a is the larger of the two: */
2425 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002426 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002427 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002428 size_a = size_b;
2429 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002430 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002431 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002432 if (z == NULL)
2433 return NULL;
2434 for (i = 0; i < size_b; ++i) {
2435 carry += a->ob_digit[i] + b->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002436 z->ob_digit[i] = carry & PyLong_MASK;
2437 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002438 }
2439 for (; i < size_a; ++i) {
2440 carry += a->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002441 z->ob_digit[i] = carry & PyLong_MASK;
2442 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002443 }
2444 z->ob_digit[i] = carry;
2445 return long_normalize(z);
2446}
2447
2448/* Subtract the absolute values of two integers. */
2449
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002450static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002451x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002452{
Christian Heimese93237d2007-12-19 02:37:44 +00002453 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002454 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002455 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002456 int sign = 1;
2457 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002458
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002459 /* Ensure a is the larger of the two: */
2460 if (size_a < size_b) {
2461 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002462 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002463 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002464 size_a = size_b;
2465 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002466 }
2467 else if (size_a == size_b) {
2468 /* Find highest digit where a and b differ: */
2469 i = size_a;
2470 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2471 ;
2472 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002473 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002474 if (a->ob_digit[i] < b->ob_digit[i]) {
2475 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002476 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002477 }
2478 size_a = size_b = i+1;
2479 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002480 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002481 if (z == NULL)
2482 return NULL;
2483 for (i = 0; i < size_b; ++i) {
2484 /* The following assumes unsigned arithmetic
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002485 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002486 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002487 z->ob_digit[i] = borrow & PyLong_MASK;
2488 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002489 borrow &= 1; /* Keep only one sign bit */
2490 }
2491 for (; i < size_a; ++i) {
2492 borrow = a->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002493 z->ob_digit[i] = borrow & PyLong_MASK;
2494 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002495 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002496 }
2497 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002498 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002499 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002500 return long_normalize(z);
2501}
2502
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002503static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002504long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002505{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002506 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002507
Neil Schemenauerba872e22001-01-04 01:46:03 +00002508 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2509
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002510 if (a->ob_size < 0) {
2511 if (b->ob_size < 0) {
2512 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002513 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002514 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002515 }
2516 else
2517 z = x_sub(b, a);
2518 }
2519 else {
2520 if (b->ob_size < 0)
2521 z = x_sub(a, b);
2522 else
2523 z = x_add(a, b);
2524 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002525 Py_DECREF(a);
2526 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002527 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002528}
2529
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002530static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002531long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002532{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002533 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002534
Neil Schemenauerba872e22001-01-04 01:46:03 +00002535 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2536
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002537 if (a->ob_size < 0) {
2538 if (b->ob_size < 0)
2539 z = x_sub(a, b);
2540 else
2541 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002542 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002543 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002544 }
2545 else {
2546 if (b->ob_size < 0)
2547 z = x_add(a, b);
2548 else
2549 z = x_sub(a, b);
2550 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002551 Py_DECREF(a);
2552 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002553 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002554}
2555
Tim Peters5af4e6c2002-08-12 02:31:19 +00002556/* Grade school multiplication, ignoring the signs.
2557 * Returns the absolute value of the product, or NULL if error.
2558 */
2559static PyLongObject *
2560x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002561{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002562 PyLongObject *z;
Christian Heimese93237d2007-12-19 02:37:44 +00002563 Py_ssize_t size_a = ABS(Py_SIZE(a));
2564 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002565 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002566
Tim Peters5af4e6c2002-08-12 02:31:19 +00002567 z = _PyLong_New(size_a + size_b);
2568 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002569 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002570
Christian Heimese93237d2007-12-19 02:37:44 +00002571 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002572 if (a == b) {
2573 /* Efficient squaring per HAC, Algorithm 14.16:
2574 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2575 * Gives slightly less than a 2x speedup when a == b,
2576 * via exploiting that each entry in the multiplication
2577 * pyramid appears twice (except for the size_a squares).
2578 */
2579 for (i = 0; i < size_a; ++i) {
2580 twodigits carry;
2581 twodigits f = a->ob_digit[i];
2582 digit *pz = z->ob_digit + (i << 1);
2583 digit *pa = a->ob_digit + i + 1;
2584 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002585
Tim Peters0973b992004-08-29 22:16:50 +00002586 SIGCHECK({
2587 Py_DECREF(z);
2588 return NULL;
2589 })
2590
2591 carry = *pz + f * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002592 *pz++ = (digit)(carry & PyLong_MASK);
2593 carry >>= PyLong_SHIFT;
2594 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002595
2596 /* Now f is added in twice in each column of the
2597 * pyramid it appears. Same as adding f<<1 once.
2598 */
2599 f <<= 1;
2600 while (pa < paend) {
2601 carry += *pz + *pa++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002602 *pz++ = (digit)(carry & PyLong_MASK);
2603 carry >>= PyLong_SHIFT;
2604 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002605 }
2606 if (carry) {
2607 carry += *pz;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002608 *pz++ = (digit)(carry & PyLong_MASK);
2609 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002610 }
2611 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002612 *pz += (digit)(carry & PyLong_MASK);
2613 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002614 }
Tim Peters0973b992004-08-29 22:16:50 +00002615 }
2616 else { /* a is not the same as b -- gradeschool long mult */
2617 for (i = 0; i < size_a; ++i) {
2618 twodigits carry = 0;
2619 twodigits f = a->ob_digit[i];
2620 digit *pz = z->ob_digit + i;
2621 digit *pb = b->ob_digit;
2622 digit *pbend = b->ob_digit + size_b;
2623
2624 SIGCHECK({
2625 Py_DECREF(z);
2626 return NULL;
2627 })
2628
2629 while (pb < pbend) {
2630 carry += *pz + *pb++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002631 *pz++ = (digit)(carry & PyLong_MASK);
2632 carry >>= PyLong_SHIFT;
2633 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002634 }
2635 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002636 *pz += (digit)(carry & PyLong_MASK);
2637 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002638 }
2639 }
Tim Peters44121a62002-08-12 06:17:58 +00002640 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002641}
2642
2643/* A helper for Karatsuba multiplication (k_mul).
2644 Takes a long "n" and an integer "size" representing the place to
2645 split, and sets low and high such that abs(n) == (high << size) + low,
2646 viewing the shift as being by digits. The sign bit is ignored, and
2647 the return values are >= 0.
2648 Returns 0 on success, -1 on failure.
2649*/
2650static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002651kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002652{
2653 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002654 Py_ssize_t size_lo, size_hi;
Christian Heimese93237d2007-12-19 02:37:44 +00002655 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002656
2657 size_lo = MIN(size_n, size);
2658 size_hi = size_n - size_lo;
2659
2660 if ((hi = _PyLong_New(size_hi)) == NULL)
2661 return -1;
2662 if ((lo = _PyLong_New(size_lo)) == NULL) {
2663 Py_DECREF(hi);
2664 return -1;
2665 }
2666
2667 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2668 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2669
2670 *high = long_normalize(hi);
2671 *low = long_normalize(lo);
2672 return 0;
2673}
2674
Tim Peters60004642002-08-12 22:01:34 +00002675static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2676
Tim Peters5af4e6c2002-08-12 02:31:19 +00002677/* Karatsuba multiplication. Ignores the input signs, and returns the
2678 * absolute value of the product (or NULL if error).
2679 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2680 */
2681static PyLongObject *
2682k_mul(PyLongObject *a, PyLongObject *b)
2683{
Christian Heimese93237d2007-12-19 02:37:44 +00002684 Py_ssize_t asize = ABS(Py_SIZE(a));
2685 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002686 PyLongObject *ah = NULL;
2687 PyLongObject *al = NULL;
2688 PyLongObject *bh = NULL;
2689 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002690 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002691 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002692 Py_ssize_t shift; /* the number of digits we split off */
2693 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002694
Tim Peters5af4e6c2002-08-12 02:31:19 +00002695 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2696 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2697 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002698 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002699 * By picking X to be a power of 2, "*X" is just shifting, and it's
2700 * been reduced to 3 multiplies on numbers half the size.
2701 */
2702
Tim Petersfc07e562002-08-12 02:54:10 +00002703 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002704 * is largest.
2705 */
Tim Peters738eda72002-08-12 15:08:20 +00002706 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002707 t1 = a;
2708 a = b;
2709 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002710
2711 i = asize;
2712 asize = bsize;
2713 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002714 }
2715
2716 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002717 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2718 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002719 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002720 return _PyLong_New(0);
2721 else
2722 return x_mul(a, b);
2723 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002724
Tim Peters60004642002-08-12 22:01:34 +00002725 /* If a is small compared to b, splitting on b gives a degenerate
2726 * case with ah==0, and Karatsuba may be (even much) less efficient
2727 * than "grade school" then. However, we can still win, by viewing
2728 * b as a string of "big digits", each of width a->ob_size. That
2729 * leads to a sequence of balanced calls to k_mul.
2730 */
2731 if (2 * asize <= bsize)
2732 return k_lopsided_mul(a, b);
2733
Tim Petersd6974a52002-08-13 20:37:51 +00002734 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002735 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002736 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002737 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002738
Tim Peters0973b992004-08-29 22:16:50 +00002739 if (a == b) {
2740 bh = ah;
2741 bl = al;
2742 Py_INCREF(bh);
2743 Py_INCREF(bl);
2744 }
2745 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002746
Tim Petersd64c1de2002-08-12 17:36:03 +00002747 /* The plan:
2748 * 1. Allocate result space (asize + bsize digits: that's always
2749 * enough).
2750 * 2. Compute ah*bh, and copy into result at 2*shift.
2751 * 3. Compute al*bl, and copy into result at 0. Note that this
2752 * can't overlap with #2.
2753 * 4. Subtract al*bl from the result, starting at shift. This may
2754 * underflow (borrow out of the high digit), but we don't care:
2755 * we're effectively doing unsigned arithmetic mod
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002756 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
Tim Petersd64c1de2002-08-12 17:36:03 +00002757 * borrows and carries out of the high digit can be ignored.
2758 * 5. Subtract ah*bh from the result, starting at shift.
2759 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2760 * at shift.
2761 */
2762
2763 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002764 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002765 if (ret == NULL) goto fail;
2766#ifdef Py_DEBUG
2767 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002768 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002769#endif
Tim Peters44121a62002-08-12 06:17:58 +00002770
Tim Petersd64c1de2002-08-12 17:36:03 +00002771 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002772 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002773 assert(Py_SIZE(t1) >= 0);
2774 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002775 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimese93237d2007-12-19 02:37:44 +00002776 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002777
2778 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimese93237d2007-12-19 02:37:44 +00002779 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002780 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002781 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002782 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002783
Tim Petersd64c1de2002-08-12 17:36:03 +00002784 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002785 if ((t2 = k_mul(al, bl)) == NULL) {
2786 Py_DECREF(t1);
2787 goto fail;
2788 }
Christian Heimese93237d2007-12-19 02:37:44 +00002789 assert(Py_SIZE(t2) >= 0);
2790 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2791 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002792
2793 /* Zero out remaining digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002794 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002795 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002796 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002797
Tim Petersd64c1de2002-08-12 17:36:03 +00002798 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2799 * because it's fresher in cache.
2800 */
Christian Heimese93237d2007-12-19 02:37:44 +00002801 i = Py_SIZE(ret) - shift; /* # digits after shift */
2802 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002803 Py_DECREF(t2);
2804
Christian Heimese93237d2007-12-19 02:37:44 +00002805 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002806 Py_DECREF(t1);
2807
Tim Petersd64c1de2002-08-12 17:36:03 +00002808 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002809 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2810 Py_DECREF(ah);
2811 Py_DECREF(al);
2812 ah = al = NULL;
2813
Tim Peters0973b992004-08-29 22:16:50 +00002814 if (a == b) {
2815 t2 = t1;
2816 Py_INCREF(t2);
2817 }
2818 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002819 Py_DECREF(t1);
2820 goto fail;
2821 }
2822 Py_DECREF(bh);
2823 Py_DECREF(bl);
2824 bh = bl = NULL;
2825
Tim Peters738eda72002-08-12 15:08:20 +00002826 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002827 Py_DECREF(t1);
2828 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002829 if (t3 == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002830 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002831
Tim Petersd6974a52002-08-13 20:37:51 +00002832 /* Add t3. It's not obvious why we can't run out of room here.
2833 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002834 */
Christian Heimese93237d2007-12-19 02:37:44 +00002835 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002836 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002837
Tim Peters5af4e6c2002-08-12 02:31:19 +00002838 return long_normalize(ret);
2839
2840 fail:
2841 Py_XDECREF(ret);
2842 Py_XDECREF(ah);
2843 Py_XDECREF(al);
2844 Py_XDECREF(bh);
2845 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002846 return NULL;
2847}
2848
Tim Petersd6974a52002-08-13 20:37:51 +00002849/* (*) Why adding t3 can't "run out of room" above.
2850
Tim Petersab86c2b2002-08-15 20:06:00 +00002851Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2852to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002853
Tim Petersab86c2b2002-08-15 20:06:00 +000028541. For any integer i, i = c(i/2) + f(i/2). In particular,
2855 bsize = c(bsize/2) + f(bsize/2).
28562. shift = f(bsize/2)
28573. asize <= bsize
28584. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2859 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002860
Tim Petersab86c2b2002-08-15 20:06:00 +00002861We allocated asize + bsize result digits, and add t3 into them at an offset
2862of shift. This leaves asize+bsize-shift allocated digit positions for t3
2863to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2864asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002865
Tim Petersab86c2b2002-08-15 20:06:00 +00002866bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2867at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002868
Tim Petersab86c2b2002-08-15 20:06:00 +00002869If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2870digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2871most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002872
Tim Petersab86c2b2002-08-15 20:06:00 +00002873The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002874
Tim Petersab86c2b2002-08-15 20:06:00 +00002875 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002876
Tim Petersab86c2b2002-08-15 20:06:00 +00002877and we have asize + c(bsize/2) available digit positions. We need to show
2878this is always enough. An instance of c(bsize/2) cancels out in both, so
2879the question reduces to whether asize digits is enough to hold
2880(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2881then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2882asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002883digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002884asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002885c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2886is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2887bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002888
Tim Peters48d52c02002-08-14 17:07:32 +00002889Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2890clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2891ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002892*/
2893
Tim Peters60004642002-08-12 22:01:34 +00002894/* b has at least twice the digits of a, and a is big enough that Karatsuba
2895 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2896 * of slices, each with a->ob_size digits, and multiply the slices by a,
2897 * one at a time. This gives k_mul balanced inputs to work with, and is
2898 * also cache-friendly (we compute one double-width slice of the result
2899 * at a time, then move on, never bactracking except for the helpful
2900 * single-width slice overlap between successive partial sums).
2901 */
2902static PyLongObject *
2903k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2904{
Christian Heimese93237d2007-12-19 02:37:44 +00002905 const Py_ssize_t asize = ABS(Py_SIZE(a));
2906 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002907 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002908 PyLongObject *ret;
2909 PyLongObject *bslice = NULL;
2910
2911 assert(asize > KARATSUBA_CUTOFF);
2912 assert(2 * asize <= bsize);
2913
2914 /* Allocate result space, and zero it out. */
2915 ret = _PyLong_New(asize + bsize);
2916 if (ret == NULL)
2917 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002918 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002919
2920 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002921 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002922 if (bslice == NULL)
2923 goto fail;
2924
2925 nbdone = 0;
2926 while (bsize > 0) {
2927 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002928 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002929
2930 /* Multiply the next slice of b by a. */
2931 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2932 nbtouse * sizeof(digit));
Christian Heimese93237d2007-12-19 02:37:44 +00002933 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002934 product = k_mul(a, bslice);
2935 if (product == NULL)
2936 goto fail;
2937
2938 /* Add into result. */
Christian Heimese93237d2007-12-19 02:37:44 +00002939 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2940 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002941 Py_DECREF(product);
2942
2943 bsize -= nbtouse;
2944 nbdone += nbtouse;
2945 }
2946
2947 Py_DECREF(bslice);
2948 return long_normalize(ret);
2949
2950 fail:
2951 Py_DECREF(ret);
2952 Py_XDECREF(bslice);
2953 return NULL;
2954}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002955
2956static PyObject *
2957long_mul(PyLongObject *v, PyLongObject *w)
2958{
2959 PyLongObject *a, *b, *z;
2960
2961 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002962 Py_INCREF(Py_NotImplemented);
2963 return Py_NotImplemented;
2964 }
2965
Tim Petersd64c1de2002-08-12 17:36:03 +00002966 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002967 /* Negate if exactly one of the inputs is negative. */
2968 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002969 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002970 Py_DECREF(a);
2971 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002972 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002973}
2974
Guido van Rossume32e0141992-01-19 16:31:05 +00002975/* The / and % operators are now defined in terms of divmod().
2976 The expression a mod b has the value a - b*floor(a/b).
2977 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002978 |a| by |b|, with the sign of a. This is also expressed
2979 as a - b*trunc(a/b), if trunc truncates towards zero.
2980 Some examples:
2981 a b a rem b a mod b
2982 13 10 3 3
2983 -13 10 -3 7
2984 13 -10 3 -7
2985 -13 -10 -3 -3
2986 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002987 have different signs. We then subtract one from the 'div'
2988 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002989
Tim Peters47e52ee2004-08-30 02:44:38 +00002990/* Compute
2991 * *pdiv, *pmod = divmod(v, w)
2992 * NULL can be passed for pdiv or pmod, in which case that part of
2993 * the result is simply thrown away. The caller owns a reference to
2994 * each of these it requests (does not pass NULL for).
2995 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002996static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002997l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002998 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002999{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003000 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003001
Guido van Rossume32e0141992-01-19 16:31:05 +00003002 if (long_divrem(v, w, &div, &mod) < 0)
3003 return -1;
Christian Heimese93237d2007-12-19 02:37:44 +00003004 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3005 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003006 PyLongObject *temp;
3007 PyLongObject *one;
3008 temp = (PyLongObject *) long_add(mod, w);
3009 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00003010 mod = temp;
3011 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003012 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003013 return -1;
3014 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003015 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00003016 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003017 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3018 Py_DECREF(mod);
3019 Py_DECREF(div);
3020 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00003021 return -1;
3022 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003023 Py_DECREF(one);
3024 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003025 div = temp;
3026 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003027 if (pdiv != NULL)
3028 *pdiv = div;
3029 else
3030 Py_DECREF(div);
3031
3032 if (pmod != NULL)
3033 *pmod = mod;
3034 else
3035 Py_DECREF(mod);
3036
Guido van Rossume32e0141992-01-19 16:31:05 +00003037 return 0;
3038}
3039
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003040static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003041long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00003042{
Tim Peters47e52ee2004-08-30 02:44:38 +00003043 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003044
3045 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003046 if (l_divmod(a, b, &div, NULL) < 0)
3047 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003048 Py_DECREF(a);
3049 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003050 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003051}
3052
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003053static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00003054long_classic_div(PyObject *v, PyObject *w)
3055{
Tim Peters47e52ee2004-08-30 02:44:38 +00003056 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00003057
3058 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00003059 if (Py_DivisionWarningFlag &&
3060 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
3061 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003062 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00003063 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00003064 Py_DECREF(a);
3065 Py_DECREF(b);
3066 return (PyObject *)div;
3067}
3068
Mark Dickinson46572832009-12-27 14:55:57 +00003069/* PyLong/PyLong -> float, with correctly rounded result. */
3070
3071#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3072#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3073
Guido van Rossum393661d2001-08-31 17:40:15 +00003074static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00003075long_true_divide(PyObject *v, PyObject *w)
3076{
Mark Dickinson46572832009-12-27 14:55:57 +00003077 PyLongObject *a, *b, *x;
3078 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3079 digit mask, low;
3080 int inexact, negate, a_is_small, b_is_small;
3081 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003082
3083 CONVERT_BINOP(v, w, &a, &b);
Tim Peterse2a60002001-09-04 06:17:36 +00003084
Mark Dickinson46572832009-12-27 14:55:57 +00003085 /*
3086 Method in a nutshell:
3087
3088 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3089 1. choose a suitable integer 'shift'
3090 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3091 3. adjust x for correct rounding
3092 4. convert x to a double dx with the same value
3093 5. return ldexp(dx, shift).
3094
3095 In more detail:
3096
3097 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3098 returns either 0.0 or -0.0, depending on the sign of b. For a and
3099 b both nonzero, ignore signs of a and b, and add the sign back in
3100 at the end. Now write a_bits and b_bits for the bit lengths of a
3101 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3102 for b). Then
3103
3104 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
3105
3106 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3107 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3108 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3109 the way, we can assume that
3110
3111 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
3112
3113 1. The integer 'shift' is chosen so that x has the right number of
3114 bits for a double, plus two or three extra bits that will be used
3115 in the rounding decisions. Writing a_bits and b_bits for the
3116 number of significant bits in a and b respectively, a
3117 straightforward formula for shift is:
3118
3119 shift = a_bits - b_bits - DBL_MANT_DIG - 2
3120
3121 This is fine in the usual case, but if a/b is smaller than the
3122 smallest normal float then it can lead to double rounding on an
3123 IEEE 754 platform, giving incorrectly rounded results. So we
3124 adjust the formula slightly. The actual formula used is:
3125
3126 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
3127
3128 2. The quantity x is computed by first shifting a (left -shift bits
3129 if shift <= 0, right shift bits if shift > 0) and then dividing by
3130 b. For both the shift and the division, we keep track of whether
3131 the result is inexact, in a flag 'inexact'; this information is
3132 needed at the rounding stage.
3133
3134 With the choice of shift above, together with our assumption that
3135 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3136 that x >= 1.
3137
3138 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3139 this with an exactly representable float of the form
3140
3141 round(x/2**extra_bits) * 2**(extra_bits+shift).
3142
3143 For float representability, we need x/2**extra_bits <
3144 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3145 DBL_MANT_DIG. This translates to the condition:
3146
3147 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
3148
3149 To round, we just modify the bottom digit of x in-place; this can
3150 end up giving a digit with value > PyLONG_MASK, but that's not a
3151 problem since digits can hold values up to 2*PyLONG_MASK+1.
3152
3153 With the original choices for shift above, extra_bits will always
3154 be 2 or 3. Then rounding under the round-half-to-even rule, we
3155 round up iff the most significant of the extra bits is 1, and
3156 either: (a) the computation of x in step 2 had an inexact result,
3157 or (b) at least one other of the extra bits is 1, or (c) the least
3158 significant bit of x (above those to be rounded) is 1.
3159
3160 4. Conversion to a double is straightforward; all floating-point
3161 operations involved in the conversion are exact, so there's no
3162 danger of rounding errors.
3163
3164 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3165 The result will always be exactly representable as a double, except
3166 in the case that it overflows. To avoid dependence on the exact
3167 behaviour of ldexp on overflow, we check for overflow before
3168 applying ldexp. The result of ldexp is adjusted for sign before
3169 returning.
3170 */
3171
3172 /* Reduce to case where a and b are both positive. */
3173 a_size = ABS(Py_SIZE(a));
3174 b_size = ABS(Py_SIZE(b));
3175 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3176 if (b_size == 0) {
Tim Peterse2a60002001-09-04 06:17:36 +00003177 PyErr_SetString(PyExc_ZeroDivisionError,
Mark Dickinson46572832009-12-27 14:55:57 +00003178 "division by zero");
3179 goto error;
3180 }
3181 if (a_size == 0)
3182 goto underflow_or_zero;
3183
3184 /* Fast path for a and b small (exactly representable in a double).
3185 Relies on floating-point division being correctly rounded; results
3186 may be subject to double rounding on x86 machines that operate with
3187 the x87 FPU set to 64-bit precision. */
3188 a_is_small = a_size <= MANT_DIG_DIGITS ||
3189 (a_size == MANT_DIG_DIGITS+1 &&
3190 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3191 b_is_small = b_size <= MANT_DIG_DIGITS ||
3192 (b_size == MANT_DIG_DIGITS+1 &&
3193 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3194 if (a_is_small && b_is_small) {
3195 double da, db;
3196 da = a->ob_digit[--a_size];
3197 while (a_size > 0)
3198 da = da * PyLong_BASE + a->ob_digit[--a_size];
3199 db = b->ob_digit[--b_size];
3200 while (b_size > 0)
3201 db = db * PyLong_BASE + b->ob_digit[--b_size];
3202 result = da / db;
3203 goto success;
Tim Peterse2a60002001-09-04 06:17:36 +00003204 }
3205
Mark Dickinson46572832009-12-27 14:55:57 +00003206 /* Catch obvious cases of underflow and overflow */
3207 diff = a_size - b_size;
3208 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3209 /* Extreme overflow */
Tim Peterse2a60002001-09-04 06:17:36 +00003210 goto overflow;
Mark Dickinson46572832009-12-27 14:55:57 +00003211 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3212 /* Extreme underflow */
3213 goto underflow_or_zero;
3214 /* Next line is now safe from overflowing a Py_ssize_t */
3215 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3216 bits_in_digit(b->ob_digit[b_size - 1]);
3217 /* Now diff = a_bits - b_bits. */
3218 if (diff > DBL_MAX_EXP)
Tim Peterse2a60002001-09-04 06:17:36 +00003219 goto overflow;
Mark Dickinson46572832009-12-27 14:55:57 +00003220 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3221 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003222
Mark Dickinson46572832009-12-27 14:55:57 +00003223 /* Choose value for shift; see comments for step 1 above. */
3224 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
3225
3226 inexact = 0;
3227
3228 /* x = abs(a * 2**-shift) */
3229 if (shift <= 0) {
3230 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3231 digit rem;
3232 /* x = a << -shift */
3233 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3234 /* In practice, it's probably impossible to end up
3235 here. Both a and b would have to be enormous,
3236 using close to SIZE_T_MAX bytes of memory each. */
3237 PyErr_SetString(PyExc_OverflowError,
3238 "intermediate overflow during division");
3239 goto error;
3240 }
3241 x = _PyLong_New(a_size + shift_digits + 1);
3242 if (x == NULL)
3243 goto error;
3244 for (i = 0; i < shift_digits; i++)
3245 x->ob_digit[i] = 0;
3246 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3247 a_size, -shift % PyLong_SHIFT);
3248 x->ob_digit[a_size + shift_digits] = rem;
3249 }
3250 else {
3251 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3252 digit rem;
3253 /* x = a >> shift */
3254 assert(a_size >= shift_digits);
3255 x = _PyLong_New(a_size - shift_digits);
3256 if (x == NULL)
3257 goto error;
3258 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3259 a_size - shift_digits, shift % PyLong_SHIFT);
3260 /* set inexact if any of the bits shifted out is nonzero */
3261 if (rem)
3262 inexact = 1;
3263 while (!inexact && shift_digits > 0)
3264 if (a->ob_digit[--shift_digits])
3265 inexact = 1;
3266 }
3267 long_normalize(x);
3268 x_size = Py_SIZE(x);
3269
3270 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3271 reference to x, so it's safe to modify it in-place. */
3272 if (b_size == 1) {
3273 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3274 b->ob_digit[0]);
3275 long_normalize(x);
3276 if (rem)
3277 inexact = 1;
3278 }
3279 else {
3280 PyLongObject *div, *rem;
3281 div = x_divrem(x, b, &rem);
3282 Py_DECREF(x);
3283 x = div;
3284 if (x == NULL)
3285 goto error;
3286 if (Py_SIZE(rem))
3287 inexact = 1;
3288 Py_DECREF(rem);
3289 }
3290 x_size = ABS(Py_SIZE(x));
3291 assert(x_size > 0); /* result of division is never zero */
3292 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
3293
3294 /* The number of extra bits that have to be rounded away. */
3295 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3296 assert(extra_bits == 2 || extra_bits == 3);
3297
3298 /* Round by directly modifying the low digit of x. */
3299 mask = (digit)1 << (extra_bits - 1);
3300 low = x->ob_digit[0] | inexact;
3301 if (low & mask && low & (3*mask-1))
3302 low += mask;
3303 x->ob_digit[0] = low & ~(mask-1U);
3304
3305 /* Convert x to a double dx; the conversion is exact. */
3306 dx = x->ob_digit[--x_size];
3307 while (x_size > 0)
3308 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3309 Py_DECREF(x);
3310
3311 /* Check whether ldexp result will overflow a double. */
3312 if (shift + x_bits >= DBL_MAX_EXP &&
3313 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, x_bits)))
3314 goto overflow;
3315 result = ldexp(dx, shift);
3316
3317 success:
3318 Py_DECREF(a);
3319 Py_DECREF(b);
3320 return PyFloat_FromDouble(negate ? -result : result);
3321
3322 underflow_or_zero:
3323 Py_DECREF(a);
3324 Py_DECREF(b);
3325 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
3326
3327 overflow:
Tim Peterse2a60002001-09-04 06:17:36 +00003328 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson46572832009-12-27 14:55:57 +00003329 "integer division result too large for a float");
3330 error:
3331 Py_DECREF(a);
3332 Py_DECREF(b);
Tim Peterse2a60002001-09-04 06:17:36 +00003333 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003334}
3335
3336static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003337long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00003338{
Tim Peters47e52ee2004-08-30 02:44:38 +00003339 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003340
3341 CONVERT_BINOP(v, w, &a, &b);
3342
Tim Peters47e52ee2004-08-30 02:44:38 +00003343 if (l_divmod(a, b, NULL, &mod) < 0)
3344 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003345 Py_DECREF(a);
3346 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003347 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003348}
3349
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003350static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003351long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003352{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003353 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003354 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003355
3356 CONVERT_BINOP(v, w, &a, &b);
3357
3358 if (l_divmod(a, b, &div, &mod) < 0) {
3359 Py_DECREF(a);
3360 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003361 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003362 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003363 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003364 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003365 PyTuple_SetItem(z, 0, (PyObject *) div);
3366 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003367 }
3368 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003369 Py_DECREF(div);
3370 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003371 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003372 Py_DECREF(a);
3373 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003374 return z;
3375}
3376
Tim Peters47e52ee2004-08-30 02:44:38 +00003377/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003378static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003379long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003380{
Tim Peters47e52ee2004-08-30 02:44:38 +00003381 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3382 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003383
Tim Peters47e52ee2004-08-30 02:44:38 +00003384 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003385 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003386 PyLongObject *temp = NULL;
3387
3388 /* 5-ary values. If the exponent is large enough, table is
3389 * precomputed so that table[i] == a**i % c for i in range(32).
3390 */
3391 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3392 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3393
3394 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003395 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003396 if (PyLong_Check(x)) {
3397 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003398 Py_INCREF(x);
3399 }
Tim Petersde7990b2005-07-17 23:45:23 +00003400 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003401 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00003402 if (c == NULL)
3403 goto Error;
3404 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003405 else if (x == Py_None)
3406 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003407 else {
3408 Py_DECREF(a);
3409 Py_DECREF(b);
3410 Py_INCREF(Py_NotImplemented);
3411 return Py_NotImplemented;
3412 }
Tim Peters4c483c42001-09-05 06:24:58 +00003413
Christian Heimese93237d2007-12-19 02:37:44 +00003414 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003415 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003416 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003417 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003418 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003419 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003420 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003421 /* else return a float. This works because we know
3422 that this calls float_pow() which converts its
3423 arguments to double. */
3424 Py_DECREF(a);
3425 Py_DECREF(b);
3426 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003427 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003428 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003429
3430 if (c) {
3431 /* if modulus == 0:
3432 raise ValueError() */
Christian Heimese93237d2007-12-19 02:37:44 +00003433 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003434 PyErr_SetString(PyExc_ValueError,
3435 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003436 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003437 }
3438
3439 /* if modulus < 0:
3440 negativeOutput = True
3441 modulus = -modulus */
Christian Heimese93237d2007-12-19 02:37:44 +00003442 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003443 negativeOutput = 1;
3444 temp = (PyLongObject *)_PyLong_Copy(c);
3445 if (temp == NULL)
3446 goto Error;
3447 Py_DECREF(c);
3448 c = temp;
3449 temp = NULL;
3450 c->ob_size = - c->ob_size;
3451 }
3452
3453 /* if modulus == 1:
3454 return 0 */
Christian Heimese93237d2007-12-19 02:37:44 +00003455 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003456 z = (PyLongObject *)PyLong_FromLong(0L);
3457 goto Done;
3458 }
3459
3460 /* if base < 0:
3461 base = base % modulus
3462 Having the base positive just makes things easier. */
Christian Heimese93237d2007-12-19 02:37:44 +00003463 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003464 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003465 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003466 Py_DECREF(a);
3467 a = temp;
3468 temp = NULL;
3469 }
3470 }
3471
3472 /* At this point a, b, and c are guaranteed non-negative UNLESS
3473 c is NULL, in which case a may be negative. */
3474
3475 z = (PyLongObject *)PyLong_FromLong(1L);
3476 if (z == NULL)
3477 goto Error;
3478
3479 /* Perform a modular reduction, X = X % c, but leave X alone if c
3480 * is NULL.
3481 */
3482#define REDUCE(X) \
3483 if (c != NULL) { \
3484 if (l_divmod(X, c, NULL, &temp) < 0) \
3485 goto Error; \
3486 Py_XDECREF(X); \
3487 X = temp; \
3488 temp = NULL; \
3489 }
3490
3491 /* Multiply two values, then reduce the result:
3492 result = X*Y % c. If c is NULL, skip the mod. */
3493#define MULT(X, Y, result) \
3494{ \
3495 temp = (PyLongObject *)long_mul(X, Y); \
3496 if (temp == NULL) \
3497 goto Error; \
3498 Py_XDECREF(result); \
3499 result = temp; \
3500 temp = NULL; \
3501 REDUCE(result) \
3502}
3503
Christian Heimese93237d2007-12-19 02:37:44 +00003504 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003505 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3506 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimese93237d2007-12-19 02:37:44 +00003507 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003508 digit bi = b->ob_digit[i];
3509
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00003510 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003511 MULT(z, z, z)
3512 if (bi & j)
3513 MULT(z, a, z)
3514 }
3515 }
3516 }
3517 else {
3518 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3519 Py_INCREF(z); /* still holds 1L */
3520 table[0] = z;
3521 for (i = 1; i < 32; ++i)
3522 MULT(table[i-1], a, table[i])
3523
Christian Heimese93237d2007-12-19 02:37:44 +00003524 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003525 const digit bi = b->ob_digit[i];
3526
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003527 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003528 const int index = (bi >> j) & 0x1f;
3529 for (k = 0; k < 5; ++k)
3530 MULT(z, z, z)
3531 if (index)
3532 MULT(z, table[index], z)
3533 }
3534 }
3535 }
3536
Christian Heimese93237d2007-12-19 02:37:44 +00003537 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003538 temp = (PyLongObject *)long_sub(z, c);
3539 if (temp == NULL)
3540 goto Error;
3541 Py_DECREF(z);
3542 z = temp;
3543 temp = NULL;
3544 }
3545 goto Done;
3546
3547 Error:
3548 if (z != NULL) {
3549 Py_DECREF(z);
3550 z = NULL;
3551 }
3552 /* fall through */
3553 Done:
Christian Heimese93237d2007-12-19 02:37:44 +00003554 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003555 for (i = 0; i < 32; ++i)
3556 Py_XDECREF(table[i]);
3557 }
Tim Petersde7990b2005-07-17 23:45:23 +00003558 Py_DECREF(a);
3559 Py_DECREF(b);
3560 Py_XDECREF(c);
3561 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003562 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003563}
3564
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003565static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003566long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003567{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003568 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003569 PyLongObject *x;
3570 PyLongObject *w;
3571 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003572 if (w == NULL)
3573 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003574 x = (PyLongObject *) long_add(v, w);
3575 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003576 if (x == NULL)
3577 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00003578 Py_SIZE(x) = -(Py_SIZE(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003579 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003580}
3581
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003582static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003583long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003584{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003585 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003586 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003587 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003588 Py_INCREF(v);
3589 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003590 }
Tim Peters69c2de32001-09-11 22:31:33 +00003591 z = (PyLongObject *)_PyLong_Copy(v);
3592 if (z != NULL)
3593 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003594 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003595}
3596
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003597static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003598long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003599{
3600 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003601 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003602 else
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003603 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003604}
3605
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003606static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003607long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003608{
Christian Heimese93237d2007-12-19 02:37:44 +00003609 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003610}
3611
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003612static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003613long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003614{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003615 PyLongObject *a, *b;
3616 PyLongObject *z = NULL;
Mark Dickinson3ec9b942010-04-06 16:46:09 +00003617 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003618 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003619
Neil Schemenauerba872e22001-01-04 01:46:03 +00003620 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3621
Christian Heimese93237d2007-12-19 02:37:44 +00003622 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003623 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003624 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003625 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003626 if (a1 == NULL)
3627 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003628 a2 = (PyLongObject *) long_rshift(a1, b);
3629 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003630 if (a2 == NULL)
3631 goto rshift_error;
3632 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003633 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003634 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003635 else {
Mark Dickinson3ec9b942010-04-06 16:46:09 +00003636 shiftby = PyLong_AsSsize_t((PyObject *)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003637 if (shiftby == -1L && PyErr_Occurred())
3638 goto rshift_error;
3639 if (shiftby < 0) {
3640 PyErr_SetString(PyExc_ValueError,
3641 "negative shift count");
3642 goto rshift_error;
3643 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003644 wordshift = shiftby / PyLong_SHIFT;
Christian Heimese93237d2007-12-19 02:37:44 +00003645 newsize = ABS(Py_SIZE(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003646 if (newsize <= 0) {
3647 z = _PyLong_New(0);
3648 Py_DECREF(a);
3649 Py_DECREF(b);
3650 return (PyObject *)z;
3651 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003652 loshift = shiftby % PyLong_SHIFT;
3653 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003654 lomask = ((digit)1 << hishift) - 1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003655 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003656 z = _PyLong_New(newsize);
3657 if (z == NULL)
3658 goto rshift_error;
Christian Heimese93237d2007-12-19 02:37:44 +00003659 if (Py_SIZE(a) < 0)
3660 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003661 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3662 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3663 if (i+1 < newsize)
3664 z->ob_digit[i] |=
3665 (a->ob_digit[j+1] << hishift) & himask;
3666 }
3667 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003668 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003669rshift_error:
3670 Py_DECREF(a);
3671 Py_DECREF(b);
3672 return (PyObject *) z;
3673
Guido van Rossumc6913e71991-11-19 20:26:46 +00003674}
3675
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003676static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003677long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003678{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003679 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003680 PyLongObject *a, *b;
3681 PyLongObject *z = NULL;
Mark Dickinson3ec9b942010-04-06 16:46:09 +00003682 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003683 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003684
Neil Schemenauerba872e22001-01-04 01:46:03 +00003685 CONVERT_BINOP(v, w, &a, &b);
3686
Mark Dickinson3ec9b942010-04-06 16:46:09 +00003687 shiftby = PyLong_AsSsize_t((PyObject *)b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003688 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003689 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003690 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003691 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003692 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003693 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003694 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
Mark Dickinson3ec9b942010-04-06 16:46:09 +00003695 wordshift = shiftby / PyLong_SHIFT;
3696 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003697
3698 oldsize = ABS(a->ob_size);
3699 newsize = oldsize + wordshift;
3700 if (remshift)
3701 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003702 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003703 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003704 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003705 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003706 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003707 for (i = 0; i < wordshift; i++)
3708 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003709 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003710 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003711 accum |= (twodigits)a->ob_digit[j] << remshift;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003712 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3713 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003714 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003715 if (remshift)
3716 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003717 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003718 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003719 z = long_normalize(z);
3720lshift_error:
3721 Py_DECREF(a);
3722 Py_DECREF(b);
3723 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003724}
3725
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003726/* Compute two's complement of digit vector a[0:m], writing result to
3727 z[0:m]. The digit vector a need not be normalized, but should not
3728 be entirely zero. a and z may point to the same digit vector. */
3729
3730static void
3731v_complement(digit *z, digit *a, Py_ssize_t m)
3732{
3733 Py_ssize_t i;
3734 digit carry = 1;
3735 for (i = 0; i < m; ++i) {
3736 carry += a[i] ^ PyLong_MASK;
3737 z[i] = carry & PyLong_MASK;
3738 carry >>= PyLong_SHIFT;
3739 }
3740 assert(carry == 0);
3741}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003742
3743/* Bitwise and/xor/or operations */
3744
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003745static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003746long_bitwise(PyLongObject *a,
3747 int op, /* '&', '|', '^' */
3748 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003749{
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003750 int nega, negb, negz;
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00003751 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003752 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003753
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003754 /* Bitwise operations for negative numbers operate as though
3755 on a two's complement representation. So convert arguments
3756 from sign-magnitude to two's complement, and convert the
3757 result back to sign-magnitude at the end. */
3758
3759 /* If a is negative, replace it by its two's complement. */
3760 size_a = ABS(Py_SIZE(a));
3761 nega = Py_SIZE(a) < 0;
3762 if (nega) {
3763 z = _PyLong_New(size_a);
3764 if (z == NULL)
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003765 return NULL;
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003766 v_complement(z->ob_digit, a->ob_digit, size_a);
3767 a = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003768 }
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003769 else
3770 /* Keep reference count consistent. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003771 Py_INCREF(a);
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003772
3773 /* Same for b. */
3774 size_b = ABS(Py_SIZE(b));
3775 negb = Py_SIZE(b) < 0;
3776 if (negb) {
3777 z = _PyLong_New(size_b);
3778 if (z == NULL) {
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003779 Py_DECREF(a);
3780 return NULL;
3781 }
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003782 v_complement(z->ob_digit, b->ob_digit, size_b);
3783 b = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003784 }
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003785 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003786 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003787
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003788 /* Swap a and b if necessary to ensure size_a >= size_b. */
3789 if (size_a < size_b) {
3790 z = a; a = b; b = z;
3791 size_z = size_a; size_a = size_b; size_b = size_z;
3792 negz = nega; nega = negb; negb = negz;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003793 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003794
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003795 /* JRH: The original logic here was to allocate the result value (z)
3796 as the longer of the two operands. However, there are some cases
3797 where the result is guaranteed to be shorter than that: AND of two
3798 positives, OR of two negatives: use the shorter number. AND with
3799 mixed signs: use the positive number. OR with mixed signs: use the
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003800 negative number.
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003801 */
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003802 switch (op) {
3803 case '^':
3804 negz = nega ^ negb;
3805 size_z = size_a;
3806 break;
3807 case '&':
3808 negz = nega & negb;
3809 size_z = negb ? size_a : size_b;
3810 break;
3811 case '|':
3812 negz = nega | negb;
3813 size_z = negb ? size_b : size_a;
3814 break;
3815 default:
3816 PyErr_BadArgument();
3817 return NULL;
3818 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003819
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003820 /* We allow an extra digit if z is negative, to make sure that
3821 the final two's complement of z doesn't overflow. */
3822 z = _PyLong_New(size_z + negz);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003823 if (z == NULL) {
Neal Norwitzef02b9e2006-07-16 02:00:32 +00003824 Py_DECREF(a);
3825 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003826 return NULL;
3827 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003828
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003829 /* Compute digits for overlap of a and b. */
3830 switch(op) {
3831 case '&':
3832 for (i = 0; i < size_b; ++i)
3833 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
3834 break;
3835 case '|':
3836 for (i = 0; i < size_b; ++i)
3837 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
3838 break;
3839 case '^':
3840 for (i = 0; i < size_b; ++i)
3841 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
3842 break;
3843 default:
3844 PyErr_BadArgument();
3845 return NULL;
3846 }
3847
3848 /* Copy any remaining digits of a, inverting if necessary. */
3849 if (op == '^' && negb)
3850 for (; i < size_z; ++i)
3851 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
3852 else if (i < size_z)
3853 memcpy(&z->ob_digit[i], &a->ob_digit[i],
3854 (size_z-i)*sizeof(digit));
3855
3856 /* Complement result if negative. */
3857 if (negz) {
3858 Py_SIZE(z) = -(Py_SIZE(z));
3859 z->ob_digit[size_z] = PyLong_MASK;
3860 v_complement(z->ob_digit, z->ob_digit, size_z+1);
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003861 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003862
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003863 Py_DECREF(a);
3864 Py_DECREF(b);
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003865 return (PyObject *)long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003866}
3867
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003868static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003869long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003870{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003871 PyLongObject *a, *b;
3872 PyObject *c;
3873 CONVERT_BINOP(v, w, &a, &b);
3874 c = long_bitwise(a, '&', b);
3875 Py_DECREF(a);
3876 Py_DECREF(b);
3877 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003878}
3879
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003880static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003881long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003882{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003883 PyLongObject *a, *b;
3884 PyObject *c;
3885 CONVERT_BINOP(v, w, &a, &b);
3886 c = long_bitwise(a, '^', b);
3887 Py_DECREF(a);
3888 Py_DECREF(b);
3889 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003890}
3891
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003892static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003893long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003894{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003895 PyLongObject *a, *b;
3896 PyObject *c;
3897 CONVERT_BINOP(v, w, &a, &b);
3898 c = long_bitwise(a, '|', b);
3899 Py_DECREF(a);
3900 Py_DECREF(b);
3901 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003902}
3903
Guido van Rossum234f9421993-06-17 12:35:49 +00003904static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003905long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003906{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003907 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00003908 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Georg Brandlc02e1312007-04-11 17:16:24 +00003909 if (*pw == NULL)
3910 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003911 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00003912 return 0;
3913 }
Guido van Rossum1952e382001-09-19 01:25:16 +00003914 else if (PyLong_Check(*pw)) {
3915 Py_INCREF(*pv);
3916 Py_INCREF(*pw);
3917 return 0;
3918 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00003919 return 1; /* Can't do it */
3920}
3921
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003922static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003923long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003924{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003925 if (PyLong_CheckExact(v))
3926 Py_INCREF(v);
3927 else
3928 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003929 return v;
3930}
3931
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003932static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003933long_int(PyObject *v)
3934{
3935 long x;
3936 x = PyLong_AsLong(v);
3937 if (PyErr_Occurred()) {
3938 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3939 PyErr_Clear();
3940 if (PyLong_CheckExact(v)) {
3941 Py_INCREF(v);
3942 return v;
3943 }
3944 else
3945 return _PyLong_Copy((PyLongObject *)v);
3946 }
3947 else
3948 return NULL;
3949 }
3950 return PyInt_FromLong(x);
3951}
3952
3953static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003954long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003955{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003956 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003957 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003958 if (result == -1.0 && PyErr_Occurred())
3959 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003960 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003961}
3962
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003963static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003964long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003965{
Eric Smith5e527eb2008-02-10 01:36:53 +00003966 return _PyLong_Format(v, 8, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003967}
3968
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003969static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003970long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003971{
Eric Smith5e527eb2008-02-10 01:36:53 +00003972 return _PyLong_Format(v, 16, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003973}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003974
3975static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003976long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003977
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978static PyObject *
3979long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3980{
3981 PyObject *x = NULL;
3982 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003983 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003984
Guido van Rossumbef14172001-08-29 15:47:46 +00003985 if (type != &PyLong_Type)
3986 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003987 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3988 &x, &base))
3989 return NULL;
3990 if (x == NULL)
3991 return PyLong_FromLong(0L);
3992 if (base == -909)
3993 return PyNumber_Long(x);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003994 else if (PyString_Check(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003995 /* Since PyLong_FromString doesn't have a length parameter,
3996 * check here for possible NULs in the string. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003997 char *string = PyString_AS_STRING(x);
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00003998 if (strlen(string) != (size_t)PyString_Size(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003999 /* create a repr() of the input string,
4000 * just like PyLong_FromString does. */
4001 PyObject *srepr;
4002 srepr = PyObject_Repr(x);
4003 if (srepr == NULL)
4004 return NULL;
4005 PyErr_Format(PyExc_ValueError,
4006 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00004007 base, PyString_AS_STRING(srepr));
Georg Brandl00cd8182007-03-06 18:41:12 +00004008 Py_DECREF(srepr);
4009 return NULL;
4010 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00004011 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Georg Brandl00cd8182007-03-06 18:41:12 +00004012 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004013#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00004014 else if (PyUnicode_Check(x))
4015 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4016 PyUnicode_GET_SIZE(x),
4017 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004018#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00004019 else {
4020 PyErr_SetString(PyExc_TypeError,
4021 "long() can't convert non-string with explicit base");
4022 return NULL;
4023 }
4024}
4025
Guido van Rossumbef14172001-08-29 15:47:46 +00004026/* Wimpy, slow approach to tp_new calls for subtypes of long:
4027 first create a regular long from whatever arguments we got,
4028 then allocate a subtype instance and initialize it from
4029 the regular long. The regular long is then thrown away.
4030*/
4031static PyObject *
4032long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4033{
Anthony Baxter377be112006-04-11 06:54:30 +00004034 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004035 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004036
4037 assert(PyType_IsSubtype(type, &PyLong_Type));
4038 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4039 if (tmp == NULL)
4040 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00004041 assert(PyLong_CheckExact(tmp));
Christian Heimese93237d2007-12-19 02:37:44 +00004042 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00004043 if (n < 0)
4044 n = -n;
Anthony Baxter377be112006-04-11 06:54:30 +00004045 newobj = (PyLongObject *)type->tp_alloc(type, n);
4046 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00004047 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00004048 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00004049 }
Anthony Baxter377be112006-04-11 06:54:30 +00004050 assert(PyLong_Check(newobj));
Christian Heimese93237d2007-12-19 02:37:44 +00004051 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00004052 for (i = 0; i < n; i++)
Anthony Baxter377be112006-04-11 06:54:30 +00004053 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00004054 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00004055 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004056}
4057
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004058static PyObject *
4059long_getnewargs(PyLongObject *v)
4060{
4061 return Py_BuildValue("(N)", _PyLong_Copy(v));
4062}
4063
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004064static PyObject *
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004065long_get0(PyLongObject *v, void *context) {
4066 return PyLong_FromLong(0L);
4067}
4068
4069static PyObject *
4070long_get1(PyLongObject *v, void *context) {
4071 return PyLong_FromLong(1L);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004072}
4073
Eric Smitha9f7d622008-02-17 19:46:49 +00004074static PyObject *
4075long__format__(PyObject *self, PyObject *args)
4076{
4077 PyObject *format_spec;
4078
4079 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
4080 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00004081 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00004082 return _PyLong_FormatAdvanced(self,
4083 PyBytes_AS_STRING(format_spec),
4084 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00004085 if (PyUnicode_Check(format_spec)) {
4086 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00004087 PyObject *result;
4088 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00004089
Eric Smithdc13b792008-05-30 18:10:04 +00004090 if (str_spec == NULL)
4091 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00004092
Eric Smithdc13b792008-05-30 18:10:04 +00004093 result = _PyLong_FormatAdvanced(self,
4094 PyBytes_AS_STRING(str_spec),
4095 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00004096
Eric Smithdc13b792008-05-30 18:10:04 +00004097 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00004098 return result;
4099 }
4100 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
4101 return NULL;
4102}
4103
Robert Schuppenies51df0642008-06-01 16:16:17 +00004104static PyObject *
4105long_sizeof(PyLongObject *v)
4106{
4107 Py_ssize_t res;
4108
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00004109 res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);
Robert Schuppenies51df0642008-06-01 16:16:17 +00004110 return PyInt_FromSsize_t(res);
4111}
4112
Mark Dickinson1a707982008-12-17 16:14:37 +00004113static PyObject *
4114long_bit_length(PyLongObject *v)
4115{
4116 PyLongObject *result, *x, *y;
4117 Py_ssize_t ndigits, msd_bits = 0;
4118 digit msd;
4119
4120 assert(v != NULL);
4121 assert(PyLong_Check(v));
4122
4123 ndigits = ABS(Py_SIZE(v));
4124 if (ndigits == 0)
4125 return PyInt_FromLong(0);
4126
4127 msd = v->ob_digit[ndigits-1];
4128 while (msd >= 32) {
4129 msd_bits += 6;
4130 msd >>= 6;
4131 }
4132 msd_bits += (long)(BitLengthTable[msd]);
4133
4134 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4135 return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
4136
4137 /* expression above may overflow; use Python integers instead */
4138 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4139 if (result == NULL)
4140 return NULL;
4141 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4142 if (x == NULL)
4143 goto error;
4144 y = (PyLongObject *)long_mul(result, x);
4145 Py_DECREF(x);
4146 if (y == NULL)
4147 goto error;
4148 Py_DECREF(result);
4149 result = y;
4150
4151 x = (PyLongObject *)PyLong_FromLong(msd_bits);
4152 if (x == NULL)
4153 goto error;
4154 y = (PyLongObject *)long_add(result, x);
4155 Py_DECREF(x);
4156 if (y == NULL)
4157 goto error;
4158 Py_DECREF(result);
4159 result = y;
4160
4161 return (PyObject *)result;
4162
4163error:
4164 Py_DECREF(result);
4165 return NULL;
4166}
4167
4168PyDoc_STRVAR(long_bit_length_doc,
4169"long.bit_length() -> int or long\n\
4170\n\
4171Number of bits necessary to represent self in binary.\n\
4172>>> bin(37L)\n\
4173'0b100101'\n\
4174>>> (37L).bit_length()\n\
41756");
4176
Christian Heimes6f341092008-04-18 23:13:07 +00004177#if 0
4178static PyObject *
4179long_is_finite(PyObject *v)
4180{
4181 Py_RETURN_TRUE;
4182}
4183#endif
4184
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004185static PyMethodDef long_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004186 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4187 "Returns self, the complex conjugate of any long."},
Mark Dickinson1a707982008-12-17 16:14:37 +00004188 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4189 long_bit_length_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00004190#if 0
4191 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4192 "Returns always True."},
4193#endif
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004194 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4195 "Truncating an Integral returns itself."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004196 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smitha9f7d622008-02-17 19:46:49 +00004197 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Robert Schuppenies51df0642008-06-01 16:16:17 +00004198 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00004199 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004200 {NULL, NULL} /* sentinel */
4201};
4202
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004203static PyGetSetDef long_getset[] = {
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004204 {"real",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004205 (getter)long_long, (setter)NULL,
4206 "the real part of a complex number",
4207 NULL},
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004208 {"imag",
4209 (getter)long_get0, (setter)NULL,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004210 "the imaginary part of a complex number",
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004211 NULL},
4212 {"numerator",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004213 (getter)long_long, (setter)NULL,
4214 "the numerator of a rational number in lowest terms",
4215 NULL},
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004216 {"denominator",
4217 (getter)long_get1, (setter)NULL,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004218 "the denominator of a rational number in lowest terms",
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004219 NULL},
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004220 {NULL} /* Sentinel */
4221};
4222
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004223PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00004224"long(x[, base]) -> integer\n\
4225\n\
4226Convert a string or number to a long integer, if possible. A floating\n\
4227point argument will be truncated towards zero (this does not include a\n\
4228string representation of a floating point number!) When converting a\n\
4229string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004230converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004231
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004232static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00004233 (binaryfunc) long_add, /*nb_add*/
4234 (binaryfunc) long_sub, /*nb_subtract*/
4235 (binaryfunc) long_mul, /*nb_multiply*/
Georg Brandl347b3002006-03-30 11:57:00 +00004236 long_classic_div, /*nb_divide*/
4237 long_mod, /*nb_remainder*/
4238 long_divmod, /*nb_divmod*/
4239 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004240 (unaryfunc) long_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004241 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004242 (unaryfunc) long_abs, /*tp_absolute*/
4243 (inquiry) long_nonzero, /*tp_nonzero*/
4244 (unaryfunc) long_invert, /*nb_invert*/
Georg Brandl347b3002006-03-30 11:57:00 +00004245 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004246 (binaryfunc) long_rshift, /*nb_rshift*/
Georg Brandl347b3002006-03-30 11:57:00 +00004247 long_and, /*nb_and*/
4248 long_xor, /*nb_xor*/
4249 long_or, /*nb_or*/
4250 long_coerce, /*nb_coerce*/
4251 long_int, /*nb_int*/
4252 long_long, /*nb_long*/
4253 long_float, /*nb_float*/
4254 long_oct, /*nb_oct*/
4255 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00004256 0, /* nb_inplace_add */
4257 0, /* nb_inplace_subtract */
4258 0, /* nb_inplace_multiply */
4259 0, /* nb_inplace_divide */
4260 0, /* nb_inplace_remainder */
4261 0, /* nb_inplace_power */
4262 0, /* nb_inplace_lshift */
4263 0, /* nb_inplace_rshift */
4264 0, /* nb_inplace_and */
4265 0, /* nb_inplace_xor */
4266 0, /* nb_inplace_or */
Georg Brandl347b3002006-03-30 11:57:00 +00004267 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00004268 long_true_divide, /* nb_true_divide */
4269 0, /* nb_inplace_floor_divide */
4270 0, /* nb_inplace_true_divide */
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004271 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004272};
4273
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004274PyTypeObject PyLong_Type = {
4275 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004276 0, /* ob_size */
4277 "long", /* tp_name */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00004278 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004279 sizeof(digit), /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00004280 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004281 0, /* tp_print */
4282 0, /* tp_getattr */
4283 0, /* tp_setattr */
4284 (cmpfunc)long_compare, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00004285 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286 &long_as_number, /* tp_as_number */
4287 0, /* tp_as_sequence */
4288 0, /* tp_as_mapping */
4289 (hashfunc)long_hash, /* tp_hash */
4290 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00004291 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004292 PyObject_GenericGetAttr, /* tp_getattro */
4293 0, /* tp_setattro */
4294 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00004295 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00004296 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004297 long_doc, /* tp_doc */
4298 0, /* tp_traverse */
4299 0, /* tp_clear */
4300 0, /* tp_richcompare */
4301 0, /* tp_weaklistoffset */
4302 0, /* tp_iter */
4303 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004304 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004305 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004306 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004307 0, /* tp_base */
4308 0, /* tp_dict */
4309 0, /* tp_descr_get */
4310 0, /* tp_descr_set */
4311 0, /* tp_dictoffset */
4312 0, /* tp_init */
4313 0, /* tp_alloc */
4314 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00004315 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004316};
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004317
4318static PyTypeObject Long_InfoType;
4319
4320PyDoc_STRVAR(long_info__doc__,
4321"sys.long_info\n\
4322\n\
4323A struct sequence that holds information about Python's\n\
4324internal representation of integers. The attributes are read only.");
4325
4326static PyStructSequence_Field long_info_fields[] = {
4327 {"bits_per_digit", "size of a digit in bits"},
4328 {"sizeof_digit", "size in bytes of the C type used to "
4329 "represent a digit"},
4330 {NULL, NULL}
4331};
4332
4333static PyStructSequence_Desc long_info_desc = {
4334 "sys.long_info", /* name */
4335 long_info__doc__, /* doc */
4336 long_info_fields, /* fields */
4337 2 /* number of fields */
4338};
4339
4340PyObject *
4341PyLong_GetInfo(void)
4342{
4343 PyObject* long_info;
4344 int field = 0;
4345 long_info = PyStructSequence_New(&Long_InfoType);
4346 if (long_info == NULL)
4347 return NULL;
Mark Dickinson48e3fd22009-04-02 18:39:37 +00004348 PyStructSequence_SET_ITEM(long_info, field++,
4349 PyInt_FromLong(PyLong_SHIFT));
4350 PyStructSequence_SET_ITEM(long_info, field++,
4351 PyInt_FromLong(sizeof(digit)));
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004352 if (PyErr_Occurred()) {
4353 Py_CLEAR(long_info);
4354 return NULL;
4355 }
4356 return long_info;
4357}
4358
4359int
4360_PyLong_Init(void)
4361{
4362 /* initialize long_info */
4363 if (Long_InfoType.tp_name == 0)
4364 PyStructSequence_InitType(&Long_InfoType, &long_info_desc);
4365 return 1;
4366}