blob: ad5557be0aa2914722ef85c6fb6b31ca22a3c3db [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003/* Long (arbitrary precision) integer object implementation */
4
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00005/* XXX The functional organization of this file is terrible */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00008#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00009
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Tim Peters5af4e6c2002-08-12 02:31:19 +000012/* For long multiplication, use the O(N**2) school algorithm unless
13 * both operands contain more than KARATSUBA_CUTOFF digits (this
Christian Heimes7f39c9f2008-01-25 12:18:43 +000014 * being an internal Python long digit, in base PyLong_BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000015 */
Tim Peters0973b992004-08-29 22:16:50 +000016#define KARATSUBA_CUTOFF 70
17#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000018
Tim Peters47e52ee2004-08-30 02:44:38 +000019/* For exponentiation, use the binary left-to-right algorithm
20 * unless the exponent contains more than FIVEARY_CUTOFF digits.
21 * In that case, do 5 bits at a time. The potential drawback is that
22 * a table of 2**5 intermediate results is computed.
23 */
24#define FIVEARY_CUTOFF 8
25
Guido van Rossume32e0141992-01-19 16:31:05 +000026#define ABS(x) ((x) < 0 ? -(x) : (x))
27
Tim Peters5af4e6c2002-08-12 02:31:19 +000028#undef MIN
29#undef MAX
30#define MAX(x, y) ((x) < (y) ? (y) : (x))
31#define MIN(x, y) ((x) > (y) ? (y) : (x))
32
Guido van Rossume32e0141992-01-19 16:31:05 +000033/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000034static PyLongObject *long_normalize(PyLongObject *);
35static PyLongObject *mul1(PyLongObject *, wdigit);
36static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000037static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Guido van Rossume32e0141992-01-19 16:31:05 +000038
Guido van Rossumc0b618a1997-05-02 03:12:38 +000039#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000040 if (--_Py_Ticker < 0) { \
41 _Py_Ticker = _Py_CheckInterval; \
Tim Petersd89fc222006-05-25 22:28:46 +000042 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000043 }
44
Guido van Rossumedcc38a1991-05-05 20:09:44 +000045/* Normalize (remove leading zeros from) a long int object.
46 Doesn't attempt to free the storage--in most cases, due to the nature
47 of the algorithms used, this could save at most be one word anyway. */
48
Guido van Rossumc0b618a1997-05-02 03:12:38 +000049static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000050long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000051{
Christian Heimese93237d2007-12-19 02:37:44 +000052 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +000053 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +000054
Guido van Rossumedcc38a1991-05-05 20:09:44 +000055 while (i > 0 && v->ob_digit[i-1] == 0)
56 --i;
57 if (i != j)
Christian Heimese93237d2007-12-19 02:37:44 +000058 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +000059 return v;
60}
61
62/* Allocate a new long int object with size digits.
63 Return NULL and set exception if we run out of memory. */
64
Guido van Rossumc0b618a1997-05-02 03:12:38 +000065PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000066_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000067{
Neal Norwitzc6a989a2006-05-10 06:57:58 +000068 if (size > PY_SSIZE_T_MAX) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000069 PyErr_NoMemory();
70 return NULL;
71 }
Christian Heimes4956d2b2008-01-18 19:12:56 +000072 /* coverity[ampersand_in_size] */
Neal Norwitze7d8be82008-07-31 17:17:14 +000073 /* XXX(nnorwitz): This can overflow --
74 PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect overflow */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000076}
77
Tim Peters64b5ce32001-09-10 20:52:51 +000078PyObject *
79_PyLong_Copy(PyLongObject *src)
80{
81 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +000082 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000083
84 assert(src != NULL);
85 i = src->ob_size;
86 if (i < 0)
87 i = -(i);
88 result = _PyLong_New(i);
89 if (result != NULL) {
Tim Peters5329cdb2002-03-02 04:18:04 +000090 result->ob_size = src->ob_size;
Tim Peters64b5ce32001-09-10 20:52:51 +000091 while (--i >= 0)
92 result->ob_digit[i] = src->ob_digit[i];
93 }
94 return (PyObject *)result;
95}
96
Guido van Rossumedcc38a1991-05-05 20:09:44 +000097/* Create a new long int object from a C long int */
98
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000100PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000101{
Tim Petersce9de2f2001-06-14 04:56:19 +0000102 PyLongObject *v;
Mark Dickinson27a63252008-04-15 20:51:18 +0000103 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000104 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
105 int ndigits = 0;
106 int negative = 0;
107
108 if (ival < 0) {
Mark Dickinson27a63252008-04-15 20:51:18 +0000109 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
110 ANSI C says that the result of -ival is undefined when ival
111 == LONG_MIN. Hence the following workaround. */
112 abs_ival = (unsigned long)(-1-ival) + 1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000113 negative = 1;
114 }
Mark Dickinson27a63252008-04-15 20:51:18 +0000115 else {
116 abs_ival = (unsigned long)ival;
117 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000118
119 /* Count the number of Python digits.
120 We used to pick 5 ("big enough for anything"), but that's a
121 waste of time and space given that 5*15 = 75 bits are rarely
122 needed. */
Mark Dickinson27a63252008-04-15 20:51:18 +0000123 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000124 while (t) {
125 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000126 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000127 }
128 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000129 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000130 digit *p = v->ob_digit;
131 v->ob_size = negative ? -ndigits : ndigits;
Mark Dickinson27a63252008-04-15 20:51:18 +0000132 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000133 while (t) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000134 *p++ = (digit)(t & PyLong_MASK);
135 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000136 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000137 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000138 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000139}
140
Guido van Rossum53756b11997-01-03 17:14:46 +0000141/* Create a new long int object from a C unsigned long int */
142
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000144PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000145{
Tim Petersce9de2f2001-06-14 04:56:19 +0000146 PyLongObject *v;
147 unsigned long t;
148 int ndigits = 0;
149
150 /* Count the number of Python digits. */
151 t = (unsigned long)ival;
152 while (t) {
153 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000154 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000155 }
156 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000157 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000158 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000159 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000160 while (ival) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000161 *p++ = (digit)(ival & PyLong_MASK);
162 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000163 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000164 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000165 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000166}
167
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000168/* Create a new long int object from a C double */
169
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000172{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000174 double frac;
175 int i, ndig, expo, neg;
176 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000177 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000178 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonb6467572008-08-04 21:30:09 +0000179 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000180 return NULL;
181 }
Christian Heimes8267d1d2008-01-04 00:37:34 +0000182 if (Py_IS_NAN(dval)) {
Mark Dickinsonb6467572008-08-04 21:30:09 +0000183 PyErr_SetString(PyExc_ValueError,
184 "cannot convert float NaN to integer");
185 return NULL;
Christian Heimes8267d1d2008-01-04 00:37:34 +0000186 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000187 if (dval < 0.0) {
188 neg = 1;
189 dval = -dval;
190 }
191 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
192 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000193 return PyLong_FromLong(0L);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000194 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000195 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000196 if (v == NULL)
197 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000198 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000199 for (i = ndig; --i >= 0; ) {
200 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000201 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000202 frac = frac - (double)bits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000203 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000204 }
205 if (neg)
Christian Heimese93237d2007-12-19 02:37:44 +0000206 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000207 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000208}
209
Armin Rigo7ccbca92006-10-04 12:17:45 +0000210/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
211 * anything about what happens when a signed integer operation overflows,
212 * and some compilers think they're doing you a favor by being "clever"
213 * then. The bit pattern for the largest postive signed long is
214 * (unsigned long)LONG_MAX, and for the smallest negative signed long
215 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
216 * However, some other compilers warn about applying unary minus to an
217 * unsigned operand. Hence the weird "0-".
218 */
219#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
220#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
221
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000222/* Get a C long int from a long int object.
223 Returns -1 and sets an error condition if overflow occurs. */
224
225long
Tim Peters9f688bf2000-07-07 15:53:28 +0000226PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000227{
Guido van Rossumf7531811998-05-26 14:33:37 +0000228 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000229 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000230 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000231 Py_ssize_t i;
232 int sign;
Guido van Rossumf7531811998-05-26 14:33:37 +0000233
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000234 if (vv == NULL || !PyLong_Check(vv)) {
Guido van Rossum7e35d572001-09-15 03:14:32 +0000235 if (vv != NULL && PyInt_Check(vv))
236 return PyInt_AsLong(vv);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000237 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238 return -1;
239 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000240 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000241 i = v->ob_size;
242 sign = 1;
243 x = 0;
244 if (i < 0) {
245 sign = -1;
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000246 i = -(i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000247 }
248 while (--i >= 0) {
249 prev = x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000250 x = (x << PyLong_SHIFT) + v->ob_digit[i];
251 if ((x >> PyLong_SHIFT) != prev)
Guido van Rossumf7531811998-05-26 14:33:37 +0000252 goto overflow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000253 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000254 /* Haven't lost any bits, but casting to long requires extra care
255 * (see comment above).
256 */
257 if (x <= (unsigned long)LONG_MAX) {
258 return (long)x * sign;
259 }
260 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
261 return LONG_MIN;
262 }
263 /* else overflow */
Guido van Rossumf7531811998-05-26 14:33:37 +0000264
265 overflow:
266 PyErr_SetString(PyExc_OverflowError,
Skip Montanarobafedec2001-09-13 19:05:30 +0000267 "long int too large to convert to int");
Guido van Rossumf7531811998-05-26 14:33:37 +0000268 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000269}
270
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000271/* Get a Py_ssize_t from a long int object.
272 Returns -1 and sets an error condition if overflow occurs. */
273
274Py_ssize_t
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000275PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000276 register PyLongObject *v;
277 size_t x, prev;
278 Py_ssize_t i;
279 int sign;
280
281 if (vv == NULL || !PyLong_Check(vv)) {
282 PyErr_BadInternalCall();
283 return -1;
284 }
285 v = (PyLongObject *)vv;
286 i = v->ob_size;
287 sign = 1;
288 x = 0;
289 if (i < 0) {
290 sign = -1;
291 i = -(i);
292 }
293 while (--i >= 0) {
294 prev = x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000295 x = (x << PyLong_SHIFT) + v->ob_digit[i];
296 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000297 goto overflow;
298 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000299 /* Haven't lost any bits, but casting to a signed type requires
300 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000301 */
Armin Rigo7ccbca92006-10-04 12:17:45 +0000302 if (x <= (size_t)PY_SSIZE_T_MAX) {
303 return (Py_ssize_t)x * sign;
304 }
305 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
306 return PY_SSIZE_T_MIN;
307 }
308 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000309
310 overflow:
311 PyErr_SetString(PyExc_OverflowError,
312 "long int too large to convert to int");
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000313 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000314}
315
Guido van Rossumd8c80482002-08-13 00:24:58 +0000316/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000317 Returns -1 and sets an error condition if overflow occurs. */
318
319unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000320PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000321{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000322 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000323 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000324 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000325
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000327 if (vv != NULL && PyInt_Check(vv)) {
328 long val = PyInt_AsLong(vv);
329 if (val < 0) {
330 PyErr_SetString(PyExc_OverflowError,
331 "can't convert negative value to unsigned long");
332 return (unsigned long) -1;
333 }
334 return val;
335 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000336 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000337 return (unsigned long) -1;
338 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000339 v = (PyLongObject *)vv;
Christian Heimese93237d2007-12-19 02:37:44 +0000340 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000341 x = 0;
342 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum53756b11997-01-03 17:14:46 +0000344 "can't convert negative value to unsigned long");
345 return (unsigned long) -1;
346 }
347 while (--i >= 0) {
348 prev = x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000349 x = (x << PyLong_SHIFT) + v->ob_digit[i];
350 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000351 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +0000352 "long int too large to convert");
Guido van Rossum53756b11997-01-03 17:14:46 +0000353 return (unsigned long) -1;
354 }
355 }
356 return x;
357}
358
Thomas Hellera4ea6032003-04-17 18:55:45 +0000359/* Get a C unsigned long int from a long int object, ignoring the high bits.
360 Returns -1 and sets an error condition if an error occurs. */
361
362unsigned long
363PyLong_AsUnsignedLongMask(PyObject *vv)
364{
365 register PyLongObject *v;
366 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000367 Py_ssize_t i;
368 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000369
370 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000371 if (vv != NULL && PyInt_Check(vv))
372 return PyInt_AsUnsignedLongMask(vv);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000373 PyErr_BadInternalCall();
374 return (unsigned long) -1;
375 }
376 v = (PyLongObject *)vv;
377 i = v->ob_size;
378 sign = 1;
379 x = 0;
380 if (i < 0) {
381 sign = -1;
382 i = -i;
383 }
384 while (--i >= 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000385 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000386 }
387 return x * sign;
388}
389
Tim Peters5b8132f2003-01-31 15:52:05 +0000390int
391_PyLong_Sign(PyObject *vv)
392{
393 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000394
395 assert(v != NULL);
396 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000397
Christian Heimese93237d2007-12-19 02:37:44 +0000398 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000399}
400
Tim Petersbaefd9e2003-01-28 20:37:45 +0000401size_t
402_PyLong_NumBits(PyObject *vv)
403{
404 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000405 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000406 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000407
408 assert(v != NULL);
409 assert(PyLong_Check(v));
Christian Heimese93237d2007-12-19 02:37:44 +0000410 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000411 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
412 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000413 digit msd = v->ob_digit[ndigits - 1];
414
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000415 result = (ndigits - 1) * PyLong_SHIFT;
416 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000417 goto Overflow;
418 do {
419 ++result;
420 if (result == 0)
421 goto Overflow;
422 msd >>= 1;
423 } while (msd);
424 }
425 return result;
426
427Overflow:
428 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
429 "to express in a platform size_t");
430 return (size_t)-1;
431}
432
Tim Peters2a9b3672001-06-11 21:23:58 +0000433PyObject *
434_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
435 int little_endian, int is_signed)
436{
437 const unsigned char* pstartbyte;/* LSB of bytes */
438 int incr; /* direction to move pstartbyte */
439 const unsigned char* pendbyte; /* MSB of bytes */
440 size_t numsignificantbytes; /* number of bytes that matter */
441 size_t ndigits; /* number of Python long digits */
442 PyLongObject* v; /* result */
443 int idigit = 0; /* next free index in v->ob_digit */
444
445 if (n == 0)
446 return PyLong_FromLong(0L);
447
448 if (little_endian) {
449 pstartbyte = bytes;
450 pendbyte = bytes + n - 1;
451 incr = 1;
452 }
453 else {
454 pstartbyte = bytes + n - 1;
455 pendbyte = bytes;
456 incr = -1;
457 }
458
459 if (is_signed)
460 is_signed = *pendbyte >= 0x80;
461
462 /* Compute numsignificantbytes. This consists of finding the most
463 significant byte. Leading 0 bytes are insignficant if the number
464 is positive, and leading 0xff bytes if negative. */
465 {
466 size_t i;
467 const unsigned char* p = pendbyte;
468 const int pincr = -incr; /* search MSB to LSB */
469 const unsigned char insignficant = is_signed ? 0xff : 0x00;
470
471 for (i = 0; i < n; ++i, p += pincr) {
472 if (*p != insignficant)
473 break;
474 }
475 numsignificantbytes = n - i;
476 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
477 actually has 2 significant bytes. OTOH, 0xff0001 ==
478 -0x00ffff, so we wouldn't *need* to bump it there; but we
479 do for 0xffff = -0x0001. To be safe without bothering to
480 check every case, bump it regardless. */
481 if (is_signed && numsignificantbytes < n)
482 ++numsignificantbytes;
483 }
484
485 /* How many Python long digits do we need? We have
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000486 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000487 bits, so it's the ceiling of the quotient. */
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000488 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000489 if (ndigits > (size_t)INT_MAX)
490 return PyErr_NoMemory();
491 v = _PyLong_New((int)ndigits);
492 if (v == NULL)
493 return NULL;
494
495 /* Copy the bits over. The tricky parts are computing 2's-comp on
496 the fly for signed numbers, and dealing with the mismatch between
497 8-bit bytes and (probably) 15-bit Python digits.*/
498 {
499 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000500 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000501 twodigits accum = 0; /* sliding register */
502 unsigned int accumbits = 0; /* number of bits in accum */
503 const unsigned char* p = pstartbyte;
504
505 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000506 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000507 /* Compute correction for 2's comp, if needed. */
508 if (is_signed) {
509 thisbyte = (0xff ^ thisbyte) + carry;
510 carry = thisbyte >> 8;
511 thisbyte &= 0xff;
512 }
513 /* Because we're going LSB to MSB, thisbyte is
514 more significant than what's already in accum,
515 so needs to be prepended to accum. */
516 accum |= thisbyte << accumbits;
517 accumbits += 8;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000518 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000519 /* There's enough to fill a Python digit. */
520 assert(idigit < (int)ndigits);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000521 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000522 ++idigit;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000523 accum >>= PyLong_SHIFT;
524 accumbits -= PyLong_SHIFT;
525 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000526 }
527 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000528 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000529 if (accumbits) {
530 assert(idigit < (int)ndigits);
531 v->ob_digit[idigit] = (digit)accum;
532 ++idigit;
533 }
534 }
535
Christian Heimese93237d2007-12-19 02:37:44 +0000536 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000537 return (PyObject *)long_normalize(v);
538}
539
540int
541_PyLong_AsByteArray(PyLongObject* v,
542 unsigned char* bytes, size_t n,
543 int little_endian, int is_signed)
544{
545 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000546 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000547 twodigits accum; /* sliding register */
548 unsigned int accumbits; /* # bits in accum */
549 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
550 twodigits carry; /* for computing 2's-comp */
551 size_t j; /* # bytes filled */
552 unsigned char* p; /* pointer to next byte in bytes */
553 int pincr; /* direction to move p */
554
555 assert(v != NULL && PyLong_Check(v));
556
Christian Heimese93237d2007-12-19 02:37:44 +0000557 if (Py_SIZE(v) < 0) {
558 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000559 if (!is_signed) {
560 PyErr_SetString(PyExc_TypeError,
561 "can't convert negative long to unsigned");
562 return -1;
563 }
564 do_twos_comp = 1;
565 }
566 else {
Christian Heimese93237d2007-12-19 02:37:44 +0000567 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000568 do_twos_comp = 0;
569 }
570
571 if (little_endian) {
572 p = bytes;
573 pincr = 1;
574 }
575 else {
576 p = bytes + n - 1;
577 pincr = -1;
578 }
579
Tim Peters898cf852001-06-13 20:50:08 +0000580 /* Copy over all the Python digits.
581 It's crucial that every Python digit except for the MSD contribute
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000582 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000583 normalized. */
584 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000585 j = 0;
586 accum = 0;
587 accumbits = 0;
588 carry = do_twos_comp ? 1 : 0;
589 for (i = 0; i < ndigits; ++i) {
590 twodigits thisdigit = v->ob_digit[i];
591 if (do_twos_comp) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000592 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
593 carry = thisdigit >> PyLong_SHIFT;
594 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000595 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000596 /* Because we're going LSB to MSB, thisdigit is more
597 significant than what's already in accum, so needs to be
598 prepended to accum. */
599 accum |= thisdigit << accumbits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000600 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000601
Tim Petersede05092001-06-14 08:53:38 +0000602 /* The most-significant digit may be (probably is) at least
603 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000604 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000605 /* Count # of sign bits -- they needn't be stored,
606 * although for signed conversion we need later to
607 * make sure at least one sign bit gets stored.
608 * First shift conceptual sign bit to real sign bit.
609 */
610 stwodigits s = (stwodigits)(thisdigit <<
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000611 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000612 unsigned int nsignbits = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000613 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000614 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000615 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000616 }
Tim Petersede05092001-06-14 08:53:38 +0000617 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000618 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000619
Tim Peters2a9b3672001-06-11 21:23:58 +0000620 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000621 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000622 if (j >= n)
623 goto Overflow;
624 ++j;
625 *p = (unsigned char)(accum & 0xff);
626 p += pincr;
627 accumbits -= 8;
628 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000629 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000630 }
631
632 /* Store the straggler (if any). */
633 assert(accumbits < 8);
634 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000635 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000636 if (j >= n)
637 goto Overflow;
638 ++j;
639 if (do_twos_comp) {
640 /* Fill leading bits of the byte with sign bits
641 (appropriately pretending that the long had an
642 infinite supply of sign bits). */
643 accum |= (~(twodigits)0) << accumbits;
644 }
645 *p = (unsigned char)(accum & 0xff);
646 p += pincr;
647 }
Tim Peters05607ad2001-06-13 21:01:27 +0000648 else if (j == n && n > 0 && is_signed) {
649 /* The main loop filled the byte array exactly, so the code
650 just above didn't get to ensure there's a sign bit, and the
651 loop below wouldn't add one either. Make sure a sign bit
652 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000653 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000654 int sign_bit_set = msb >= 0x80;
655 assert(accumbits == 0);
656 if (sign_bit_set == do_twos_comp)
657 return 0;
658 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000659 goto Overflow;
660 }
Tim Peters05607ad2001-06-13 21:01:27 +0000661
662 /* Fill remaining bytes with copies of the sign bit. */
663 {
664 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
665 for ( ; j < n; ++j, p += pincr)
666 *p = signbyte;
667 }
668
Tim Peters2a9b3672001-06-11 21:23:58 +0000669 return 0;
670
671Overflow:
672 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
673 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000674
Tim Peters2a9b3672001-06-11 21:23:58 +0000675}
676
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000677double
678_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
679{
680/* NBITS_WANTED should be > the number of bits in a double's precision,
681 but small enough so that 2**NBITS_WANTED is within the normal double
682 range. nbitsneeded is set to 1 less than that because the most-significant
683 Python digit contains at least 1 significant bit, but we don't want to
684 bother counting them (catering to the worst case cheaply).
685
686 57 is one more than VAX-D double precision; I (Tim) don't know of a double
687 format with more precision than that; it's 1 larger so that we add in at
688 least one round bit to stand in for the ignored least-significant bits.
689*/
690#define NBITS_WANTED 57
691 PyLongObject *v;
692 double x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000693 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000694 Py_ssize_t i;
695 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000696 int nbitsneeded;
697
698 if (vv == NULL || !PyLong_Check(vv)) {
699 PyErr_BadInternalCall();
700 return -1;
701 }
702 v = (PyLongObject *)vv;
Christian Heimese93237d2007-12-19 02:37:44 +0000703 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000704 sign = 1;
705 if (i < 0) {
706 sign = -1;
707 i = -(i);
708 }
709 else if (i == 0) {
710 *exponent = 0;
711 return 0.0;
712 }
713 --i;
714 x = (double)v->ob_digit[i];
715 nbitsneeded = NBITS_WANTED - 1;
716 /* Invariant: i Python digits remain unaccounted for. */
717 while (i > 0 && nbitsneeded > 0) {
718 --i;
719 x = x * multiplier + (double)v->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000720 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000721 }
722 /* There are i digits we didn't shift in. Pretending they're all
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000723 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000724 *exponent = i;
725 assert(x > 0.0);
726 return x * sign;
727#undef NBITS_WANTED
728}
729
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000730/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000731
732double
Tim Peters9f688bf2000-07-07 15:53:28 +0000733PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000734{
Thomas Wouters553489a2006-02-01 21:32:04 +0000735 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000736 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000737
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738 if (vv == NULL || !PyLong_Check(vv)) {
739 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000740 return -1;
741 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000742 x = _PyLong_AsScaledDouble(vv, &e);
743 if (x == -1.0 && PyErr_Occurred())
744 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000745 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
746 set correctly after a successful _PyLong_AsScaledDouble() call */
747 assert(e >= 0);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000748 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000749 goto overflow;
750 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000751 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000752 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000753 goto overflow;
754 return x;
755
756overflow:
757 PyErr_SetString(PyExc_OverflowError,
758 "long int too large to convert to float");
759 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000760}
761
Guido van Rossum78694d91998-09-18 14:14:13 +0000762/* Create a new long (or int) object from a C pointer */
763
764PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000765PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000766{
Tim Peters70128a12001-06-16 08:48:40 +0000767#if SIZEOF_VOID_P <= SIZEOF_LONG
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000768 if ((long)p < 0)
769 return PyLong_FromUnsignedLong((unsigned long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000770 return PyInt_FromLong((long)p);
771#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000772
Tim Peters70128a12001-06-16 08:48:40 +0000773#ifndef HAVE_LONG_LONG
774# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
775#endif
776#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000777# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000778#endif
779 /* optimize null pointers */
780 if (p == NULL)
781 return PyInt_FromLong(0);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000782 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000783
784#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000785}
786
787/* Get a C pointer from a long object (or an int object in some cases) */
788
789void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000790PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000791{
792 /* This function will allow int or long objects. If vv is neither,
793 then the PyLong_AsLong*() functions will raise the exception:
794 PyExc_SystemError, "bad argument to internal function"
795 */
Tim Peters70128a12001-06-16 08:48:40 +0000796#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000797 long x;
798
Tim Peters70128a12001-06-16 08:48:40 +0000799 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000800 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000801 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000802 x = PyLong_AsLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000803 else
804 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000805#else
Tim Peters70128a12001-06-16 08:48:40 +0000806
807#ifndef HAVE_LONG_LONG
808# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
809#endif
810#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000811# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000812#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000813 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000814
Tim Peters70128a12001-06-16 08:48:40 +0000815 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000816 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000817 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000818 x = PyLong_AsLongLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000819 else
820 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000821
822#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000823
824 if (x == -1 && PyErr_Occurred())
825 return NULL;
826 return (void *)x;
827}
828
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000829#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000830
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000831/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000832 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000833 */
834
Tim Peterscf37dfc2001-06-14 18:42:50 +0000835#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000836
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000837/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000838
839PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000840PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000841{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000842 PyLongObject *v;
Mark Dickinson27a63252008-04-15 20:51:18 +0000843 unsigned PY_LONG_LONG abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000844 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
845 int ndigits = 0;
846 int negative = 0;
847
848 if (ival < 0) {
Mark Dickinson27a63252008-04-15 20:51:18 +0000849 /* avoid signed overflow on negation; see comments
850 in PyLong_FromLong above. */
851 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000852 negative = 1;
853 }
Mark Dickinson27a63252008-04-15 20:51:18 +0000854 else {
855 abs_ival = (unsigned PY_LONG_LONG)ival;
856 }
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000857
858 /* Count the number of Python digits.
859 We used to pick 5 ("big enough for anything"), but that's a
860 waste of time and space given that 5*15 = 75 bits are rarely
861 needed. */
Mark Dickinson27a63252008-04-15 20:51:18 +0000862 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000863 while (t) {
864 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000865 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000866 }
867 v = _PyLong_New(ndigits);
868 if (v != NULL) {
869 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000870 Py_SIZE(v) = negative ? -ndigits : ndigits;
Mark Dickinson27a63252008-04-15 20:51:18 +0000871 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000872 while (t) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000873 *p++ = (digit)(t & PyLong_MASK);
874 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000875 }
876 }
877 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000878}
879
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000880/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000881
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000882PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000883PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000884{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000885 PyLongObject *v;
886 unsigned PY_LONG_LONG t;
887 int ndigits = 0;
888
889 /* Count the number of Python digits. */
890 t = (unsigned PY_LONG_LONG)ival;
891 while (t) {
892 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000893 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000894 }
895 v = _PyLong_New(ndigits);
896 if (v != NULL) {
897 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000898 Py_SIZE(v) = ndigits;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000899 while (ival) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000900 *p++ = (digit)(ival & PyLong_MASK);
901 ival >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000902 }
903 }
904 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000905}
906
Martin v. Löwis18e16552006-02-15 17:27:45 +0000907/* Create a new long int object from a C Py_ssize_t. */
908
909PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000910PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000911{
912 Py_ssize_t bytes = ival;
913 int one = 1;
914 return _PyLong_FromByteArray(
915 (unsigned char *)&bytes,
Kristján Valur Jónssonf0303942007-05-03 20:27:03 +0000916 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000917}
918
919/* Create a new long int object from a C size_t. */
920
921PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000922PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000923{
924 size_t bytes = ival;
925 int one = 1;
926 return _PyLong_FromByteArray(
927 (unsigned char *)&bytes,
928 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
929}
930
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000931/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000932 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000933
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000934PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000935PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000936{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000937 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000938 int one = 1;
939 int res;
940
Tim Petersd38b1c72001-09-30 05:09:37 +0000941 if (vv == NULL) {
942 PyErr_BadInternalCall();
943 return -1;
944 }
945 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000946 PyNumberMethods *nb;
947 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +0000948 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000949 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000950 if ((nb = vv->ob_type->tp_as_number) == NULL ||
951 nb->nb_int == NULL) {
952 PyErr_SetString(PyExc_TypeError, "an integer is required");
953 return -1;
954 }
955 io = (*nb->nb_int) (vv);
956 if (io == NULL)
957 return -1;
958 if (PyInt_Check(io)) {
959 bytes = PyInt_AsLong(io);
960 Py_DECREF(io);
961 return bytes;
962 }
963 if (PyLong_Check(io)) {
964 bytes = PyLong_AsLongLong(io);
965 Py_DECREF(io);
966 return bytes;
967 }
968 Py_DECREF(io);
969 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000970 return -1;
971 }
972
Tim Petersd1a7da62001-06-13 00:35:57 +0000973 res = _PyLong_AsByteArray(
974 (PyLongObject *)vv, (unsigned char *)&bytes,
975 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000976
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000977 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000978 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000979 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000980 else
981 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000982}
983
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000984/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000985 Return -1 and set an error if overflow occurs. */
986
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000987unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000988PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000989{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000990 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000991 int one = 1;
992 int res;
993
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000994 if (vv == NULL || !PyLong_Check(vv)) {
995 PyErr_BadInternalCall();
Skip Montanaro429433b2006-04-18 00:35:43 +0000996 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000997 }
998
Tim Petersd1a7da62001-06-13 00:35:57 +0000999 res = _PyLong_AsByteArray(
1000 (PyLongObject *)vv, (unsigned char *)&bytes,
1001 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001002
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001003 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001004 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001005 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001006 else
1007 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001008}
Tim Petersd1a7da62001-06-13 00:35:57 +00001009
Thomas Hellera4ea6032003-04-17 18:55:45 +00001010/* Get a C unsigned long int from a long int object, ignoring the high bits.
1011 Returns -1 and sets an error condition if an error occurs. */
1012
1013unsigned PY_LONG_LONG
1014PyLong_AsUnsignedLongLongMask(PyObject *vv)
1015{
1016 register PyLongObject *v;
1017 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001018 Py_ssize_t i;
1019 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001020
1021 if (vv == NULL || !PyLong_Check(vv)) {
1022 PyErr_BadInternalCall();
1023 return (unsigned long) -1;
1024 }
1025 v = (PyLongObject *)vv;
1026 i = v->ob_size;
1027 sign = 1;
1028 x = 0;
1029 if (i < 0) {
1030 sign = -1;
1031 i = -i;
1032 }
1033 while (--i >= 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001034 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001035 }
1036 return x * sign;
1037}
Tim Petersd1a7da62001-06-13 00:35:57 +00001038#undef IS_LITTLE_ENDIAN
1039
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001040#endif /* HAVE_LONG_LONG */
1041
Neil Schemenauerba872e22001-01-04 01:46:03 +00001042
1043static int
1044convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001045 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001046 *a = (PyLongObject *) v;
1047 Py_INCREF(v);
1048 }
1049 else if (PyInt_Check(v)) {
1050 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1051 }
1052 else {
1053 return 0;
1054 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001055 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001056 *b = (PyLongObject *) w;
1057 Py_INCREF(w);
1058 }
1059 else if (PyInt_Check(w)) {
1060 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1061 }
1062 else {
1063 Py_DECREF(*a);
1064 return 0;
1065 }
1066 return 1;
1067}
1068
1069#define CONVERT_BINOP(v, w, a, b) \
1070 if (!convert_binop(v, w, a, b)) { \
1071 Py_INCREF(Py_NotImplemented); \
1072 return Py_NotImplemented; \
1073 }
1074
Tim Peters877a2122002-08-12 05:09:36 +00001075/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1076 * is modified in place, by adding y to it. Carries are propagated as far as
1077 * x[m-1], and the remaining carry (0 or 1) is returned.
1078 */
1079static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001080v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001081{
1082 int i;
1083 digit carry = 0;
1084
1085 assert(m >= n);
1086 for (i = 0; i < n; ++i) {
1087 carry += x[i] + y[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001088 x[i] = carry & PyLong_MASK;
1089 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001090 assert((carry & 1) == carry);
1091 }
1092 for (; carry && i < m; ++i) {
1093 carry += x[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001094 x[i] = carry & PyLong_MASK;
1095 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001096 assert((carry & 1) == carry);
1097 }
1098 return carry;
1099}
1100
1101/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1102 * is modified in place, by subtracting y from it. Borrows are propagated as
1103 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1104 */
1105static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001106v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001107{
1108 int i;
1109 digit borrow = 0;
1110
1111 assert(m >= n);
1112 for (i = 0; i < n; ++i) {
1113 borrow = x[i] - y[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001114 x[i] = borrow & PyLong_MASK;
1115 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001116 borrow &= 1; /* keep only 1 sign bit */
1117 }
1118 for (; borrow && i < m; ++i) {
1119 borrow = x[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001120 x[i] = borrow & PyLong_MASK;
1121 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001122 borrow &= 1;
1123 }
1124 return borrow;
1125}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001126
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001127/* Multiply by a single digit, ignoring the sign. */
1128
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001129static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001130mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001131{
1132 return muladd1(a, n, (digit)0);
1133}
1134
1135/* Multiply by a single digit and add a single digit, ignoring the sign. */
1136
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001137static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001138muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001139{
Christian Heimese93237d2007-12-19 02:37:44 +00001140 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001141 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001142 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001143 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001144
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001145 if (z == NULL)
1146 return NULL;
1147 for (i = 0; i < size_a; ++i) {
1148 carry += (twodigits)a->ob_digit[i] * n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001149 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1150 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001151 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001152 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001153 return long_normalize(z);
1154}
1155
Tim Peters212e6142001-07-14 12:23:19 +00001156/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1157 in pout, and returning the remainder. pin and pout point at the LSD.
1158 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Eric Smith5e527eb2008-02-10 01:36:53 +00001159 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001160 immutable. */
1161
1162static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001163inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001164{
1165 twodigits rem = 0;
1166
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001167 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001168 pin += size;
1169 pout += size;
1170 while (--size >= 0) {
1171 digit hi;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001172 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001173 *--pout = hi = (digit)(rem / n);
1174 rem -= hi * n;
1175 }
1176 return (digit)rem;
1177}
1178
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001179/* Divide a long integer by a digit, returning both the quotient
1180 (as function result) and the remainder (through *prem).
1181 The sign of a is ignored; n should not be zero. */
1182
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001183static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001184divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001185{
Christian Heimese93237d2007-12-19 02:37:44 +00001186 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001187 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001188
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001189 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001190 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001191 if (z == NULL)
1192 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001193 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001194 return long_normalize(z);
1195}
1196
Eric Smith5e527eb2008-02-10 01:36:53 +00001197/* Convert the long to a string object with given base,
1198 appending a base prefix of 0[box] if base is 2, 8 or 16.
1199 Add a trailing "L" if addL is non-zero.
1200 If newstyle is zero, then use the pre-2.6 behavior of octal having
1201 a leading "0", instead of the prefix "0o" */
1202PyAPI_FUNC(PyObject *)
1203_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001204{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001205 register PyLongObject *a = (PyLongObject *)aa;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001206 PyStringObject *str;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001207 Py_ssize_t i, j, sz;
Neal Norwitzc09efa82006-07-23 07:53:14 +00001208 Py_ssize_t size_a;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001209 char *p;
1210 int bits;
1211 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001212
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001213 if (a == NULL || !PyLong_Check(a)) {
1214 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001215 return NULL;
1216 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001217 assert(base >= 2 && base <= 36);
Christian Heimese93237d2007-12-19 02:37:44 +00001218 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001219
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001220 /* Compute a rough upper bound for the length of the string */
1221 i = base;
1222 bits = 0;
1223 while (i > 1) {
1224 ++bits;
1225 i >>= 1;
1226 }
Armin Rigo7ccbca92006-10-04 12:17:45 +00001227 i = 5 + (addL ? 1 : 0);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001228 j = size_a*PyLong_SHIFT + bits-1;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001229 sz = i + j / bits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001230 if (j / PyLong_SHIFT < size_a || sz < i) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00001231 PyErr_SetString(PyExc_OverflowError,
1232 "long is too large to format");
1233 return NULL;
1234 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001235 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001236 if (str == NULL)
1237 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001238 p = PyString_AS_STRING(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001239 *p = '\0';
Fred Drake121ee271999-12-23 15:41:28 +00001240 if (addL)
1241 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001242 if (a->ob_size < 0)
1243 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001244
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001245 if (a->ob_size == 0) {
1246 *--p = '0';
1247 }
1248 else if ((base & (base - 1)) == 0) {
1249 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001250 twodigits accum = 0;
1251 int accumbits = 0; /* # of bits in accum */
1252 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001253 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001254 while ((i >>= 1) > 1)
1255 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001256
1257 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001258 accum |= (twodigits)a->ob_digit[i] << accumbits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001259 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001260 assert(accumbits >= basebits);
1261 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001262 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001263 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001264 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001265 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001266 accumbits -= basebits;
1267 accum >>= basebits;
1268 } while (i < size_a-1 ? accumbits >= basebits :
1269 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001270 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001271 }
1272 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001273 /* Not 0, and base not a power of 2. Divide repeatedly by
1274 base, but for speed use the highest power of base that
1275 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001276 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001277 digit *pin = a->ob_digit;
1278 PyLongObject *scratch;
1279 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001280 digit powbase = base; /* powbase == base ** power */
1281 int power = 1;
1282 for (;;) {
1283 unsigned long newpow = powbase * (unsigned long)base;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001284 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001285 break;
1286 powbase = (digit)newpow;
1287 ++power;
1288 }
Tim Peters212e6142001-07-14 12:23:19 +00001289
1290 /* Get a scratch area for repeated division. */
1291 scratch = _PyLong_New(size);
1292 if (scratch == NULL) {
1293 Py_DECREF(str);
1294 return NULL;
1295 }
1296
1297 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001298 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001299 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001300 digit rem = inplace_divrem1(scratch->ob_digit,
1301 pin, size, powbase);
1302 pin = scratch->ob_digit; /* no need to use a again */
1303 if (pin[size - 1] == 0)
1304 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001305 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001306 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001307 Py_DECREF(str);
1308 return NULL;
1309 })
Tim Peters212e6142001-07-14 12:23:19 +00001310
1311 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001312 assert(ntostore > 0);
1313 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001314 digit nextrem = (digit)(rem / base);
1315 char c = (char)(rem - nextrem * base);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001316 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001317 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001318 *--p = c;
1319 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001320 --ntostore;
1321 /* Termination is a bit delicate: must not
1322 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001323 remaining quotient and rem are both 0. */
1324 } while (ntostore && (size || rem));
1325 } while (size != 0);
1326 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001327 }
1328
Eric Smith5e527eb2008-02-10 01:36:53 +00001329 if (base == 2) {
1330 *--p = 'b';
1331 *--p = '0';
1332 }
1333 else if (base == 8) {
1334 if (newstyle) {
1335 *--p = 'o';
Guido van Rossum2c475421992-08-14 15:13:07 +00001336 *--p = '0';
Eric Smith5e527eb2008-02-10 01:36:53 +00001337 }
1338 else
1339 if (size_a != 0)
1340 *--p = '0';
Guido van Rossum2c475421992-08-14 15:13:07 +00001341 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001342 else if (base == 16) {
1343 *--p = 'x';
1344 *--p = '0';
1345 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001346 else if (base != 10) {
1347 *--p = '#';
1348 *--p = '0' + base%10;
1349 if (base > 10)
1350 *--p = '0' + base/10;
1351 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001352 if (sign)
1353 *--p = sign;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001354 if (p != PyString_AS_STRING(str)) {
1355 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001356 assert(p > q);
1357 do {
1358 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001359 q--;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001360 _PyString_Resize((PyObject **)&str,
1361 (Py_ssize_t) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001362 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001363 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001364}
1365
Tim Petersda53afa2006-05-25 17:34:03 +00001366/* Table of digit values for 8-bit string -> integer conversion.
1367 * '0' maps to 0, ..., '9' maps to 9.
1368 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1369 * All other indices map to 37.
1370 * Note that when converting a base B string, a char c is a legitimate
1371 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1372 */
1373int _PyLong_DigitValue[256] = {
Tim Peters696cf432006-05-24 21:10:40 +00001374 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1375 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1376 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1377 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1378 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1379 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1380 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1381 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1382 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1383 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1384 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1385 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1386 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1387 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1388 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1389 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Tim Peters696cf432006-05-24 21:10:40 +00001390};
1391
1392/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001393 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1394 * non-digit (which may be *str!). A normalized long is returned.
1395 * The point to this routine is that it takes time linear in the number of
1396 * string characters.
1397 */
1398static PyLongObject *
1399long_from_binary_base(char **str, int base)
1400{
1401 char *p = *str;
1402 char *start = p;
1403 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001404 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001405 PyLongObject *z;
1406 twodigits accum;
1407 int bits_in_accum;
1408 digit *pdigit;
1409
1410 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1411 n = base;
1412 for (bits_per_char = -1; n; ++bits_per_char)
1413 n >>= 1;
1414 /* n <- total # of bits needed, while setting p to end-of-string */
1415 n = 0;
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001416 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001417 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001418 *str = p;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001419 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1420 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001421 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001422 PyErr_SetString(PyExc_ValueError,
1423 "long string too large to convert");
1424 return NULL;
1425 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001426 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001427 z = _PyLong_New(n);
1428 if (z == NULL)
1429 return NULL;
1430 /* Read string from right, and fill in long from left; i.e.,
1431 * from least to most significant in both.
1432 */
1433 accum = 0;
1434 bits_in_accum = 0;
1435 pdigit = z->ob_digit;
1436 while (--p >= start) {
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001437 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001438 assert(k >= 0 && k < base);
1439 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001440 bits_in_accum += bits_per_char;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001441 if (bits_in_accum >= PyLong_SHIFT) {
1442 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001443 assert(pdigit - z->ob_digit <= (int)n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001444 accum >>= PyLong_SHIFT;
1445 bits_in_accum -= PyLong_SHIFT;
1446 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001447 }
1448 }
1449 if (bits_in_accum) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001450 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001451 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001452 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001453 }
1454 while (pdigit - z->ob_digit < n)
1455 *pdigit++ = 0;
1456 return long_normalize(z);
1457}
1458
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001459PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001460PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001461{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001462 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001463 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001464 PyLongObject *z;
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001465 PyObject *strobj, *strrepr;
1466 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001467
Guido van Rossum472c04f1996-12-05 21:57:21 +00001468 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001469 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001470 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001471 return NULL;
1472 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001473 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001474 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001475 if (*str == '+')
1476 ++str;
1477 else if (*str == '-') {
1478 ++str;
1479 sign = -1;
1480 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001481 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001482 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001483 if (base == 0) {
Eric Smith9ff19b52008-03-17 17:32:20 +00001484 /* No base given. Deduce the base from the contents
1485 of the string */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001486 if (str[0] != '0')
1487 base = 10;
1488 else if (str[1] == 'x' || str[1] == 'X')
1489 base = 16;
Eric Smith9ff19b52008-03-17 17:32:20 +00001490 else if (str[1] == 'o' || str[1] == 'O')
1491 base = 8;
1492 else if (str[1] == 'b' || str[1] == 'B')
1493 base = 2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001494 else
Eric Smith9ff19b52008-03-17 17:32:20 +00001495 /* "old" (C-style) octal literal, still valid in
1496 2.x, although illegal in 3.x */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001497 base = 8;
1498 }
Eric Smith9ff19b52008-03-17 17:32:20 +00001499 /* Whether or not we were deducing the base, skip leading chars
1500 as needed */
1501 if (str[0] == '0' &&
1502 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1503 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1504 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001505 str += 2;
Tim Peters696cf432006-05-24 21:10:40 +00001506
Guido van Rossume6762971998-06-22 03:54:46 +00001507 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001508 if ((base & (base - 1)) == 0)
1509 z = long_from_binary_base(&str, base);
1510 else {
Tim Peters696cf432006-05-24 21:10:40 +00001511/***
1512Binary bases can be converted in time linear in the number of digits, because
1513Python's representation base is binary. Other bases (including decimal!) use
1514the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001515
Tim Peters696cf432006-05-24 21:10:40 +00001516First some math: the largest integer that can be expressed in N base-B digits
1517is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1518case number of Python digits needed to hold it is the smallest integer n s.t.
1519
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001520 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1521 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1522 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001523
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001524The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute
Tim Peters696cf432006-05-24 21:10:40 +00001525this quickly. A Python long with that much space is reserved near the start,
1526and the result is computed into it.
1527
1528The input string is actually treated as being in base base**i (i.e., i digits
1529are processed at a time), where two more static arrays hold:
1530
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001531 convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE
Tim Peters696cf432006-05-24 21:10:40 +00001532 convmultmax_base[base] = base ** convwidth_base[base]
1533
1534The first of these is the largest i such that i consecutive input digits
1535must fit in a single Python digit. The second is effectively the input
1536base we're really using.
1537
1538Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1539convmultmax_base[base], the result is "simply"
1540
1541 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1542
1543where B = convmultmax_base[base].
Tim Peters9faa3ed2006-05-30 15:53:34 +00001544
1545Error analysis: as above, the number of Python digits `n` needed is worst-
1546case
1547
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001548 n >= N * log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001549
1550where `N` is the number of input digits in base `B`. This is computed via
1551
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001552 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001553
1554below. Two numeric concerns are how much space this can waste, and whether
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001555the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15,
Tim Peters9faa3ed2006-05-30 15:53:34 +00001556which is the default (and it's unlikely anyone changes that).
1557
1558Waste isn't a problem: provided the first input digit isn't 0, the difference
1559between the worst-case input with N digits and the smallest input with N
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001560digits is about a factor of B, but B is small compared to PyLong_BASE so at most
Tim Peters9faa3ed2006-05-30 15:53:34 +00001561one allocated Python digit can remain unused on that count. If
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001562N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001563and adding 1 returns a result 1 larger than necessary. However, that can't
1564happen: whenever B is a power of 2, long_from_binary_base() is called
1565instead, and it's impossible for B**i to be an integer power of 2**15 when
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001566B 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 +00001567an exact integer when B is not a power of 2, since B**i has a prime factor
1568other than 2 in that case, but (2**15)**j's only prime factor is 2).
1569
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001570The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001571is a little bit larger than an exact integer, but due to roundoff errors (in
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001572computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001573yields a numeric result a little less than that integer. Unfortunately, "how
1574close can a transcendental function get to an integer over some range?"
1575questions are generally theoretically intractable. Computer analysis via
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001576continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued
Tim Peters9faa3ed2006-05-30 15:53:34 +00001577fractions, giving a sequence i/j of "the best" rational approximations. Then
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001578j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001579we can get very close to being in trouble, but very rarely. For example,
158076573 is a denominator in one of the continued-fraction approximations to
1581log(10)/log(2**15), and indeed:
1582
1583 >>> log(10)/log(2**15)*76573
1584 16958.000000654003
1585
1586is very close to an integer. If we were working with IEEE single-precision,
1587rounding errors could kill us. Finding worst cases in IEEE double-precision
1588requires better-than-double-precision log() functions, and Tim didn't bother.
1589Instead the code checks to see whether the allocated space is enough as each
1590new Python digit is added, and copies the whole thing to a larger long if not.
1591This should happen extremely rarely, and in fact I don't have a test case
1592that triggers it(!). Instead the code was tested by artificially allocating
1593just 1 digit at the start, so that the copying code was exercised for every
1594digit beyond the first.
Tim Peters696cf432006-05-24 21:10:40 +00001595***/
1596 register twodigits c; /* current input character */
1597 Py_ssize_t size_z;
1598 int i;
1599 int convwidth;
1600 twodigits convmultmax, convmult;
1601 digit *pz, *pzstop;
1602 char* scan;
1603
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001604 static double log_base_PyLong_BASE[37] = {0.0e0,};
Tim Peters696cf432006-05-24 21:10:40 +00001605 static int convwidth_base[37] = {0,};
1606 static twodigits convmultmax_base[37] = {0,};
1607
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001608 if (log_base_PyLong_BASE[base] == 0.0) {
Tim Peters696cf432006-05-24 21:10:40 +00001609 twodigits convmax = base;
1610 int i = 1;
1611
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001612 log_base_PyLong_BASE[base] = log((double)base) /
1613 log((double)PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001614 for (;;) {
1615 twodigits next = convmax * base;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001616 if (next > PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001617 break;
1618 convmax = next;
1619 ++i;
1620 }
1621 convmultmax_base[base] = convmax;
1622 assert(i > 0);
1623 convwidth_base[base] = i;
1624 }
1625
1626 /* Find length of the string of numeric characters. */
1627 scan = str;
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001628 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Tim Peters696cf432006-05-24 21:10:40 +00001629 ++scan;
1630
1631 /* Create a long object that can contain the largest possible
1632 * integer with this base and length. Note that there's no
1633 * need to initialize z->ob_digit -- no slot is read up before
1634 * being stored into.
1635 */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001636 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001637 /* Uncomment next line to test exceedingly rare copy code */
1638 /* size_z = 1; */
Tim Peters696cf432006-05-24 21:10:40 +00001639 assert(size_z > 0);
1640 z = _PyLong_New(size_z);
1641 if (z == NULL)
1642 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00001643 Py_SIZE(z) = 0;
Tim Peters696cf432006-05-24 21:10:40 +00001644
1645 /* `convwidth` consecutive input digits are treated as a single
1646 * digit in base `convmultmax`.
1647 */
1648 convwidth = convwidth_base[base];
1649 convmultmax = convmultmax_base[base];
1650
1651 /* Work ;-) */
1652 while (str < scan) {
1653 /* grab up to convwidth digits from the input string */
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001654 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Tim Peters696cf432006-05-24 21:10:40 +00001655 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1656 c = (twodigits)(c * base +
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001657 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001658 assert(c < PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001659 }
1660
1661 convmult = convmultmax;
1662 /* Calculate the shift only if we couldn't get
1663 * convwidth digits.
1664 */
1665 if (i != convwidth) {
1666 convmult = base;
1667 for ( ; i > 1; --i)
1668 convmult *= base;
1669 }
1670
1671 /* Multiply z by convmult, and add c. */
1672 pz = z->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +00001673 pzstop = pz + Py_SIZE(z);
Tim Peters696cf432006-05-24 21:10:40 +00001674 for (; pz < pzstop; ++pz) {
1675 c += (twodigits)*pz * convmult;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001676 *pz = (digit)(c & PyLong_MASK);
1677 c >>= PyLong_SHIFT;
Tim Peters696cf432006-05-24 21:10:40 +00001678 }
1679 /* carry off the current end? */
1680 if (c) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001681 assert(c < PyLong_BASE);
Christian Heimese93237d2007-12-19 02:37:44 +00001682 if (Py_SIZE(z) < size_z) {
Tim Peters9faa3ed2006-05-30 15:53:34 +00001683 *pz = (digit)c;
Christian Heimese93237d2007-12-19 02:37:44 +00001684 ++Py_SIZE(z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001685 }
1686 else {
1687 PyLongObject *tmp;
1688 /* Extremely rare. Get more space. */
Christian Heimese93237d2007-12-19 02:37:44 +00001689 assert(Py_SIZE(z) == size_z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001690 tmp = _PyLong_New(size_z + 1);
1691 if (tmp == NULL) {
1692 Py_DECREF(z);
1693 return NULL;
1694 }
1695 memcpy(tmp->ob_digit,
1696 z->ob_digit,
1697 sizeof(digit) * size_z);
1698 Py_DECREF(z);
1699 z = tmp;
1700 z->ob_digit[size_z] = (digit)c;
1701 ++size_z;
1702 }
Tim Peters696cf432006-05-24 21:10:40 +00001703 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001704 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001705 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001706 if (z == NULL)
1707 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001708 if (str == start)
1709 goto onError;
Tim Peters696cf432006-05-24 21:10:40 +00001710 if (sign < 0)
Christian Heimese93237d2007-12-19 02:37:44 +00001711 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001712 if (*str == 'L' || *str == 'l')
1713 str++;
1714 while (*str && isspace(Py_CHARMASK(*str)))
1715 str++;
1716 if (*str != '\0')
1717 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001718 if (pend)
1719 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001720 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001721
1722 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001723 Py_XDECREF(z);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001724 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001725 strobj = PyString_FromStringAndSize(orig_str, slen);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001726 if (strobj == NULL)
1727 return NULL;
1728 strrepr = PyObject_Repr(strobj);
1729 Py_DECREF(strobj);
1730 if (strrepr == NULL)
1731 return NULL;
1732 PyErr_Format(PyExc_ValueError,
1733 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001734 base, PyString_AS_STRING(strrepr));
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001735 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001736 return NULL;
1737}
1738
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001739#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001740PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001741PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001742{
Walter Dörwald07e14762002-11-06 16:15:14 +00001743 PyObject *result;
Anthony Baxter377be112006-04-11 06:54:30 +00001744 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001745
Walter Dörwald07e14762002-11-06 16:15:14 +00001746 if (buffer == NULL)
1747 return NULL;
1748
1749 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1750 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001751 return NULL;
1752 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001753 result = PyLong_FromString(buffer, NULL, base);
1754 PyMem_FREE(buffer);
1755 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001756}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001757#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001758
Tim Peters9f688bf2000-07-07 15:53:28 +00001759/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001760static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001761 (PyLongObject *, PyLongObject *, PyLongObject **);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001762static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00001763static int long_divrem(PyLongObject *, PyLongObject *,
1764 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001765
1766/* Long division with remainder, top-level routine */
1767
Guido van Rossume32e0141992-01-19 16:31:05 +00001768static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001769long_divrem(PyLongObject *a, PyLongObject *b,
1770 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001771{
Christian Heimese93237d2007-12-19 02:37:44 +00001772 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001773 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001774
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001775 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001776 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001777 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001778 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001779 }
1780 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001781 (size_a == size_b &&
1782 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001783 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001784 *pdiv = _PyLong_New(0);
Georg Brandlc02e1312007-04-11 17:16:24 +00001785 if (*pdiv == NULL)
1786 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001787 Py_INCREF(a);
1788 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001789 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001790 }
1791 if (size_b == 1) {
1792 digit rem = 0;
1793 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001794 if (z == NULL)
1795 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001796 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Georg Brandlc02e1312007-04-11 17:16:24 +00001797 if (*prem == NULL) {
1798 Py_DECREF(z);
1799 return -1;
1800 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001801 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001802 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001803 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001804 if (z == NULL)
1805 return -1;
1806 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001807 /* Set the signs.
1808 The quotient z has the sign of a*b;
1809 the remainder r has the sign of a,
1810 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001811 if ((a->ob_size < 0) != (b->ob_size < 0))
1812 z->ob_size = -(z->ob_size);
1813 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1814 (*prem)->ob_size = -((*prem)->ob_size);
1815 *pdiv = z;
1816 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001817}
1818
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001819/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001820
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001821static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001822x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001823{
Christian Heimese93237d2007-12-19 02:37:44 +00001824 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001825 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001826 PyLongObject *v = mul1(v1, d);
1827 PyLongObject *w = mul1(w1, d);
1828 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001829 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001830
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001831 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001832 Py_XDECREF(v);
1833 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001834 return NULL;
1835 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001836
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001837 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimese93237d2007-12-19 02:37:44 +00001838 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
1839 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001840
Christian Heimese93237d2007-12-19 02:37:44 +00001841 size_v = ABS(Py_SIZE(v));
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001842 k = size_v - size_w;
1843 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001844
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001845 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001846 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
1847 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001848 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001849 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001850
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001851 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001852 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001853 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001854 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001855 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001856 if (vj == w->ob_digit[size_w-1])
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001857 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001858 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001859 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001860 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00001861
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001862 while (w->ob_digit[size_w-2]*q >
1863 ((
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001864 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001865 + v->ob_digit[j-1]
1866 - q*w->ob_digit[size_w-1]
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001867 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001868 + v->ob_digit[j-2])
1869 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001870
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001871 for (i = 0; i < size_w && i+k < size_v; ++i) {
1872 twodigits z = w->ob_digit[i] * q;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001873 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001874 carry += v->ob_digit[i+k] - z
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001875 + ((twodigits)zz << PyLong_SHIFT);
1876 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
1877 carry = Py_ARITHMETIC_RIGHT_SHIFT(PyLong_BASE_TWODIGITS_TYPE,
1878 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00001879 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001880 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001881
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001882 if (i+k < size_v) {
1883 carry += v->ob_digit[i+k];
1884 v->ob_digit[i+k] = 0;
1885 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001886
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001887 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00001888 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001889 else {
1890 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00001891 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001892 carry = 0;
1893 for (i = 0; i < size_w && i+k < size_v; ++i) {
1894 carry += v->ob_digit[i+k] + w->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001895 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001896 carry = Py_ARITHMETIC_RIGHT_SHIFT(
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001897 PyLong_BASE_TWODIGITS_TYPE,
1898 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001899 }
1900 }
1901 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001902
Guido van Rossumc206c761995-01-10 15:23:19 +00001903 if (a == NULL)
1904 *prem = NULL;
1905 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00001906 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001907 *prem = divrem1(v, d, &d);
1908 /* d receives the (unused) remainder */
1909 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001910 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001911 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001912 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001913 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001914 Py_DECREF(v);
1915 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001916 return a;
1917}
1918
1919/* Methods */
1920
1921static void
Tim Peters9f688bf2000-07-07 15:53:28 +00001922long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001923{
Christian Heimese93237d2007-12-19 02:37:44 +00001924 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001925}
1926
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001927static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001928long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001929{
Eric Smith5e527eb2008-02-10 01:36:53 +00001930 return _PyLong_Format(v, 10, 1, 0);
Fred Drake121ee271999-12-23 15:41:28 +00001931}
1932
1933static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001934long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00001935{
Eric Smith5e527eb2008-02-10 01:36:53 +00001936 return _PyLong_Format(v, 10, 0, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001937}
1938
1939static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001940long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001941{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001942 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001943
Christian Heimese93237d2007-12-19 02:37:44 +00001944 if (Py_SIZE(a) != Py_SIZE(b)) {
1945 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00001946 sign = 0;
1947 else
Christian Heimese93237d2007-12-19 02:37:44 +00001948 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001949 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001950 else {
Christian Heimese93237d2007-12-19 02:37:44 +00001951 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001952 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1953 ;
1954 if (i < 0)
1955 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001956 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001957 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Christian Heimese93237d2007-12-19 02:37:44 +00001958 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001959 sign = -sign;
1960 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001961 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001962 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001963}
1964
Guido van Rossum9bfef441993-03-29 10:43:31 +00001965static long
Tim Peters9f688bf2000-07-07 15:53:28 +00001966long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001967{
1968 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001969 Py_ssize_t i;
1970 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001971
1972 /* This is designed so that Python ints and longs with the
1973 same value hash to the same value, otherwise comparisons
1974 of mapping keys will turn out weird */
1975 i = v->ob_size;
1976 sign = 1;
1977 x = 0;
1978 if (i < 0) {
1979 sign = -1;
1980 i = -(i);
1981 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001982#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Facundo Batistad544df72007-09-19 15:10:06 +00001983 /* The following loop produces a C long x such that (unsigned long)x
1984 is congruent to the absolute value of v modulo ULONG_MAX. The
1985 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00001986 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001987 /* Force a native long #-bits (32 or 64) circular shift */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001988 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001989 x += v->ob_digit[i];
Facundo Batistad544df72007-09-19 15:10:06 +00001990 /* If the addition above overflowed (thinking of x as
1991 unsigned), we compensate by incrementing. This preserves
1992 the value modulo ULONG_MAX. */
1993 if ((unsigned long)x < v->ob_digit[i])
1994 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001995 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001996#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00001997 x = x * sign;
1998 if (x == -1)
1999 x = -2;
2000 return x;
2001}
2002
2003
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002004/* Add the absolute values of two long integers. */
2005
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002006static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002007x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002008{
Christian Heimese93237d2007-12-19 02:37:44 +00002009 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002010 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002011 int i;
2012 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002013
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002014 /* Ensure a is the larger of the two: */
2015 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002016 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002017 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002018 size_a = size_b;
2019 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002020 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002021 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002022 if (z == NULL)
2023 return NULL;
2024 for (i = 0; i < size_b; ++i) {
2025 carry += a->ob_digit[i] + b->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002026 z->ob_digit[i] = carry & PyLong_MASK;
2027 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002028 }
2029 for (; i < size_a; ++i) {
2030 carry += a->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002031 z->ob_digit[i] = carry & PyLong_MASK;
2032 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002033 }
2034 z->ob_digit[i] = carry;
2035 return long_normalize(z);
2036}
2037
2038/* Subtract the absolute values of two integers. */
2039
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002040static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002041x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002042{
Christian Heimese93237d2007-12-19 02:37:44 +00002043 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002044 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002045 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002046 int sign = 1;
2047 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002048
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002049 /* Ensure a is the larger of the two: */
2050 if (size_a < size_b) {
2051 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002052 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002053 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002054 size_a = size_b;
2055 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002056 }
2057 else if (size_a == size_b) {
2058 /* Find highest digit where a and b differ: */
2059 i = size_a;
2060 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2061 ;
2062 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002063 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002064 if (a->ob_digit[i] < b->ob_digit[i]) {
2065 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002066 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002067 }
2068 size_a = size_b = i+1;
2069 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002070 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002071 if (z == NULL)
2072 return NULL;
2073 for (i = 0; i < size_b; ++i) {
2074 /* The following assumes unsigned arithmetic
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002075 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002076 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002077 z->ob_digit[i] = borrow & PyLong_MASK;
2078 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079 borrow &= 1; /* Keep only one sign bit */
2080 }
2081 for (; i < size_a; ++i) {
2082 borrow = a->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002083 z->ob_digit[i] = borrow & PyLong_MASK;
2084 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002085 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002086 }
2087 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002088 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002089 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090 return long_normalize(z);
2091}
2092
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002093static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002094long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002095{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002096 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002097
Neil Schemenauerba872e22001-01-04 01:46:03 +00002098 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2099
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002100 if (a->ob_size < 0) {
2101 if (b->ob_size < 0) {
2102 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002103 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002104 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002105 }
2106 else
2107 z = x_sub(b, a);
2108 }
2109 else {
2110 if (b->ob_size < 0)
2111 z = x_sub(a, b);
2112 else
2113 z = x_add(a, b);
2114 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002115 Py_DECREF(a);
2116 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002117 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002118}
2119
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002120static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002121long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002122{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002123 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002124
Neil Schemenauerba872e22001-01-04 01:46:03 +00002125 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2126
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002127 if (a->ob_size < 0) {
2128 if (b->ob_size < 0)
2129 z = x_sub(a, b);
2130 else
2131 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002132 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002133 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002134 }
2135 else {
2136 if (b->ob_size < 0)
2137 z = x_add(a, b);
2138 else
2139 z = x_sub(a, b);
2140 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002141 Py_DECREF(a);
2142 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002143 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002144}
2145
Tim Peters5af4e6c2002-08-12 02:31:19 +00002146/* Grade school multiplication, ignoring the signs.
2147 * Returns the absolute value of the product, or NULL if error.
2148 */
2149static PyLongObject *
2150x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002151{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002152 PyLongObject *z;
Christian Heimese93237d2007-12-19 02:37:44 +00002153 Py_ssize_t size_a = ABS(Py_SIZE(a));
2154 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002155 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002156
Tim Peters5af4e6c2002-08-12 02:31:19 +00002157 z = _PyLong_New(size_a + size_b);
2158 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002159 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002160
Christian Heimese93237d2007-12-19 02:37:44 +00002161 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002162 if (a == b) {
2163 /* Efficient squaring per HAC, Algorithm 14.16:
2164 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2165 * Gives slightly less than a 2x speedup when a == b,
2166 * via exploiting that each entry in the multiplication
2167 * pyramid appears twice (except for the size_a squares).
2168 */
2169 for (i = 0; i < size_a; ++i) {
2170 twodigits carry;
2171 twodigits f = a->ob_digit[i];
2172 digit *pz = z->ob_digit + (i << 1);
2173 digit *pa = a->ob_digit + i + 1;
2174 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002175
Tim Peters0973b992004-08-29 22:16:50 +00002176 SIGCHECK({
2177 Py_DECREF(z);
2178 return NULL;
2179 })
2180
2181 carry = *pz + f * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002182 *pz++ = (digit)(carry & PyLong_MASK);
2183 carry >>= PyLong_SHIFT;
2184 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002185
2186 /* Now f is added in twice in each column of the
2187 * pyramid it appears. Same as adding f<<1 once.
2188 */
2189 f <<= 1;
2190 while (pa < paend) {
2191 carry += *pz + *pa++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002192 *pz++ = (digit)(carry & PyLong_MASK);
2193 carry >>= PyLong_SHIFT;
2194 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002195 }
2196 if (carry) {
2197 carry += *pz;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002198 *pz++ = (digit)(carry & PyLong_MASK);
2199 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002200 }
2201 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002202 *pz += (digit)(carry & PyLong_MASK);
2203 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002204 }
Tim Peters0973b992004-08-29 22:16:50 +00002205 }
2206 else { /* a is not the same as b -- gradeschool long mult */
2207 for (i = 0; i < size_a; ++i) {
2208 twodigits carry = 0;
2209 twodigits f = a->ob_digit[i];
2210 digit *pz = z->ob_digit + i;
2211 digit *pb = b->ob_digit;
2212 digit *pbend = b->ob_digit + size_b;
2213
2214 SIGCHECK({
2215 Py_DECREF(z);
2216 return NULL;
2217 })
2218
2219 while (pb < pbend) {
2220 carry += *pz + *pb++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002221 *pz++ = (digit)(carry & PyLong_MASK);
2222 carry >>= PyLong_SHIFT;
2223 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002224 }
2225 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002226 *pz += (digit)(carry & PyLong_MASK);
2227 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002228 }
2229 }
Tim Peters44121a62002-08-12 06:17:58 +00002230 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002231}
2232
2233/* A helper for Karatsuba multiplication (k_mul).
2234 Takes a long "n" and an integer "size" representing the place to
2235 split, and sets low and high such that abs(n) == (high << size) + low,
2236 viewing the shift as being by digits. The sign bit is ignored, and
2237 the return values are >= 0.
2238 Returns 0 on success, -1 on failure.
2239*/
2240static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002241kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002242{
2243 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002244 Py_ssize_t size_lo, size_hi;
Christian Heimese93237d2007-12-19 02:37:44 +00002245 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002246
2247 size_lo = MIN(size_n, size);
2248 size_hi = size_n - size_lo;
2249
2250 if ((hi = _PyLong_New(size_hi)) == NULL)
2251 return -1;
2252 if ((lo = _PyLong_New(size_lo)) == NULL) {
2253 Py_DECREF(hi);
2254 return -1;
2255 }
2256
2257 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2258 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2259
2260 *high = long_normalize(hi);
2261 *low = long_normalize(lo);
2262 return 0;
2263}
2264
Tim Peters60004642002-08-12 22:01:34 +00002265static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2266
Tim Peters5af4e6c2002-08-12 02:31:19 +00002267/* Karatsuba multiplication. Ignores the input signs, and returns the
2268 * absolute value of the product (or NULL if error).
2269 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2270 */
2271static PyLongObject *
2272k_mul(PyLongObject *a, PyLongObject *b)
2273{
Christian Heimese93237d2007-12-19 02:37:44 +00002274 Py_ssize_t asize = ABS(Py_SIZE(a));
2275 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002276 PyLongObject *ah = NULL;
2277 PyLongObject *al = NULL;
2278 PyLongObject *bh = NULL;
2279 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002280 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002281 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002282 Py_ssize_t shift; /* the number of digits we split off */
2283 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002284
Tim Peters5af4e6c2002-08-12 02:31:19 +00002285 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2286 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2287 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002288 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002289 * By picking X to be a power of 2, "*X" is just shifting, and it's
2290 * been reduced to 3 multiplies on numbers half the size.
2291 */
2292
Tim Petersfc07e562002-08-12 02:54:10 +00002293 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002294 * is largest.
2295 */
Tim Peters738eda72002-08-12 15:08:20 +00002296 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002297 t1 = a;
2298 a = b;
2299 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002300
2301 i = asize;
2302 asize = bsize;
2303 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002304 }
2305
2306 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002307 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2308 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002309 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002310 return _PyLong_New(0);
2311 else
2312 return x_mul(a, b);
2313 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002314
Tim Peters60004642002-08-12 22:01:34 +00002315 /* If a is small compared to b, splitting on b gives a degenerate
2316 * case with ah==0, and Karatsuba may be (even much) less efficient
2317 * than "grade school" then. However, we can still win, by viewing
2318 * b as a string of "big digits", each of width a->ob_size. That
2319 * leads to a sequence of balanced calls to k_mul.
2320 */
2321 if (2 * asize <= bsize)
2322 return k_lopsided_mul(a, b);
2323
Tim Petersd6974a52002-08-13 20:37:51 +00002324 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002325 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002326 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002327 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002328
Tim Peters0973b992004-08-29 22:16:50 +00002329 if (a == b) {
2330 bh = ah;
2331 bl = al;
2332 Py_INCREF(bh);
2333 Py_INCREF(bl);
2334 }
2335 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002336
Tim Petersd64c1de2002-08-12 17:36:03 +00002337 /* The plan:
2338 * 1. Allocate result space (asize + bsize digits: that's always
2339 * enough).
2340 * 2. Compute ah*bh, and copy into result at 2*shift.
2341 * 3. Compute al*bl, and copy into result at 0. Note that this
2342 * can't overlap with #2.
2343 * 4. Subtract al*bl from the result, starting at shift. This may
2344 * underflow (borrow out of the high digit), but we don't care:
2345 * we're effectively doing unsigned arithmetic mod
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002346 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
Tim Petersd64c1de2002-08-12 17:36:03 +00002347 * borrows and carries out of the high digit can be ignored.
2348 * 5. Subtract ah*bh from the result, starting at shift.
2349 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2350 * at shift.
2351 */
2352
2353 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002354 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002355 if (ret == NULL) goto fail;
2356#ifdef Py_DEBUG
2357 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002358 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002359#endif
Tim Peters44121a62002-08-12 06:17:58 +00002360
Tim Petersd64c1de2002-08-12 17:36:03 +00002361 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002362 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002363 assert(Py_SIZE(t1) >= 0);
2364 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002365 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimese93237d2007-12-19 02:37:44 +00002366 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002367
2368 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimese93237d2007-12-19 02:37:44 +00002369 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002370 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002371 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002372 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002373
Tim Petersd64c1de2002-08-12 17:36:03 +00002374 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002375 if ((t2 = k_mul(al, bl)) == NULL) {
2376 Py_DECREF(t1);
2377 goto fail;
2378 }
Christian Heimese93237d2007-12-19 02:37:44 +00002379 assert(Py_SIZE(t2) >= 0);
2380 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2381 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002382
2383 /* Zero out remaining digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002384 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002385 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002386 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002387
Tim Petersd64c1de2002-08-12 17:36:03 +00002388 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2389 * because it's fresher in cache.
2390 */
Christian Heimese93237d2007-12-19 02:37:44 +00002391 i = Py_SIZE(ret) - shift; /* # digits after shift */
2392 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002393 Py_DECREF(t2);
2394
Christian Heimese93237d2007-12-19 02:37:44 +00002395 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002396 Py_DECREF(t1);
2397
Tim Petersd64c1de2002-08-12 17:36:03 +00002398 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002399 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2400 Py_DECREF(ah);
2401 Py_DECREF(al);
2402 ah = al = NULL;
2403
Tim Peters0973b992004-08-29 22:16:50 +00002404 if (a == b) {
2405 t2 = t1;
2406 Py_INCREF(t2);
2407 }
2408 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002409 Py_DECREF(t1);
2410 goto fail;
2411 }
2412 Py_DECREF(bh);
2413 Py_DECREF(bl);
2414 bh = bl = NULL;
2415
Tim Peters738eda72002-08-12 15:08:20 +00002416 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002417 Py_DECREF(t1);
2418 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002419 if (t3 == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002420 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002421
Tim Petersd6974a52002-08-13 20:37:51 +00002422 /* Add t3. It's not obvious why we can't run out of room here.
2423 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002424 */
Christian Heimese93237d2007-12-19 02:37:44 +00002425 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002426 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002427
Tim Peters5af4e6c2002-08-12 02:31:19 +00002428 return long_normalize(ret);
2429
2430 fail:
2431 Py_XDECREF(ret);
2432 Py_XDECREF(ah);
2433 Py_XDECREF(al);
2434 Py_XDECREF(bh);
2435 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002436 return NULL;
2437}
2438
Tim Petersd6974a52002-08-13 20:37:51 +00002439/* (*) Why adding t3 can't "run out of room" above.
2440
Tim Petersab86c2b2002-08-15 20:06:00 +00002441Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2442to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002443
Tim Petersab86c2b2002-08-15 20:06:00 +000024441. For any integer i, i = c(i/2) + f(i/2). In particular,
2445 bsize = c(bsize/2) + f(bsize/2).
24462. shift = f(bsize/2)
24473. asize <= bsize
24484. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2449 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002450
Tim Petersab86c2b2002-08-15 20:06:00 +00002451We allocated asize + bsize result digits, and add t3 into them at an offset
2452of shift. This leaves asize+bsize-shift allocated digit positions for t3
2453to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2454asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002455
Tim Petersab86c2b2002-08-15 20:06:00 +00002456bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2457at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002458
Tim Petersab86c2b2002-08-15 20:06:00 +00002459If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2460digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2461most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002462
Tim Petersab86c2b2002-08-15 20:06:00 +00002463The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002464
Tim Petersab86c2b2002-08-15 20:06:00 +00002465 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002466
Tim Petersab86c2b2002-08-15 20:06:00 +00002467and we have asize + c(bsize/2) available digit positions. We need to show
2468this is always enough. An instance of c(bsize/2) cancels out in both, so
2469the question reduces to whether asize digits is enough to hold
2470(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2471then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2472asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002473digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002474asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002475c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2476is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2477bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002478
Tim Peters48d52c02002-08-14 17:07:32 +00002479Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2480clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2481ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002482*/
2483
Tim Peters60004642002-08-12 22:01:34 +00002484/* b has at least twice the digits of a, and a is big enough that Karatsuba
2485 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2486 * of slices, each with a->ob_size digits, and multiply the slices by a,
2487 * one at a time. This gives k_mul balanced inputs to work with, and is
2488 * also cache-friendly (we compute one double-width slice of the result
2489 * at a time, then move on, never bactracking except for the helpful
2490 * single-width slice overlap between successive partial sums).
2491 */
2492static PyLongObject *
2493k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2494{
Christian Heimese93237d2007-12-19 02:37:44 +00002495 const Py_ssize_t asize = ABS(Py_SIZE(a));
2496 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002497 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002498 PyLongObject *ret;
2499 PyLongObject *bslice = NULL;
2500
2501 assert(asize > KARATSUBA_CUTOFF);
2502 assert(2 * asize <= bsize);
2503
2504 /* Allocate result space, and zero it out. */
2505 ret = _PyLong_New(asize + bsize);
2506 if (ret == NULL)
2507 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002508 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002509
2510 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002511 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002512 if (bslice == NULL)
2513 goto fail;
2514
2515 nbdone = 0;
2516 while (bsize > 0) {
2517 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002518 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002519
2520 /* Multiply the next slice of b by a. */
2521 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2522 nbtouse * sizeof(digit));
Christian Heimese93237d2007-12-19 02:37:44 +00002523 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002524 product = k_mul(a, bslice);
2525 if (product == NULL)
2526 goto fail;
2527
2528 /* Add into result. */
Christian Heimese93237d2007-12-19 02:37:44 +00002529 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2530 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002531 Py_DECREF(product);
2532
2533 bsize -= nbtouse;
2534 nbdone += nbtouse;
2535 }
2536
2537 Py_DECREF(bslice);
2538 return long_normalize(ret);
2539
2540 fail:
2541 Py_DECREF(ret);
2542 Py_XDECREF(bslice);
2543 return NULL;
2544}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002545
2546static PyObject *
2547long_mul(PyLongObject *v, PyLongObject *w)
2548{
2549 PyLongObject *a, *b, *z;
2550
2551 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002552 Py_INCREF(Py_NotImplemented);
2553 return Py_NotImplemented;
2554 }
2555
Tim Petersd64c1de2002-08-12 17:36:03 +00002556 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002557 /* Negate if exactly one of the inputs is negative. */
2558 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002559 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002560 Py_DECREF(a);
2561 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002562 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002563}
2564
Guido van Rossume32e0141992-01-19 16:31:05 +00002565/* The / and % operators are now defined in terms of divmod().
2566 The expression a mod b has the value a - b*floor(a/b).
2567 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002568 |a| by |b|, with the sign of a. This is also expressed
2569 as a - b*trunc(a/b), if trunc truncates towards zero.
2570 Some examples:
2571 a b a rem b a mod b
2572 13 10 3 3
2573 -13 10 -3 7
2574 13 -10 3 -7
2575 -13 -10 -3 -3
2576 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002577 have different signs. We then subtract one from the 'div'
2578 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002579
Tim Peters47e52ee2004-08-30 02:44:38 +00002580/* Compute
2581 * *pdiv, *pmod = divmod(v, w)
2582 * NULL can be passed for pdiv or pmod, in which case that part of
2583 * the result is simply thrown away. The caller owns a reference to
2584 * each of these it requests (does not pass NULL for).
2585 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002586static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002587l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002588 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002589{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002590 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002591
Guido van Rossume32e0141992-01-19 16:31:05 +00002592 if (long_divrem(v, w, &div, &mod) < 0)
2593 return -1;
Christian Heimese93237d2007-12-19 02:37:44 +00002594 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2595 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002596 PyLongObject *temp;
2597 PyLongObject *one;
2598 temp = (PyLongObject *) long_add(mod, w);
2599 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002600 mod = temp;
2601 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002602 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002603 return -1;
2604 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002605 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002606 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002607 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2608 Py_DECREF(mod);
2609 Py_DECREF(div);
2610 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002611 return -1;
2612 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002613 Py_DECREF(one);
2614 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002615 div = temp;
2616 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002617 if (pdiv != NULL)
2618 *pdiv = div;
2619 else
2620 Py_DECREF(div);
2621
2622 if (pmod != NULL)
2623 *pmod = mod;
2624 else
2625 Py_DECREF(mod);
2626
Guido van Rossume32e0141992-01-19 16:31:05 +00002627 return 0;
2628}
2629
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002630static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002631long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002632{
Tim Peters47e52ee2004-08-30 02:44:38 +00002633 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002634
2635 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002636 if (l_divmod(a, b, &div, NULL) < 0)
2637 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002638 Py_DECREF(a);
2639 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002640 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002641}
2642
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002643static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00002644long_classic_div(PyObject *v, PyObject *w)
2645{
Tim Peters47e52ee2004-08-30 02:44:38 +00002646 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002647
2648 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00002649 if (Py_DivisionWarningFlag &&
2650 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
2651 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00002652 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00002653 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00002654 Py_DECREF(a);
2655 Py_DECREF(b);
2656 return (PyObject *)div;
2657}
2658
2659static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002660long_true_divide(PyObject *v, PyObject *w)
2661{
Tim Peterse2a60002001-09-04 06:17:36 +00002662 PyLongObject *a, *b;
2663 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002664 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002665
2666 CONVERT_BINOP(v, w, &a, &b);
2667 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2668 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002669 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2670 Py_DECREF(a);
2671 Py_DECREF(b);
2672 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002673 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002674 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2675 but should really be set correctly after sucessful calls to
2676 _PyLong_AsScaledDouble() */
2677 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002678
2679 if (bd == 0.0) {
2680 PyErr_SetString(PyExc_ZeroDivisionError,
2681 "long division or modulo by zero");
2682 return NULL;
2683 }
2684
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002685 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002686 ad /= bd; /* overflow/underflow impossible here */
2687 aexp -= bexp;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002688 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002689 goto overflow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002690 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002691 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002692 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002693 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002694 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002695 goto overflow;
2696 return PyFloat_FromDouble(ad);
2697
2698overflow:
2699 PyErr_SetString(PyExc_OverflowError,
2700 "long/long too large for a float");
2701 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002702
Tim Peters20dab9f2001-09-04 05:31:47 +00002703}
2704
2705static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002706long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002707{
Tim Peters47e52ee2004-08-30 02:44:38 +00002708 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002709
2710 CONVERT_BINOP(v, w, &a, &b);
2711
Tim Peters47e52ee2004-08-30 02:44:38 +00002712 if (l_divmod(a, b, NULL, &mod) < 0)
2713 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002714 Py_DECREF(a);
2715 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002716 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002717}
2718
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002719static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002720long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002721{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002722 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002723 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002724
2725 CONVERT_BINOP(v, w, &a, &b);
2726
2727 if (l_divmod(a, b, &div, &mod) < 0) {
2728 Py_DECREF(a);
2729 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002730 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002731 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002732 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002733 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002734 PyTuple_SetItem(z, 0, (PyObject *) div);
2735 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002736 }
2737 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002738 Py_DECREF(div);
2739 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002740 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002741 Py_DECREF(a);
2742 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002743 return z;
2744}
2745
Tim Peters47e52ee2004-08-30 02:44:38 +00002746/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002747static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002748long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002749{
Tim Peters47e52ee2004-08-30 02:44:38 +00002750 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2751 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002752
Tim Peters47e52ee2004-08-30 02:44:38 +00002753 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002754 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002755 PyLongObject *temp = NULL;
2756
2757 /* 5-ary values. If the exponent is large enough, table is
2758 * precomputed so that table[i] == a**i % c for i in range(32).
2759 */
2760 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2761 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2762
2763 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002764 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002765 if (PyLong_Check(x)) {
2766 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002767 Py_INCREF(x);
2768 }
Tim Petersde7990b2005-07-17 23:45:23 +00002769 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002770 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00002771 if (c == NULL)
2772 goto Error;
2773 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002774 else if (x == Py_None)
2775 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002776 else {
2777 Py_DECREF(a);
2778 Py_DECREF(b);
2779 Py_INCREF(Py_NotImplemented);
2780 return Py_NotImplemented;
2781 }
Tim Peters4c483c42001-09-05 06:24:58 +00002782
Christian Heimese93237d2007-12-19 02:37:44 +00002783 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00002784 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002785 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002786 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002787 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002788 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002789 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002790 /* else return a float. This works because we know
2791 that this calls float_pow() which converts its
2792 arguments to double. */
2793 Py_DECREF(a);
2794 Py_DECREF(b);
2795 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002796 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002797 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002798
2799 if (c) {
2800 /* if modulus == 0:
2801 raise ValueError() */
Christian Heimese93237d2007-12-19 02:37:44 +00002802 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002803 PyErr_SetString(PyExc_ValueError,
2804 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002805 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002806 }
2807
2808 /* if modulus < 0:
2809 negativeOutput = True
2810 modulus = -modulus */
Christian Heimese93237d2007-12-19 02:37:44 +00002811 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002812 negativeOutput = 1;
2813 temp = (PyLongObject *)_PyLong_Copy(c);
2814 if (temp == NULL)
2815 goto Error;
2816 Py_DECREF(c);
2817 c = temp;
2818 temp = NULL;
2819 c->ob_size = - c->ob_size;
2820 }
2821
2822 /* if modulus == 1:
2823 return 0 */
Christian Heimese93237d2007-12-19 02:37:44 +00002824 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002825 z = (PyLongObject *)PyLong_FromLong(0L);
2826 goto Done;
2827 }
2828
2829 /* if base < 0:
2830 base = base % modulus
2831 Having the base positive just makes things easier. */
Christian Heimese93237d2007-12-19 02:37:44 +00002832 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002833 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00002834 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002835 Py_DECREF(a);
2836 a = temp;
2837 temp = NULL;
2838 }
2839 }
2840
2841 /* At this point a, b, and c are guaranteed non-negative UNLESS
2842 c is NULL, in which case a may be negative. */
2843
2844 z = (PyLongObject *)PyLong_FromLong(1L);
2845 if (z == NULL)
2846 goto Error;
2847
2848 /* Perform a modular reduction, X = X % c, but leave X alone if c
2849 * is NULL.
2850 */
2851#define REDUCE(X) \
2852 if (c != NULL) { \
2853 if (l_divmod(X, c, NULL, &temp) < 0) \
2854 goto Error; \
2855 Py_XDECREF(X); \
2856 X = temp; \
2857 temp = NULL; \
2858 }
2859
2860 /* Multiply two values, then reduce the result:
2861 result = X*Y % c. If c is NULL, skip the mod. */
2862#define MULT(X, Y, result) \
2863{ \
2864 temp = (PyLongObject *)long_mul(X, Y); \
2865 if (temp == NULL) \
2866 goto Error; \
2867 Py_XDECREF(result); \
2868 result = temp; \
2869 temp = NULL; \
2870 REDUCE(result) \
2871}
2872
Christian Heimese93237d2007-12-19 02:37:44 +00002873 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002874 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2875 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimese93237d2007-12-19 02:37:44 +00002876 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002877 digit bi = b->ob_digit[i];
2878
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002879 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002880 MULT(z, z, z)
2881 if (bi & j)
2882 MULT(z, a, z)
2883 }
2884 }
2885 }
2886 else {
2887 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2888 Py_INCREF(z); /* still holds 1L */
2889 table[0] = z;
2890 for (i = 1; i < 32; ++i)
2891 MULT(table[i-1], a, table[i])
2892
Christian Heimese93237d2007-12-19 02:37:44 +00002893 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002894 const digit bi = b->ob_digit[i];
2895
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002896 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002897 const int index = (bi >> j) & 0x1f;
2898 for (k = 0; k < 5; ++k)
2899 MULT(z, z, z)
2900 if (index)
2901 MULT(z, table[index], z)
2902 }
2903 }
2904 }
2905
Christian Heimese93237d2007-12-19 02:37:44 +00002906 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002907 temp = (PyLongObject *)long_sub(z, c);
2908 if (temp == NULL)
2909 goto Error;
2910 Py_DECREF(z);
2911 z = temp;
2912 temp = NULL;
2913 }
2914 goto Done;
2915
2916 Error:
2917 if (z != NULL) {
2918 Py_DECREF(z);
2919 z = NULL;
2920 }
2921 /* fall through */
2922 Done:
Christian Heimese93237d2007-12-19 02:37:44 +00002923 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002924 for (i = 0; i < 32; ++i)
2925 Py_XDECREF(table[i]);
2926 }
Tim Petersde7990b2005-07-17 23:45:23 +00002927 Py_DECREF(a);
2928 Py_DECREF(b);
2929 Py_XDECREF(c);
2930 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002931 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002932}
2933
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002934static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002935long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002936{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002937 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002938 PyLongObject *x;
2939 PyLongObject *w;
2940 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002941 if (w == NULL)
2942 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002943 x = (PyLongObject *) long_add(v, w);
2944 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002945 if (x == NULL)
2946 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002947 Py_SIZE(x) = -(Py_SIZE(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002948 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002949}
2950
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002951static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002952long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002953{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002954 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002955 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002956 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002957 Py_INCREF(v);
2958 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002959 }
Tim Peters69c2de32001-09-11 22:31:33 +00002960 z = (PyLongObject *)_PyLong_Copy(v);
2961 if (z != NULL)
2962 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002963 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002964}
2965
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002966static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002967long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002968{
2969 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002970 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00002971 else
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002972 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002973}
2974
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002975static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002976long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002977{
Christian Heimese93237d2007-12-19 02:37:44 +00002978 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002979}
2980
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002981static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002982long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002983{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002984 PyLongObject *a, *b;
2985 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002986 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002987 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002988 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002989
Neil Schemenauerba872e22001-01-04 01:46:03 +00002990 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2991
Christian Heimese93237d2007-12-19 02:37:44 +00002992 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002993 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002994 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002995 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002996 if (a1 == NULL)
2997 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002998 a2 = (PyLongObject *) long_rshift(a1, b);
2999 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003000 if (a2 == NULL)
3001 goto rshift_error;
3002 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003003 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003004 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003005 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003006
Neil Schemenauerba872e22001-01-04 01:46:03 +00003007 shiftby = PyLong_AsLong((PyObject *)b);
3008 if (shiftby == -1L && PyErr_Occurred())
3009 goto rshift_error;
3010 if (shiftby < 0) {
3011 PyErr_SetString(PyExc_ValueError,
3012 "negative shift count");
3013 goto rshift_error;
3014 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003015 wordshift = shiftby / PyLong_SHIFT;
Christian Heimese93237d2007-12-19 02:37:44 +00003016 newsize = ABS(Py_SIZE(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003017 if (newsize <= 0) {
3018 z = _PyLong_New(0);
3019 Py_DECREF(a);
3020 Py_DECREF(b);
3021 return (PyObject *)z;
3022 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003023 loshift = shiftby % PyLong_SHIFT;
3024 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003025 lomask = ((digit)1 << hishift) - 1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003026 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003027 z = _PyLong_New(newsize);
3028 if (z == NULL)
3029 goto rshift_error;
Christian Heimese93237d2007-12-19 02:37:44 +00003030 if (Py_SIZE(a) < 0)
3031 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003032 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3033 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3034 if (i+1 < newsize)
3035 z->ob_digit[i] |=
3036 (a->ob_digit[j+1] << hishift) & himask;
3037 }
3038 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003039 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003040rshift_error:
3041 Py_DECREF(a);
3042 Py_DECREF(b);
3043 return (PyObject *) z;
3044
Guido van Rossumc6913e71991-11-19 20:26:46 +00003045}
3046
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003047static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003048long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003049{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003050 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003051 PyLongObject *a, *b;
3052 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003053 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003054 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003055 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003056
Neil Schemenauerba872e22001-01-04 01:46:03 +00003057 CONVERT_BINOP(v, w, &a, &b);
3058
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003059 shiftby = PyLong_AsLong((PyObject *)b);
3060 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003061 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003062 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003063 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003064 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003065 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003066 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003067 PyErr_SetString(PyExc_ValueError,
3068 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003069 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003070 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003071 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3072 wordshift = (int)shiftby / PyLong_SHIFT;
3073 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003074
3075 oldsize = ABS(a->ob_size);
3076 newsize = oldsize + wordshift;
3077 if (remshift)
3078 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003079 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003080 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003081 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003082 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003083 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003084 for (i = 0; i < wordshift; i++)
3085 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003086 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003087 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003088 accum |= (twodigits)a->ob_digit[j] << remshift;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003089 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3090 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003091 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003092 if (remshift)
3093 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003094 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003095 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003096 z = long_normalize(z);
3097lshift_error:
3098 Py_DECREF(a);
3099 Py_DECREF(b);
3100 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003101}
3102
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003103
3104/* Bitwise and/xor/or operations */
3105
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003106static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003107long_bitwise(PyLongObject *a,
3108 int op, /* '&', '|', '^' */
3109 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003110{
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003111 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003112 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003113 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003114 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003115 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003116 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003117 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003118
Christian Heimese93237d2007-12-19 02:37:44 +00003119 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003120 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003121 if (a == NULL)
3122 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003123 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003124 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003125 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003126 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003127 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003128 }
Christian Heimese93237d2007-12-19 02:37:44 +00003129 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003130 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003131 if (b == NULL) {
3132 Py_DECREF(a);
3133 return NULL;
3134 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003135 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003136 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003137 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003138 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003139 maskb = 0;
3140 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003141
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003142 negz = 0;
3143 switch (op) {
3144 case '^':
3145 if (maska != maskb) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003146 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003147 negz = -1;
3148 }
3149 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003150 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003151 if (maska && maskb) {
3152 op = '|';
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003153 maska ^= PyLong_MASK;
3154 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003155 negz = -1;
3156 }
3157 break;
3158 case '|':
3159 if (maska || maskb) {
3160 op = '&';
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003161 maska ^= PyLong_MASK;
3162 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003163 negz = -1;
3164 }
3165 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003166 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003167
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003168 /* JRH: The original logic here was to allocate the result value (z)
3169 as the longer of the two operands. However, there are some cases
3170 where the result is guaranteed to be shorter than that: AND of two
3171 positives, OR of two negatives: use the shorter number. AND with
3172 mixed signs: use the positive number. OR with mixed signs: use the
3173 negative number. After the transformations above, op will be '&'
3174 iff one of these cases applies, and mask will be non-0 for operands
3175 whose length should be ignored.
3176 */
3177
Christian Heimese93237d2007-12-19 02:37:44 +00003178 size_a = Py_SIZE(a);
3179 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003180 size_z = op == '&'
3181 ? (maska
3182 ? size_b
3183 : (maskb ? size_a : MIN(size_a, size_b)))
3184 : MAX(size_a, size_b);
3185 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003186 if (z == NULL) {
Neal Norwitzef02b9e2006-07-16 02:00:32 +00003187 Py_DECREF(a);
3188 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003189 return NULL;
3190 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003191
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003192 for (i = 0; i < size_z; ++i) {
3193 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3194 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3195 switch (op) {
3196 case '&': z->ob_digit[i] = diga & digb; break;
3197 case '|': z->ob_digit[i] = diga | digb; break;
3198 case '^': z->ob_digit[i] = diga ^ digb; break;
3199 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003200 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003201
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003202 Py_DECREF(a);
3203 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003204 z = long_normalize(z);
3205 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003206 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003207 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003208 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003209 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003210}
3211
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003212static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003213long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003214{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003215 PyLongObject *a, *b;
3216 PyObject *c;
3217 CONVERT_BINOP(v, w, &a, &b);
3218 c = long_bitwise(a, '&', b);
3219 Py_DECREF(a);
3220 Py_DECREF(b);
3221 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003222}
3223
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003224static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003225long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003226{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003227 PyLongObject *a, *b;
3228 PyObject *c;
3229 CONVERT_BINOP(v, w, &a, &b);
3230 c = long_bitwise(a, '^', b);
3231 Py_DECREF(a);
3232 Py_DECREF(b);
3233 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003234}
3235
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003236static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003237long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003238{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003239 PyLongObject *a, *b;
3240 PyObject *c;
3241 CONVERT_BINOP(v, w, &a, &b);
3242 c = long_bitwise(a, '|', b);
3243 Py_DECREF(a);
3244 Py_DECREF(b);
3245 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003246}
3247
Guido van Rossum234f9421993-06-17 12:35:49 +00003248static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003249long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003250{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003251 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00003252 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Georg Brandlc02e1312007-04-11 17:16:24 +00003253 if (*pw == NULL)
3254 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003255 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00003256 return 0;
3257 }
Guido van Rossum1952e382001-09-19 01:25:16 +00003258 else if (PyLong_Check(*pw)) {
3259 Py_INCREF(*pv);
3260 Py_INCREF(*pw);
3261 return 0;
3262 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00003263 return 1; /* Can't do it */
3264}
3265
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003266static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003267long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003268{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003269 if (PyLong_CheckExact(v))
3270 Py_INCREF(v);
3271 else
3272 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003273 return v;
3274}
3275
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003276static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003277long_int(PyObject *v)
3278{
3279 long x;
3280 x = PyLong_AsLong(v);
3281 if (PyErr_Occurred()) {
3282 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3283 PyErr_Clear();
3284 if (PyLong_CheckExact(v)) {
3285 Py_INCREF(v);
3286 return v;
3287 }
3288 else
3289 return _PyLong_Copy((PyLongObject *)v);
3290 }
3291 else
3292 return NULL;
3293 }
3294 return PyInt_FromLong(x);
3295}
3296
3297static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003298long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003299{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003300 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003301 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003302 if (result == -1.0 && PyErr_Occurred())
3303 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003304 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003305}
3306
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003307static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003308long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003309{
Eric Smith5e527eb2008-02-10 01:36:53 +00003310 return _PyLong_Format(v, 8, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003311}
3312
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003313static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003314long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003315{
Eric Smith5e527eb2008-02-10 01:36:53 +00003316 return _PyLong_Format(v, 16, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003317}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003318
3319static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003320long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003321
Tim Peters6d6c1a32001-08-02 04:15:00 +00003322static PyObject *
3323long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3324{
3325 PyObject *x = NULL;
3326 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003327 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003328
Guido van Rossumbef14172001-08-29 15:47:46 +00003329 if (type != &PyLong_Type)
3330 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003331 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3332 &x, &base))
3333 return NULL;
3334 if (x == NULL)
3335 return PyLong_FromLong(0L);
3336 if (base == -909)
3337 return PyNumber_Long(x);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003338 else if (PyString_Check(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003339 /* Since PyLong_FromString doesn't have a length parameter,
3340 * check here for possible NULs in the string. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003341 char *string = PyString_AS_STRING(x);
3342 if (strlen(string) != PyString_Size(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003343 /* create a repr() of the input string,
3344 * just like PyLong_FromString does. */
3345 PyObject *srepr;
3346 srepr = PyObject_Repr(x);
3347 if (srepr == NULL)
3348 return NULL;
3349 PyErr_Format(PyExc_ValueError,
3350 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003351 base, PyString_AS_STRING(srepr));
Georg Brandl00cd8182007-03-06 18:41:12 +00003352 Py_DECREF(srepr);
3353 return NULL;
3354 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003355 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Georg Brandl00cd8182007-03-06 18:41:12 +00003356 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003357#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003358 else if (PyUnicode_Check(x))
3359 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3360 PyUnicode_GET_SIZE(x),
3361 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003362#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003363 else {
3364 PyErr_SetString(PyExc_TypeError,
3365 "long() can't convert non-string with explicit base");
3366 return NULL;
3367 }
3368}
3369
Guido van Rossumbef14172001-08-29 15:47:46 +00003370/* Wimpy, slow approach to tp_new calls for subtypes of long:
3371 first create a regular long from whatever arguments we got,
3372 then allocate a subtype instance and initialize it from
3373 the regular long. The regular long is then thrown away.
3374*/
3375static PyObject *
3376long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3377{
Anthony Baxter377be112006-04-11 06:54:30 +00003378 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003379 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003380
3381 assert(PyType_IsSubtype(type, &PyLong_Type));
3382 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3383 if (tmp == NULL)
3384 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003385 assert(PyLong_CheckExact(tmp));
Christian Heimese93237d2007-12-19 02:37:44 +00003386 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003387 if (n < 0)
3388 n = -n;
Anthony Baxter377be112006-04-11 06:54:30 +00003389 newobj = (PyLongObject *)type->tp_alloc(type, n);
3390 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003391 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003392 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003393 }
Anthony Baxter377be112006-04-11 06:54:30 +00003394 assert(PyLong_Check(newobj));
Christian Heimese93237d2007-12-19 02:37:44 +00003395 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003396 for (i = 0; i < n; i++)
Anthony Baxter377be112006-04-11 06:54:30 +00003397 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003398 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00003399 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003400}
3401
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003402static PyObject *
3403long_getnewargs(PyLongObject *v)
3404{
3405 return Py_BuildValue("(N)", _PyLong_Copy(v));
3406}
3407
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003408static PyObject *
3409long_getN(PyLongObject *v, void *context) {
Jeffrey Yasskin5de250e2008-03-18 01:09:59 +00003410 return PyLong_FromLong((Py_intptr_t)context);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003411}
3412
Eric Smitha9f7d622008-02-17 19:46:49 +00003413static PyObject *
3414long__format__(PyObject *self, PyObject *args)
3415{
3416 PyObject *format_spec;
3417
3418 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3419 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00003420 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00003421 return _PyLong_FormatAdvanced(self,
3422 PyBytes_AS_STRING(format_spec),
3423 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00003424 if (PyUnicode_Check(format_spec)) {
3425 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00003426 PyObject *result;
3427 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00003428
Eric Smithdc13b792008-05-30 18:10:04 +00003429 if (str_spec == NULL)
3430 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00003431
Eric Smithdc13b792008-05-30 18:10:04 +00003432 result = _PyLong_FormatAdvanced(self,
3433 PyBytes_AS_STRING(str_spec),
3434 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00003435
Eric Smithdc13b792008-05-30 18:10:04 +00003436 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00003437 return result;
3438 }
3439 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
3440 return NULL;
3441}
3442
Robert Schuppenies51df0642008-06-01 16:16:17 +00003443static PyObject *
3444long_sizeof(PyLongObject *v)
3445{
3446 Py_ssize_t res;
3447
Robert Schuppenies9be2ec12008-07-10 15:24:04 +00003448 res = v->ob_type->tp_basicsize;
Robert Schuppenies51df0642008-06-01 16:16:17 +00003449 if (v->ob_size != 0)
Robert Schuppenies9be2ec12008-07-10 15:24:04 +00003450 res += abs(v->ob_size) * sizeof(digit);
Robert Schuppenies51df0642008-06-01 16:16:17 +00003451 return PyInt_FromSsize_t(res);
3452}
3453
Mark Dickinson1a707982008-12-17 16:14:37 +00003454static const unsigned char BitLengthTable[32] = {
3455 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
3456 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
3457};
3458
3459static PyObject *
3460long_bit_length(PyLongObject *v)
3461{
3462 PyLongObject *result, *x, *y;
3463 Py_ssize_t ndigits, msd_bits = 0;
3464 digit msd;
3465
3466 assert(v != NULL);
3467 assert(PyLong_Check(v));
3468
3469 ndigits = ABS(Py_SIZE(v));
3470 if (ndigits == 0)
3471 return PyInt_FromLong(0);
3472
3473 msd = v->ob_digit[ndigits-1];
3474 while (msd >= 32) {
3475 msd_bits += 6;
3476 msd >>= 6;
3477 }
3478 msd_bits += (long)(BitLengthTable[msd]);
3479
3480 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
3481 return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
3482
3483 /* expression above may overflow; use Python integers instead */
3484 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
3485 if (result == NULL)
3486 return NULL;
3487 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
3488 if (x == NULL)
3489 goto error;
3490 y = (PyLongObject *)long_mul(result, x);
3491 Py_DECREF(x);
3492 if (y == NULL)
3493 goto error;
3494 Py_DECREF(result);
3495 result = y;
3496
3497 x = (PyLongObject *)PyLong_FromLong(msd_bits);
3498 if (x == NULL)
3499 goto error;
3500 y = (PyLongObject *)long_add(result, x);
3501 Py_DECREF(x);
3502 if (y == NULL)
3503 goto error;
3504 Py_DECREF(result);
3505 result = y;
3506
3507 return (PyObject *)result;
3508
3509error:
3510 Py_DECREF(result);
3511 return NULL;
3512}
3513
3514PyDoc_STRVAR(long_bit_length_doc,
3515"long.bit_length() -> int or long\n\
3516\n\
3517Number of bits necessary to represent self in binary.\n\
3518>>> bin(37L)\n\
3519'0b100101'\n\
3520>>> (37L).bit_length()\n\
35216");
3522
Christian Heimes6f341092008-04-18 23:13:07 +00003523#if 0
3524static PyObject *
3525long_is_finite(PyObject *v)
3526{
3527 Py_RETURN_TRUE;
3528}
3529#endif
3530
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003531static PyMethodDef long_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003532 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3533 "Returns self, the complex conjugate of any long."},
Mark Dickinson1a707982008-12-17 16:14:37 +00003534 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
3535 long_bit_length_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00003536#if 0
3537 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3538 "Returns always True."},
3539#endif
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003540 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3541 "Truncating an Integral returns itself."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003542 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smitha9f7d622008-02-17 19:46:49 +00003543 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Robert Schuppenies51df0642008-06-01 16:16:17 +00003544 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00003545 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003546 {NULL, NULL} /* sentinel */
3547};
3548
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003549static PyGetSetDef long_getset[] = {
3550 {"real",
3551 (getter)long_long, (setter)NULL,
3552 "the real part of a complex number",
3553 NULL},
3554 {"imag",
3555 (getter)long_getN, (setter)NULL,
3556 "the imaginary part of a complex number",
3557 (void*)0},
3558 {"numerator",
3559 (getter)long_long, (setter)NULL,
3560 "the numerator of a rational number in lowest terms",
3561 NULL},
3562 {"denominator",
3563 (getter)long_getN, (setter)NULL,
3564 "the denominator of a rational number in lowest terms",
3565 (void*)1},
3566 {NULL} /* Sentinel */
3567};
3568
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003569PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003570"long(x[, base]) -> integer\n\
3571\n\
3572Convert a string or number to a long integer, if possible. A floating\n\
3573point argument will be truncated towards zero (this does not include a\n\
3574string representation of a floating point number!) When converting a\n\
3575string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003576converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003577
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003578static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003579 (binaryfunc) long_add, /*nb_add*/
3580 (binaryfunc) long_sub, /*nb_subtract*/
3581 (binaryfunc) long_mul, /*nb_multiply*/
Georg Brandl347b3002006-03-30 11:57:00 +00003582 long_classic_div, /*nb_divide*/
3583 long_mod, /*nb_remainder*/
3584 long_divmod, /*nb_divmod*/
3585 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003586 (unaryfunc) long_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003587 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003588 (unaryfunc) long_abs, /*tp_absolute*/
3589 (inquiry) long_nonzero, /*tp_nonzero*/
3590 (unaryfunc) long_invert, /*nb_invert*/
Georg Brandl347b3002006-03-30 11:57:00 +00003591 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003592 (binaryfunc) long_rshift, /*nb_rshift*/
Georg Brandl347b3002006-03-30 11:57:00 +00003593 long_and, /*nb_and*/
3594 long_xor, /*nb_xor*/
3595 long_or, /*nb_or*/
3596 long_coerce, /*nb_coerce*/
3597 long_int, /*nb_int*/
3598 long_long, /*nb_long*/
3599 long_float, /*nb_float*/
3600 long_oct, /*nb_oct*/
3601 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003602 0, /* nb_inplace_add */
3603 0, /* nb_inplace_subtract */
3604 0, /* nb_inplace_multiply */
3605 0, /* nb_inplace_divide */
3606 0, /* nb_inplace_remainder */
3607 0, /* nb_inplace_power */
3608 0, /* nb_inplace_lshift */
3609 0, /* nb_inplace_rshift */
3610 0, /* nb_inplace_and */
3611 0, /* nb_inplace_xor */
3612 0, /* nb_inplace_or */
Georg Brandl347b3002006-03-30 11:57:00 +00003613 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003614 long_true_divide, /* nb_true_divide */
3615 0, /* nb_inplace_floor_divide */
3616 0, /* nb_inplace_true_divide */
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003617 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003618};
3619
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003620PyTypeObject PyLong_Type = {
3621 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003622 0, /* ob_size */
3623 "long", /* tp_name */
3624 sizeof(PyLongObject) - sizeof(digit), /* tp_basicsize */
3625 sizeof(digit), /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003626 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627 0, /* tp_print */
3628 0, /* tp_getattr */
3629 0, /* tp_setattr */
3630 (cmpfunc)long_compare, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00003631 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632 &long_as_number, /* tp_as_number */
3633 0, /* tp_as_sequence */
3634 0, /* tp_as_mapping */
3635 (hashfunc)long_hash, /* tp_hash */
3636 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00003637 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003638 PyObject_GenericGetAttr, /* tp_getattro */
3639 0, /* tp_setattro */
3640 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00003641 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003642 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003643 long_doc, /* tp_doc */
3644 0, /* tp_traverse */
3645 0, /* tp_clear */
3646 0, /* tp_richcompare */
3647 0, /* tp_weaklistoffset */
3648 0, /* tp_iter */
3649 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003650 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003651 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003652 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003653 0, /* tp_base */
3654 0, /* tp_dict */
3655 0, /* tp_descr_get */
3656 0, /* tp_descr_set */
3657 0, /* tp_dictoffset */
3658 0, /* tp_init */
3659 0, /* tp_alloc */
3660 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003661 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003662};