blob: 228376a9dfb9ed438919a3a5a932c07babd54dd3 [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,
179 "cannot convert float infinity to long");
180 return NULL;
181 }
Christian Heimes8267d1d2008-01-04 00:37:34 +0000182 if (Py_IS_NAN(dval)) {
183 return PyLong_FromLong(0L);
184 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000185 if (dval < 0.0) {
186 neg = 1;
187 dval = -dval;
188 }
189 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
190 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000191 return PyLong_FromLong(0L);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000192 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000193 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000194 if (v == NULL)
195 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000196 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000197 for (i = ndig; --i >= 0; ) {
198 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000199 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000200 frac = frac - (double)bits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000201 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000202 }
203 if (neg)
Christian Heimese93237d2007-12-19 02:37:44 +0000204 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000206}
207
Armin Rigo7ccbca92006-10-04 12:17:45 +0000208/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
209 * anything about what happens when a signed integer operation overflows,
210 * and some compilers think they're doing you a favor by being "clever"
211 * then. The bit pattern for the largest postive signed long is
212 * (unsigned long)LONG_MAX, and for the smallest negative signed long
213 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
214 * However, some other compilers warn about applying unary minus to an
215 * unsigned operand. Hence the weird "0-".
216 */
217#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
218#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
219
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000220/* Get a C long int from a long int object.
221 Returns -1 and sets an error condition if overflow occurs. */
222
223long
Tim Peters9f688bf2000-07-07 15:53:28 +0000224PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000225{
Guido van Rossumf7531811998-05-26 14:33:37 +0000226 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000227 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000228 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000229 Py_ssize_t i;
230 int sign;
Guido van Rossumf7531811998-05-26 14:33:37 +0000231
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000232 if (vv == NULL || !PyLong_Check(vv)) {
Guido van Rossum7e35d572001-09-15 03:14:32 +0000233 if (vv != NULL && PyInt_Check(vv))
234 return PyInt_AsLong(vv);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000235 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000236 return -1;
237 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000239 i = v->ob_size;
240 sign = 1;
241 x = 0;
242 if (i < 0) {
243 sign = -1;
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000244 i = -(i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000245 }
246 while (--i >= 0) {
247 prev = x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000248 x = (x << PyLong_SHIFT) + v->ob_digit[i];
249 if ((x >> PyLong_SHIFT) != prev)
Guido van Rossumf7531811998-05-26 14:33:37 +0000250 goto overflow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000251 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000252 /* Haven't lost any bits, but casting to long requires extra care
253 * (see comment above).
254 */
255 if (x <= (unsigned long)LONG_MAX) {
256 return (long)x * sign;
257 }
258 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
259 return LONG_MIN;
260 }
261 /* else overflow */
Guido van Rossumf7531811998-05-26 14:33:37 +0000262
263 overflow:
264 PyErr_SetString(PyExc_OverflowError,
Skip Montanarobafedec2001-09-13 19:05:30 +0000265 "long int too large to convert to int");
Guido van Rossumf7531811998-05-26 14:33:37 +0000266 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000267}
268
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000269/* Get a Py_ssize_t from a long int object.
270 Returns -1 and sets an error condition if overflow occurs. */
271
272Py_ssize_t
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000273PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000274 register PyLongObject *v;
275 size_t x, prev;
276 Py_ssize_t i;
277 int sign;
278
279 if (vv == NULL || !PyLong_Check(vv)) {
280 PyErr_BadInternalCall();
281 return -1;
282 }
283 v = (PyLongObject *)vv;
284 i = v->ob_size;
285 sign = 1;
286 x = 0;
287 if (i < 0) {
288 sign = -1;
289 i = -(i);
290 }
291 while (--i >= 0) {
292 prev = x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000293 x = (x << PyLong_SHIFT) + v->ob_digit[i];
294 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000295 goto overflow;
296 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000297 /* Haven't lost any bits, but casting to a signed type requires
298 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000299 */
Armin Rigo7ccbca92006-10-04 12:17:45 +0000300 if (x <= (size_t)PY_SSIZE_T_MAX) {
301 return (Py_ssize_t)x * sign;
302 }
303 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
304 return PY_SSIZE_T_MIN;
305 }
306 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000307
308 overflow:
309 PyErr_SetString(PyExc_OverflowError,
310 "long int too large to convert to int");
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000311 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000312}
313
Guido van Rossumd8c80482002-08-13 00:24:58 +0000314/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000315 Returns -1 and sets an error condition if overflow occurs. */
316
317unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000318PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000319{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000320 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000321 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000322 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000323
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000324 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000325 if (vv != NULL && PyInt_Check(vv)) {
326 long val = PyInt_AsLong(vv);
327 if (val < 0) {
328 PyErr_SetString(PyExc_OverflowError,
329 "can't convert negative value to unsigned long");
330 return (unsigned long) -1;
331 }
332 return val;
333 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000334 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000335 return (unsigned long) -1;
336 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000337 v = (PyLongObject *)vv;
Christian Heimese93237d2007-12-19 02:37:44 +0000338 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000339 x = 0;
340 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum53756b11997-01-03 17:14:46 +0000342 "can't convert negative value to unsigned long");
343 return (unsigned long) -1;
344 }
345 while (--i >= 0) {
346 prev = x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000347 x = (x << PyLong_SHIFT) + v->ob_digit[i];
348 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000349 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +0000350 "long int too large to convert");
Guido van Rossum53756b11997-01-03 17:14:46 +0000351 return (unsigned long) -1;
352 }
353 }
354 return x;
355}
356
Thomas Hellera4ea6032003-04-17 18:55:45 +0000357/* Get a C unsigned long int from a long int object, ignoring the high bits.
358 Returns -1 and sets an error condition if an error occurs. */
359
360unsigned long
361PyLong_AsUnsignedLongMask(PyObject *vv)
362{
363 register PyLongObject *v;
364 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000365 Py_ssize_t i;
366 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000367
368 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000369 if (vv != NULL && PyInt_Check(vv))
370 return PyInt_AsUnsignedLongMask(vv);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000371 PyErr_BadInternalCall();
372 return (unsigned long) -1;
373 }
374 v = (PyLongObject *)vv;
375 i = v->ob_size;
376 sign = 1;
377 x = 0;
378 if (i < 0) {
379 sign = -1;
380 i = -i;
381 }
382 while (--i >= 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000383 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000384 }
385 return x * sign;
386}
387
Tim Peters5b8132f2003-01-31 15:52:05 +0000388int
389_PyLong_Sign(PyObject *vv)
390{
391 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000392
393 assert(v != NULL);
394 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000395
Christian Heimese93237d2007-12-19 02:37:44 +0000396 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000397}
398
Tim Petersbaefd9e2003-01-28 20:37:45 +0000399size_t
400_PyLong_NumBits(PyObject *vv)
401{
402 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000403 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000404 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000405
406 assert(v != NULL);
407 assert(PyLong_Check(v));
Christian Heimese93237d2007-12-19 02:37:44 +0000408 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000409 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
410 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000411 digit msd = v->ob_digit[ndigits - 1];
412
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000413 result = (ndigits - 1) * PyLong_SHIFT;
414 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000415 goto Overflow;
416 do {
417 ++result;
418 if (result == 0)
419 goto Overflow;
420 msd >>= 1;
421 } while (msd);
422 }
423 return result;
424
425Overflow:
426 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
427 "to express in a platform size_t");
428 return (size_t)-1;
429}
430
Tim Peters2a9b3672001-06-11 21:23:58 +0000431PyObject *
432_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
433 int little_endian, int is_signed)
434{
435 const unsigned char* pstartbyte;/* LSB of bytes */
436 int incr; /* direction to move pstartbyte */
437 const unsigned char* pendbyte; /* MSB of bytes */
438 size_t numsignificantbytes; /* number of bytes that matter */
439 size_t ndigits; /* number of Python long digits */
440 PyLongObject* v; /* result */
441 int idigit = 0; /* next free index in v->ob_digit */
442
443 if (n == 0)
444 return PyLong_FromLong(0L);
445
446 if (little_endian) {
447 pstartbyte = bytes;
448 pendbyte = bytes + n - 1;
449 incr = 1;
450 }
451 else {
452 pstartbyte = bytes + n - 1;
453 pendbyte = bytes;
454 incr = -1;
455 }
456
457 if (is_signed)
458 is_signed = *pendbyte >= 0x80;
459
460 /* Compute numsignificantbytes. This consists of finding the most
461 significant byte. Leading 0 bytes are insignficant if the number
462 is positive, and leading 0xff bytes if negative. */
463 {
464 size_t i;
465 const unsigned char* p = pendbyte;
466 const int pincr = -incr; /* search MSB to LSB */
467 const unsigned char insignficant = is_signed ? 0xff : 0x00;
468
469 for (i = 0; i < n; ++i, p += pincr) {
470 if (*p != insignficant)
471 break;
472 }
473 numsignificantbytes = n - i;
474 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
475 actually has 2 significant bytes. OTOH, 0xff0001 ==
476 -0x00ffff, so we wouldn't *need* to bump it there; but we
477 do for 0xffff = -0x0001. To be safe without bothering to
478 check every case, bump it regardless. */
479 if (is_signed && numsignificantbytes < n)
480 ++numsignificantbytes;
481 }
482
483 /* How many Python long digits do we need? We have
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000484 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000485 bits, so it's the ceiling of the quotient. */
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000486 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000487 if (ndigits > (size_t)INT_MAX)
488 return PyErr_NoMemory();
489 v = _PyLong_New((int)ndigits);
490 if (v == NULL)
491 return NULL;
492
493 /* Copy the bits over. The tricky parts are computing 2's-comp on
494 the fly for signed numbers, and dealing with the mismatch between
495 8-bit bytes and (probably) 15-bit Python digits.*/
496 {
497 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000498 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000499 twodigits accum = 0; /* sliding register */
500 unsigned int accumbits = 0; /* number of bits in accum */
501 const unsigned char* p = pstartbyte;
502
503 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000504 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000505 /* Compute correction for 2's comp, if needed. */
506 if (is_signed) {
507 thisbyte = (0xff ^ thisbyte) + carry;
508 carry = thisbyte >> 8;
509 thisbyte &= 0xff;
510 }
511 /* Because we're going LSB to MSB, thisbyte is
512 more significant than what's already in accum,
513 so needs to be prepended to accum. */
514 accum |= thisbyte << accumbits;
515 accumbits += 8;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000516 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000517 /* There's enough to fill a Python digit. */
518 assert(idigit < (int)ndigits);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000519 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000520 ++idigit;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000521 accum >>= PyLong_SHIFT;
522 accumbits -= PyLong_SHIFT;
523 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000524 }
525 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000526 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000527 if (accumbits) {
528 assert(idigit < (int)ndigits);
529 v->ob_digit[idigit] = (digit)accum;
530 ++idigit;
531 }
532 }
533
Christian Heimese93237d2007-12-19 02:37:44 +0000534 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000535 return (PyObject *)long_normalize(v);
536}
537
538int
539_PyLong_AsByteArray(PyLongObject* v,
540 unsigned char* bytes, size_t n,
541 int little_endian, int is_signed)
542{
543 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000544 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000545 twodigits accum; /* sliding register */
546 unsigned int accumbits; /* # bits in accum */
547 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
548 twodigits carry; /* for computing 2's-comp */
549 size_t j; /* # bytes filled */
550 unsigned char* p; /* pointer to next byte in bytes */
551 int pincr; /* direction to move p */
552
553 assert(v != NULL && PyLong_Check(v));
554
Christian Heimese93237d2007-12-19 02:37:44 +0000555 if (Py_SIZE(v) < 0) {
556 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000557 if (!is_signed) {
558 PyErr_SetString(PyExc_TypeError,
559 "can't convert negative long to unsigned");
560 return -1;
561 }
562 do_twos_comp = 1;
563 }
564 else {
Christian Heimese93237d2007-12-19 02:37:44 +0000565 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000566 do_twos_comp = 0;
567 }
568
569 if (little_endian) {
570 p = bytes;
571 pincr = 1;
572 }
573 else {
574 p = bytes + n - 1;
575 pincr = -1;
576 }
577
Tim Peters898cf852001-06-13 20:50:08 +0000578 /* Copy over all the Python digits.
579 It's crucial that every Python digit except for the MSD contribute
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000580 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000581 normalized. */
582 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000583 j = 0;
584 accum = 0;
585 accumbits = 0;
586 carry = do_twos_comp ? 1 : 0;
587 for (i = 0; i < ndigits; ++i) {
588 twodigits thisdigit = v->ob_digit[i];
589 if (do_twos_comp) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000590 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
591 carry = thisdigit >> PyLong_SHIFT;
592 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000593 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000594 /* Because we're going LSB to MSB, thisdigit is more
595 significant than what's already in accum, so needs to be
596 prepended to accum. */
597 accum |= thisdigit << accumbits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000598 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000599
Tim Petersede05092001-06-14 08:53:38 +0000600 /* The most-significant digit may be (probably is) at least
601 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000602 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000603 /* Count # of sign bits -- they needn't be stored,
604 * although for signed conversion we need later to
605 * make sure at least one sign bit gets stored.
606 * First shift conceptual sign bit to real sign bit.
607 */
608 stwodigits s = (stwodigits)(thisdigit <<
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000609 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000610 unsigned int nsignbits = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000611 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000612 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000613 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000614 }
Tim Petersede05092001-06-14 08:53:38 +0000615 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000616 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000617
Tim Peters2a9b3672001-06-11 21:23:58 +0000618 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000619 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000620 if (j >= n)
621 goto Overflow;
622 ++j;
623 *p = (unsigned char)(accum & 0xff);
624 p += pincr;
625 accumbits -= 8;
626 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000627 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000628 }
629
630 /* Store the straggler (if any). */
631 assert(accumbits < 8);
632 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000633 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000634 if (j >= n)
635 goto Overflow;
636 ++j;
637 if (do_twos_comp) {
638 /* Fill leading bits of the byte with sign bits
639 (appropriately pretending that the long had an
640 infinite supply of sign bits). */
641 accum |= (~(twodigits)0) << accumbits;
642 }
643 *p = (unsigned char)(accum & 0xff);
644 p += pincr;
645 }
Tim Peters05607ad2001-06-13 21:01:27 +0000646 else if (j == n && n > 0 && is_signed) {
647 /* The main loop filled the byte array exactly, so the code
648 just above didn't get to ensure there's a sign bit, and the
649 loop below wouldn't add one either. Make sure a sign bit
650 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000651 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000652 int sign_bit_set = msb >= 0x80;
653 assert(accumbits == 0);
654 if (sign_bit_set == do_twos_comp)
655 return 0;
656 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000657 goto Overflow;
658 }
Tim Peters05607ad2001-06-13 21:01:27 +0000659
660 /* Fill remaining bytes with copies of the sign bit. */
661 {
662 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
663 for ( ; j < n; ++j, p += pincr)
664 *p = signbyte;
665 }
666
Tim Peters2a9b3672001-06-11 21:23:58 +0000667 return 0;
668
669Overflow:
670 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
671 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000672
Tim Peters2a9b3672001-06-11 21:23:58 +0000673}
674
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000675double
676_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
677{
678/* NBITS_WANTED should be > the number of bits in a double's precision,
679 but small enough so that 2**NBITS_WANTED is within the normal double
680 range. nbitsneeded is set to 1 less than that because the most-significant
681 Python digit contains at least 1 significant bit, but we don't want to
682 bother counting them (catering to the worst case cheaply).
683
684 57 is one more than VAX-D double precision; I (Tim) don't know of a double
685 format with more precision than that; it's 1 larger so that we add in at
686 least one round bit to stand in for the ignored least-significant bits.
687*/
688#define NBITS_WANTED 57
689 PyLongObject *v;
690 double x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000691 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000692 Py_ssize_t i;
693 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000694 int nbitsneeded;
695
696 if (vv == NULL || !PyLong_Check(vv)) {
697 PyErr_BadInternalCall();
698 return -1;
699 }
700 v = (PyLongObject *)vv;
Christian Heimese93237d2007-12-19 02:37:44 +0000701 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000702 sign = 1;
703 if (i < 0) {
704 sign = -1;
705 i = -(i);
706 }
707 else if (i == 0) {
708 *exponent = 0;
709 return 0.0;
710 }
711 --i;
712 x = (double)v->ob_digit[i];
713 nbitsneeded = NBITS_WANTED - 1;
714 /* Invariant: i Python digits remain unaccounted for. */
715 while (i > 0 && nbitsneeded > 0) {
716 --i;
717 x = x * multiplier + (double)v->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000718 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000719 }
720 /* There are i digits we didn't shift in. Pretending they're all
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000721 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000722 *exponent = i;
723 assert(x > 0.0);
724 return x * sign;
725#undef NBITS_WANTED
726}
727
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000728/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000729
730double
Tim Peters9f688bf2000-07-07 15:53:28 +0000731PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000732{
Thomas Wouters553489a2006-02-01 21:32:04 +0000733 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000734 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000735
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000736 if (vv == NULL || !PyLong_Check(vv)) {
737 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000738 return -1;
739 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000740 x = _PyLong_AsScaledDouble(vv, &e);
741 if (x == -1.0 && PyErr_Occurred())
742 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000743 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
744 set correctly after a successful _PyLong_AsScaledDouble() call */
745 assert(e >= 0);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000746 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000747 goto overflow;
748 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000749 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000750 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000751 goto overflow;
752 return x;
753
754overflow:
755 PyErr_SetString(PyExc_OverflowError,
756 "long int too large to convert to float");
757 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000758}
759
Guido van Rossum78694d91998-09-18 14:14:13 +0000760/* Create a new long (or int) object from a C pointer */
761
762PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000763PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000764{
Tim Peters70128a12001-06-16 08:48:40 +0000765#if SIZEOF_VOID_P <= SIZEOF_LONG
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000766 if ((long)p < 0)
767 return PyLong_FromUnsignedLong((unsigned long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000768 return PyInt_FromLong((long)p);
769#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000770
Tim Peters70128a12001-06-16 08:48:40 +0000771#ifndef HAVE_LONG_LONG
772# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
773#endif
774#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000775# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000776#endif
777 /* optimize null pointers */
778 if (p == NULL)
779 return PyInt_FromLong(0);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000780 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000781
782#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000783}
784
785/* Get a C pointer from a long object (or an int object in some cases) */
786
787void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000788PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000789{
790 /* This function will allow int or long objects. If vv is neither,
791 then the PyLong_AsLong*() functions will raise the exception:
792 PyExc_SystemError, "bad argument to internal function"
793 */
Tim Peters70128a12001-06-16 08:48:40 +0000794#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000795 long x;
796
Tim Peters70128a12001-06-16 08:48:40 +0000797 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000798 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000799 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000800 x = PyLong_AsLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000801 else
802 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000803#else
Tim Peters70128a12001-06-16 08:48:40 +0000804
805#ifndef HAVE_LONG_LONG
806# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
807#endif
808#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000809# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000810#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000811 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000812
Tim Peters70128a12001-06-16 08:48:40 +0000813 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000814 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000815 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000816 x = PyLong_AsLongLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000817 else
818 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000819
820#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000821
822 if (x == -1 && PyErr_Occurred())
823 return NULL;
824 return (void *)x;
825}
826
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000827#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000828
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000829/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000830 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000831 */
832
Tim Peterscf37dfc2001-06-14 18:42:50 +0000833#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000834
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000835/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000836
837PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000838PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000839{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000840 PyLongObject *v;
Mark Dickinson27a63252008-04-15 20:51:18 +0000841 unsigned PY_LONG_LONG abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000842 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
843 int ndigits = 0;
844 int negative = 0;
845
846 if (ival < 0) {
Mark Dickinson27a63252008-04-15 20:51:18 +0000847 /* avoid signed overflow on negation; see comments
848 in PyLong_FromLong above. */
849 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000850 negative = 1;
851 }
Mark Dickinson27a63252008-04-15 20:51:18 +0000852 else {
853 abs_ival = (unsigned PY_LONG_LONG)ival;
854 }
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000855
856 /* Count the number of Python digits.
857 We used to pick 5 ("big enough for anything"), but that's a
858 waste of time and space given that 5*15 = 75 bits are rarely
859 needed. */
Mark Dickinson27a63252008-04-15 20:51:18 +0000860 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000861 while (t) {
862 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000863 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000864 }
865 v = _PyLong_New(ndigits);
866 if (v != NULL) {
867 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000868 Py_SIZE(v) = negative ? -ndigits : ndigits;
Mark Dickinson27a63252008-04-15 20:51:18 +0000869 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000870 while (t) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000871 *p++ = (digit)(t & PyLong_MASK);
872 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000873 }
874 }
875 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000876}
877
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000878/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000879
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000880PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000881PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000882{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000883 PyLongObject *v;
884 unsigned PY_LONG_LONG t;
885 int ndigits = 0;
886
887 /* Count the number of Python digits. */
888 t = (unsigned PY_LONG_LONG)ival;
889 while (t) {
890 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000891 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000892 }
893 v = _PyLong_New(ndigits);
894 if (v != NULL) {
895 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000896 Py_SIZE(v) = ndigits;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000897 while (ival) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000898 *p++ = (digit)(ival & PyLong_MASK);
899 ival >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000900 }
901 }
902 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000903}
904
Martin v. Löwis18e16552006-02-15 17:27:45 +0000905/* Create a new long int object from a C Py_ssize_t. */
906
907PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000908PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000909{
910 Py_ssize_t bytes = ival;
911 int one = 1;
912 return _PyLong_FromByteArray(
913 (unsigned char *)&bytes,
Kristján Valur Jónssonf0303942007-05-03 20:27:03 +0000914 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000915}
916
917/* Create a new long int object from a C size_t. */
918
919PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000920PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000921{
922 size_t bytes = ival;
923 int one = 1;
924 return _PyLong_FromByteArray(
925 (unsigned char *)&bytes,
926 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
927}
928
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000929/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000930 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000931
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000932PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000933PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000934{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000935 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000936 int one = 1;
937 int res;
938
Tim Petersd38b1c72001-09-30 05:09:37 +0000939 if (vv == NULL) {
940 PyErr_BadInternalCall();
941 return -1;
942 }
943 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000944 PyNumberMethods *nb;
945 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +0000946 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000947 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000948 if ((nb = vv->ob_type->tp_as_number) == NULL ||
949 nb->nb_int == NULL) {
950 PyErr_SetString(PyExc_TypeError, "an integer is required");
951 return -1;
952 }
953 io = (*nb->nb_int) (vv);
954 if (io == NULL)
955 return -1;
956 if (PyInt_Check(io)) {
957 bytes = PyInt_AsLong(io);
958 Py_DECREF(io);
959 return bytes;
960 }
961 if (PyLong_Check(io)) {
962 bytes = PyLong_AsLongLong(io);
963 Py_DECREF(io);
964 return bytes;
965 }
966 Py_DECREF(io);
967 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000968 return -1;
969 }
970
Tim Petersd1a7da62001-06-13 00:35:57 +0000971 res = _PyLong_AsByteArray(
972 (PyLongObject *)vv, (unsigned char *)&bytes,
973 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000974
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000975 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000976 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000977 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000978 else
979 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000980}
981
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000982/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000983 Return -1 and set an error if overflow occurs. */
984
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000985unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000986PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000987{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000988 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000989 int one = 1;
990 int res;
991
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000992 if (vv == NULL || !PyLong_Check(vv)) {
993 PyErr_BadInternalCall();
Skip Montanaro429433b2006-04-18 00:35:43 +0000994 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000995 }
996
Tim Petersd1a7da62001-06-13 00:35:57 +0000997 res = _PyLong_AsByteArray(
998 (PyLongObject *)vv, (unsigned char *)&bytes,
999 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001000
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001001 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001002 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001003 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001004 else
1005 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001006}
Tim Petersd1a7da62001-06-13 00:35:57 +00001007
Thomas Hellera4ea6032003-04-17 18:55:45 +00001008/* Get a C unsigned long int from a long int object, ignoring the high bits.
1009 Returns -1 and sets an error condition if an error occurs. */
1010
1011unsigned PY_LONG_LONG
1012PyLong_AsUnsignedLongLongMask(PyObject *vv)
1013{
1014 register PyLongObject *v;
1015 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001016 Py_ssize_t i;
1017 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001018
1019 if (vv == NULL || !PyLong_Check(vv)) {
1020 PyErr_BadInternalCall();
1021 return (unsigned long) -1;
1022 }
1023 v = (PyLongObject *)vv;
1024 i = v->ob_size;
1025 sign = 1;
1026 x = 0;
1027 if (i < 0) {
1028 sign = -1;
1029 i = -i;
1030 }
1031 while (--i >= 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001032 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001033 }
1034 return x * sign;
1035}
Tim Petersd1a7da62001-06-13 00:35:57 +00001036#undef IS_LITTLE_ENDIAN
1037
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001038#endif /* HAVE_LONG_LONG */
1039
Neil Schemenauerba872e22001-01-04 01:46:03 +00001040
1041static int
1042convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001043 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001044 *a = (PyLongObject *) v;
1045 Py_INCREF(v);
1046 }
1047 else if (PyInt_Check(v)) {
1048 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1049 }
1050 else {
1051 return 0;
1052 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001053 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001054 *b = (PyLongObject *) w;
1055 Py_INCREF(w);
1056 }
1057 else if (PyInt_Check(w)) {
1058 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1059 }
1060 else {
1061 Py_DECREF(*a);
1062 return 0;
1063 }
1064 return 1;
1065}
1066
1067#define CONVERT_BINOP(v, w, a, b) \
1068 if (!convert_binop(v, w, a, b)) { \
1069 Py_INCREF(Py_NotImplemented); \
1070 return Py_NotImplemented; \
1071 }
1072
Tim Peters877a2122002-08-12 05:09:36 +00001073/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1074 * is modified in place, by adding y to it. Carries are propagated as far as
1075 * x[m-1], and the remaining carry (0 or 1) is returned.
1076 */
1077static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001078v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001079{
1080 int i;
1081 digit carry = 0;
1082
1083 assert(m >= n);
1084 for (i = 0; i < n; ++i) {
1085 carry += x[i] + y[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001086 x[i] = carry & PyLong_MASK;
1087 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001088 assert((carry & 1) == carry);
1089 }
1090 for (; carry && i < m; ++i) {
1091 carry += x[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001092 x[i] = carry & PyLong_MASK;
1093 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001094 assert((carry & 1) == carry);
1095 }
1096 return carry;
1097}
1098
1099/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1100 * is modified in place, by subtracting y from it. Borrows are propagated as
1101 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1102 */
1103static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001104v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001105{
1106 int i;
1107 digit borrow = 0;
1108
1109 assert(m >= n);
1110 for (i = 0; i < n; ++i) {
1111 borrow = x[i] - y[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001112 x[i] = borrow & PyLong_MASK;
1113 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001114 borrow &= 1; /* keep only 1 sign bit */
1115 }
1116 for (; borrow && i < m; ++i) {
1117 borrow = x[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001118 x[i] = borrow & PyLong_MASK;
1119 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001120 borrow &= 1;
1121 }
1122 return borrow;
1123}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001124
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001125/* Multiply by a single digit, ignoring the sign. */
1126
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001127static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001128mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001129{
1130 return muladd1(a, n, (digit)0);
1131}
1132
1133/* Multiply by a single digit and add a single digit, ignoring the sign. */
1134
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001135static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001136muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001137{
Christian Heimese93237d2007-12-19 02:37:44 +00001138 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001139 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001140 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001141 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001142
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001143 if (z == NULL)
1144 return NULL;
1145 for (i = 0; i < size_a; ++i) {
1146 carry += (twodigits)a->ob_digit[i] * n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001147 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1148 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001149 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001150 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001151 return long_normalize(z);
1152}
1153
Tim Peters212e6142001-07-14 12:23:19 +00001154/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1155 in pout, and returning the remainder. pin and pout point at the LSD.
1156 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Eric Smith5e527eb2008-02-10 01:36:53 +00001157 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001158 immutable. */
1159
1160static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001161inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001162{
1163 twodigits rem = 0;
1164
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001165 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001166 pin += size;
1167 pout += size;
1168 while (--size >= 0) {
1169 digit hi;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001170 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001171 *--pout = hi = (digit)(rem / n);
1172 rem -= hi * n;
1173 }
1174 return (digit)rem;
1175}
1176
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001177/* Divide a long integer by a digit, returning both the quotient
1178 (as function result) and the remainder (through *prem).
1179 The sign of a is ignored; n should not be zero. */
1180
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001181static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001182divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001183{
Christian Heimese93237d2007-12-19 02:37:44 +00001184 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001185 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001186
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001187 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001188 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001189 if (z == NULL)
1190 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001191 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001192 return long_normalize(z);
1193}
1194
Eric Smith5e527eb2008-02-10 01:36:53 +00001195/* Convert the long to a string object with given base,
1196 appending a base prefix of 0[box] if base is 2, 8 or 16.
1197 Add a trailing "L" if addL is non-zero.
1198 If newstyle is zero, then use the pre-2.6 behavior of octal having
1199 a leading "0", instead of the prefix "0o" */
1200PyAPI_FUNC(PyObject *)
1201_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001202{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001203 register PyLongObject *a = (PyLongObject *)aa;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001204 PyStringObject *str;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001205 Py_ssize_t i, j, sz;
Neal Norwitzc09efa82006-07-23 07:53:14 +00001206 Py_ssize_t size_a;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001207 char *p;
1208 int bits;
1209 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001210
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001211 if (a == NULL || !PyLong_Check(a)) {
1212 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001213 return NULL;
1214 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001215 assert(base >= 2 && base <= 36);
Christian Heimese93237d2007-12-19 02:37:44 +00001216 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001217
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001218 /* Compute a rough upper bound for the length of the string */
1219 i = base;
1220 bits = 0;
1221 while (i > 1) {
1222 ++bits;
1223 i >>= 1;
1224 }
Armin Rigo7ccbca92006-10-04 12:17:45 +00001225 i = 5 + (addL ? 1 : 0);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001226 j = size_a*PyLong_SHIFT + bits-1;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001227 sz = i + j / bits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001228 if (j / PyLong_SHIFT < size_a || sz < i) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00001229 PyErr_SetString(PyExc_OverflowError,
1230 "long is too large to format");
1231 return NULL;
1232 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001233 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001234 if (str == NULL)
1235 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001236 p = PyString_AS_STRING(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001237 *p = '\0';
Fred Drake121ee271999-12-23 15:41:28 +00001238 if (addL)
1239 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001240 if (a->ob_size < 0)
1241 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001242
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001243 if (a->ob_size == 0) {
1244 *--p = '0';
1245 }
1246 else if ((base & (base - 1)) == 0) {
1247 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001248 twodigits accum = 0;
1249 int accumbits = 0; /* # of bits in accum */
1250 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001251 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001252 while ((i >>= 1) > 1)
1253 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001254
1255 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001256 accum |= (twodigits)a->ob_digit[i] << accumbits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001257 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001258 assert(accumbits >= basebits);
1259 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001260 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001261 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001262 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001263 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001264 accumbits -= basebits;
1265 accum >>= basebits;
1266 } while (i < size_a-1 ? accumbits >= basebits :
1267 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001268 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001269 }
1270 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001271 /* Not 0, and base not a power of 2. Divide repeatedly by
1272 base, but for speed use the highest power of base that
1273 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001274 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001275 digit *pin = a->ob_digit;
1276 PyLongObject *scratch;
1277 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001278 digit powbase = base; /* powbase == base ** power */
1279 int power = 1;
1280 for (;;) {
1281 unsigned long newpow = powbase * (unsigned long)base;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001282 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001283 break;
1284 powbase = (digit)newpow;
1285 ++power;
1286 }
Tim Peters212e6142001-07-14 12:23:19 +00001287
1288 /* Get a scratch area for repeated division. */
1289 scratch = _PyLong_New(size);
1290 if (scratch == NULL) {
1291 Py_DECREF(str);
1292 return NULL;
1293 }
1294
1295 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001296 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001297 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001298 digit rem = inplace_divrem1(scratch->ob_digit,
1299 pin, size, powbase);
1300 pin = scratch->ob_digit; /* no need to use a again */
1301 if (pin[size - 1] == 0)
1302 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001303 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001304 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001305 Py_DECREF(str);
1306 return NULL;
1307 })
Tim Peters212e6142001-07-14 12:23:19 +00001308
1309 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001310 assert(ntostore > 0);
1311 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001312 digit nextrem = (digit)(rem / base);
1313 char c = (char)(rem - nextrem * base);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001314 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001315 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001316 *--p = c;
1317 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001318 --ntostore;
1319 /* Termination is a bit delicate: must not
1320 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001321 remaining quotient and rem are both 0. */
1322 } while (ntostore && (size || rem));
1323 } while (size != 0);
1324 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001325 }
1326
Eric Smith5e527eb2008-02-10 01:36:53 +00001327 if (base == 2) {
1328 *--p = 'b';
1329 *--p = '0';
1330 }
1331 else if (base == 8) {
1332 if (newstyle) {
1333 *--p = 'o';
Guido van Rossum2c475421992-08-14 15:13:07 +00001334 *--p = '0';
Eric Smith5e527eb2008-02-10 01:36:53 +00001335 }
1336 else
1337 if (size_a != 0)
1338 *--p = '0';
Guido van Rossum2c475421992-08-14 15:13:07 +00001339 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001340 else if (base == 16) {
1341 *--p = 'x';
1342 *--p = '0';
1343 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001344 else if (base != 10) {
1345 *--p = '#';
1346 *--p = '0' + base%10;
1347 if (base > 10)
1348 *--p = '0' + base/10;
1349 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001350 if (sign)
1351 *--p = sign;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001352 if (p != PyString_AS_STRING(str)) {
1353 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001354 assert(p > q);
1355 do {
1356 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001357 q--;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001358 _PyString_Resize((PyObject **)&str,
1359 (Py_ssize_t) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001360 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001361 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001362}
1363
Tim Petersda53afa2006-05-25 17:34:03 +00001364/* Table of digit values for 8-bit string -> integer conversion.
1365 * '0' maps to 0, ..., '9' maps to 9.
1366 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1367 * All other indices map to 37.
1368 * Note that when converting a base B string, a char c is a legitimate
1369 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1370 */
1371int _PyLong_DigitValue[256] = {
Tim Peters696cf432006-05-24 21:10:40 +00001372 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1373 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1374 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1375 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1376 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1377 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1381 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1382 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1383 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1384 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1385 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1386 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1387 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Tim Peters696cf432006-05-24 21:10:40 +00001388};
1389
1390/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001391 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1392 * non-digit (which may be *str!). A normalized long is returned.
1393 * The point to this routine is that it takes time linear in the number of
1394 * string characters.
1395 */
1396static PyLongObject *
1397long_from_binary_base(char **str, int base)
1398{
1399 char *p = *str;
1400 char *start = p;
1401 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001402 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001403 PyLongObject *z;
1404 twodigits accum;
1405 int bits_in_accum;
1406 digit *pdigit;
1407
1408 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1409 n = base;
1410 for (bits_per_char = -1; n; ++bits_per_char)
1411 n >>= 1;
1412 /* n <- total # of bits needed, while setting p to end-of-string */
1413 n = 0;
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001414 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001415 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001416 *str = p;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001417 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1418 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001419 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001420 PyErr_SetString(PyExc_ValueError,
1421 "long string too large to convert");
1422 return NULL;
1423 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001424 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001425 z = _PyLong_New(n);
1426 if (z == NULL)
1427 return NULL;
1428 /* Read string from right, and fill in long from left; i.e.,
1429 * from least to most significant in both.
1430 */
1431 accum = 0;
1432 bits_in_accum = 0;
1433 pdigit = z->ob_digit;
1434 while (--p >= start) {
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001435 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001436 assert(k >= 0 && k < base);
1437 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001438 bits_in_accum += bits_per_char;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001439 if (bits_in_accum >= PyLong_SHIFT) {
1440 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001441 assert(pdigit - z->ob_digit <= (int)n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001442 accum >>= PyLong_SHIFT;
1443 bits_in_accum -= PyLong_SHIFT;
1444 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001445 }
1446 }
1447 if (bits_in_accum) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001448 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001449 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001450 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001451 }
1452 while (pdigit - z->ob_digit < n)
1453 *pdigit++ = 0;
1454 return long_normalize(z);
1455}
1456
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001457PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001458PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001459{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001460 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001461 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001462 PyLongObject *z;
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001463 PyObject *strobj, *strrepr;
1464 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001465
Guido van Rossum472c04f1996-12-05 21:57:21 +00001466 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001467 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001468 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001469 return NULL;
1470 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001471 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001472 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001473 if (*str == '+')
1474 ++str;
1475 else if (*str == '-') {
1476 ++str;
1477 sign = -1;
1478 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001479 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001480 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001481 if (base == 0) {
Eric Smith9ff19b52008-03-17 17:32:20 +00001482 /* No base given. Deduce the base from the contents
1483 of the string */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001484 if (str[0] != '0')
1485 base = 10;
1486 else if (str[1] == 'x' || str[1] == 'X')
1487 base = 16;
Eric Smith9ff19b52008-03-17 17:32:20 +00001488 else if (str[1] == 'o' || str[1] == 'O')
1489 base = 8;
1490 else if (str[1] == 'b' || str[1] == 'B')
1491 base = 2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001492 else
Eric Smith9ff19b52008-03-17 17:32:20 +00001493 /* "old" (C-style) octal literal, still valid in
1494 2.x, although illegal in 3.x */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001495 base = 8;
1496 }
Eric Smith9ff19b52008-03-17 17:32:20 +00001497 /* Whether or not we were deducing the base, skip leading chars
1498 as needed */
1499 if (str[0] == '0' &&
1500 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1501 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1502 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001503 str += 2;
Tim Peters696cf432006-05-24 21:10:40 +00001504
Guido van Rossume6762971998-06-22 03:54:46 +00001505 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001506 if ((base & (base - 1)) == 0)
1507 z = long_from_binary_base(&str, base);
1508 else {
Tim Peters696cf432006-05-24 21:10:40 +00001509/***
1510Binary bases can be converted in time linear in the number of digits, because
1511Python's representation base is binary. Other bases (including decimal!) use
1512the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001513
Tim Peters696cf432006-05-24 21:10:40 +00001514First some math: the largest integer that can be expressed in N base-B digits
1515is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1516case number of Python digits needed to hold it is the smallest integer n s.t.
1517
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001518 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1519 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1520 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001521
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001522The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute
Tim Peters696cf432006-05-24 21:10:40 +00001523this quickly. A Python long with that much space is reserved near the start,
1524and the result is computed into it.
1525
1526The input string is actually treated as being in base base**i (i.e., i digits
1527are processed at a time), where two more static arrays hold:
1528
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001529 convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE
Tim Peters696cf432006-05-24 21:10:40 +00001530 convmultmax_base[base] = base ** convwidth_base[base]
1531
1532The first of these is the largest i such that i consecutive input digits
1533must fit in a single Python digit. The second is effectively the input
1534base we're really using.
1535
1536Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1537convmultmax_base[base], the result is "simply"
1538
1539 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1540
1541where B = convmultmax_base[base].
Tim Peters9faa3ed2006-05-30 15:53:34 +00001542
1543Error analysis: as above, the number of Python digits `n` needed is worst-
1544case
1545
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001546 n >= N * log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001547
1548where `N` is the number of input digits in base `B`. This is computed via
1549
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001550 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001551
1552below. Two numeric concerns are how much space this can waste, and whether
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001553the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15,
Tim Peters9faa3ed2006-05-30 15:53:34 +00001554which is the default (and it's unlikely anyone changes that).
1555
1556Waste isn't a problem: provided the first input digit isn't 0, the difference
1557between the worst-case input with N digits and the smallest input with N
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001558digits is about a factor of B, but B is small compared to PyLong_BASE so at most
Tim Peters9faa3ed2006-05-30 15:53:34 +00001559one allocated Python digit can remain unused on that count. If
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001560N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001561and adding 1 returns a result 1 larger than necessary. However, that can't
1562happen: whenever B is a power of 2, long_from_binary_base() is called
1563instead, and it's impossible for B**i to be an integer power of 2**15 when
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001564B is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be
Tim Peters9faa3ed2006-05-30 15:53:34 +00001565an exact integer when B is not a power of 2, since B**i has a prime factor
1566other than 2 in that case, but (2**15)**j's only prime factor is 2).
1567
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001568The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001569is a little bit larger than an exact integer, but due to roundoff errors (in
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001570computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001571yields a numeric result a little less than that integer. Unfortunately, "how
1572close can a transcendental function get to an integer over some range?"
1573questions are generally theoretically intractable. Computer analysis via
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001574continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued
Tim Peters9faa3ed2006-05-30 15:53:34 +00001575fractions, giving a sequence i/j of "the best" rational approximations. Then
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001576j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001577we can get very close to being in trouble, but very rarely. For example,
157876573 is a denominator in one of the continued-fraction approximations to
1579log(10)/log(2**15), and indeed:
1580
1581 >>> log(10)/log(2**15)*76573
1582 16958.000000654003
1583
1584is very close to an integer. If we were working with IEEE single-precision,
1585rounding errors could kill us. Finding worst cases in IEEE double-precision
1586requires better-than-double-precision log() functions, and Tim didn't bother.
1587Instead the code checks to see whether the allocated space is enough as each
1588new Python digit is added, and copies the whole thing to a larger long if not.
1589This should happen extremely rarely, and in fact I don't have a test case
1590that triggers it(!). Instead the code was tested by artificially allocating
1591just 1 digit at the start, so that the copying code was exercised for every
1592digit beyond the first.
Tim Peters696cf432006-05-24 21:10:40 +00001593***/
1594 register twodigits c; /* current input character */
1595 Py_ssize_t size_z;
1596 int i;
1597 int convwidth;
1598 twodigits convmultmax, convmult;
1599 digit *pz, *pzstop;
1600 char* scan;
1601
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001602 static double log_base_PyLong_BASE[37] = {0.0e0,};
Tim Peters696cf432006-05-24 21:10:40 +00001603 static int convwidth_base[37] = {0,};
1604 static twodigits convmultmax_base[37] = {0,};
1605
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001606 if (log_base_PyLong_BASE[base] == 0.0) {
Tim Peters696cf432006-05-24 21:10:40 +00001607 twodigits convmax = base;
1608 int i = 1;
1609
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001610 log_base_PyLong_BASE[base] = log((double)base) /
1611 log((double)PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001612 for (;;) {
1613 twodigits next = convmax * base;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001614 if (next > PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001615 break;
1616 convmax = next;
1617 ++i;
1618 }
1619 convmultmax_base[base] = convmax;
1620 assert(i > 0);
1621 convwidth_base[base] = i;
1622 }
1623
1624 /* Find length of the string of numeric characters. */
1625 scan = str;
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001626 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Tim Peters696cf432006-05-24 21:10:40 +00001627 ++scan;
1628
1629 /* Create a long object that can contain the largest possible
1630 * integer with this base and length. Note that there's no
1631 * need to initialize z->ob_digit -- no slot is read up before
1632 * being stored into.
1633 */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001634 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001635 /* Uncomment next line to test exceedingly rare copy code */
1636 /* size_z = 1; */
Tim Peters696cf432006-05-24 21:10:40 +00001637 assert(size_z > 0);
1638 z = _PyLong_New(size_z);
1639 if (z == NULL)
1640 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00001641 Py_SIZE(z) = 0;
Tim Peters696cf432006-05-24 21:10:40 +00001642
1643 /* `convwidth` consecutive input digits are treated as a single
1644 * digit in base `convmultmax`.
1645 */
1646 convwidth = convwidth_base[base];
1647 convmultmax = convmultmax_base[base];
1648
1649 /* Work ;-) */
1650 while (str < scan) {
1651 /* grab up to convwidth digits from the input string */
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001652 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Tim Peters696cf432006-05-24 21:10:40 +00001653 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1654 c = (twodigits)(c * base +
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001655 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001656 assert(c < PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001657 }
1658
1659 convmult = convmultmax;
1660 /* Calculate the shift only if we couldn't get
1661 * convwidth digits.
1662 */
1663 if (i != convwidth) {
1664 convmult = base;
1665 for ( ; i > 1; --i)
1666 convmult *= base;
1667 }
1668
1669 /* Multiply z by convmult, and add c. */
1670 pz = z->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +00001671 pzstop = pz + Py_SIZE(z);
Tim Peters696cf432006-05-24 21:10:40 +00001672 for (; pz < pzstop; ++pz) {
1673 c += (twodigits)*pz * convmult;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001674 *pz = (digit)(c & PyLong_MASK);
1675 c >>= PyLong_SHIFT;
Tim Peters696cf432006-05-24 21:10:40 +00001676 }
1677 /* carry off the current end? */
1678 if (c) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001679 assert(c < PyLong_BASE);
Christian Heimese93237d2007-12-19 02:37:44 +00001680 if (Py_SIZE(z) < size_z) {
Tim Peters9faa3ed2006-05-30 15:53:34 +00001681 *pz = (digit)c;
Christian Heimese93237d2007-12-19 02:37:44 +00001682 ++Py_SIZE(z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001683 }
1684 else {
1685 PyLongObject *tmp;
1686 /* Extremely rare. Get more space. */
Christian Heimese93237d2007-12-19 02:37:44 +00001687 assert(Py_SIZE(z) == size_z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001688 tmp = _PyLong_New(size_z + 1);
1689 if (tmp == NULL) {
1690 Py_DECREF(z);
1691 return NULL;
1692 }
1693 memcpy(tmp->ob_digit,
1694 z->ob_digit,
1695 sizeof(digit) * size_z);
1696 Py_DECREF(z);
1697 z = tmp;
1698 z->ob_digit[size_z] = (digit)c;
1699 ++size_z;
1700 }
Tim Peters696cf432006-05-24 21:10:40 +00001701 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001702 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001703 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001704 if (z == NULL)
1705 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001706 if (str == start)
1707 goto onError;
Tim Peters696cf432006-05-24 21:10:40 +00001708 if (sign < 0)
Christian Heimese93237d2007-12-19 02:37:44 +00001709 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001710 if (*str == 'L' || *str == 'l')
1711 str++;
1712 while (*str && isspace(Py_CHARMASK(*str)))
1713 str++;
1714 if (*str != '\0')
1715 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001716 if (pend)
1717 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001718 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001719
1720 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001721 Py_XDECREF(z);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001722 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001723 strobj = PyString_FromStringAndSize(orig_str, slen);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001724 if (strobj == NULL)
1725 return NULL;
1726 strrepr = PyObject_Repr(strobj);
1727 Py_DECREF(strobj);
1728 if (strrepr == NULL)
1729 return NULL;
1730 PyErr_Format(PyExc_ValueError,
1731 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001732 base, PyString_AS_STRING(strrepr));
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001733 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001734 return NULL;
1735}
1736
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001737#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001738PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001739PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001740{
Walter Dörwald07e14762002-11-06 16:15:14 +00001741 PyObject *result;
Anthony Baxter377be112006-04-11 06:54:30 +00001742 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001743
Walter Dörwald07e14762002-11-06 16:15:14 +00001744 if (buffer == NULL)
1745 return NULL;
1746
1747 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1748 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001749 return NULL;
1750 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001751 result = PyLong_FromString(buffer, NULL, base);
1752 PyMem_FREE(buffer);
1753 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001754}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001755#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001756
Tim Peters9f688bf2000-07-07 15:53:28 +00001757/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001758static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001759 (PyLongObject *, PyLongObject *, PyLongObject **);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001760static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00001761static int long_divrem(PyLongObject *, PyLongObject *,
1762 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001763
1764/* Long division with remainder, top-level routine */
1765
Guido van Rossume32e0141992-01-19 16:31:05 +00001766static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001767long_divrem(PyLongObject *a, PyLongObject *b,
1768 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001769{
Christian Heimese93237d2007-12-19 02:37:44 +00001770 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001771 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001772
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001773 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001774 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001775 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001776 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001777 }
1778 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001779 (size_a == size_b &&
1780 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001781 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001782 *pdiv = _PyLong_New(0);
Georg Brandlc02e1312007-04-11 17:16:24 +00001783 if (*pdiv == NULL)
1784 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001785 Py_INCREF(a);
1786 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001787 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001788 }
1789 if (size_b == 1) {
1790 digit rem = 0;
1791 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001792 if (z == NULL)
1793 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001794 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Georg Brandlc02e1312007-04-11 17:16:24 +00001795 if (*prem == NULL) {
1796 Py_DECREF(z);
1797 return -1;
1798 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001799 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001800 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001801 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001802 if (z == NULL)
1803 return -1;
1804 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001805 /* Set the signs.
1806 The quotient z has the sign of a*b;
1807 the remainder r has the sign of a,
1808 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001809 if ((a->ob_size < 0) != (b->ob_size < 0))
1810 z->ob_size = -(z->ob_size);
1811 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1812 (*prem)->ob_size = -((*prem)->ob_size);
1813 *pdiv = z;
1814 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001815}
1816
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001817/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001818
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001819static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001820x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001821{
Christian Heimese93237d2007-12-19 02:37:44 +00001822 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001823 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001824 PyLongObject *v = mul1(v1, d);
1825 PyLongObject *w = mul1(w1, d);
1826 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001827 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001828
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001829 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001830 Py_XDECREF(v);
1831 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001832 return NULL;
1833 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001834
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001835 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimese93237d2007-12-19 02:37:44 +00001836 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
1837 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001838
Christian Heimese93237d2007-12-19 02:37:44 +00001839 size_v = ABS(Py_SIZE(v));
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001840 k = size_v - size_w;
1841 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001842
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001843 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001844 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
1845 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001846 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001847 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001848
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001849 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001850 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001851 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001852 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001853 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001854 if (vj == w->ob_digit[size_w-1])
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001855 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001856 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001857 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001858 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00001859
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001860 while (w->ob_digit[size_w-2]*q >
1861 ((
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001862 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001863 + v->ob_digit[j-1]
1864 - q*w->ob_digit[size_w-1]
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001865 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001866 + v->ob_digit[j-2])
1867 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001868
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001869 for (i = 0; i < size_w && i+k < size_v; ++i) {
1870 twodigits z = w->ob_digit[i] * q;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001871 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001872 carry += v->ob_digit[i+k] - z
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001873 + ((twodigits)zz << PyLong_SHIFT);
1874 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
1875 carry = Py_ARITHMETIC_RIGHT_SHIFT(PyLong_BASE_TWODIGITS_TYPE,
1876 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00001877 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001878 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001879
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001880 if (i+k < size_v) {
1881 carry += v->ob_digit[i+k];
1882 v->ob_digit[i+k] = 0;
1883 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001884
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001885 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00001886 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001887 else {
1888 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00001889 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001890 carry = 0;
1891 for (i = 0; i < size_w && i+k < size_v; ++i) {
1892 carry += v->ob_digit[i+k] + w->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001893 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001894 carry = Py_ARITHMETIC_RIGHT_SHIFT(
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001895 PyLong_BASE_TWODIGITS_TYPE,
1896 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001897 }
1898 }
1899 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001900
Guido van Rossumc206c761995-01-10 15:23:19 +00001901 if (a == NULL)
1902 *prem = NULL;
1903 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00001904 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001905 *prem = divrem1(v, d, &d);
1906 /* d receives the (unused) remainder */
1907 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001908 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001909 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001910 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001911 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001912 Py_DECREF(v);
1913 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001914 return a;
1915}
1916
1917/* Methods */
1918
1919static void
Tim Peters9f688bf2000-07-07 15:53:28 +00001920long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001921{
Christian Heimese93237d2007-12-19 02:37:44 +00001922 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001923}
1924
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001925static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001926long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001927{
Eric Smith5e527eb2008-02-10 01:36:53 +00001928 return _PyLong_Format(v, 10, 1, 0);
Fred Drake121ee271999-12-23 15:41:28 +00001929}
1930
1931static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001932long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00001933{
Eric Smith5e527eb2008-02-10 01:36:53 +00001934 return _PyLong_Format(v, 10, 0, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001935}
1936
1937static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001938long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001939{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001940 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001941
Christian Heimese93237d2007-12-19 02:37:44 +00001942 if (Py_SIZE(a) != Py_SIZE(b)) {
1943 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00001944 sign = 0;
1945 else
Christian Heimese93237d2007-12-19 02:37:44 +00001946 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001947 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001948 else {
Christian Heimese93237d2007-12-19 02:37:44 +00001949 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001950 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1951 ;
1952 if (i < 0)
1953 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001954 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001955 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Christian Heimese93237d2007-12-19 02:37:44 +00001956 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001957 sign = -sign;
1958 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001959 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001960 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001961}
1962
Guido van Rossum9bfef441993-03-29 10:43:31 +00001963static long
Tim Peters9f688bf2000-07-07 15:53:28 +00001964long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001965{
1966 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001967 Py_ssize_t i;
1968 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001969
1970 /* This is designed so that Python ints and longs with the
1971 same value hash to the same value, otherwise comparisons
1972 of mapping keys will turn out weird */
1973 i = v->ob_size;
1974 sign = 1;
1975 x = 0;
1976 if (i < 0) {
1977 sign = -1;
1978 i = -(i);
1979 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001980#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Facundo Batistad544df72007-09-19 15:10:06 +00001981 /* The following loop produces a C long x such that (unsigned long)x
1982 is congruent to the absolute value of v modulo ULONG_MAX. The
1983 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00001984 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001985 /* Force a native long #-bits (32 or 64) circular shift */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001986 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001987 x += v->ob_digit[i];
Facundo Batistad544df72007-09-19 15:10:06 +00001988 /* If the addition above overflowed (thinking of x as
1989 unsigned), we compensate by incrementing. This preserves
1990 the value modulo ULONG_MAX. */
1991 if ((unsigned long)x < v->ob_digit[i])
1992 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001993 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001994#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00001995 x = x * sign;
1996 if (x == -1)
1997 x = -2;
1998 return x;
1999}
2000
2001
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002002/* Add the absolute values of two long integers. */
2003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002004static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002005x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002006{
Christian Heimese93237d2007-12-19 02:37:44 +00002007 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002008 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002009 int i;
2010 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002011
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002012 /* Ensure a is the larger of the two: */
2013 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002014 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002015 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002016 size_a = size_b;
2017 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002018 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002019 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002020 if (z == NULL)
2021 return NULL;
2022 for (i = 0; i < size_b; ++i) {
2023 carry += a->ob_digit[i] + b->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002024 z->ob_digit[i] = carry & PyLong_MASK;
2025 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002026 }
2027 for (; i < size_a; ++i) {
2028 carry += a->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002029 z->ob_digit[i] = carry & PyLong_MASK;
2030 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002031 }
2032 z->ob_digit[i] = carry;
2033 return long_normalize(z);
2034}
2035
2036/* Subtract the absolute values of two integers. */
2037
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002038static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002039x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002040{
Christian Heimese93237d2007-12-19 02:37:44 +00002041 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002042 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002043 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002044 int sign = 1;
2045 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002046
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002047 /* Ensure a is the larger of the two: */
2048 if (size_a < size_b) {
2049 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002050 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002051 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002052 size_a = size_b;
2053 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002054 }
2055 else if (size_a == size_b) {
2056 /* Find highest digit where a and b differ: */
2057 i = size_a;
2058 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2059 ;
2060 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002061 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002062 if (a->ob_digit[i] < b->ob_digit[i]) {
2063 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002064 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002065 }
2066 size_a = size_b = i+1;
2067 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002068 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002069 if (z == NULL)
2070 return NULL;
2071 for (i = 0; i < size_b; ++i) {
2072 /* The following assumes unsigned arithmetic
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002073 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002074 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002075 z->ob_digit[i] = borrow & PyLong_MASK;
2076 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002077 borrow &= 1; /* Keep only one sign bit */
2078 }
2079 for (; i < size_a; ++i) {
2080 borrow = a->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002081 z->ob_digit[i] = borrow & PyLong_MASK;
2082 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002083 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002084 }
2085 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002086 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002087 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002088 return long_normalize(z);
2089}
2090
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002091static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002092long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002093{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002094 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002095
Neil Schemenauerba872e22001-01-04 01:46:03 +00002096 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2097
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002098 if (a->ob_size < 0) {
2099 if (b->ob_size < 0) {
2100 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002101 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002102 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002103 }
2104 else
2105 z = x_sub(b, a);
2106 }
2107 else {
2108 if (b->ob_size < 0)
2109 z = x_sub(a, b);
2110 else
2111 z = x_add(a, b);
2112 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002113 Py_DECREF(a);
2114 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002115 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002116}
2117
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002118static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002119long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002120{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002121 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002122
Neil Schemenauerba872e22001-01-04 01:46:03 +00002123 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2124
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002125 if (a->ob_size < 0) {
2126 if (b->ob_size < 0)
2127 z = x_sub(a, b);
2128 else
2129 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002130 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002131 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002132 }
2133 else {
2134 if (b->ob_size < 0)
2135 z = x_add(a, b);
2136 else
2137 z = x_sub(a, b);
2138 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002139 Py_DECREF(a);
2140 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002141 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002142}
2143
Tim Peters5af4e6c2002-08-12 02:31:19 +00002144/* Grade school multiplication, ignoring the signs.
2145 * Returns the absolute value of the product, or NULL if error.
2146 */
2147static PyLongObject *
2148x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002149{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002150 PyLongObject *z;
Christian Heimese93237d2007-12-19 02:37:44 +00002151 Py_ssize_t size_a = ABS(Py_SIZE(a));
2152 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002153 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002154
Tim Peters5af4e6c2002-08-12 02:31:19 +00002155 z = _PyLong_New(size_a + size_b);
2156 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002157 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002158
Christian Heimese93237d2007-12-19 02:37:44 +00002159 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002160 if (a == b) {
2161 /* Efficient squaring per HAC, Algorithm 14.16:
2162 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2163 * Gives slightly less than a 2x speedup when a == b,
2164 * via exploiting that each entry in the multiplication
2165 * pyramid appears twice (except for the size_a squares).
2166 */
2167 for (i = 0; i < size_a; ++i) {
2168 twodigits carry;
2169 twodigits f = a->ob_digit[i];
2170 digit *pz = z->ob_digit + (i << 1);
2171 digit *pa = a->ob_digit + i + 1;
2172 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002173
Tim Peters0973b992004-08-29 22:16:50 +00002174 SIGCHECK({
2175 Py_DECREF(z);
2176 return NULL;
2177 })
2178
2179 carry = *pz + f * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002180 *pz++ = (digit)(carry & PyLong_MASK);
2181 carry >>= PyLong_SHIFT;
2182 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002183
2184 /* Now f is added in twice in each column of the
2185 * pyramid it appears. Same as adding f<<1 once.
2186 */
2187 f <<= 1;
2188 while (pa < paend) {
2189 carry += *pz + *pa++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002190 *pz++ = (digit)(carry & PyLong_MASK);
2191 carry >>= PyLong_SHIFT;
2192 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002193 }
2194 if (carry) {
2195 carry += *pz;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002196 *pz++ = (digit)(carry & PyLong_MASK);
2197 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002198 }
2199 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002200 *pz += (digit)(carry & PyLong_MASK);
2201 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002202 }
Tim Peters0973b992004-08-29 22:16:50 +00002203 }
2204 else { /* a is not the same as b -- gradeschool long mult */
2205 for (i = 0; i < size_a; ++i) {
2206 twodigits carry = 0;
2207 twodigits f = a->ob_digit[i];
2208 digit *pz = z->ob_digit + i;
2209 digit *pb = b->ob_digit;
2210 digit *pbend = b->ob_digit + size_b;
2211
2212 SIGCHECK({
2213 Py_DECREF(z);
2214 return NULL;
2215 })
2216
2217 while (pb < pbend) {
2218 carry += *pz + *pb++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002219 *pz++ = (digit)(carry & PyLong_MASK);
2220 carry >>= PyLong_SHIFT;
2221 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002222 }
2223 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002224 *pz += (digit)(carry & PyLong_MASK);
2225 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002226 }
2227 }
Tim Peters44121a62002-08-12 06:17:58 +00002228 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002229}
2230
2231/* A helper for Karatsuba multiplication (k_mul).
2232 Takes a long "n" and an integer "size" representing the place to
2233 split, and sets low and high such that abs(n) == (high << size) + low,
2234 viewing the shift as being by digits. The sign bit is ignored, and
2235 the return values are >= 0.
2236 Returns 0 on success, -1 on failure.
2237*/
2238static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002239kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002240{
2241 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002242 Py_ssize_t size_lo, size_hi;
Christian Heimese93237d2007-12-19 02:37:44 +00002243 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002244
2245 size_lo = MIN(size_n, size);
2246 size_hi = size_n - size_lo;
2247
2248 if ((hi = _PyLong_New(size_hi)) == NULL)
2249 return -1;
2250 if ((lo = _PyLong_New(size_lo)) == NULL) {
2251 Py_DECREF(hi);
2252 return -1;
2253 }
2254
2255 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2256 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2257
2258 *high = long_normalize(hi);
2259 *low = long_normalize(lo);
2260 return 0;
2261}
2262
Tim Peters60004642002-08-12 22:01:34 +00002263static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2264
Tim Peters5af4e6c2002-08-12 02:31:19 +00002265/* Karatsuba multiplication. Ignores the input signs, and returns the
2266 * absolute value of the product (or NULL if error).
2267 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2268 */
2269static PyLongObject *
2270k_mul(PyLongObject *a, PyLongObject *b)
2271{
Christian Heimese93237d2007-12-19 02:37:44 +00002272 Py_ssize_t asize = ABS(Py_SIZE(a));
2273 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002274 PyLongObject *ah = NULL;
2275 PyLongObject *al = NULL;
2276 PyLongObject *bh = NULL;
2277 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002278 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002279 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002280 Py_ssize_t shift; /* the number of digits we split off */
2281 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002282
Tim Peters5af4e6c2002-08-12 02:31:19 +00002283 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2284 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2285 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002286 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002287 * By picking X to be a power of 2, "*X" is just shifting, and it's
2288 * been reduced to 3 multiplies on numbers half the size.
2289 */
2290
Tim Petersfc07e562002-08-12 02:54:10 +00002291 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002292 * is largest.
2293 */
Tim Peters738eda72002-08-12 15:08:20 +00002294 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002295 t1 = a;
2296 a = b;
2297 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002298
2299 i = asize;
2300 asize = bsize;
2301 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002302 }
2303
2304 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002305 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2306 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002307 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002308 return _PyLong_New(0);
2309 else
2310 return x_mul(a, b);
2311 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002312
Tim Peters60004642002-08-12 22:01:34 +00002313 /* If a is small compared to b, splitting on b gives a degenerate
2314 * case with ah==0, and Karatsuba may be (even much) less efficient
2315 * than "grade school" then. However, we can still win, by viewing
2316 * b as a string of "big digits", each of width a->ob_size. That
2317 * leads to a sequence of balanced calls to k_mul.
2318 */
2319 if (2 * asize <= bsize)
2320 return k_lopsided_mul(a, b);
2321
Tim Petersd6974a52002-08-13 20:37:51 +00002322 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002323 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002324 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002325 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002326
Tim Peters0973b992004-08-29 22:16:50 +00002327 if (a == b) {
2328 bh = ah;
2329 bl = al;
2330 Py_INCREF(bh);
2331 Py_INCREF(bl);
2332 }
2333 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002334
Tim Petersd64c1de2002-08-12 17:36:03 +00002335 /* The plan:
2336 * 1. Allocate result space (asize + bsize digits: that's always
2337 * enough).
2338 * 2. Compute ah*bh, and copy into result at 2*shift.
2339 * 3. Compute al*bl, and copy into result at 0. Note that this
2340 * can't overlap with #2.
2341 * 4. Subtract al*bl from the result, starting at shift. This may
2342 * underflow (borrow out of the high digit), but we don't care:
2343 * we're effectively doing unsigned arithmetic mod
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002344 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
Tim Petersd64c1de2002-08-12 17:36:03 +00002345 * borrows and carries out of the high digit can be ignored.
2346 * 5. Subtract ah*bh from the result, starting at shift.
2347 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2348 * at shift.
2349 */
2350
2351 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002352 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002353 if (ret == NULL) goto fail;
2354#ifdef Py_DEBUG
2355 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002356 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002357#endif
Tim Peters44121a62002-08-12 06:17:58 +00002358
Tim Petersd64c1de2002-08-12 17:36:03 +00002359 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002360 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002361 assert(Py_SIZE(t1) >= 0);
2362 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002363 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimese93237d2007-12-19 02:37:44 +00002364 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002365
2366 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimese93237d2007-12-19 02:37:44 +00002367 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002368 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002369 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002370 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002371
Tim Petersd64c1de2002-08-12 17:36:03 +00002372 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002373 if ((t2 = k_mul(al, bl)) == NULL) {
2374 Py_DECREF(t1);
2375 goto fail;
2376 }
Christian Heimese93237d2007-12-19 02:37:44 +00002377 assert(Py_SIZE(t2) >= 0);
2378 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2379 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002380
2381 /* Zero out remaining digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002382 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002383 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002384 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002385
Tim Petersd64c1de2002-08-12 17:36:03 +00002386 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2387 * because it's fresher in cache.
2388 */
Christian Heimese93237d2007-12-19 02:37:44 +00002389 i = Py_SIZE(ret) - shift; /* # digits after shift */
2390 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002391 Py_DECREF(t2);
2392
Christian Heimese93237d2007-12-19 02:37:44 +00002393 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002394 Py_DECREF(t1);
2395
Tim Petersd64c1de2002-08-12 17:36:03 +00002396 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002397 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2398 Py_DECREF(ah);
2399 Py_DECREF(al);
2400 ah = al = NULL;
2401
Tim Peters0973b992004-08-29 22:16:50 +00002402 if (a == b) {
2403 t2 = t1;
2404 Py_INCREF(t2);
2405 }
2406 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002407 Py_DECREF(t1);
2408 goto fail;
2409 }
2410 Py_DECREF(bh);
2411 Py_DECREF(bl);
2412 bh = bl = NULL;
2413
Tim Peters738eda72002-08-12 15:08:20 +00002414 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002415 Py_DECREF(t1);
2416 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002417 if (t3 == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002418 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002419
Tim Petersd6974a52002-08-13 20:37:51 +00002420 /* Add t3. It's not obvious why we can't run out of room here.
2421 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002422 */
Christian Heimese93237d2007-12-19 02:37:44 +00002423 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002424 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002425
Tim Peters5af4e6c2002-08-12 02:31:19 +00002426 return long_normalize(ret);
2427
2428 fail:
2429 Py_XDECREF(ret);
2430 Py_XDECREF(ah);
2431 Py_XDECREF(al);
2432 Py_XDECREF(bh);
2433 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002434 return NULL;
2435}
2436
Tim Petersd6974a52002-08-13 20:37:51 +00002437/* (*) Why adding t3 can't "run out of room" above.
2438
Tim Petersab86c2b2002-08-15 20:06:00 +00002439Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2440to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002441
Tim Petersab86c2b2002-08-15 20:06:00 +000024421. For any integer i, i = c(i/2) + f(i/2). In particular,
2443 bsize = c(bsize/2) + f(bsize/2).
24442. shift = f(bsize/2)
24453. asize <= bsize
24464. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2447 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002448
Tim Petersab86c2b2002-08-15 20:06:00 +00002449We allocated asize + bsize result digits, and add t3 into them at an offset
2450of shift. This leaves asize+bsize-shift allocated digit positions for t3
2451to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2452asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002453
Tim Petersab86c2b2002-08-15 20:06:00 +00002454bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2455at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002456
Tim Petersab86c2b2002-08-15 20:06:00 +00002457If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2458digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2459most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002460
Tim Petersab86c2b2002-08-15 20:06:00 +00002461The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002462
Tim Petersab86c2b2002-08-15 20:06:00 +00002463 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002464
Tim Petersab86c2b2002-08-15 20:06:00 +00002465and we have asize + c(bsize/2) available digit positions. We need to show
2466this is always enough. An instance of c(bsize/2) cancels out in both, so
2467the question reduces to whether asize digits is enough to hold
2468(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2469then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2470asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002471digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002472asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002473c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2474is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2475bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002476
Tim Peters48d52c02002-08-14 17:07:32 +00002477Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2478clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2479ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002480*/
2481
Tim Peters60004642002-08-12 22:01:34 +00002482/* b has at least twice the digits of a, and a is big enough that Karatsuba
2483 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2484 * of slices, each with a->ob_size digits, and multiply the slices by a,
2485 * one at a time. This gives k_mul balanced inputs to work with, and is
2486 * also cache-friendly (we compute one double-width slice of the result
2487 * at a time, then move on, never bactracking except for the helpful
2488 * single-width slice overlap between successive partial sums).
2489 */
2490static PyLongObject *
2491k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2492{
Christian Heimese93237d2007-12-19 02:37:44 +00002493 const Py_ssize_t asize = ABS(Py_SIZE(a));
2494 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002495 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002496 PyLongObject *ret;
2497 PyLongObject *bslice = NULL;
2498
2499 assert(asize > KARATSUBA_CUTOFF);
2500 assert(2 * asize <= bsize);
2501
2502 /* Allocate result space, and zero it out. */
2503 ret = _PyLong_New(asize + bsize);
2504 if (ret == NULL)
2505 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002506 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002507
2508 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002509 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002510 if (bslice == NULL)
2511 goto fail;
2512
2513 nbdone = 0;
2514 while (bsize > 0) {
2515 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002516 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002517
2518 /* Multiply the next slice of b by a. */
2519 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2520 nbtouse * sizeof(digit));
Christian Heimese93237d2007-12-19 02:37:44 +00002521 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002522 product = k_mul(a, bslice);
2523 if (product == NULL)
2524 goto fail;
2525
2526 /* Add into result. */
Christian Heimese93237d2007-12-19 02:37:44 +00002527 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2528 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002529 Py_DECREF(product);
2530
2531 bsize -= nbtouse;
2532 nbdone += nbtouse;
2533 }
2534
2535 Py_DECREF(bslice);
2536 return long_normalize(ret);
2537
2538 fail:
2539 Py_DECREF(ret);
2540 Py_XDECREF(bslice);
2541 return NULL;
2542}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002543
2544static PyObject *
2545long_mul(PyLongObject *v, PyLongObject *w)
2546{
2547 PyLongObject *a, *b, *z;
2548
2549 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002550 Py_INCREF(Py_NotImplemented);
2551 return Py_NotImplemented;
2552 }
2553
Tim Petersd64c1de2002-08-12 17:36:03 +00002554 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002555 /* Negate if exactly one of the inputs is negative. */
2556 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002557 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002558 Py_DECREF(a);
2559 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002560 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002561}
2562
Guido van Rossume32e0141992-01-19 16:31:05 +00002563/* The / and % operators are now defined in terms of divmod().
2564 The expression a mod b has the value a - b*floor(a/b).
2565 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002566 |a| by |b|, with the sign of a. This is also expressed
2567 as a - b*trunc(a/b), if trunc truncates towards zero.
2568 Some examples:
2569 a b a rem b a mod b
2570 13 10 3 3
2571 -13 10 -3 7
2572 13 -10 3 -7
2573 -13 -10 -3 -3
2574 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002575 have different signs. We then subtract one from the 'div'
2576 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002577
Tim Peters47e52ee2004-08-30 02:44:38 +00002578/* Compute
2579 * *pdiv, *pmod = divmod(v, w)
2580 * NULL can be passed for pdiv or pmod, in which case that part of
2581 * the result is simply thrown away. The caller owns a reference to
2582 * each of these it requests (does not pass NULL for).
2583 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002584static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002585l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002586 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002587{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002588 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002589
Guido van Rossume32e0141992-01-19 16:31:05 +00002590 if (long_divrem(v, w, &div, &mod) < 0)
2591 return -1;
Christian Heimese93237d2007-12-19 02:37:44 +00002592 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2593 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002594 PyLongObject *temp;
2595 PyLongObject *one;
2596 temp = (PyLongObject *) long_add(mod, w);
2597 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002598 mod = temp;
2599 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002600 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002601 return -1;
2602 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002603 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002604 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002605 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2606 Py_DECREF(mod);
2607 Py_DECREF(div);
2608 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002609 return -1;
2610 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002611 Py_DECREF(one);
2612 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002613 div = temp;
2614 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002615 if (pdiv != NULL)
2616 *pdiv = div;
2617 else
2618 Py_DECREF(div);
2619
2620 if (pmod != NULL)
2621 *pmod = mod;
2622 else
2623 Py_DECREF(mod);
2624
Guido van Rossume32e0141992-01-19 16:31:05 +00002625 return 0;
2626}
2627
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002628static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002629long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002630{
Tim Peters47e52ee2004-08-30 02:44:38 +00002631 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002632
2633 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002634 if (l_divmod(a, b, &div, NULL) < 0)
2635 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002636 Py_DECREF(a);
2637 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002638 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002639}
2640
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002641static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00002642long_classic_div(PyObject *v, PyObject *w)
2643{
Tim Peters47e52ee2004-08-30 02:44:38 +00002644 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002645
2646 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00002647 if (Py_DivisionWarningFlag &&
2648 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
2649 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00002650 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00002651 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00002652 Py_DECREF(a);
2653 Py_DECREF(b);
2654 return (PyObject *)div;
2655}
2656
2657static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002658long_true_divide(PyObject *v, PyObject *w)
2659{
Tim Peterse2a60002001-09-04 06:17:36 +00002660 PyLongObject *a, *b;
2661 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002662 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002663
2664 CONVERT_BINOP(v, w, &a, &b);
2665 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2666 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002667 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2668 Py_DECREF(a);
2669 Py_DECREF(b);
2670 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002671 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002672 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2673 but should really be set correctly after sucessful calls to
2674 _PyLong_AsScaledDouble() */
2675 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002676
2677 if (bd == 0.0) {
2678 PyErr_SetString(PyExc_ZeroDivisionError,
2679 "long division or modulo by zero");
2680 return NULL;
2681 }
2682
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002683 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002684 ad /= bd; /* overflow/underflow impossible here */
2685 aexp -= bexp;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002686 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002687 goto overflow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002688 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002689 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002690 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002691 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002692 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002693 goto overflow;
2694 return PyFloat_FromDouble(ad);
2695
2696overflow:
2697 PyErr_SetString(PyExc_OverflowError,
2698 "long/long too large for a float");
2699 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002700
Tim Peters20dab9f2001-09-04 05:31:47 +00002701}
2702
2703static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002704long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002705{
Tim Peters47e52ee2004-08-30 02:44:38 +00002706 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002707
2708 CONVERT_BINOP(v, w, &a, &b);
2709
Tim Peters47e52ee2004-08-30 02:44:38 +00002710 if (l_divmod(a, b, NULL, &mod) < 0)
2711 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002712 Py_DECREF(a);
2713 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002714 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002715}
2716
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002717static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002718long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002719{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002720 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002721 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002722
2723 CONVERT_BINOP(v, w, &a, &b);
2724
2725 if (l_divmod(a, b, &div, &mod) < 0) {
2726 Py_DECREF(a);
2727 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002728 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002729 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002730 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002731 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002732 PyTuple_SetItem(z, 0, (PyObject *) div);
2733 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002734 }
2735 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002736 Py_DECREF(div);
2737 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002738 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002739 Py_DECREF(a);
2740 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002741 return z;
2742}
2743
Tim Peters47e52ee2004-08-30 02:44:38 +00002744/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002745static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002746long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002747{
Tim Peters47e52ee2004-08-30 02:44:38 +00002748 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2749 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002750
Tim Peters47e52ee2004-08-30 02:44:38 +00002751 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002752 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002753 PyLongObject *temp = NULL;
2754
2755 /* 5-ary values. If the exponent is large enough, table is
2756 * precomputed so that table[i] == a**i % c for i in range(32).
2757 */
2758 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2759 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2760
2761 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002762 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002763 if (PyLong_Check(x)) {
2764 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002765 Py_INCREF(x);
2766 }
Tim Petersde7990b2005-07-17 23:45:23 +00002767 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002768 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00002769 if (c == NULL)
2770 goto Error;
2771 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002772 else if (x == Py_None)
2773 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002774 else {
2775 Py_DECREF(a);
2776 Py_DECREF(b);
2777 Py_INCREF(Py_NotImplemented);
2778 return Py_NotImplemented;
2779 }
Tim Peters4c483c42001-09-05 06:24:58 +00002780
Christian Heimese93237d2007-12-19 02:37:44 +00002781 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00002782 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002783 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002784 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002785 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002786 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002787 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002788 /* else return a float. This works because we know
2789 that this calls float_pow() which converts its
2790 arguments to double. */
2791 Py_DECREF(a);
2792 Py_DECREF(b);
2793 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002794 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002795 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002796
2797 if (c) {
2798 /* if modulus == 0:
2799 raise ValueError() */
Christian Heimese93237d2007-12-19 02:37:44 +00002800 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002801 PyErr_SetString(PyExc_ValueError,
2802 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002803 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002804 }
2805
2806 /* if modulus < 0:
2807 negativeOutput = True
2808 modulus = -modulus */
Christian Heimese93237d2007-12-19 02:37:44 +00002809 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002810 negativeOutput = 1;
2811 temp = (PyLongObject *)_PyLong_Copy(c);
2812 if (temp == NULL)
2813 goto Error;
2814 Py_DECREF(c);
2815 c = temp;
2816 temp = NULL;
2817 c->ob_size = - c->ob_size;
2818 }
2819
2820 /* if modulus == 1:
2821 return 0 */
Christian Heimese93237d2007-12-19 02:37:44 +00002822 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002823 z = (PyLongObject *)PyLong_FromLong(0L);
2824 goto Done;
2825 }
2826
2827 /* if base < 0:
2828 base = base % modulus
2829 Having the base positive just makes things easier. */
Christian Heimese93237d2007-12-19 02:37:44 +00002830 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002831 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00002832 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002833 Py_DECREF(a);
2834 a = temp;
2835 temp = NULL;
2836 }
2837 }
2838
2839 /* At this point a, b, and c are guaranteed non-negative UNLESS
2840 c is NULL, in which case a may be negative. */
2841
2842 z = (PyLongObject *)PyLong_FromLong(1L);
2843 if (z == NULL)
2844 goto Error;
2845
2846 /* Perform a modular reduction, X = X % c, but leave X alone if c
2847 * is NULL.
2848 */
2849#define REDUCE(X) \
2850 if (c != NULL) { \
2851 if (l_divmod(X, c, NULL, &temp) < 0) \
2852 goto Error; \
2853 Py_XDECREF(X); \
2854 X = temp; \
2855 temp = NULL; \
2856 }
2857
2858 /* Multiply two values, then reduce the result:
2859 result = X*Y % c. If c is NULL, skip the mod. */
2860#define MULT(X, Y, result) \
2861{ \
2862 temp = (PyLongObject *)long_mul(X, Y); \
2863 if (temp == NULL) \
2864 goto Error; \
2865 Py_XDECREF(result); \
2866 result = temp; \
2867 temp = NULL; \
2868 REDUCE(result) \
2869}
2870
Christian Heimese93237d2007-12-19 02:37:44 +00002871 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002872 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2873 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimese93237d2007-12-19 02:37:44 +00002874 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002875 digit bi = b->ob_digit[i];
2876
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002877 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002878 MULT(z, z, z)
2879 if (bi & j)
2880 MULT(z, a, z)
2881 }
2882 }
2883 }
2884 else {
2885 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2886 Py_INCREF(z); /* still holds 1L */
2887 table[0] = z;
2888 for (i = 1; i < 32; ++i)
2889 MULT(table[i-1], a, table[i])
2890
Christian Heimese93237d2007-12-19 02:37:44 +00002891 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002892 const digit bi = b->ob_digit[i];
2893
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002894 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002895 const int index = (bi >> j) & 0x1f;
2896 for (k = 0; k < 5; ++k)
2897 MULT(z, z, z)
2898 if (index)
2899 MULT(z, table[index], z)
2900 }
2901 }
2902 }
2903
Christian Heimese93237d2007-12-19 02:37:44 +00002904 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002905 temp = (PyLongObject *)long_sub(z, c);
2906 if (temp == NULL)
2907 goto Error;
2908 Py_DECREF(z);
2909 z = temp;
2910 temp = NULL;
2911 }
2912 goto Done;
2913
2914 Error:
2915 if (z != NULL) {
2916 Py_DECREF(z);
2917 z = NULL;
2918 }
2919 /* fall through */
2920 Done:
Christian Heimese93237d2007-12-19 02:37:44 +00002921 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002922 for (i = 0; i < 32; ++i)
2923 Py_XDECREF(table[i]);
2924 }
Tim Petersde7990b2005-07-17 23:45:23 +00002925 Py_DECREF(a);
2926 Py_DECREF(b);
2927 Py_XDECREF(c);
2928 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002929 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002930}
2931
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002932static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002933long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002934{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002935 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002936 PyLongObject *x;
2937 PyLongObject *w;
2938 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002939 if (w == NULL)
2940 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002941 x = (PyLongObject *) long_add(v, w);
2942 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002943 if (x == NULL)
2944 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002945 Py_SIZE(x) = -(Py_SIZE(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002946 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002947}
2948
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002949static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002950long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002951{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002952 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002953 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002954 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002955 Py_INCREF(v);
2956 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002957 }
Tim Peters69c2de32001-09-11 22:31:33 +00002958 z = (PyLongObject *)_PyLong_Copy(v);
2959 if (z != NULL)
2960 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002961 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002962}
2963
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002964static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002965long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002966{
2967 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002968 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00002969 else
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002970 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002971}
2972
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002973static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002974long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002975{
Christian Heimese93237d2007-12-19 02:37:44 +00002976 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002977}
2978
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002979static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002980long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002981{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002982 PyLongObject *a, *b;
2983 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002984 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002985 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002986 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002987
Neil Schemenauerba872e22001-01-04 01:46:03 +00002988 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2989
Christian Heimese93237d2007-12-19 02:37:44 +00002990 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002991 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002992 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002993 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002994 if (a1 == NULL)
2995 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002996 a2 = (PyLongObject *) long_rshift(a1, b);
2997 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002998 if (a2 == NULL)
2999 goto rshift_error;
3000 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003001 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003002 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003003 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003004
Neil Schemenauerba872e22001-01-04 01:46:03 +00003005 shiftby = PyLong_AsLong((PyObject *)b);
3006 if (shiftby == -1L && PyErr_Occurred())
3007 goto rshift_error;
3008 if (shiftby < 0) {
3009 PyErr_SetString(PyExc_ValueError,
3010 "negative shift count");
3011 goto rshift_error;
3012 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003013 wordshift = shiftby / PyLong_SHIFT;
Christian Heimese93237d2007-12-19 02:37:44 +00003014 newsize = ABS(Py_SIZE(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003015 if (newsize <= 0) {
3016 z = _PyLong_New(0);
3017 Py_DECREF(a);
3018 Py_DECREF(b);
3019 return (PyObject *)z;
3020 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003021 loshift = shiftby % PyLong_SHIFT;
3022 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003023 lomask = ((digit)1 << hishift) - 1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003024 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003025 z = _PyLong_New(newsize);
3026 if (z == NULL)
3027 goto rshift_error;
Christian Heimese93237d2007-12-19 02:37:44 +00003028 if (Py_SIZE(a) < 0)
3029 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003030 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3031 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3032 if (i+1 < newsize)
3033 z->ob_digit[i] |=
3034 (a->ob_digit[j+1] << hishift) & himask;
3035 }
3036 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003037 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003038rshift_error:
3039 Py_DECREF(a);
3040 Py_DECREF(b);
3041 return (PyObject *) z;
3042
Guido van Rossumc6913e71991-11-19 20:26:46 +00003043}
3044
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003045static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003046long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003047{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003048 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003049 PyLongObject *a, *b;
3050 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003051 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003052 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003053 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003054
Neil Schemenauerba872e22001-01-04 01:46:03 +00003055 CONVERT_BINOP(v, w, &a, &b);
3056
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003057 shiftby = PyLong_AsLong((PyObject *)b);
3058 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003059 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003060 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003061 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003062 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003063 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003064 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003065 PyErr_SetString(PyExc_ValueError,
3066 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003067 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003068 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003069 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3070 wordshift = (int)shiftby / PyLong_SHIFT;
3071 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003072
3073 oldsize = ABS(a->ob_size);
3074 newsize = oldsize + wordshift;
3075 if (remshift)
3076 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003077 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003078 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003079 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003080 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003081 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003082 for (i = 0; i < wordshift; i++)
3083 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003084 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003085 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003086 accum |= (twodigits)a->ob_digit[j] << remshift;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003087 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3088 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003089 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003090 if (remshift)
3091 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003092 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003093 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003094 z = long_normalize(z);
3095lshift_error:
3096 Py_DECREF(a);
3097 Py_DECREF(b);
3098 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003099}
3100
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003101
3102/* Bitwise and/xor/or operations */
3103
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003104static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003105long_bitwise(PyLongObject *a,
3106 int op, /* '&', '|', '^' */
3107 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003108{
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003109 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003110 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003111 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003112 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003113 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003114 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003115 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003116
Christian Heimese93237d2007-12-19 02:37:44 +00003117 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003118 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003119 if (a == NULL)
3120 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003121 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003122 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003123 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003124 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003125 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003126 }
Christian Heimese93237d2007-12-19 02:37:44 +00003127 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003128 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003129 if (b == NULL) {
3130 Py_DECREF(a);
3131 return NULL;
3132 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003133 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003134 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003135 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003136 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003137 maskb = 0;
3138 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003139
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003140 negz = 0;
3141 switch (op) {
3142 case '^':
3143 if (maska != maskb) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003144 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003145 negz = -1;
3146 }
3147 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003148 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003149 if (maska && maskb) {
3150 op = '|';
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003151 maska ^= PyLong_MASK;
3152 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003153 negz = -1;
3154 }
3155 break;
3156 case '|':
3157 if (maska || maskb) {
3158 op = '&';
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003159 maska ^= PyLong_MASK;
3160 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003161 negz = -1;
3162 }
3163 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003164 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003165
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003166 /* JRH: The original logic here was to allocate the result value (z)
3167 as the longer of the two operands. However, there are some cases
3168 where the result is guaranteed to be shorter than that: AND of two
3169 positives, OR of two negatives: use the shorter number. AND with
3170 mixed signs: use the positive number. OR with mixed signs: use the
3171 negative number. After the transformations above, op will be '&'
3172 iff one of these cases applies, and mask will be non-0 for operands
3173 whose length should be ignored.
3174 */
3175
Christian Heimese93237d2007-12-19 02:37:44 +00003176 size_a = Py_SIZE(a);
3177 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003178 size_z = op == '&'
3179 ? (maska
3180 ? size_b
3181 : (maskb ? size_a : MIN(size_a, size_b)))
3182 : MAX(size_a, size_b);
3183 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003184 if (z == NULL) {
Neal Norwitzef02b9e2006-07-16 02:00:32 +00003185 Py_DECREF(a);
3186 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003187 return NULL;
3188 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003189
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003190 for (i = 0; i < size_z; ++i) {
3191 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3192 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3193 switch (op) {
3194 case '&': z->ob_digit[i] = diga & digb; break;
3195 case '|': z->ob_digit[i] = diga | digb; break;
3196 case '^': z->ob_digit[i] = diga ^ digb; break;
3197 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003198 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003199
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003200 Py_DECREF(a);
3201 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003202 z = long_normalize(z);
3203 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003204 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003205 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003206 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003207 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003208}
3209
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003210static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003211long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003212{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003213 PyLongObject *a, *b;
3214 PyObject *c;
3215 CONVERT_BINOP(v, w, &a, &b);
3216 c = long_bitwise(a, '&', b);
3217 Py_DECREF(a);
3218 Py_DECREF(b);
3219 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003220}
3221
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003222static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003223long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003224{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003225 PyLongObject *a, *b;
3226 PyObject *c;
3227 CONVERT_BINOP(v, w, &a, &b);
3228 c = long_bitwise(a, '^', b);
3229 Py_DECREF(a);
3230 Py_DECREF(b);
3231 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003232}
3233
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003234static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003235long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003236{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003237 PyLongObject *a, *b;
3238 PyObject *c;
3239 CONVERT_BINOP(v, w, &a, &b);
3240 c = long_bitwise(a, '|', b);
3241 Py_DECREF(a);
3242 Py_DECREF(b);
3243 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003244}
3245
Guido van Rossum234f9421993-06-17 12:35:49 +00003246static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003247long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003248{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003249 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00003250 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Georg Brandlc02e1312007-04-11 17:16:24 +00003251 if (*pw == NULL)
3252 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003253 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00003254 return 0;
3255 }
Guido van Rossum1952e382001-09-19 01:25:16 +00003256 else if (PyLong_Check(*pw)) {
3257 Py_INCREF(*pv);
3258 Py_INCREF(*pw);
3259 return 0;
3260 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00003261 return 1; /* Can't do it */
3262}
3263
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003264static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003265long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003266{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003267 if (PyLong_CheckExact(v))
3268 Py_INCREF(v);
3269 else
3270 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003271 return v;
3272}
3273
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003274static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003275long_int(PyObject *v)
3276{
3277 long x;
3278 x = PyLong_AsLong(v);
3279 if (PyErr_Occurred()) {
3280 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3281 PyErr_Clear();
3282 if (PyLong_CheckExact(v)) {
3283 Py_INCREF(v);
3284 return v;
3285 }
3286 else
3287 return _PyLong_Copy((PyLongObject *)v);
3288 }
3289 else
3290 return NULL;
3291 }
3292 return PyInt_FromLong(x);
3293}
3294
3295static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003296long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003297{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003298 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003299 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003300 if (result == -1.0 && PyErr_Occurred())
3301 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003302 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003303}
3304
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003305static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003306long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003307{
Eric Smith5e527eb2008-02-10 01:36:53 +00003308 return _PyLong_Format(v, 8, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003309}
3310
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003311static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003312long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003313{
Eric Smith5e527eb2008-02-10 01:36:53 +00003314 return _PyLong_Format(v, 16, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003315}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003316
3317static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003318long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003319
Tim Peters6d6c1a32001-08-02 04:15:00 +00003320static PyObject *
3321long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3322{
3323 PyObject *x = NULL;
3324 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003325 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003326
Guido van Rossumbef14172001-08-29 15:47:46 +00003327 if (type != &PyLong_Type)
3328 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003329 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3330 &x, &base))
3331 return NULL;
3332 if (x == NULL)
3333 return PyLong_FromLong(0L);
3334 if (base == -909)
3335 return PyNumber_Long(x);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003336 else if (PyString_Check(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003337 /* Since PyLong_FromString doesn't have a length parameter,
3338 * check here for possible NULs in the string. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003339 char *string = PyString_AS_STRING(x);
3340 if (strlen(string) != PyString_Size(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003341 /* create a repr() of the input string,
3342 * just like PyLong_FromString does. */
3343 PyObject *srepr;
3344 srepr = PyObject_Repr(x);
3345 if (srepr == NULL)
3346 return NULL;
3347 PyErr_Format(PyExc_ValueError,
3348 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003349 base, PyString_AS_STRING(srepr));
Georg Brandl00cd8182007-03-06 18:41:12 +00003350 Py_DECREF(srepr);
3351 return NULL;
3352 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003353 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Georg Brandl00cd8182007-03-06 18:41:12 +00003354 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003355#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003356 else if (PyUnicode_Check(x))
3357 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3358 PyUnicode_GET_SIZE(x),
3359 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003360#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003361 else {
3362 PyErr_SetString(PyExc_TypeError,
3363 "long() can't convert non-string with explicit base");
3364 return NULL;
3365 }
3366}
3367
Guido van Rossumbef14172001-08-29 15:47:46 +00003368/* Wimpy, slow approach to tp_new calls for subtypes of long:
3369 first create a regular long from whatever arguments we got,
3370 then allocate a subtype instance and initialize it from
3371 the regular long. The regular long is then thrown away.
3372*/
3373static PyObject *
3374long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3375{
Anthony Baxter377be112006-04-11 06:54:30 +00003376 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003377 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003378
3379 assert(PyType_IsSubtype(type, &PyLong_Type));
3380 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3381 if (tmp == NULL)
3382 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003383 assert(PyLong_CheckExact(tmp));
Christian Heimese93237d2007-12-19 02:37:44 +00003384 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003385 if (n < 0)
3386 n = -n;
Anthony Baxter377be112006-04-11 06:54:30 +00003387 newobj = (PyLongObject *)type->tp_alloc(type, n);
3388 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003389 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003390 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003391 }
Anthony Baxter377be112006-04-11 06:54:30 +00003392 assert(PyLong_Check(newobj));
Christian Heimese93237d2007-12-19 02:37:44 +00003393 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003394 for (i = 0; i < n; i++)
Anthony Baxter377be112006-04-11 06:54:30 +00003395 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003396 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00003397 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003398}
3399
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003400static PyObject *
3401long_getnewargs(PyLongObject *v)
3402{
3403 return Py_BuildValue("(N)", _PyLong_Copy(v));
3404}
3405
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003406static PyObject *
3407long_getN(PyLongObject *v, void *context) {
Jeffrey Yasskin5de250e2008-03-18 01:09:59 +00003408 return PyLong_FromLong((Py_intptr_t)context);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003409}
3410
Eric Smitha9f7d622008-02-17 19:46:49 +00003411static PyObject *
3412long__format__(PyObject *self, PyObject *args)
3413{
3414 PyObject *format_spec;
3415
3416 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3417 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00003418 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00003419 return _PyLong_FormatAdvanced(self,
3420 PyBytes_AS_STRING(format_spec),
3421 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00003422 if (PyUnicode_Check(format_spec)) {
3423 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00003424 PyObject *result;
3425 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00003426
Eric Smithdc13b792008-05-30 18:10:04 +00003427 if (str_spec == NULL)
3428 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00003429
Eric Smithdc13b792008-05-30 18:10:04 +00003430 result = _PyLong_FormatAdvanced(self,
3431 PyBytes_AS_STRING(str_spec),
3432 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00003433
Eric Smithdc13b792008-05-30 18:10:04 +00003434 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00003435 return result;
3436 }
3437 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
3438 return NULL;
3439}
3440
Robert Schuppenies51df0642008-06-01 16:16:17 +00003441static PyObject *
3442long_sizeof(PyLongObject *v)
3443{
3444 Py_ssize_t res;
3445
Robert Schuppenies9be2ec12008-07-10 15:24:04 +00003446 res = v->ob_type->tp_basicsize;
Robert Schuppenies51df0642008-06-01 16:16:17 +00003447 if (v->ob_size != 0)
Robert Schuppenies9be2ec12008-07-10 15:24:04 +00003448 res += abs(v->ob_size) * sizeof(digit);
Robert Schuppenies51df0642008-06-01 16:16:17 +00003449 return PyInt_FromSsize_t(res);
3450}
3451
Christian Heimes6f341092008-04-18 23:13:07 +00003452#if 0
3453static PyObject *
3454long_is_finite(PyObject *v)
3455{
3456 Py_RETURN_TRUE;
3457}
3458#endif
3459
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003460static PyMethodDef long_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003461 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3462 "Returns self, the complex conjugate of any long."},
Christian Heimes6f341092008-04-18 23:13:07 +00003463#if 0
3464 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3465 "Returns always True."},
3466#endif
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003467 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3468 "Truncating an Integral returns itself."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003469 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smitha9f7d622008-02-17 19:46:49 +00003470 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Robert Schuppenies51df0642008-06-01 16:16:17 +00003471 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00003472 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003473 {NULL, NULL} /* sentinel */
3474};
3475
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003476static PyGetSetDef long_getset[] = {
3477 {"real",
3478 (getter)long_long, (setter)NULL,
3479 "the real part of a complex number",
3480 NULL},
3481 {"imag",
3482 (getter)long_getN, (setter)NULL,
3483 "the imaginary part of a complex number",
3484 (void*)0},
3485 {"numerator",
3486 (getter)long_long, (setter)NULL,
3487 "the numerator of a rational number in lowest terms",
3488 NULL},
3489 {"denominator",
3490 (getter)long_getN, (setter)NULL,
3491 "the denominator of a rational number in lowest terms",
3492 (void*)1},
3493 {NULL} /* Sentinel */
3494};
3495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003496PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003497"long(x[, base]) -> integer\n\
3498\n\
3499Convert a string or number to a long integer, if possible. A floating\n\
3500point argument will be truncated towards zero (this does not include a\n\
3501string representation of a floating point number!) When converting a\n\
3502string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003503converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003504
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003505static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003506 (binaryfunc) long_add, /*nb_add*/
3507 (binaryfunc) long_sub, /*nb_subtract*/
3508 (binaryfunc) long_mul, /*nb_multiply*/
Georg Brandl347b3002006-03-30 11:57:00 +00003509 long_classic_div, /*nb_divide*/
3510 long_mod, /*nb_remainder*/
3511 long_divmod, /*nb_divmod*/
3512 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003513 (unaryfunc) long_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003514 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003515 (unaryfunc) long_abs, /*tp_absolute*/
3516 (inquiry) long_nonzero, /*tp_nonzero*/
3517 (unaryfunc) long_invert, /*nb_invert*/
Georg Brandl347b3002006-03-30 11:57:00 +00003518 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003519 (binaryfunc) long_rshift, /*nb_rshift*/
Georg Brandl347b3002006-03-30 11:57:00 +00003520 long_and, /*nb_and*/
3521 long_xor, /*nb_xor*/
3522 long_or, /*nb_or*/
3523 long_coerce, /*nb_coerce*/
3524 long_int, /*nb_int*/
3525 long_long, /*nb_long*/
3526 long_float, /*nb_float*/
3527 long_oct, /*nb_oct*/
3528 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003529 0, /* nb_inplace_add */
3530 0, /* nb_inplace_subtract */
3531 0, /* nb_inplace_multiply */
3532 0, /* nb_inplace_divide */
3533 0, /* nb_inplace_remainder */
3534 0, /* nb_inplace_power */
3535 0, /* nb_inplace_lshift */
3536 0, /* nb_inplace_rshift */
3537 0, /* nb_inplace_and */
3538 0, /* nb_inplace_xor */
3539 0, /* nb_inplace_or */
Georg Brandl347b3002006-03-30 11:57:00 +00003540 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003541 long_true_divide, /* nb_true_divide */
3542 0, /* nb_inplace_floor_divide */
3543 0, /* nb_inplace_true_divide */
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003544 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003545};
3546
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003547PyTypeObject PyLong_Type = {
3548 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003549 0, /* ob_size */
3550 "long", /* tp_name */
3551 sizeof(PyLongObject) - sizeof(digit), /* tp_basicsize */
3552 sizeof(digit), /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003553 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003554 0, /* tp_print */
3555 0, /* tp_getattr */
3556 0, /* tp_setattr */
3557 (cmpfunc)long_compare, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00003558 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003559 &long_as_number, /* tp_as_number */
3560 0, /* tp_as_sequence */
3561 0, /* tp_as_mapping */
3562 (hashfunc)long_hash, /* tp_hash */
3563 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00003564 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003565 PyObject_GenericGetAttr, /* tp_getattro */
3566 0, /* tp_setattro */
3567 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00003568 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003569 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003570 long_doc, /* tp_doc */
3571 0, /* tp_traverse */
3572 0, /* tp_clear */
3573 0, /* tp_richcompare */
3574 0, /* tp_weaklistoffset */
3575 0, /* tp_iter */
3576 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003577 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003578 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003579 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003580 0, /* tp_base */
3581 0, /* tp_dict */
3582 0, /* tp_descr_get */
3583 0, /* tp_descr_set */
3584 0, /* tp_dictoffset */
3585 0, /* tp_init */
3586 0, /* tp_alloc */
3587 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003588 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003589};