blob: a41782ae250011499d81256d41bea8e09af49d12 [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,
Stefan Krahef7590e2010-04-07 08:24:44 +00002258 (int)shift_bits);
Mark Dickinsond3e32322010-01-02 14:45:40 +00002259 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,
Stefan Krahef7590e2010-04-07 08:24:44 +00002266 a_size - shift_digits, (int)shift_bits);
Mark Dickinsond3e32322010-01-02 14:45:40 +00002267 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 }
Stefan Krahef7590e2010-04-07 08:24:44 +00002328 return ldexp(x, (int)exponent);
Mark Dickinsond3e32322010-01-02 14:45:40 +00002329}
2330
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002331/* Methods */
2332
2333static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002334long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002335{
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)) {
Mark Dickinson22ff6642010-05-08 08:01:19 +00002357 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002358 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002359 else {
Christian Heimese93237d2007-12-19 02:37:44 +00002360 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002361 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2362 ;
2363 if (i < 0)
2364 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002365 else {
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00002366 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimese93237d2007-12-19 02:37:44 +00002367 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002368 sign = -sign;
2369 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002370 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002371 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002372}
2373
Guido van Rossum9bfef441993-03-29 10:43:31 +00002374static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002375long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002376{
Mark Dickinson6ffa4a22009-01-26 21:36:30 +00002377 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002378 Py_ssize_t i;
2379 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002380
2381 /* This is designed so that Python ints and longs with the
2382 same value hash to the same value, otherwise comparisons
2383 of mapping keys will turn out weird */
2384 i = v->ob_size;
2385 sign = 1;
2386 x = 0;
2387 if (i < 0) {
2388 sign = -1;
2389 i = -(i);
2390 }
Mark Dickinsona0eae032009-01-26 21:40:08 +00002391 /* The following loop produces a C unsigned long x such that x is
2392 congruent to the absolute value of v modulo ULONG_MAX. The
2393 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002394 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002395 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00002396 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002397 x += v->ob_digit[i];
Mark Dickinson6ffa4a22009-01-26 21:36:30 +00002398 /* If the addition above overflowed we compensate by
2399 incrementing. This preserves the value modulo
2400 ULONG_MAX. */
2401 if (x < v->ob_digit[i])
Facundo Batistad544df72007-09-19 15:10:06 +00002402 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002403 }
2404 x = x * sign;
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00002405 if (x == (unsigned long)-1)
2406 x = (unsigned long)-2;
2407 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002408}
2409
2410
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002411/* Add the absolute values of two long integers. */
2412
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002413static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002414x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002415{
Christian Heimese93237d2007-12-19 02:37:44 +00002416 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002417 PyLongObject *z;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00002418 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002419 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002420
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002421 /* Ensure a is the larger of the two: */
2422 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002423 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002424 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002425 size_a = size_b;
2426 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002427 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002428 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002429 if (z == NULL)
2430 return NULL;
2431 for (i = 0; i < size_b; ++i) {
2432 carry += a->ob_digit[i] + b->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002433 z->ob_digit[i] = carry & PyLong_MASK;
2434 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002435 }
2436 for (; i < size_a; ++i) {
2437 carry += a->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002438 z->ob_digit[i] = carry & PyLong_MASK;
2439 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002440 }
2441 z->ob_digit[i] = carry;
2442 return long_normalize(z);
2443}
2444
2445/* Subtract the absolute values of two integers. */
2446
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002447static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002448x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002449{
Christian Heimese93237d2007-12-19 02:37:44 +00002450 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002451 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002452 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002453 int sign = 1;
2454 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002455
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002456 /* Ensure a is the larger of the two: */
2457 if (size_a < size_b) {
2458 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002459 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002460 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002461 size_a = size_b;
2462 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002463 }
2464 else if (size_a == size_b) {
2465 /* Find highest digit where a and b differ: */
2466 i = size_a;
2467 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2468 ;
2469 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002470 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002471 if (a->ob_digit[i] < b->ob_digit[i]) {
2472 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002473 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002474 }
2475 size_a = size_b = i+1;
2476 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002477 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002478 if (z == NULL)
2479 return NULL;
2480 for (i = 0; i < size_b; ++i) {
2481 /* The following assumes unsigned arithmetic
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002482 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002483 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002484 z->ob_digit[i] = borrow & PyLong_MASK;
2485 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002486 borrow &= 1; /* Keep only one sign bit */
2487 }
2488 for (; i < size_a; ++i) {
2489 borrow = a->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002490 z->ob_digit[i] = borrow & PyLong_MASK;
2491 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002492 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002493 }
2494 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002495 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002496 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002497 return long_normalize(z);
2498}
2499
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002500static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002501long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002502{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002503 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002504
Neil Schemenauerba872e22001-01-04 01:46:03 +00002505 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2506
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002507 if (a->ob_size < 0) {
2508 if (b->ob_size < 0) {
2509 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002510 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002511 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002512 }
2513 else
2514 z = x_sub(b, a);
2515 }
2516 else {
2517 if (b->ob_size < 0)
2518 z = x_sub(a, b);
2519 else
2520 z = x_add(a, b);
2521 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002522 Py_DECREF(a);
2523 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002524 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002525}
2526
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002527static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002528long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002529{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002530 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002531
Neil Schemenauerba872e22001-01-04 01:46:03 +00002532 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2533
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002534 if (a->ob_size < 0) {
2535 if (b->ob_size < 0)
2536 z = x_sub(a, b);
2537 else
2538 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002539 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002540 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002541 }
2542 else {
2543 if (b->ob_size < 0)
2544 z = x_add(a, b);
2545 else
2546 z = x_sub(a, b);
2547 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002548 Py_DECREF(a);
2549 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002550 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002551}
2552
Tim Peters5af4e6c2002-08-12 02:31:19 +00002553/* Grade school multiplication, ignoring the signs.
2554 * Returns the absolute value of the product, or NULL if error.
2555 */
2556static PyLongObject *
2557x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002558{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002559 PyLongObject *z;
Christian Heimese93237d2007-12-19 02:37:44 +00002560 Py_ssize_t size_a = ABS(Py_SIZE(a));
2561 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002562 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002563
Tim Peters5af4e6c2002-08-12 02:31:19 +00002564 z = _PyLong_New(size_a + size_b);
2565 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002566 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002567
Christian Heimese93237d2007-12-19 02:37:44 +00002568 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002569 if (a == b) {
2570 /* Efficient squaring per HAC, Algorithm 14.16:
2571 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2572 * Gives slightly less than a 2x speedup when a == b,
2573 * via exploiting that each entry in the multiplication
2574 * pyramid appears twice (except for the size_a squares).
2575 */
2576 for (i = 0; i < size_a; ++i) {
2577 twodigits carry;
2578 twodigits f = a->ob_digit[i];
2579 digit *pz = z->ob_digit + (i << 1);
2580 digit *pa = a->ob_digit + i + 1;
2581 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002582
Tim Peters0973b992004-08-29 22:16:50 +00002583 SIGCHECK({
2584 Py_DECREF(z);
2585 return NULL;
2586 })
2587
2588 carry = *pz + f * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002589 *pz++ = (digit)(carry & PyLong_MASK);
2590 carry >>= PyLong_SHIFT;
2591 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002592
2593 /* Now f is added in twice in each column of the
2594 * pyramid it appears. Same as adding f<<1 once.
2595 */
2596 f <<= 1;
2597 while (pa < paend) {
2598 carry += *pz + *pa++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002599 *pz++ = (digit)(carry & PyLong_MASK);
2600 carry >>= PyLong_SHIFT;
2601 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002602 }
2603 if (carry) {
2604 carry += *pz;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002605 *pz++ = (digit)(carry & PyLong_MASK);
2606 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002607 }
2608 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002609 *pz += (digit)(carry & PyLong_MASK);
2610 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002611 }
Tim Peters0973b992004-08-29 22:16:50 +00002612 }
2613 else { /* a is not the same as b -- gradeschool long mult */
2614 for (i = 0; i < size_a; ++i) {
2615 twodigits carry = 0;
2616 twodigits f = a->ob_digit[i];
2617 digit *pz = z->ob_digit + i;
2618 digit *pb = b->ob_digit;
2619 digit *pbend = b->ob_digit + size_b;
2620
2621 SIGCHECK({
2622 Py_DECREF(z);
2623 return NULL;
2624 })
2625
2626 while (pb < pbend) {
2627 carry += *pz + *pb++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002628 *pz++ = (digit)(carry & PyLong_MASK);
2629 carry >>= PyLong_SHIFT;
2630 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002631 }
2632 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002633 *pz += (digit)(carry & PyLong_MASK);
2634 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002635 }
2636 }
Tim Peters44121a62002-08-12 06:17:58 +00002637 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002638}
2639
2640/* A helper for Karatsuba multiplication (k_mul).
2641 Takes a long "n" and an integer "size" representing the place to
2642 split, and sets low and high such that abs(n) == (high << size) + low,
2643 viewing the shift as being by digits. The sign bit is ignored, and
2644 the return values are >= 0.
2645 Returns 0 on success, -1 on failure.
2646*/
2647static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002648kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002649{
2650 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002651 Py_ssize_t size_lo, size_hi;
Christian Heimese93237d2007-12-19 02:37:44 +00002652 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002653
2654 size_lo = MIN(size_n, size);
2655 size_hi = size_n - size_lo;
2656
2657 if ((hi = _PyLong_New(size_hi)) == NULL)
2658 return -1;
2659 if ((lo = _PyLong_New(size_lo)) == NULL) {
2660 Py_DECREF(hi);
2661 return -1;
2662 }
2663
2664 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2665 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2666
2667 *high = long_normalize(hi);
2668 *low = long_normalize(lo);
2669 return 0;
2670}
2671
Tim Peters60004642002-08-12 22:01:34 +00002672static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2673
Tim Peters5af4e6c2002-08-12 02:31:19 +00002674/* Karatsuba multiplication. Ignores the input signs, and returns the
2675 * absolute value of the product (or NULL if error).
2676 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2677 */
2678static PyLongObject *
2679k_mul(PyLongObject *a, PyLongObject *b)
2680{
Christian Heimese93237d2007-12-19 02:37:44 +00002681 Py_ssize_t asize = ABS(Py_SIZE(a));
2682 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002683 PyLongObject *ah = NULL;
2684 PyLongObject *al = NULL;
2685 PyLongObject *bh = NULL;
2686 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002687 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002688 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002689 Py_ssize_t shift; /* the number of digits we split off */
2690 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002691
Tim Peters5af4e6c2002-08-12 02:31:19 +00002692 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2693 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2694 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002695 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002696 * By picking X to be a power of 2, "*X" is just shifting, and it's
2697 * been reduced to 3 multiplies on numbers half the size.
2698 */
2699
Tim Petersfc07e562002-08-12 02:54:10 +00002700 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002701 * is largest.
2702 */
Tim Peters738eda72002-08-12 15:08:20 +00002703 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002704 t1 = a;
2705 a = b;
2706 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002707
2708 i = asize;
2709 asize = bsize;
2710 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002711 }
2712
2713 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002714 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2715 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002716 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002717 return _PyLong_New(0);
2718 else
2719 return x_mul(a, b);
2720 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002721
Tim Peters60004642002-08-12 22:01:34 +00002722 /* If a is small compared to b, splitting on b gives a degenerate
2723 * case with ah==0, and Karatsuba may be (even much) less efficient
2724 * than "grade school" then. However, we can still win, by viewing
2725 * b as a string of "big digits", each of width a->ob_size. That
2726 * leads to a sequence of balanced calls to k_mul.
2727 */
2728 if (2 * asize <= bsize)
2729 return k_lopsided_mul(a, b);
2730
Tim Petersd6974a52002-08-13 20:37:51 +00002731 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002732 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002733 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002734 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002735
Tim Peters0973b992004-08-29 22:16:50 +00002736 if (a == b) {
2737 bh = ah;
2738 bl = al;
2739 Py_INCREF(bh);
2740 Py_INCREF(bl);
2741 }
2742 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002743
Tim Petersd64c1de2002-08-12 17:36:03 +00002744 /* The plan:
2745 * 1. Allocate result space (asize + bsize digits: that's always
2746 * enough).
2747 * 2. Compute ah*bh, and copy into result at 2*shift.
2748 * 3. Compute al*bl, and copy into result at 0. Note that this
2749 * can't overlap with #2.
2750 * 4. Subtract al*bl from the result, starting at shift. This may
2751 * underflow (borrow out of the high digit), but we don't care:
2752 * we're effectively doing unsigned arithmetic mod
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002753 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
Tim Petersd64c1de2002-08-12 17:36:03 +00002754 * borrows and carries out of the high digit can be ignored.
2755 * 5. Subtract ah*bh from the result, starting at shift.
2756 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2757 * at shift.
2758 */
2759
2760 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002761 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002762 if (ret == NULL) goto fail;
2763#ifdef Py_DEBUG
2764 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002765 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002766#endif
Tim Peters44121a62002-08-12 06:17:58 +00002767
Tim Petersd64c1de2002-08-12 17:36:03 +00002768 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002769 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002770 assert(Py_SIZE(t1) >= 0);
2771 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002772 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimese93237d2007-12-19 02:37:44 +00002773 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002774
2775 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimese93237d2007-12-19 02:37:44 +00002776 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002777 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002778 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002779 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002780
Tim Petersd64c1de2002-08-12 17:36:03 +00002781 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002782 if ((t2 = k_mul(al, bl)) == NULL) {
2783 Py_DECREF(t1);
2784 goto fail;
2785 }
Christian Heimese93237d2007-12-19 02:37:44 +00002786 assert(Py_SIZE(t2) >= 0);
2787 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2788 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002789
2790 /* Zero out remaining digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002791 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002792 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002793 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002794
Tim Petersd64c1de2002-08-12 17:36:03 +00002795 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2796 * because it's fresher in cache.
2797 */
Christian Heimese93237d2007-12-19 02:37:44 +00002798 i = Py_SIZE(ret) - shift; /* # digits after shift */
2799 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002800 Py_DECREF(t2);
2801
Christian Heimese93237d2007-12-19 02:37:44 +00002802 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002803 Py_DECREF(t1);
2804
Tim Petersd64c1de2002-08-12 17:36:03 +00002805 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002806 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2807 Py_DECREF(ah);
2808 Py_DECREF(al);
2809 ah = al = NULL;
2810
Tim Peters0973b992004-08-29 22:16:50 +00002811 if (a == b) {
2812 t2 = t1;
2813 Py_INCREF(t2);
2814 }
2815 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002816 Py_DECREF(t1);
2817 goto fail;
2818 }
2819 Py_DECREF(bh);
2820 Py_DECREF(bl);
2821 bh = bl = NULL;
2822
Tim Peters738eda72002-08-12 15:08:20 +00002823 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002824 Py_DECREF(t1);
2825 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002826 if (t3 == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002827 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002828
Tim Petersd6974a52002-08-13 20:37:51 +00002829 /* Add t3. It's not obvious why we can't run out of room here.
2830 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002831 */
Christian Heimese93237d2007-12-19 02:37:44 +00002832 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002833 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002834
Tim Peters5af4e6c2002-08-12 02:31:19 +00002835 return long_normalize(ret);
2836
2837 fail:
2838 Py_XDECREF(ret);
2839 Py_XDECREF(ah);
2840 Py_XDECREF(al);
2841 Py_XDECREF(bh);
2842 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002843 return NULL;
2844}
2845
Tim Petersd6974a52002-08-13 20:37:51 +00002846/* (*) Why adding t3 can't "run out of room" above.
2847
Tim Petersab86c2b2002-08-15 20:06:00 +00002848Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2849to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002850
Tim Petersab86c2b2002-08-15 20:06:00 +000028511. For any integer i, i = c(i/2) + f(i/2). In particular,
2852 bsize = c(bsize/2) + f(bsize/2).
28532. shift = f(bsize/2)
28543. asize <= bsize
28554. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2856 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002857
Tim Petersab86c2b2002-08-15 20:06:00 +00002858We allocated asize + bsize result digits, and add t3 into them at an offset
2859of shift. This leaves asize+bsize-shift allocated digit positions for t3
2860to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2861asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002862
Tim Petersab86c2b2002-08-15 20:06:00 +00002863bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2864at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002865
Tim Petersab86c2b2002-08-15 20:06:00 +00002866If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2867digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2868most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002869
Tim Petersab86c2b2002-08-15 20:06:00 +00002870The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002871
Tim Petersab86c2b2002-08-15 20:06:00 +00002872 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002873
Tim Petersab86c2b2002-08-15 20:06:00 +00002874and we have asize + c(bsize/2) available digit positions. We need to show
2875this is always enough. An instance of c(bsize/2) cancels out in both, so
2876the question reduces to whether asize digits is enough to hold
2877(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2878then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2879asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002880digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002881asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002882c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2883is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2884bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002885
Tim Peters48d52c02002-08-14 17:07:32 +00002886Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2887clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2888ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002889*/
2890
Tim Peters60004642002-08-12 22:01:34 +00002891/* b has at least twice the digits of a, and a is big enough that Karatsuba
2892 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2893 * of slices, each with a->ob_size digits, and multiply the slices by a,
2894 * one at a time. This gives k_mul balanced inputs to work with, and is
2895 * also cache-friendly (we compute one double-width slice of the result
2896 * at a time, then move on, never bactracking except for the helpful
2897 * single-width slice overlap between successive partial sums).
2898 */
2899static PyLongObject *
2900k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2901{
Christian Heimese93237d2007-12-19 02:37:44 +00002902 const Py_ssize_t asize = ABS(Py_SIZE(a));
2903 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002904 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002905 PyLongObject *ret;
2906 PyLongObject *bslice = NULL;
2907
2908 assert(asize > KARATSUBA_CUTOFF);
2909 assert(2 * asize <= bsize);
2910
2911 /* Allocate result space, and zero it out. */
2912 ret = _PyLong_New(asize + bsize);
2913 if (ret == NULL)
2914 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002915 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002916
2917 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002918 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002919 if (bslice == NULL)
2920 goto fail;
2921
2922 nbdone = 0;
2923 while (bsize > 0) {
2924 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002925 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002926
2927 /* Multiply the next slice of b by a. */
2928 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2929 nbtouse * sizeof(digit));
Christian Heimese93237d2007-12-19 02:37:44 +00002930 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002931 product = k_mul(a, bslice);
2932 if (product == NULL)
2933 goto fail;
2934
2935 /* Add into result. */
Christian Heimese93237d2007-12-19 02:37:44 +00002936 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2937 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002938 Py_DECREF(product);
2939
2940 bsize -= nbtouse;
2941 nbdone += nbtouse;
2942 }
2943
2944 Py_DECREF(bslice);
2945 return long_normalize(ret);
2946
2947 fail:
2948 Py_DECREF(ret);
2949 Py_XDECREF(bslice);
2950 return NULL;
2951}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002952
2953static PyObject *
2954long_mul(PyLongObject *v, PyLongObject *w)
2955{
2956 PyLongObject *a, *b, *z;
2957
2958 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002959 Py_INCREF(Py_NotImplemented);
2960 return Py_NotImplemented;
2961 }
2962
Tim Petersd64c1de2002-08-12 17:36:03 +00002963 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002964 /* Negate if exactly one of the inputs is negative. */
2965 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002966 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002967 Py_DECREF(a);
2968 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002969 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002970}
2971
Guido van Rossume32e0141992-01-19 16:31:05 +00002972/* The / and % operators are now defined in terms of divmod().
2973 The expression a mod b has the value a - b*floor(a/b).
2974 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002975 |a| by |b|, with the sign of a. This is also expressed
2976 as a - b*trunc(a/b), if trunc truncates towards zero.
2977 Some examples:
2978 a b a rem b a mod b
2979 13 10 3 3
2980 -13 10 -3 7
2981 13 -10 3 -7
2982 -13 -10 -3 -3
2983 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002984 have different signs. We then subtract one from the 'div'
2985 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002986
Tim Peters47e52ee2004-08-30 02:44:38 +00002987/* Compute
2988 * *pdiv, *pmod = divmod(v, w)
2989 * NULL can be passed for pdiv or pmod, in which case that part of
2990 * the result is simply thrown away. The caller owns a reference to
2991 * each of these it requests (does not pass NULL for).
2992 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002993static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002994l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002995 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002996{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002997 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002998
Guido van Rossume32e0141992-01-19 16:31:05 +00002999 if (long_divrem(v, w, &div, &mod) < 0)
3000 return -1;
Christian Heimese93237d2007-12-19 02:37:44 +00003001 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3002 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003003 PyLongObject *temp;
3004 PyLongObject *one;
3005 temp = (PyLongObject *) long_add(mod, w);
3006 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00003007 mod = temp;
3008 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003009 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003010 return -1;
3011 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003012 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00003013 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003014 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3015 Py_DECREF(mod);
3016 Py_DECREF(div);
3017 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00003018 return -1;
3019 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003020 Py_DECREF(one);
3021 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003022 div = temp;
3023 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003024 if (pdiv != NULL)
3025 *pdiv = div;
3026 else
3027 Py_DECREF(div);
3028
3029 if (pmod != NULL)
3030 *pmod = mod;
3031 else
3032 Py_DECREF(mod);
3033
Guido van Rossume32e0141992-01-19 16:31:05 +00003034 return 0;
3035}
3036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003037static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003038long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00003039{
Tim Peters47e52ee2004-08-30 02:44:38 +00003040 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003041
3042 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003043 if (l_divmod(a, b, &div, NULL) < 0)
3044 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003045 Py_DECREF(a);
3046 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003047 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003048}
3049
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003050static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00003051long_classic_div(PyObject *v, PyObject *w)
3052{
Tim Peters47e52ee2004-08-30 02:44:38 +00003053 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00003054
3055 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00003056 if (Py_DivisionWarningFlag &&
3057 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
3058 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003059 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00003060 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00003061 Py_DECREF(a);
3062 Py_DECREF(b);
3063 return (PyObject *)div;
3064}
3065
Mark Dickinson46572832009-12-27 14:55:57 +00003066/* PyLong/PyLong -> float, with correctly rounded result. */
3067
3068#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3069#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3070
Guido van Rossum393661d2001-08-31 17:40:15 +00003071static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00003072long_true_divide(PyObject *v, PyObject *w)
3073{
Mark Dickinson46572832009-12-27 14:55:57 +00003074 PyLongObject *a, *b, *x;
3075 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3076 digit mask, low;
3077 int inexact, negate, a_is_small, b_is_small;
3078 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003079
3080 CONVERT_BINOP(v, w, &a, &b);
Tim Peterse2a60002001-09-04 06:17:36 +00003081
Mark Dickinson46572832009-12-27 14:55:57 +00003082 /*
3083 Method in a nutshell:
3084
3085 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3086 1. choose a suitable integer 'shift'
3087 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3088 3. adjust x for correct rounding
3089 4. convert x to a double dx with the same value
3090 5. return ldexp(dx, shift).
3091
3092 In more detail:
3093
3094 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3095 returns either 0.0 or -0.0, depending on the sign of b. For a and
3096 b both nonzero, ignore signs of a and b, and add the sign back in
3097 at the end. Now write a_bits and b_bits for the bit lengths of a
3098 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3099 for b). Then
3100
3101 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
3102
3103 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3104 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3105 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3106 the way, we can assume that
3107
3108 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
3109
3110 1. The integer 'shift' is chosen so that x has the right number of
3111 bits for a double, plus two or three extra bits that will be used
3112 in the rounding decisions. Writing a_bits and b_bits for the
3113 number of significant bits in a and b respectively, a
3114 straightforward formula for shift is:
3115
3116 shift = a_bits - b_bits - DBL_MANT_DIG - 2
3117
3118 This is fine in the usual case, but if a/b is smaller than the
3119 smallest normal float then it can lead to double rounding on an
3120 IEEE 754 platform, giving incorrectly rounded results. So we
3121 adjust the formula slightly. The actual formula used is:
3122
3123 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
3124
3125 2. The quantity x is computed by first shifting a (left -shift bits
3126 if shift <= 0, right shift bits if shift > 0) and then dividing by
3127 b. For both the shift and the division, we keep track of whether
3128 the result is inexact, in a flag 'inexact'; this information is
3129 needed at the rounding stage.
3130
3131 With the choice of shift above, together with our assumption that
3132 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3133 that x >= 1.
3134
3135 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3136 this with an exactly representable float of the form
3137
3138 round(x/2**extra_bits) * 2**(extra_bits+shift).
3139
3140 For float representability, we need x/2**extra_bits <
3141 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3142 DBL_MANT_DIG. This translates to the condition:
3143
3144 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
3145
3146 To round, we just modify the bottom digit of x in-place; this can
3147 end up giving a digit with value > PyLONG_MASK, but that's not a
3148 problem since digits can hold values up to 2*PyLONG_MASK+1.
3149
3150 With the original choices for shift above, extra_bits will always
3151 be 2 or 3. Then rounding under the round-half-to-even rule, we
3152 round up iff the most significant of the extra bits is 1, and
3153 either: (a) the computation of x in step 2 had an inexact result,
3154 or (b) at least one other of the extra bits is 1, or (c) the least
3155 significant bit of x (above those to be rounded) is 1.
3156
3157 4. Conversion to a double is straightforward; all floating-point
3158 operations involved in the conversion are exact, so there's no
3159 danger of rounding errors.
3160
3161 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3162 The result will always be exactly representable as a double, except
3163 in the case that it overflows. To avoid dependence on the exact
3164 behaviour of ldexp on overflow, we check for overflow before
3165 applying ldexp. The result of ldexp is adjusted for sign before
3166 returning.
3167 */
3168
3169 /* Reduce to case where a and b are both positive. */
3170 a_size = ABS(Py_SIZE(a));
3171 b_size = ABS(Py_SIZE(b));
3172 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3173 if (b_size == 0) {
Tim Peterse2a60002001-09-04 06:17:36 +00003174 PyErr_SetString(PyExc_ZeroDivisionError,
Mark Dickinson46572832009-12-27 14:55:57 +00003175 "division by zero");
3176 goto error;
3177 }
3178 if (a_size == 0)
3179 goto underflow_or_zero;
3180
3181 /* Fast path for a and b small (exactly representable in a double).
3182 Relies on floating-point division being correctly rounded; results
3183 may be subject to double rounding on x86 machines that operate with
3184 the x87 FPU set to 64-bit precision. */
3185 a_is_small = a_size <= MANT_DIG_DIGITS ||
3186 (a_size == MANT_DIG_DIGITS+1 &&
3187 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3188 b_is_small = b_size <= MANT_DIG_DIGITS ||
3189 (b_size == MANT_DIG_DIGITS+1 &&
3190 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3191 if (a_is_small && b_is_small) {
3192 double da, db;
3193 da = a->ob_digit[--a_size];
3194 while (a_size > 0)
3195 da = da * PyLong_BASE + a->ob_digit[--a_size];
3196 db = b->ob_digit[--b_size];
3197 while (b_size > 0)
3198 db = db * PyLong_BASE + b->ob_digit[--b_size];
3199 result = da / db;
3200 goto success;
Tim Peterse2a60002001-09-04 06:17:36 +00003201 }
3202
Mark Dickinson46572832009-12-27 14:55:57 +00003203 /* Catch obvious cases of underflow and overflow */
3204 diff = a_size - b_size;
3205 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3206 /* Extreme overflow */
Tim Peterse2a60002001-09-04 06:17:36 +00003207 goto overflow;
Mark Dickinson46572832009-12-27 14:55:57 +00003208 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3209 /* Extreme underflow */
3210 goto underflow_or_zero;
3211 /* Next line is now safe from overflowing a Py_ssize_t */
3212 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3213 bits_in_digit(b->ob_digit[b_size - 1]);
3214 /* Now diff = a_bits - b_bits. */
3215 if (diff > DBL_MAX_EXP)
Tim Peterse2a60002001-09-04 06:17:36 +00003216 goto overflow;
Mark Dickinson46572832009-12-27 14:55:57 +00003217 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3218 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003219
Mark Dickinson46572832009-12-27 14:55:57 +00003220 /* Choose value for shift; see comments for step 1 above. */
3221 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
3222
3223 inexact = 0;
3224
3225 /* x = abs(a * 2**-shift) */
3226 if (shift <= 0) {
3227 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3228 digit rem;
3229 /* x = a << -shift */
3230 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3231 /* In practice, it's probably impossible to end up
3232 here. Both a and b would have to be enormous,
3233 using close to SIZE_T_MAX bytes of memory each. */
3234 PyErr_SetString(PyExc_OverflowError,
3235 "intermediate overflow during division");
3236 goto error;
3237 }
3238 x = _PyLong_New(a_size + shift_digits + 1);
3239 if (x == NULL)
3240 goto error;
3241 for (i = 0; i < shift_digits; i++)
3242 x->ob_digit[i] = 0;
3243 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3244 a_size, -shift % PyLong_SHIFT);
3245 x->ob_digit[a_size + shift_digits] = rem;
3246 }
3247 else {
3248 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3249 digit rem;
3250 /* x = a >> shift */
3251 assert(a_size >= shift_digits);
3252 x = _PyLong_New(a_size - shift_digits);
3253 if (x == NULL)
3254 goto error;
3255 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3256 a_size - shift_digits, shift % PyLong_SHIFT);
3257 /* set inexact if any of the bits shifted out is nonzero */
3258 if (rem)
3259 inexact = 1;
3260 while (!inexact && shift_digits > 0)
3261 if (a->ob_digit[--shift_digits])
3262 inexact = 1;
3263 }
3264 long_normalize(x);
3265 x_size = Py_SIZE(x);
3266
3267 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3268 reference to x, so it's safe to modify it in-place. */
3269 if (b_size == 1) {
3270 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3271 b->ob_digit[0]);
3272 long_normalize(x);
3273 if (rem)
3274 inexact = 1;
3275 }
3276 else {
3277 PyLongObject *div, *rem;
3278 div = x_divrem(x, b, &rem);
3279 Py_DECREF(x);
3280 x = div;
3281 if (x == NULL)
3282 goto error;
3283 if (Py_SIZE(rem))
3284 inexact = 1;
3285 Py_DECREF(rem);
3286 }
3287 x_size = ABS(Py_SIZE(x));
3288 assert(x_size > 0); /* result of division is never zero */
3289 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
3290
3291 /* The number of extra bits that have to be rounded away. */
3292 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3293 assert(extra_bits == 2 || extra_bits == 3);
3294
3295 /* Round by directly modifying the low digit of x. */
3296 mask = (digit)1 << (extra_bits - 1);
3297 low = x->ob_digit[0] | inexact;
3298 if (low & mask && low & (3*mask-1))
3299 low += mask;
3300 x->ob_digit[0] = low & ~(mask-1U);
3301
3302 /* Convert x to a double dx; the conversion is exact. */
3303 dx = x->ob_digit[--x_size];
3304 while (x_size > 0)
3305 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3306 Py_DECREF(x);
3307
3308 /* Check whether ldexp result will overflow a double. */
3309 if (shift + x_bits >= DBL_MAX_EXP &&
Stefan Krahef7590e2010-04-07 08:24:44 +00003310 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
Mark Dickinson46572832009-12-27 14:55:57 +00003311 goto overflow;
Stefan Krahef7590e2010-04-07 08:24:44 +00003312 result = ldexp(dx, (int)shift);
Mark Dickinson46572832009-12-27 14:55:57 +00003313
3314 success:
3315 Py_DECREF(a);
3316 Py_DECREF(b);
3317 return PyFloat_FromDouble(negate ? -result : result);
3318
3319 underflow_or_zero:
3320 Py_DECREF(a);
3321 Py_DECREF(b);
3322 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
3323
3324 overflow:
Tim Peterse2a60002001-09-04 06:17:36 +00003325 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson46572832009-12-27 14:55:57 +00003326 "integer division result too large for a float");
3327 error:
3328 Py_DECREF(a);
3329 Py_DECREF(b);
Tim Peterse2a60002001-09-04 06:17:36 +00003330 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003331}
3332
3333static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003334long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00003335{
Tim Peters47e52ee2004-08-30 02:44:38 +00003336 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003337
3338 CONVERT_BINOP(v, w, &a, &b);
3339
Tim Peters47e52ee2004-08-30 02:44:38 +00003340 if (l_divmod(a, b, NULL, &mod) < 0)
3341 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003342 Py_DECREF(a);
3343 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003344 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003345}
3346
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003347static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003348long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003349{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003350 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003351 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003352
3353 CONVERT_BINOP(v, w, &a, &b);
3354
3355 if (l_divmod(a, b, &div, &mod) < 0) {
3356 Py_DECREF(a);
3357 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003358 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003359 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003360 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003361 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003362 PyTuple_SetItem(z, 0, (PyObject *) div);
3363 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003364 }
3365 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003366 Py_DECREF(div);
3367 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003368 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003369 Py_DECREF(a);
3370 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003371 return z;
3372}
3373
Tim Peters47e52ee2004-08-30 02:44:38 +00003374/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003375static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003376long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003377{
Tim Peters47e52ee2004-08-30 02:44:38 +00003378 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3379 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003380
Tim Peters47e52ee2004-08-30 02:44:38 +00003381 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003382 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003383 PyLongObject *temp = NULL;
3384
3385 /* 5-ary values. If the exponent is large enough, table is
3386 * precomputed so that table[i] == a**i % c for i in range(32).
3387 */
3388 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3389 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3390
3391 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003392 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003393 if (PyLong_Check(x)) {
3394 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003395 Py_INCREF(x);
3396 }
Tim Petersde7990b2005-07-17 23:45:23 +00003397 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003398 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00003399 if (c == NULL)
3400 goto Error;
3401 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003402 else if (x == Py_None)
3403 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003404 else {
3405 Py_DECREF(a);
3406 Py_DECREF(b);
3407 Py_INCREF(Py_NotImplemented);
3408 return Py_NotImplemented;
3409 }
Tim Peters4c483c42001-09-05 06:24:58 +00003410
Christian Heimese93237d2007-12-19 02:37:44 +00003411 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003412 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003413 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003414 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003415 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003416 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003417 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003418 /* else return a float. This works because we know
3419 that this calls float_pow() which converts its
3420 arguments to double. */
3421 Py_DECREF(a);
3422 Py_DECREF(b);
3423 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003424 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003425 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003426
3427 if (c) {
3428 /* if modulus == 0:
3429 raise ValueError() */
Christian Heimese93237d2007-12-19 02:37:44 +00003430 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003431 PyErr_SetString(PyExc_ValueError,
3432 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003433 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003434 }
3435
3436 /* if modulus < 0:
3437 negativeOutput = True
3438 modulus = -modulus */
Christian Heimese93237d2007-12-19 02:37:44 +00003439 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003440 negativeOutput = 1;
3441 temp = (PyLongObject *)_PyLong_Copy(c);
3442 if (temp == NULL)
3443 goto Error;
3444 Py_DECREF(c);
3445 c = temp;
3446 temp = NULL;
3447 c->ob_size = - c->ob_size;
3448 }
3449
3450 /* if modulus == 1:
3451 return 0 */
Christian Heimese93237d2007-12-19 02:37:44 +00003452 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003453 z = (PyLongObject *)PyLong_FromLong(0L);
3454 goto Done;
3455 }
3456
3457 /* if base < 0:
3458 base = base % modulus
3459 Having the base positive just makes things easier. */
Christian Heimese93237d2007-12-19 02:37:44 +00003460 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003461 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003462 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003463 Py_DECREF(a);
3464 a = temp;
3465 temp = NULL;
3466 }
3467 }
3468
3469 /* At this point a, b, and c are guaranteed non-negative UNLESS
3470 c is NULL, in which case a may be negative. */
3471
3472 z = (PyLongObject *)PyLong_FromLong(1L);
3473 if (z == NULL)
3474 goto Error;
3475
3476 /* Perform a modular reduction, X = X % c, but leave X alone if c
3477 * is NULL.
3478 */
3479#define REDUCE(X) \
3480 if (c != NULL) { \
3481 if (l_divmod(X, c, NULL, &temp) < 0) \
3482 goto Error; \
3483 Py_XDECREF(X); \
3484 X = temp; \
3485 temp = NULL; \
3486 }
3487
3488 /* Multiply two values, then reduce the result:
3489 result = X*Y % c. If c is NULL, skip the mod. */
3490#define MULT(X, Y, result) \
3491{ \
3492 temp = (PyLongObject *)long_mul(X, Y); \
3493 if (temp == NULL) \
3494 goto Error; \
3495 Py_XDECREF(result); \
3496 result = temp; \
3497 temp = NULL; \
3498 REDUCE(result) \
3499}
3500
Christian Heimese93237d2007-12-19 02:37:44 +00003501 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003502 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3503 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimese93237d2007-12-19 02:37:44 +00003504 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003505 digit bi = b->ob_digit[i];
3506
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00003507 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003508 MULT(z, z, z)
3509 if (bi & j)
3510 MULT(z, a, z)
3511 }
3512 }
3513 }
3514 else {
3515 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3516 Py_INCREF(z); /* still holds 1L */
3517 table[0] = z;
3518 for (i = 1; i < 32; ++i)
3519 MULT(table[i-1], a, table[i])
3520
Christian Heimese93237d2007-12-19 02:37:44 +00003521 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003522 const digit bi = b->ob_digit[i];
3523
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003524 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003525 const int index = (bi >> j) & 0x1f;
3526 for (k = 0; k < 5; ++k)
3527 MULT(z, z, z)
3528 if (index)
3529 MULT(z, table[index], z)
3530 }
3531 }
3532 }
3533
Christian Heimese93237d2007-12-19 02:37:44 +00003534 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003535 temp = (PyLongObject *)long_sub(z, c);
3536 if (temp == NULL)
3537 goto Error;
3538 Py_DECREF(z);
3539 z = temp;
3540 temp = NULL;
3541 }
3542 goto Done;
3543
3544 Error:
3545 if (z != NULL) {
3546 Py_DECREF(z);
3547 z = NULL;
3548 }
3549 /* fall through */
3550 Done:
Christian Heimese93237d2007-12-19 02:37:44 +00003551 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003552 for (i = 0; i < 32; ++i)
3553 Py_XDECREF(table[i]);
3554 }
Tim Petersde7990b2005-07-17 23:45:23 +00003555 Py_DECREF(a);
3556 Py_DECREF(b);
3557 Py_XDECREF(c);
3558 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003559 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003560}
3561
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003562static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003563long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003564{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003565 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003566 PyLongObject *x;
3567 PyLongObject *w;
3568 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003569 if (w == NULL)
3570 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003571 x = (PyLongObject *) long_add(v, w);
3572 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003573 if (x == NULL)
3574 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00003575 Py_SIZE(x) = -(Py_SIZE(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003576 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003577}
3578
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003579static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003580long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003581{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003582 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003583 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003584 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003585 Py_INCREF(v);
3586 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003587 }
Tim Peters69c2de32001-09-11 22:31:33 +00003588 z = (PyLongObject *)_PyLong_Copy(v);
3589 if (z != NULL)
3590 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003591 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003592}
3593
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003594static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003595long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003596{
3597 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003598 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003599 else
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003600 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003601}
3602
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003603static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003604long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003605{
Mark Dickinson22ff6642010-05-08 08:01:19 +00003606 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003607}
3608
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003609static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003610long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003611{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003612 PyLongObject *a, *b;
3613 PyLongObject *z = NULL;
Mark Dickinson3ec9b942010-04-06 16:46:09 +00003614 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003615 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003616
Neil Schemenauerba872e22001-01-04 01:46:03 +00003617 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3618
Christian Heimese93237d2007-12-19 02:37:44 +00003619 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003620 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003621 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003622 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003623 if (a1 == NULL)
3624 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003625 a2 = (PyLongObject *) long_rshift(a1, b);
3626 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003627 if (a2 == NULL)
3628 goto rshift_error;
3629 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003630 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003631 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003632 else {
Mark Dickinson3ec9b942010-04-06 16:46:09 +00003633 shiftby = PyLong_AsSsize_t((PyObject *)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003634 if (shiftby == -1L && PyErr_Occurred())
3635 goto rshift_error;
3636 if (shiftby < 0) {
3637 PyErr_SetString(PyExc_ValueError,
3638 "negative shift count");
3639 goto rshift_error;
3640 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003641 wordshift = shiftby / PyLong_SHIFT;
Christian Heimese93237d2007-12-19 02:37:44 +00003642 newsize = ABS(Py_SIZE(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003643 if (newsize <= 0) {
3644 z = _PyLong_New(0);
3645 Py_DECREF(a);
3646 Py_DECREF(b);
3647 return (PyObject *)z;
3648 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003649 loshift = shiftby % PyLong_SHIFT;
3650 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003651 lomask = ((digit)1 << hishift) - 1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003652 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003653 z = _PyLong_New(newsize);
3654 if (z == NULL)
3655 goto rshift_error;
Christian Heimese93237d2007-12-19 02:37:44 +00003656 if (Py_SIZE(a) < 0)
3657 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003658 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3659 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3660 if (i+1 < newsize)
3661 z->ob_digit[i] |=
3662 (a->ob_digit[j+1] << hishift) & himask;
3663 }
3664 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003665 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003666rshift_error:
3667 Py_DECREF(a);
3668 Py_DECREF(b);
3669 return (PyObject *) z;
3670
Guido van Rossumc6913e71991-11-19 20:26:46 +00003671}
3672
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003673static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003674long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003675{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003676 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003677 PyLongObject *a, *b;
3678 PyLongObject *z = NULL;
Mark Dickinson3ec9b942010-04-06 16:46:09 +00003679 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003680 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003681
Neil Schemenauerba872e22001-01-04 01:46:03 +00003682 CONVERT_BINOP(v, w, &a, &b);
3683
Mark Dickinson3ec9b942010-04-06 16:46:09 +00003684 shiftby = PyLong_AsSsize_t((PyObject *)b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003685 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003686 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003687 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003688 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003689 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003690 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003691 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
Mark Dickinson3ec9b942010-04-06 16:46:09 +00003692 wordshift = shiftby / PyLong_SHIFT;
3693 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003694
3695 oldsize = ABS(a->ob_size);
3696 newsize = oldsize + wordshift;
3697 if (remshift)
3698 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003699 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003700 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003701 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003702 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003703 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003704 for (i = 0; i < wordshift; i++)
3705 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003706 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003707 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003708 accum |= (twodigits)a->ob_digit[j] << remshift;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003709 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3710 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003711 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003712 if (remshift)
3713 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003714 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003715 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003716 z = long_normalize(z);
3717lshift_error:
3718 Py_DECREF(a);
3719 Py_DECREF(b);
3720 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003721}
3722
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003723/* Compute two's complement of digit vector a[0:m], writing result to
3724 z[0:m]. The digit vector a need not be normalized, but should not
3725 be entirely zero. a and z may point to the same digit vector. */
3726
3727static void
3728v_complement(digit *z, digit *a, Py_ssize_t m)
3729{
3730 Py_ssize_t i;
3731 digit carry = 1;
3732 for (i = 0; i < m; ++i) {
3733 carry += a[i] ^ PyLong_MASK;
3734 z[i] = carry & PyLong_MASK;
3735 carry >>= PyLong_SHIFT;
3736 }
3737 assert(carry == 0);
3738}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003739
3740/* Bitwise and/xor/or operations */
3741
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003742static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003743long_bitwise(PyLongObject *a,
3744 int op, /* '&', '|', '^' */
3745 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003746{
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003747 int nega, negb, negz;
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00003748 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003749 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003750
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003751 /* Bitwise operations for negative numbers operate as though
3752 on a two's complement representation. So convert arguments
3753 from sign-magnitude to two's complement, and convert the
3754 result back to sign-magnitude at the end. */
3755
3756 /* If a is negative, replace it by its two's complement. */
3757 size_a = ABS(Py_SIZE(a));
3758 nega = Py_SIZE(a) < 0;
3759 if (nega) {
3760 z = _PyLong_New(size_a);
3761 if (z == NULL)
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003762 return NULL;
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003763 v_complement(z->ob_digit, a->ob_digit, size_a);
3764 a = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003765 }
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003766 else
3767 /* Keep reference count consistent. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003768 Py_INCREF(a);
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003769
3770 /* Same for b. */
3771 size_b = ABS(Py_SIZE(b));
3772 negb = Py_SIZE(b) < 0;
3773 if (negb) {
3774 z = _PyLong_New(size_b);
3775 if (z == NULL) {
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003776 Py_DECREF(a);
3777 return NULL;
3778 }
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003779 v_complement(z->ob_digit, b->ob_digit, size_b);
3780 b = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003781 }
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003782 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003783 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003784
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003785 /* Swap a and b if necessary to ensure size_a >= size_b. */
3786 if (size_a < size_b) {
3787 z = a; a = b; b = z;
3788 size_z = size_a; size_a = size_b; size_b = size_z;
3789 negz = nega; nega = negb; negb = negz;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003790 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003791
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003792 /* JRH: The original logic here was to allocate the result value (z)
3793 as the longer of the two operands. However, there are some cases
3794 where the result is guaranteed to be shorter than that: AND of two
3795 positives, OR of two negatives: use the shorter number. AND with
3796 mixed signs: use the positive number. OR with mixed signs: use the
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003797 negative number.
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003798 */
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003799 switch (op) {
3800 case '^':
3801 negz = nega ^ negb;
3802 size_z = size_a;
3803 break;
3804 case '&':
3805 negz = nega & negb;
3806 size_z = negb ? size_a : size_b;
3807 break;
3808 case '|':
3809 negz = nega | negb;
3810 size_z = negb ? size_b : size_a;
3811 break;
3812 default:
3813 PyErr_BadArgument();
3814 return NULL;
3815 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003816
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003817 /* We allow an extra digit if z is negative, to make sure that
3818 the final two's complement of z doesn't overflow. */
3819 z = _PyLong_New(size_z + negz);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003820 if (z == NULL) {
Neal Norwitzef02b9e2006-07-16 02:00:32 +00003821 Py_DECREF(a);
3822 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003823 return NULL;
3824 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003825
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003826 /* Compute digits for overlap of a and b. */
3827 switch(op) {
3828 case '&':
3829 for (i = 0; i < size_b; ++i)
3830 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
3831 break;
3832 case '|':
3833 for (i = 0; i < size_b; ++i)
3834 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
3835 break;
3836 case '^':
3837 for (i = 0; i < size_b; ++i)
3838 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
3839 break;
3840 default:
3841 PyErr_BadArgument();
3842 return NULL;
3843 }
3844
3845 /* Copy any remaining digits of a, inverting if necessary. */
3846 if (op == '^' && negb)
3847 for (; i < size_z; ++i)
3848 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
3849 else if (i < size_z)
3850 memcpy(&z->ob_digit[i], &a->ob_digit[i],
3851 (size_z-i)*sizeof(digit));
3852
3853 /* Complement result if negative. */
3854 if (negz) {
3855 Py_SIZE(z) = -(Py_SIZE(z));
3856 z->ob_digit[size_z] = PyLong_MASK;
3857 v_complement(z->ob_digit, z->ob_digit, size_z+1);
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003858 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003859
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003860 Py_DECREF(a);
3861 Py_DECREF(b);
Mark Dickinson8d87dc02009-10-25 20:39:06 +00003862 return (PyObject *)long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003863}
3864
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003865static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003866long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003867{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003868 PyLongObject *a, *b;
3869 PyObject *c;
3870 CONVERT_BINOP(v, w, &a, &b);
3871 c = long_bitwise(a, '&', b);
3872 Py_DECREF(a);
3873 Py_DECREF(b);
3874 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003875}
3876
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003877static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003878long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003879{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003880 PyLongObject *a, *b;
3881 PyObject *c;
3882 CONVERT_BINOP(v, w, &a, &b);
3883 c = long_bitwise(a, '^', b);
3884 Py_DECREF(a);
3885 Py_DECREF(b);
3886 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003887}
3888
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003889static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003890long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003891{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003892 PyLongObject *a, *b;
3893 PyObject *c;
3894 CONVERT_BINOP(v, w, &a, &b);
3895 c = long_bitwise(a, '|', b);
3896 Py_DECREF(a);
3897 Py_DECREF(b);
3898 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003899}
3900
Guido van Rossum234f9421993-06-17 12:35:49 +00003901static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003902long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003903{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003904 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00003905 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Georg Brandlc02e1312007-04-11 17:16:24 +00003906 if (*pw == NULL)
3907 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003908 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00003909 return 0;
3910 }
Guido van Rossum1952e382001-09-19 01:25:16 +00003911 else if (PyLong_Check(*pw)) {
3912 Py_INCREF(*pv);
3913 Py_INCREF(*pw);
3914 return 0;
3915 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00003916 return 1; /* Can't do it */
3917}
3918
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003919static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003920long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003921{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003922 if (PyLong_CheckExact(v))
3923 Py_INCREF(v);
3924 else
3925 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003926 return v;
3927}
3928
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003929static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003930long_int(PyObject *v)
3931{
3932 long x;
3933 x = PyLong_AsLong(v);
3934 if (PyErr_Occurred()) {
3935 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3936 PyErr_Clear();
3937 if (PyLong_CheckExact(v)) {
3938 Py_INCREF(v);
3939 return v;
3940 }
3941 else
3942 return _PyLong_Copy((PyLongObject *)v);
3943 }
3944 else
3945 return NULL;
3946 }
3947 return PyInt_FromLong(x);
3948}
3949
3950static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003951long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003952{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003953 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003954 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003955 if (result == -1.0 && PyErr_Occurred())
3956 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003957 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003958}
3959
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003960static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003961long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003962{
Eric Smith5e527eb2008-02-10 01:36:53 +00003963 return _PyLong_Format(v, 8, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003964}
3965
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003966static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003967long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003968{
Eric Smith5e527eb2008-02-10 01:36:53 +00003969 return _PyLong_Format(v, 16, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003970}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003971
3972static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003973long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003974
Tim Peters6d6c1a32001-08-02 04:15:00 +00003975static PyObject *
3976long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3977{
3978 PyObject *x = NULL;
3979 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003980 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981
Guido van Rossumbef14172001-08-29 15:47:46 +00003982 if (type != &PyLong_Type)
3983 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003984 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3985 &x, &base))
3986 return NULL;
3987 if (x == NULL)
3988 return PyLong_FromLong(0L);
3989 if (base == -909)
3990 return PyNumber_Long(x);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003991 else if (PyString_Check(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003992 /* Since PyLong_FromString doesn't have a length parameter,
3993 * check here for possible NULs in the string. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003994 char *string = PyString_AS_STRING(x);
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00003995 if (strlen(string) != (size_t)PyString_Size(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003996 /* create a repr() of the input string,
3997 * just like PyLong_FromString does. */
3998 PyObject *srepr;
3999 srepr = PyObject_Repr(x);
4000 if (srepr == NULL)
4001 return NULL;
4002 PyErr_Format(PyExc_ValueError,
4003 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00004004 base, PyString_AS_STRING(srepr));
Georg Brandl00cd8182007-03-06 18:41:12 +00004005 Py_DECREF(srepr);
4006 return NULL;
4007 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00004008 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Georg Brandl00cd8182007-03-06 18:41:12 +00004009 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004010#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00004011 else if (PyUnicode_Check(x))
4012 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4013 PyUnicode_GET_SIZE(x),
4014 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004015#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00004016 else {
4017 PyErr_SetString(PyExc_TypeError,
4018 "long() can't convert non-string with explicit base");
4019 return NULL;
4020 }
4021}
4022
Guido van Rossumbef14172001-08-29 15:47:46 +00004023/* Wimpy, slow approach to tp_new calls for subtypes of long:
4024 first create a regular long from whatever arguments we got,
4025 then allocate a subtype instance and initialize it from
4026 the regular long. The regular long is then thrown away.
4027*/
4028static PyObject *
4029long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4030{
Anthony Baxter377be112006-04-11 06:54:30 +00004031 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004032 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004033
4034 assert(PyType_IsSubtype(type, &PyLong_Type));
4035 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4036 if (tmp == NULL)
4037 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00004038 assert(PyLong_CheckExact(tmp));
Christian Heimese93237d2007-12-19 02:37:44 +00004039 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00004040 if (n < 0)
4041 n = -n;
Anthony Baxter377be112006-04-11 06:54:30 +00004042 newobj = (PyLongObject *)type->tp_alloc(type, n);
4043 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00004044 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00004045 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00004046 }
Anthony Baxter377be112006-04-11 06:54:30 +00004047 assert(PyLong_Check(newobj));
Christian Heimese93237d2007-12-19 02:37:44 +00004048 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00004049 for (i = 0; i < n; i++)
Anthony Baxter377be112006-04-11 06:54:30 +00004050 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00004051 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00004052 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004053}
4054
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004055static PyObject *
4056long_getnewargs(PyLongObject *v)
4057{
4058 return Py_BuildValue("(N)", _PyLong_Copy(v));
4059}
4060
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004061static PyObject *
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004062long_get0(PyLongObject *v, void *context) {
4063 return PyLong_FromLong(0L);
4064}
4065
4066static PyObject *
4067long_get1(PyLongObject *v, void *context) {
4068 return PyLong_FromLong(1L);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004069}
4070
Eric Smitha9f7d622008-02-17 19:46:49 +00004071static PyObject *
4072long__format__(PyObject *self, PyObject *args)
4073{
4074 PyObject *format_spec;
4075
4076 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
4077 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00004078 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00004079 return _PyLong_FormatAdvanced(self,
4080 PyBytes_AS_STRING(format_spec),
4081 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00004082 if (PyUnicode_Check(format_spec)) {
4083 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00004084 PyObject *result;
4085 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00004086
Eric Smithdc13b792008-05-30 18:10:04 +00004087 if (str_spec == NULL)
4088 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00004089
Eric Smithdc13b792008-05-30 18:10:04 +00004090 result = _PyLong_FormatAdvanced(self,
4091 PyBytes_AS_STRING(str_spec),
4092 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00004093
Eric Smithdc13b792008-05-30 18:10:04 +00004094 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00004095 return result;
4096 }
4097 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
4098 return NULL;
4099}
4100
Robert Schuppenies51df0642008-06-01 16:16:17 +00004101static PyObject *
4102long_sizeof(PyLongObject *v)
4103{
4104 Py_ssize_t res;
4105
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00004106 res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);
Robert Schuppenies51df0642008-06-01 16:16:17 +00004107 return PyInt_FromSsize_t(res);
4108}
4109
Mark Dickinson1a707982008-12-17 16:14:37 +00004110static PyObject *
4111long_bit_length(PyLongObject *v)
4112{
4113 PyLongObject *result, *x, *y;
4114 Py_ssize_t ndigits, msd_bits = 0;
4115 digit msd;
4116
4117 assert(v != NULL);
4118 assert(PyLong_Check(v));
4119
4120 ndigits = ABS(Py_SIZE(v));
4121 if (ndigits == 0)
4122 return PyInt_FromLong(0);
4123
4124 msd = v->ob_digit[ndigits-1];
4125 while (msd >= 32) {
4126 msd_bits += 6;
4127 msd >>= 6;
4128 }
4129 msd_bits += (long)(BitLengthTable[msd]);
4130
4131 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4132 return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
4133
4134 /* expression above may overflow; use Python integers instead */
4135 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4136 if (result == NULL)
4137 return NULL;
4138 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4139 if (x == NULL)
4140 goto error;
4141 y = (PyLongObject *)long_mul(result, x);
4142 Py_DECREF(x);
4143 if (y == NULL)
4144 goto error;
4145 Py_DECREF(result);
4146 result = y;
4147
Stefan Krahef7590e2010-04-07 08:24:44 +00004148 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
Mark Dickinson1a707982008-12-17 16:14:37 +00004149 if (x == NULL)
4150 goto error;
4151 y = (PyLongObject *)long_add(result, x);
4152 Py_DECREF(x);
4153 if (y == NULL)
4154 goto error;
4155 Py_DECREF(result);
4156 result = y;
4157
4158 return (PyObject *)result;
4159
4160error:
4161 Py_DECREF(result);
4162 return NULL;
4163}
4164
4165PyDoc_STRVAR(long_bit_length_doc,
4166"long.bit_length() -> int or long\n\
4167\n\
4168Number of bits necessary to represent self in binary.\n\
4169>>> bin(37L)\n\
4170'0b100101'\n\
4171>>> (37L).bit_length()\n\
41726");
4173
Christian Heimes6f341092008-04-18 23:13:07 +00004174#if 0
4175static PyObject *
4176long_is_finite(PyObject *v)
4177{
4178 Py_RETURN_TRUE;
4179}
4180#endif
4181
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004182static PyMethodDef long_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004183 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4184 "Returns self, the complex conjugate of any long."},
Mark Dickinson1a707982008-12-17 16:14:37 +00004185 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4186 long_bit_length_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00004187#if 0
4188 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4189 "Returns always True."},
4190#endif
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004191 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4192 "Truncating an Integral returns itself."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004193 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smitha9f7d622008-02-17 19:46:49 +00004194 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Robert Schuppenies51df0642008-06-01 16:16:17 +00004195 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00004196 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004197 {NULL, NULL} /* sentinel */
4198};
4199
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004200static PyGetSetDef long_getset[] = {
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004201 {"real",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004202 (getter)long_long, (setter)NULL,
4203 "the real part of a complex number",
4204 NULL},
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004205 {"imag",
4206 (getter)long_get0, (setter)NULL,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004207 "the imaginary part of a complex number",
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004208 NULL},
4209 {"numerator",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004210 (getter)long_long, (setter)NULL,
4211 "the numerator of a rational number in lowest terms",
4212 NULL},
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004213 {"denominator",
4214 (getter)long_get1, (setter)NULL,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004215 "the denominator of a rational number in lowest terms",
Mark Dickinsond4b5c982009-05-02 17:55:01 +00004216 NULL},
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004217 {NULL} /* Sentinel */
4218};
4219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004220PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00004221"long(x[, base]) -> integer\n\
4222\n\
4223Convert a string or number to a long integer, if possible. A floating\n\
4224point argument will be truncated towards zero (this does not include a\n\
4225string representation of a floating point number!) When converting a\n\
4226string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004227converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004228
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004229static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00004230 (binaryfunc) long_add, /*nb_add*/
4231 (binaryfunc) long_sub, /*nb_subtract*/
4232 (binaryfunc) long_mul, /*nb_multiply*/
Georg Brandl347b3002006-03-30 11:57:00 +00004233 long_classic_div, /*nb_divide*/
4234 long_mod, /*nb_remainder*/
4235 long_divmod, /*nb_divmod*/
4236 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004237 (unaryfunc) long_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004238 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004239 (unaryfunc) long_abs, /*tp_absolute*/
4240 (inquiry) long_nonzero, /*tp_nonzero*/
4241 (unaryfunc) long_invert, /*nb_invert*/
Georg Brandl347b3002006-03-30 11:57:00 +00004242 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004243 (binaryfunc) long_rshift, /*nb_rshift*/
Georg Brandl347b3002006-03-30 11:57:00 +00004244 long_and, /*nb_and*/
4245 long_xor, /*nb_xor*/
4246 long_or, /*nb_or*/
4247 long_coerce, /*nb_coerce*/
4248 long_int, /*nb_int*/
4249 long_long, /*nb_long*/
4250 long_float, /*nb_float*/
4251 long_oct, /*nb_oct*/
4252 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00004253 0, /* nb_inplace_add */
4254 0, /* nb_inplace_subtract */
4255 0, /* nb_inplace_multiply */
4256 0, /* nb_inplace_divide */
4257 0, /* nb_inplace_remainder */
4258 0, /* nb_inplace_power */
4259 0, /* nb_inplace_lshift */
4260 0, /* nb_inplace_rshift */
4261 0, /* nb_inplace_and */
4262 0, /* nb_inplace_xor */
4263 0, /* nb_inplace_or */
Georg Brandl347b3002006-03-30 11:57:00 +00004264 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00004265 long_true_divide, /* nb_true_divide */
4266 0, /* nb_inplace_floor_divide */
4267 0, /* nb_inplace_true_divide */
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004268 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004269};
4270
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004271PyTypeObject PyLong_Type = {
4272 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004273 0, /* ob_size */
4274 "long", /* tp_name */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00004275 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004276 sizeof(digit), /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00004277 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004278 0, /* tp_print */
4279 0, /* tp_getattr */
4280 0, /* tp_setattr */
4281 (cmpfunc)long_compare, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00004282 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004283 &long_as_number, /* tp_as_number */
4284 0, /* tp_as_sequence */
4285 0, /* tp_as_mapping */
4286 (hashfunc)long_hash, /* tp_hash */
4287 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00004288 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004289 PyObject_GenericGetAttr, /* tp_getattro */
4290 0, /* tp_setattro */
4291 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00004292 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00004293 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004294 long_doc, /* tp_doc */
4295 0, /* tp_traverse */
4296 0, /* tp_clear */
4297 0, /* tp_richcompare */
4298 0, /* tp_weaklistoffset */
4299 0, /* tp_iter */
4300 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004301 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004302 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004303 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004304 0, /* tp_base */
4305 0, /* tp_dict */
4306 0, /* tp_descr_get */
4307 0, /* tp_descr_set */
4308 0, /* tp_dictoffset */
4309 0, /* tp_init */
4310 0, /* tp_alloc */
4311 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00004312 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004313};
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004314
4315static PyTypeObject Long_InfoType;
4316
4317PyDoc_STRVAR(long_info__doc__,
4318"sys.long_info\n\
4319\n\
4320A struct sequence that holds information about Python's\n\
4321internal representation of integers. The attributes are read only.");
4322
4323static PyStructSequence_Field long_info_fields[] = {
4324 {"bits_per_digit", "size of a digit in bits"},
4325 {"sizeof_digit", "size in bytes of the C type used to "
4326 "represent a digit"},
4327 {NULL, NULL}
4328};
4329
4330static PyStructSequence_Desc long_info_desc = {
4331 "sys.long_info", /* name */
4332 long_info__doc__, /* doc */
4333 long_info_fields, /* fields */
4334 2 /* number of fields */
4335};
4336
4337PyObject *
4338PyLong_GetInfo(void)
4339{
4340 PyObject* long_info;
4341 int field = 0;
4342 long_info = PyStructSequence_New(&Long_InfoType);
4343 if (long_info == NULL)
4344 return NULL;
Mark Dickinson48e3fd22009-04-02 18:39:37 +00004345 PyStructSequence_SET_ITEM(long_info, field++,
4346 PyInt_FromLong(PyLong_SHIFT));
4347 PyStructSequence_SET_ITEM(long_info, field++,
4348 PyInt_FromLong(sizeof(digit)));
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004349 if (PyErr_Occurred()) {
4350 Py_CLEAR(long_info);
4351 return NULL;
4352 }
4353 return long_info;
4354}
4355
4356int
4357_PyLong_Init(void)
4358{
4359 /* initialize long_info */
4360 if (Long_InfoType.tp_name == 0)
4361 PyStructSequence_InitType(&Long_InfoType, &long_info_desc);
4362 return 1;
4363}